我的web应用程序以前运行得很好,但几天前出现了一个问题,现在我可以启动web应用程序了,但当我从本地(127.0.0.1)或远程(192.168.xxx.xxx)(只需简单地打开主页,没有鼠标和键盘输入)浏览我的网站时,web应用程序崩溃如下:
Traceback (most recent call last):
File "/path/to/project/web/application.py", line 242, in process
return self.handle()
File "/path/to/project/web/application.py", line 233, in handle
return self._delegate(fn, self.fvars, args)
File "/path/to/project/web/application.py", line 415, in _delegate
return handle_class(cls)
File "/path/to/project/web/application.py", line 390, in handle_class
return tocall(*args)
File "./my_web_app.py", line 40, in GET
simplejson.dumps(manus))
File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 286, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 226, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 296, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xcb in position 5: invalid continuation byte
192.168.xxx.xxx:2131 - - [27/Nov/2013 16:51:09] "HTTP/1.1 GET /" - 500 Internal Server Error
192.168.xxx.xxx:2131 - - [27/Nov/2013 16:51:09] "HTTP/1.1 GET /favicon.ico" - 404 Not Found
192.168.xxx.xxx:2131 - - [27/Nov/2013 16:51:09] "HTTP/1.1 GET /favicon.ico" - 404 Not Found我不认为我的代码有什么问题,因为我的代码在我的计算机上运行得很好,只有当它在服务器上运行时,错误才会出现。"web“目录是指向"web.py-0.34/web”的链接,它不是我的代码。
我的代码很简单:
urls = (
'/', 'find_alternate',
'/find_alternates', 'find_alternate',
'/show_detail/(.+)', 'show_detail'
)
app = web.application(urls, globals())
class find_alternate:
def GET(self):
brands = [b.brandName for b in Brand.q.all()]
brands.sort()
manus = [oe.brandName for oe in OeNumber.q.group_by(OeNumber.brandName)]
manus.sort()
return render.find_alternates_main(simplejson.dumps(brands), simplejson.dumps(manus))
"""
some more functions, but not relevant
"""
render = web.template.render('/path/to/templates/')
web.template.Template.globals['str'] = str
if __name__ == "__main__":
app.run()我的CREATE表:
CREATE TABLE `brand` (
`brandNo` int(11) NOT NULL,
`brandName` varchar(64) DEFAULT NULL,
PRIMARY KEY (`brandNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |我现在的问题是如何将字符从Unicode转换成utf-8,这样jsonsimple就可以解析它了。在维基上,我发现了这个:
Unicode: U+00CB
UTF-8: C3(hex) 8B(hex)我如何解决:在my.cnf中添加了以下几行:
collation-server = utf8_unicode_ci
init_connect='SET NAMES utf8'
character-set-server = utf8
skip-character-set-client-handshake已将数据库转换为utf-8:
ALTER DATABASE `db_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;发布于 2013-11-29 04:17:17
u'\xcb'是'\xc3\x8b'的unicode表示,
>>> u'CITRO\xcbN'.encode('utf-8')
'CITRO\xc3\x8bN'及其latin-1编码:
>>> u'CITRO\xcbN'.encode('latin-1')
'CITRO\xcbN'所以你的服务器数据库似乎不是utf-8编码的。
我认为最好的解决方案是检查您的服务器表编码,如果不是utf8,则迁移到utf8。如果表在utf8中,则必须修复数据,因为数据不是。
或者,您可以从db设置推断编码并传递给simplejson:
simplejson.dumps(manus, encoding=encoding)但这种方法会导致服务器和开发人员之间的差异,并导致未来的错误。
https://stackoverflow.com/questions/20250634
复制相似问题