Python 将POST方法从烧瓶更改为Django
我有一个烧瓶应用程序的代码:Python 将POST方法从烧瓶更改为Django,python,django,Python,Django,我有一个烧瓶应用程序的代码: 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') da
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
文件替代,您在其中指定了路由,但是现在,我如何使方法=['GET','POST']
行适应Django方式
我对此有点困惑,有什么想法吗?如果在django中使用基于函数的视图,则不必显式限制请求类型 您只需在视图中检查
request.method
,如果request.method==POST处理POST
请求;否则,默认情况下您将处理GET
请求
但是,如果使用Django,我强烈建议使用基于类的视图()。他们确实提供了一个非常好的样板
但是现在,我如何使方法=['GET','POST']
行适应Django方式呢
如果您只想防止使用其他方法(如PUT、PATCH等)调用视图,则可以使用:
来自django.views.decorators.http的导入需要\u http\u方法
@需要\u http\u方法(['GET','POST'])
def索引(请求):
汇率=getExchangeRates()
返回渲染模板('index.html',**locals())
如果您想使用它将不同的方法“路由”到不同的函数,您可以使用。的可能副本
from django.views.decorators.http import require_http_methods
@require_http_methods(['GET', 'POST'])
def index(request):
rates = getExchangeRates()
return render_template('index.html',**locals())