在 Python 中使用 GET 方法分配变量值

assign variable value thought GET method in Python

我有以下 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 的正确方法是什么?当前的实现不工作

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

这可能是

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

但是,您最好描述您的逻辑,使最小数量在 flask 应用程序中,而大部分在您导入的库中!

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

from mylibrary import myfunction

@route("/foo")
def foo():
    myfunction(arg1)

@route("/bar")
def bar():
    myfunction(arg2)

有趣的是,这种风格还会使您的项目更容易进行单元测试(我已经处理过几个 Flask 项目)。