Python Bottle:使用 app.mount() 时 UTF8 路径字符串无效

2023-12-21

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

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

结果是:

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

test.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 https://github.com/defnull/bottle/blob/33b1683793bc6ce8af37c9d5c34be0c4fe220d1f/bottle.py#L839 method:

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')

Here environ['PATH_INFO']转换为utf8,所以当挂载的应用再次调用相同的方法时,内容已经是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 的错误报告可能会更好。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Bottle:使用 app.mount() 时 UTF8 路径字符串无效 的相关文章

随机推荐