Django:如果没有找到请求的数据,有没有办法从GET请求移动到POST请求?



我正在使用Django制作一个天气API,用户在其中调用以下内容:

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

我的应用程序应该查询数据库并在找到时返回数据。如果数据不存在或已过时,应用将通过访问第三方天气 API 来创建或修改条目以提取相关数据。

现在,我正在使用views.pyget函数中的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 块内的POST方法,成功后回复状态201

最新更新