我有来自 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/)。他们确实提供了非常好的样板。
