将哈希“#”解析为flask routes中URL请求中的字符串

2024-09-28 11:40:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将“#”符号解析为Flask项目中的直接url。问题是,每次请求url时,它都会打断包含#init的任何值,因为它是url编码中的一个特殊字符

localhost:9999/match/keys?source=#123&destination=#123 

在flask中,我试图得到这样的论点

app.route(f'/match/keys/source=<string:start>/destination=<string:end>', methods=['GET'])

我在控制台上看到的url响应如下:

"GET /match/keys/source=' HTTP/1.0" 404 -] happens

Tags: 项目localhosturlflasksource编码getstring
2条回答

我找到了另一个解决办法。我没有使用GET方法,而是切换到POST

localhost:9999/match/keys

在app.routes中,我发送了参数以获取_json

app.route('/match/keys/',method=['POST'])
def my_func():
    arg = request.get_json 

在《邮递员》中,我发送POST请求并发送尸体,如下所示: Postman Post request

我相信您可能不完全理解“查询字符串”在flask中是如何工作的。此url:

app.route(f'/match/keys/source=<string:start>/destination=<string:end>', methods=['GET'])

无法按预期工作,因为它与请求不匹配:

localhost:9999/match/keys?source=#123&destination=#123 

相反,它可能是:

@app.route('/match/keys', methods=['GET'])

这将符合:

localhost:9999/match/keys?source=%23123&destination=%23123

然后,要捕获这些“查询字符串”,您需要执行以下操作:

source = request.args.get('source') # <- name the variable what you may
destination = request.args.get('destination') # <- same as the naming format above

因此,当您调用localhost:9999/match/keys?source=%23123&destination=%23123时,您将测试请求url中的那些“查询字符串”,如果它们是,则路由函数将执行

我写了这个测试:

def test_query_string(self):
    with app.test_client() as c:
        rc = c.get('/match/keys?source=%23123') # <- Note use of the '%23' to represent '#'
        print('Status code: {}'.format(rc.status_code))
        print(rc.data)
        assert rc.status_code == 200
        assert 'source' in request.args
        assert rc.data.decode('utf-8') == "#123"

并使用此路由功能通过:

@app.route('/match/keys', methods=['GET'])
def some_route():
    s = request.args.get('source')

    return s

您可以看到,我能够在单元测试中捕获查询字符串源值

相关问题 更多 >

    热门问题