__init__.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # -*- coding:utf-8 -*-
  2. # @Time : 2020/5/18 9:56 上午
  3. # @Author : Creat by Han
  4. from itertools import groupby
  5. from django.shortcuts import render
  6. import os
  7. import sys
  8. import json
  9. from collections import OrderedDict
  10. from importlib import import_module
  11. JsonResponse = lambda x: HttpResponse(json.dumps(x), content_type="application/javascript")
  12. from django.http import HttpResponse
  13. from django.views.decorators.csrf import csrf_exempt
  14. current_path = os.path.dirname(__file__)
  15. _modules = os.listdir(os.path.dirname(__file__))
  16. child_modules = [i for i in _modules if not i.endswith(".py") and (not i.endswith(".pyc")) and (not i.startswith("__"))]
  17. for m in os.walk(current_path):
  18. if m[0] == current_path:
  19. continue
  20. module_name = m[0].split('/')[-1]
  21. if '\\' in m[0]:
  22. module_name = m[0].split('\\')[-1]
  23. if '__init__.py' not in m[2]:
  24. continue
  25. for i in [i.replace(".py", "") for i in m[2] if i.endswith(".py") and (not i.startswith("__"))]:
  26. import_module('smartfarming.api.views.%s.%s' % (module_name,i))
  27. __all__ = [i.replace(".py", "") for i in _modules if i.endswith(".py") and (not i.startswith("__"))]
  28. __all__ += ["api_gateway", "api_document"]
  29. @csrf_exempt
  30. def api_gateway(request):
  31. method = request.GET.get("method")
  32. a = {'method': method}
  33. _ = sys.api_config.get(method)
  34. if _:
  35. function = _
  36. if function:
  37. return function(request)
  38. result = JsonResponse({"errorCode": 404, "data": None, "message": "can not find the method!", "formError": {}})
  39. if "HTTP_ORIGIN" in request.META:
  40. result["Access-Control-Allow-Origin"] = request.META.get("HTTP_ORIGIN")
  41. return JsonResponse(a)
  42. def api_document(request):
  43. if hasattr(sys, "api_config"):
  44. info = list(sys.api_config.items())
  45. else:
  46. info = []
  47. info.sort(key=lambda x: '.'.join(x[0].split(".")[:-1]))
  48. result = OrderedDict()
  49. for module_name, _iter in groupby(info, key=lambda x: ".".join(x[0].split(".")[:-1])):
  50. result[module_name] = []
  51. for j in _iter:
  52. result[module_name].append((j[0], j[1].__doc__ or '', j[1].login_required,
  53. j[1].inteam_required,
  54. j[1].inproject_required,
  55. j[1].api_factory))
  56. result = result.items()
  57. return render(request,"api_document.html",locals())