gpt4 book ai didi

python 瓶 : UTF8 path string invalid when using app. mount()

转载 作者:行者123 更新时间:2023-11-28 16:38:16 24 4
gpt4 key购买 nike

在使用 app.mount 时尝试在 URL 路径中使用特殊字符失败:

http://127.0.0.1:8080/test/äöü

结果:

Error: 400 Bad Request
Invalid path string. Expected UTF-8

测试.py:

#!/usr/bin/python
import bottle
import testapp
bottle.debug(True)
app = bottle.Bottle()
app.mount('/test',testapp.app)
app.run(reloader=True, host='0.0.0.0', port=8080)
run(host="localhost",port=8080)

测试应用程序.py:

import bottle
app = bottle.Bottle()
@app.route("/:category", method=["GET","POST"])
def admin(category):
try:
return category
except Exception(e):
print ("e:"+str(e))

当不使用 app.mount 时相同的代码运行良好:

测试工作.py:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import bottle
import testapp
bottle.debug(True)
app = bottle.Bottle()
@app.route("/test/:category", method=["GET","POST"])
def admin(category):
try:
return category
except Exception(e):
print ("e:"+str(e))
app.run(reloader=True, host='0.0.0.0', port=8080)
run(host="localhost",port=8080)

这看起来像是一个错误,还是我在这里遗漏了什么? :/

最佳答案

是的,这似乎是瓶中的一个错误。

问题出在_handle方法:

def _handle(self, environ):
path = environ['bottle.raw_path'] = environ['PATH_INFO']
if py3k:
try:
environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
except UnicodeError:
return HTTPError(400, 'Invalid path string. Expected UTF-8')

这里environ['PATH_INFO']被转成了utf8,所以当挂载的app再次调用同样的方法时,内容已经是utf8,所以转会失败。

一个非常快速的解决方法是更改​​该代码以跳过已经完成的转换:

def _handle(self, environ):
converted = 'bottle.raw_path' in environ
path = environ['bottle.raw_path'] = environ['PATH_INFO']
if py3k and not converted:
try:
environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
except UnicodeError:
return HTTPError(400, 'Invalid path string. Expected UTF-8')

提交一份针对 bottle 的错误报告可能会很好。

关于 python 瓶 : UTF8 path string invalid when using app. mount(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com