python3 中自定义wsgi函数,handlers函数报错问题

代码如下:

#coding:utf-8
from wsgiref.simple_server import make_server

def RunServer(environ, start_response):
start_response(‘200 OK’, [(‘Content-Type’, ‘text/html’)])
return ‘Hello, web!’

if name == ‘main’:
httpd = make_server(‘localhost’, 8000, RunServer)
print (“Serving HTTP on port 8000…”)
httpd.serve_forever()

这段代码在python2.7中可以运行,到python3.4中运行,就开始报错,报错内容如下

Serving HTTP on port 8000…
127.0.0.1 - - [12/Apr/2016 16:44:17] “GET / HTTP/1.1” 200 0
Traceback (most recent call last):
File “C:\Python34\lib\wsgiref\handlers.py”, line 138, in run
self.finish_response()
File “C:\Python34\lib\wsgiref\handlers.py”, line 181, in finish_response
self.write(data)
File “C:\Python34\lib\wsgiref\handlers.py”, line 267, in write
“write() argument must be a bytes instance”
AssertionError: write() argument must be a bytes instance
127.0.0.1 - - [12/Apr/2016 16:44:17] “GET / HTTP/1.1” 500 59
Traceback (most recent call last):
File “C:\Python34\lib\wsgiref\handlers.py”, line 138, in run
self.finish_response()
File “C:\Python34\lib\wsgiref\handlers.py”, line 181, in finish_response
self.write(data)
File “C:\Python34\lib\wsgiref\handlers.py”, line 267, in write
“write() argument must be a bytes instance”
AssertionError: write() argument must be a bytes instance

这里用的编辑器是pycharm,找到handlers.py文件的138行,按住ctrl点击文件中的finish_response()方法,

就找到self.finish_response()定义的位置了。根据第二条提示:

File “C:\Python34\lib\wsgiref\handlers.py”, line 181, in finish_response
self.write(data)

发现是write方法出现错误,再按住ctrl点击write方法,找到定义write方法的位置,发现第一行就定义了一条报错:

assert type(data) is bytes,
“write() argument must be a bytes instance”
对照上面的报错信息,发现可能是变量data的类型,不是bytes,所以在handlers.py181行代码self.write(data)上面加一句:
data=data.encode(),
再次刷新程序,发现所有报错居然都没了,程序正常运行。

如果无法保存修改的代码,就需要使用管理员身份重新打开pycharm,然后再进行修改

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值