2

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?

davidism
  • 121,510
  • 29
  • 395
  • 339
NeoVe
  • 3,857
  • 8
  • 54
  • 134
  • Possible duplicate of [how to discriminate based on HTTP method in django urlpatterns](https://stackoverflow.com/questions/19096227/how-to-discriminate-based-on-http-method-in-django-urlpatterns) – John Szakmeister Jan 12 '19 at 23:21

2 Answers2

4

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.

Alex
  • 2,356
  • 15
  • 19
2

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].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555