common.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # -*-coding:utf-8 -*-
  2. import json
  3. from django.shortcuts import render
  4. from django.http import HttpResponse
  5. from django.core.serializers.json import DjangoJSONEncoder
  6. def get_user_from_request(request):
  7. user = request.session.get("user", None)
  8. return user
  9. def JsonResponse(data):
  10. response = HttpResponse(json.dumps(data, cls=DjangoJSONEncoder),
  11. content_type="application/json")
  12. response['Access-Control-Allow-Origin'] = '*'
  13. return response
  14. def params(func):
  15. def _wrapper(*args, **kargs):
  16. request = args[0]
  17. if request.method == "GET":
  18. request.PARAMS = request.GET
  19. elif request.method == "POST" or request.method == "DELETE":
  20. if request.META.get('CONTENT_TYPE') == "application/json":
  21. request.PARAMS = json.loads(request.body) if request.body else {}
  22. else:
  23. request.PARAMS = request.POST
  24. elif request.method == "OPTIONS":
  25. return JsonResponse({"code": 0, "msg": "success11"})
  26. else:
  27. request.PARAMS = {}
  28. return func(*args, **kargs)
  29. return _wrapper
  30. def login_required(func):
  31. def _wrapper(*args, **kargs):
  32. request = args[0]
  33. print request.session.keys()
  34. if not ("user" in request.session):
  35. # return HttpResponseRedirect("/accounts/login/")
  36. res = {"code": 2, "msg": u"您尚未登录,请先登录!"}
  37. return JsonResponse(res)
  38. return func(*args, **kargs)
  39. return _wrapper