将后处理方法从Flask改为Djang

2024-04-19 07:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个烧瓶应用程序的代码:

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.routedecorator被urls.py文件替换,在该文件中指定路由,但是现在,如何将methods=['GET', 'POST']行调整为Django方式?你知道吗

我有点困惑,有什么想法吗?你知道吗


Tags: thefromiofordatarateresponsedef
2条回答

but now, how can I adapt the methods=['GET', 'POST'] line to a Django way?

如果您只想防止使用不同的方法(如PUT、PATCH等)调用视图,那么可以使用^{} decorator [Django-doc]

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()) 

如果您想使用它将不同的方法“路由”到不同的函数,可以使用class-based view [Django-doc]。你知道吗

如果在django中使用基于函数的视图,则不必显式限制请求类型。你知道吗

您只需检查视图中的request.method,然后if request.method == POST处理POST请求;否则,默认情况下您将处理GET请求。你知道吗

但是,如果使用Django,我强烈建议使用基于类的视图(https://docs.djangoproject.com/en/2.1/topics/class-based-views/)。他们提供了一个非常好的样板。你知道吗

相关问题 更多 >