前面一直使用HTTPServer对web请求进行处理,今天突然想能不能改下,用python3提供的wsgiref进行处理,原来的程序:
from wsgiref.simple_server import make_server
def hello_world_app(env,start_response):
start_response("200 OK",[("Content-type","text/plain;charset=utf-8")])
return ["Hello World!!"]
if __name__ == "__main__":
httpd=make_server('',8080,hello_world_app)
httpd.handle_request()
问题并不在这个程序,异常报的是在write的时候,于是,要改的就是write,改哪里呢?
就改ServerHandler
这个类在wsgiref包里的simple_server.py模块中(Lib/wsgiref/simple_server.py)
原来的ServerHandler是:
class ServerHandler(SimpleHandler):
server_software = software_version
def close(self):
try:
self.request_handler.log_request(
self.status.split(' ',1)[0], self.bytes_sent
)
finally:
SimpleHandler.close(self)
重写_write方法即可:
class ServerHandler(SimpleHandler):
server_software = software_version
def close(self):
try:
self.request_handler.log_request(
self.status.split(' ',1)[0], self.bytes_sent
)
self.buf_data.seek(0)
shutil.copyfileobj(self.buf_data,self.stdout)
finally:
SimpleHandler.close(self)
def _write(self,data):
if not hasattr(self,"buf_data"):
self.buf_data=io.BytesIO()
if type(data) is str:
data=data.encode("UTF-8")
self.buf_data.write(data)
大功告成。
测试 http://localhost:8080,Hello World出来了!
为了方便调试,这里的编码直接写UTF-8了。各位根据自己的需要配置。。
如果需要使用多线程处理,可以用上一篇文章提到的ThreadingMixIn即可。
分享到:
- 2009-03-31 16:04
- 浏览 1231
- 评论(0)
- 论坛回复 / 浏览 (0 / 1747)
- 查看更多
相关推荐
16-WSGI、mini_frame(web框架)(python和linux高级编程阶段 代码和截图)16-WSGI、mini_frame(web框架)(python和linux高级编程阶段 代码和截图)16-WSGI、mini_frame(web框架)(python和linux高级编程阶段 ...
python库。 资源全名:simple-api-management-wsgi-0.1.1.tar.gz
资源分类:Python库 所属语言:Python 资源全名:necrophos-wsgi-0.0.1.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
支持python2.7的mod_wsgi的windows版本。里面文件包括: mod_wsgi-win32-ap22py27-3.3.so python-2.7.msi
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,亲测可用
资源分类:Python库 所属语言:Python 资源全名:buildbot-wsgi-dashboards-1.5.0.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源分类:Python库 所属语言:Python 资源全名:necrophos-wsgi-0.0.4.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
官方离线安装包,亲测可用
python库。 资源全名:WSGIserver-1.0-py2.py3-none-any.whl
mod_wsgi-3.5-for-windows32/64-apache2.2/2.4-python2.6-3.4各版本组合都有。总有一款适合你。 详见列表: mod_wsgi-3.5.ap22.win32-py2.6.zip mod_wsgi-3.5.ap22.win32-py2.7.zip mod_wsgi-3.5.ap22.win32-py3.2....
Python学习笔记-WSGI接口
一、Python基础概述 二、Python基础教程 老王Python教程 基础篇 基础篇1-福利课python先入为主上 基础篇2-福利课-python先入为主下篇 基础篇3-虚拟机安装xubuntu开发环境 基础篇4-linux基本命令以及开发环境 基础篇...
资源分类:Python库 所属语言:Python 资源全名:a2wsgi-0.3.3-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,亲测可用
A tiny WSGI web framework(一个 WSGI Web 框架)(Python 3.5 ).
apache python mod_python 插件 更多到我的站点: http://www.iteedu.com/download