【问题标题】:assign variable value thought GET method in Python在 Python 中通过 GET 方法分配变量值
【发布时间】:2021-04-26 21:22:16
【问题描述】:

我有以下python 代码:

from flask import Flask
from flask import request

import requests

    @app.route("/get_city")
    get_city():
        to_echo = request.args.get("city", "")
        response = "{}".format(to_echo)
    
        return response
    
    
    @app.route('/v1/api/check_current_weather_by_city')
    def check_current_weather_by_city():
        city = get_city()

将值“Tel+aviv”放入变量city 的正确方法是什么?当前的实现不起作用

【问题讨论】:

    标签: python rest flask get


    【解决方案1】:

    从广义上讲,requests.get() 不是 Flask 的一部分(在请求中有一个细微不同的 request 值)并且是另一个第三方库,它将返回一些 Request object,它你可能想要.text 的属性

    这可能是

    r = requests.get(url)
    r.raise_for_status()  # make sure the request succeeded!
    city = r.text
    

    但是,您可能最好描述您的逻辑,以便最少数量在烧瓶应用程序中,而大部分在您导入的库中!

    然后,如果您希望它们的逻辑在多个路由中,您可以直接调用该库中的函数,而无需发出 Web 请求。

    from mylibrary import myfunction
    
    @route("/foo")
    def foo():
        myfunction(arg1)
    
    @route("/bar")
    def bar():
        myfunction(arg2)
    

    有趣的是,这种风格也会让您的项目更容易进行单元测试(我曾参与过多个 Flask 项目)。

    【讨论】:

    • 所以我的电话应该是city = echo("Tel-aviv")?我试过但它仍然抛出异常
    • 你不能这样直接调用路由,你应该创建另一个函数并让both调用它
    • 你能根据我的代码分享一个例子吗?
    • 只需声明两个路由之外的函数并调用它
    • 我不明白。 myfunction 做什么?为什么我不能用这样的参数调用get_city()@app.route("/get_city/<city>")city = get_city("Tel-aviv")
    猜你喜欢
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    相关资源
    最近更新 更多