views.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from django.shortcuts import render
  2. from .models import PublicKey
  3. from .form import AddPublicKeyForm
  4. from django.http import HttpResponse
  5. from django.contrib.auth.decorators import login_required
  6. # from dwebsocket.decorators import accept_websocket
  7. import json
  8. DEBUG = True
  9. # WS_DIC = {}
  10. #
  11. #
  12. # # 接收ws连接
  13. # @accept_websocket
  14. # def connect_user(request):
  15. # if request.is_websocket():
  16. # WS_DIC[request.user.username] = request.websocket
  17. # else:
  18. # return HttpResponse(status=400)
  19. #
  20. #
  21. # def knock_knock(username, flag):
  22. # if username in WS_DIC.keys:
  23. # websocket = WS_DIC[username]
  24. # websocket.send(flag)
  25. # return True
  26. # else:
  27. # return False
  28. @login_required(login_url='/account/login/')
  29. def test(request):
  30. return render(request, 'test.html')
  31. @login_required(login_url='/account/login/')
  32. def add_public_key(request):
  33. if request.method == 'POST':
  34. add_public_key_form = AddPublicKeyForm(data=request.POST)
  35. if add_public_key_form.is_valid():
  36. # 新建公钥表
  37. data = add_public_key_form.cleaned_data
  38. new_public_key = PublicKey()
  39. new_public_key.public_key = data['public_key']
  40. new_public_key.user = request.user
  41. # 保存
  42. new_public_key.save()
  43. return HttpResponse(status=200)
  44. else:
  45. return HttpResponse(status=400)
  46. # 用于测试
  47. elif request.method == 'GET':
  48. if DEBUG:
  49. return render(request, 'add_public_key.html')
  50. else:
  51. response = ['illegal method, please use post']
  52. return HttpResponse(json.dumps(response))
  53. @login_required(login_url='/account/login/')
  54. def get_public_key(request):
  55. if request.method == 'POST':
  56. data = request.POST
  57. # 筛选出此用户的公钥
  58. public_keys = PublicKey.objects.filter(user__username=data['username'])
  59. # 将筛选得到的此用户的公钥放入列表中并用json返回
  60. response = []
  61. for public_key in public_keys:
  62. response.append(public_key.public_key)
  63. return HttpResponse(json.dumps(response), status=200)
  64. # 用于测试
  65. elif request.method == 'GET':
  66. if DEBUG:
  67. return render(request, 'get_public_key.html')
  68. else:
  69. return HttpResponse(status=400)