我正在使用 Django 制作一个天气 API,用户可以调用如下内容:
http://127.0.0.1:8000/weather/<latitude>,<longitude>
我的应用程序应该查询数据库并返回数据(如果找到)。如果数据不存在或已过时,应用程序将通过访问第 3 方天气 API 来创建或修改条目以提取相关数据。
现在,我在 views.py
的 get
函数中使用 get_or_create()
函数来完成此操作。据我所知,这样做是不好的做法,任何数据库修改都应该作为 POST 或 PUT 来完成。
我不确定这是否是我能做的事情,或者我是否以错误的方向解决这个问题。我的应用程序目前并未执行我所说的所有操作,但如果条目不存在,它会创建条目。
我想要的是我的应用程序在确定需要创建或更新条目后跳转到 POST/PUT
。
views.py
def get(self, request, *args, **kwargs):
# Process latitude and longitude coordinates from URL
coordinates = kwargs.pop('location', None).split(",")
latitude = coordinates[0]
longitude = coordinates[1]
# Retrieve the Location by latitude and longitude
# If it doesn't exist, create an entry to generate a 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)
currently = forecast['currently']
# Assign location.pk to currently data
currently['location'] = location.pk
# Serialize and 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)
最佳答案
编写一个常用的GET
方法并检查结果,如果是not none
则可以直接返回状态200的响应。如果None
> 然后调用 If block 内的 POST
方法,成功后回复状态 201
。
关于python - Django:如果找不到请求的数据,有没有办法从 GET 请求转移到 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45367231/