Change POST method from Flask to Django

Viewed 628

I have this code from a Flask application:

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

For example, the @app.route decorator is substituted by the urls.py file, in which you specify the routes, but now, how can I adapt the methods=['GET', 'POST'] line to a Django way?

I'm a little bit confused on that, any ideas?

2 Answers

If using function based views in django, then you don't have to explicitly restrict the request type.

You can simply check request.method inside your view and if request.method == POST handle the POST request; Otherwise, you'll be handling the GET request by default.

However, I highly recommend moving to Class-based views (https://docs.djangoproject.com/en/2.1/topics/class-based-views/) if using Django. They do offer a really good boilerplate.

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

If you only aim to prevent that the view is called with a different method (like PUT, PATCH, etc.), then you can use the require_http_methods 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()) 

If you want to use this to "route" different methods to different functions, you can use a class-based view [Django-doc].

Related