views.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import json
  2. from django.http import JsonResponse, HttpResponse
  3. from django.views.decorators.csrf import csrf_exempt
  4. from .form import UserRequestForm, UserListForm
  5. from .models import friends
  6. # 批处理流程
  7. def more_clean(request, form):
  8. if request.method == 'POST':
  9. user_login_form = form(request.POST)
  10. if user_login_form.is_valid():
  11. # 清洗出合法的数据
  12. data = user_login_form.cleaned_data
  13. return data
  14. else:
  15. response = ['illegal input']
  16. return HttpResponse(json.dumps(response))
  17. # 获取好友列表
  18. @csrf_exempt
  19. def friendsList(request):
  20. data = more_clean(request, UserListForm)
  21. if data.get('token') != 'token':
  22. response = ['there has a mistake, please provide illegal token']
  23. return HttpResponse(json.dumps(response))
  24. else:
  25. try:
  26. friendsTemp = friends.objects.filter(whomfriend=data['username'])
  27. return HttpResponse(json.dumps(friendsTemp))
  28. except friends.DoesNotExist:
  29. response = ['this user do not exist']
  30. return HttpResponse(json.dumps(response))
  31. # 添加好友(通过ws发送给被请求方信息,返回等待对方回应中)
  32. # @csrf_exempt
  33. # def addFriend(request):
  34. # 由于ws不是很确定,先闲置
  35. # 同意添加好友,
  36. def acceptFriend(request):
  37. data = more_clean(request, UserRequestForm)
  38. if request.method == "POST":
  39. try:
  40. friends.objects.create(username=data["username"], whomfriend=data["otherUsername"], token=data["token"],
  41. status=1)
  42. response = ["add successfully"]
  43. return HttpResponse(json.dumps(response))
  44. except:
  45. response = ["add failed"]
  46. return HttpResponse(json.dumps(response))
  47. # 获取详细好友信息
  48. @csrf_exempt
  49. def friendDetail(request, pk):
  50. data = more_clean(request, UserRequestForm)
  51. try:
  52. loginUserid = int(data["username"])
  53. friendsTemp = friends.objects.get(whomfriend=loginUserid, userid=pk)
  54. except friends.DoesNotExist:
  55. response = ["do not exist"]
  56. return HttpResponse(json.dumps(response))
  57. if len(friendsTemp):
  58. response = [friendsTemp]
  59. return HttpResponse(json.dumps(response))
  60. else:
  61. response = ["wrong"]
  62. return HttpResponse(json.dumps(response))
  63. @csrf_exempt
  64. def deleteFriend(request):
  65. data = more_clean(request, UserRequestForm)
  66. try:
  67. tempFriend = friends.objects.get(
  68. username=data["username"], whomfriend=data["otherUsername"])
  69. tempFriend.clear()
  70. response = ["delete success"]
  71. return HttpResponse(json.dumps(response))
  72. except:
  73. response = ["delete failed"]
  74. return JsonResponse(response)