views.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import json
  7. DEBUG = True
  8. @login_required(login_url='/account/login/')
  9. def add_public_key(request):
  10. if request.method == 'POST':
  11. add_public_key_form = AddPublicKeyForm(data=request.POST)
  12. if add_public_key_form.is_valid():
  13. # 新建公钥表
  14. data = add_public_key_form.cleaned_data
  15. new_public_key = PublicKey()
  16. new_public_key.public_key = data['public_key']
  17. new_public_key.user = request.user
  18. # 保存
  19. new_public_key.save()
  20. return HttpResponse(status=200)
  21. else:
  22. return HttpResponse(status=400)
  23. # 用于测试
  24. elif request.method == 'GET':
  25. if DEBUG:
  26. return render(request, 'add_public_key.html')
  27. else:
  28. response = ['illegal method, please use post']
  29. return HttpResponse(json.dumps(response))
  30. @login_required(login_url='/account/login/')
  31. def get_public_key(request):
  32. if request.method == 'POST':
  33. data = request.POST
  34. # 筛选出此用户的公钥
  35. public_keys = PublicKey.objects.filter(user__username=data['username'])
  36. # 将筛选得到的此用户的公钥放入列表中并用json返回
  37. response = []
  38. for public_key in public_keys:
  39. response.append(public_key.public_key)
  40. return HttpResponse(json.dumps(response),status=200)
  41. # 用于测试
  42. elif request.method == 'GET':
  43. if DEBUG:
  44. return render(request, 'get_public_key.html')
  45. else:
  46. return HttpResponse(status=400)