一个简单的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()

待办事项

未来版本的功能

Content-TypeAccept支持内容协商:

Return the response body in the format specified in the ^{tt4}$ header if given, otherwise in the same ^{tt3}$ as the request.

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java无法启动应用程序:JNLP错误   java根据用户输入在PreparedStatement中使用setTime()或setNull()   java EJB与同步   java以object为键通过hashmap进行搜索   java中的模10^9+7   针对包含其他对象的对象的java OOP最佳实践   如何将字符串作为HTML代码从Java文件读取到JSP页面?   java我的POM怎么了?“解析表达式..检测到递归表达式循环”   用于Hbase的Mapreduce的java NoSuchMethodError   JAVAlang.SecurityException:权限拒绝:启动意图{act=安卓.Intent.action.MAIN cat=[安卓.Intent.category.LAUNCHER]   数组初始化谜语Java   通过arraylist搜索时的java句柄关联