python - Django: Is there a way to move from a GET request to a POST request if the requested data is not found? -


i making weather api using django user calls like:

http://127.0.0.1:8000/weather/<latitude>,<longitude> 

my application supposed query database , return data if found. if data not present or outdated, app create or modify entry accessing 3rd party weather api pull relevant data.

right now, i'm using get_or_create() function within get function in views.py accomplish this. i've read, doing bad practice , database modification should done post or put.

i'm uncertain if can or if approaching problem in wrong direction. app doesn't said should do, create entries if don't exist.

what want app jump post/put after determining entry needs created or updated.

views.py

def get(self, request, *args, **kwargs):     # process latitude , longitude coordinates url     coordinates = kwargs.pop('location', none).split(",")     latitude = coordinates[0]     longitude = coordinates[1]      # retrieve location latitude , longitude     # if doesn't exist, create entry generate parent key     location, created = location.objects.get_or_create(         latitude=latitude,         longitude=longitude,         defaults={'timezone': 'default', 'last_updated': timezone.now()},     )      # retrieve weather data.     forecast = get_weather(latitude, longitude)     = forecast['currently']      # assign location.pk data     currently['location'] = location.pk      # serialize , confirm validity of data.     location_serializer = locationserializer(location, data=forecast)     location_serializer.is_valid(raise_exception=true)      currently_serializer = currentlyserializer(data=currently)     currently_serializer.is_valid(raise_exception=true)      location_serializer.save()     currently_serializer.save()     response = location_serializer.data.copy()     response.update(currently_serializer.data)     return response(response, status=status.http_200_ok) 

write usual get method , check result, if not none can directly return response status 200. if none call post method inside if block, on success reply status 201.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -