一个简单的python http服务器,在响应中响应请求
httpd-echo的Python项目详细描述
一个简单的python http服务器,在响应中回显请求
提供一个简单的http服务器,尝试在 以最合理的方式回应。这对测试很有用, 调试,在具有硬编码的系统中截取本地服务器 提出http请求等的假设:
$ python -m httpdecho Echoing HTTP at http://localhost:8000 ...
示例
如果不指定端口,服务器将尝试查找下一个可用端口 从8000开始,尽量做到可预测:
>>> import sys >>> import time >>> import subprocess >>> from six.moves import SimpleHTTPServer >>> startup_delay = 0.5 >>> simple_popen = subprocess.Popen( ... [sys.executable, '-m', SimpleHTTPServer.__name__] ... ); time.sleep(1) >>> echo_popen = subprocess.Popen( ... [sys.executable, '-m', 'httpdecho'] ... ); time.sleep(1) >>> echo_popen.poll() >>> simple_popen.kill()
一旦运行,http请求就会在响应中得到响应。默认响应 正文格式基本上是http头格式,从 http.client.HTTPMessage:
>>> import io >>> import requests >>> import email >>> get_response = requests.delete('http://localhost:8001') >>> get_body = email.message_from_string(get_response.text) >>> print(get_body['Method']) DELETE >>> print(get_body['Path']) / >>> print(get_body.get_payload()) <BLANKLINE>
还包括查询参数:
>>> query_response = requests.get( ... 'http://localhost:8001', params=dict(Foo='foo')) >>> query_body = email.message_from_string(query_response.text) >>> print(query_body['Foo']) foo
如果请求是POST或接受 请求、正文或响应正文将包含post正文:
>>> post_response = requests.patch( ... 'http://localhost:8001', data=dict(Bar='bar')) >>> post_body = email.message_from_string(post_response.text) >>> print(post_body.get_payload()) Bar=bar
关闭服务器:
>>> echo_popen.kill()