我正在编写一个API函数(在这种情况下,我不需要休息)。 基本上,这是一个以UUID4作为api-key的URL。
功能如下:
def jsonapi(request, apikey):
try:
test = get_object_or_404(ProfileDetails, apikey=apikey)
if ProfileDetails.objects.filter(apikey=apikey).exists():
details = get_object_or_404(ProfileDetails, apikey=apikey)
if Posts.objects.filter(published=True, user=details).exists():
data = Posts.objects.filter(published=True, user=details).order_by('-timestamp')
postData = []
for a in data:
user = a.user.username
title = a.title
post = a.post
date = a.timestamp
slug = a.slug
url = "https://app.domain.co/@" + a.user.username + "/" + a.slug
# print(date.date)
newjson = {
"username": user,
"title": title,
}
postData.append(newjson)
jsonStr = json.dumps(postData, cls=DjangoJSONEncoder)
qwe = json.loads(jsonStr)
returndata = JsonResponse(qwe, safe=False)
returndata['Access-Control-Allow-Origin'] = '*'
return returndata
else:
newjson = {
"error": "Please make sure you have at least 1 item live."
}
postData.append(newjson)
jsonStr = json.dumps(postData, cls=DjangoJSONEncoder)
qwe = json.loads(jsonStr)
returndata = JsonResponse(qwe, safe=False)
returndata['Access-Control-Allow-Origin'] = '*'
return returndata
else:
newjson = {
"error": "Make sure you have at least one item set as live."
}
postData.append(newjson)
jsonStr = json.dumps(postData, cls=DjangoJSONEncoder)
qwe = json.loads(jsonStr)
returndata = JsonResponse(qwe, safe=False)
returndata['Access-Control-Allow-Origin'] = '*'
return returndata
except ValueError:
return JsonResponse({"Error":"Invalid API Key"})
现在,基本上,我需要做的是,当我在URL中输入不是UUID的内容时,它返回[“'something'不是有效的UUID。”]
我希望ValueError能够捕获错误并让我写一个响应,但是没有运气。
有什么建议吗?
谢谢!