gpt4 book ai didi

python - 将 POST 方法从 Flask 更改为 Django

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:27 24 4
gpt4 key购买 nike

我有来自 Flask 应用程序的代码:

def getExchangeRates():
""" Here we have the function that will retrieve the latest rates from fixer.io """
rates = []
response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd')
data = response.read()
rdata = json.loads(data.decode(), parse_float=float)
rates_from_rdata = rdata.get('rates', {})
for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']:
try:
rates.append(rates_from_rdata[rate_symbol])
except KeyError:
logging.warning('rate for {} not found in rdata'.format(rate_symbol))
pass

return rates

@app.route("/" , methods=['GET', 'POST'])
def index():
rates = getExchangeRates()
return render_template('index.html',**locals())

例如,@app.route 装饰器被替换为 urls.py 文件,您在其中指定路由,但现在,我该如何调整methods=['GET', 'POST'] 行到 Django 方式?

我对此有点困惑,有什么想法吗?

最佳答案

如果在 django 中使用基于函数的 View ,那么您不必明确限制请求类型。

您可以简单地在您的 View 中检查 request.method 并且 if request.method == POST 处理 POST 请求;否则,您将默认处理 GET 请求。

但是,如果使用 Django,我强烈建议转向基于类的 View (https://docs.djangoproject.com/en/2.1/topics/class-based-views/)。他们确实提供了非常好的样板。

关于python - 将 POST 方法从 Flask 更改为 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54164750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com