【问题标题】:parse Hash "#" as string in URL request in flask routes将哈希“#”解析为烧瓶路由中 URL 请求中的字符串
【发布时间】:2020-10-04 11:25:46
【问题描述】:

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

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

在烧瓶中,我试图像这样得到这些参数

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

我在控制台上看到的 url 响应是这样的:

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

【问题讨论】:

  • 尝试使用 %23 作为“#”字符
  • 请注意,您在烧瓶中捕获查询字符串,就像request.args.get('source')
  • 我认为该路由不是有效路由,它也应该是/match/keys, methods=['GET'],您使用request.args.get('source') 获取查询字符串值

标签: python url flask url-routing


【解决方案1】:

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

localhost:9999/match/keys

在 app.routes 中,我将参数发送到 get_json。

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

在邮递员中,我发送 POST 请求并将正文发送如下: Postman Post request

【讨论】:

    【解决方案2】:

    我相信您可能不完全理解“查询字符串”在烧瓶中的工作原理。这个网址:

    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&amp;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
    

    所以你看到我能够在我的单元测试中捕获查询字符串源值。

    【讨论】:

    • 非常感谢您的回答。我实际上找到了另一种解决方法。
    • 我现在请求的是 POST 方法,而不是 GET 方法。
    猜你喜欢
    • 2014-07-10
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2013-02-04
    • 2012-10-12
    • 2012-02-22
    • 1970-01-01
    • 2014-07-23
    相关资源
    最近更新 更多