views.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. from django.shortcuts import render
  2. import json
  3. from collections import defaultdict
  4. from os.path import join as path_join
  5. from django.db.models import Q
  6. from django.contrib import messages
  7. from django.contrib.auth.decorators import login_required
  8. from django.core.urlresolvers import reverse
  9. from django.shortcuts import get_object_or_404, render_to_response, redirect
  10. from django.utils.decorators import method_decorator
  11. from django.utils import formats
  12. from django.views.generic.base import TemplateView
  13. from django.http import HttpResponse, HttpResponseBadRequest
  14. # Create your views here.
  15. from iepy.webui.brat.src import dispatch
  16. JSON_HDR = ('Content-Type', 'application/json')
  17. class Home(TemplateView):
  18. template_name = 'brat/index.html'
  19. def get_context_data(self, **kwargs):
  20. context = super().get_context_data(**kwargs)
  21. # context["relations"] = Relation.objects.all()
  22. #
  23. # segments_to_tag = SegmentToTag.objects.filter(done=False)
  24. # relation_ids_to_tag = list(set(segments_to_tag.values_list("relation", flat=True)))
  25. # relations_to_tag = Relation.objects.filter(id__in=relation_ids_to_tag)
  26. # context["iepy_runs"] = relations_to_tag
  27. return context
  28. def _convert_log_level(log_level):
  29. import config
  30. import logging
  31. if log_level == config.LL_DEBUG:
  32. return logging.DEBUG
  33. elif log_level == config.LL_INFO:
  34. return logging.INFO
  35. elif log_level == config.LL_WARNING:
  36. return logging.WARNING
  37. elif log_level == config.LL_ERROR:
  38. return logging.ERROR
  39. elif log_level == config.LL_CRITICAL:
  40. return logging.CRITICAL
  41. else:
  42. assert False, 'Should not happen'
  43. class DefaultNoneDict(dict):
  44. def __missing__(self, key):
  45. return None
  46. def ajax_dispatch(request):
  47. # print("1111")
  48. # print(request.POST["action"])
  49. cookie_data = ', '.join(
  50. [_f for _f in request.COOKIES if _f])
  51. # print(cookie_data)
  52. # Note: Only logging imports here
  53. from config import WORK_DIR
  54. from logging import basicConfig as log_basic_config
  55. # Enable logging
  56. try:
  57. from config import LOG_LEVEL
  58. log_level = _convert_log_level(LOG_LEVEL)
  59. except ImportError:
  60. from logging import WARNING as LOG_LEVEL_WARNING
  61. log_level = LOG_LEVEL_WARNING
  62. log_basic_config(filename=path_join(WORK_DIR, 'server.log'),
  63. level=log_level)
  64. # Do the necessary imports after enabling the logging, order critical
  65. try:
  66. from common import ProtocolError, ProtocolArgumentError, NoPrintJSONError
  67. from dispatch import dispatch
  68. from jsonwrap import dumps
  69. from message import Messager
  70. # from session import get_session, init_session,init_session_iepy, close_session, NoSessionError, SessionStoreError
  71. except ImportError:
  72. # Note: Heisenbug trap for #612, remove after resolved
  73. from logging import critical as log_critical
  74. from sys import path as sys_path
  75. log_critical('Heisenbug trap reports: ' + str(sys_path))
  76. raise
  77. client_ip = request.META.get("REMOTE_ADDR",'')
  78. client_hostname = request.META.get("REMOTE_HOST",'')
  79. # init_session(client_ip, cookie_data=cookie_data)
  80. # init_session_iepy(request)
  81. response_is_JSON = True
  82. params = request.POST
  83. try:
  84. # Unpack the arguments into something less obscure than the
  85. # Python FieldStorage object (part dictonary, part list, part FUBAR)
  86. http_args = DefaultNoneDict()
  87. http_args["request"] = request
  88. for k in params:
  89. # Also take the opportunity to convert Strings into Unicode,
  90. # according to HTTP they should be UTF-8
  91. try:
  92. http_args[k] = params[k]
  93. except TypeError as e:
  94. # Messager.error(e)
  95. Messager.error(
  96. 'protocol argument error: expected string argument %s, got %s' %
  97. (k, type(
  98. params.params[k])))
  99. raise ProtocolArgumentError
  100. # Dispatch the request
  101. json_dic = dispatch(http_args, client_ip, client_hostname)
  102. except ProtocolError as e:
  103. # Internal error, only reported to client not to log
  104. json_dic = {}
  105. e.json(json_dic)
  106. # Add a human-readable version of the error
  107. err_str = str(e)
  108. if err_str != '':
  109. Messager.error(err_str, duration=-1)
  110. except NoPrintJSONError as e:
  111. # Terrible hack to serve other things than JSON
  112. response_data = (e.hdrs, e.data)
  113. response_is_JSON = False
  114. # Get the potential cookie headers and close the session (if any)
  115. # try:
  116. # # cookie_hdrs = get_session().cookie.hdrs()
  117. # close_session()
  118. # except SessionStoreError:
  119. # Messager.error(
  120. # "Failed to store cookie (missing write permission to brat work directory)?", -1)
  121. # except NoSessionError:
  122. # cookie_hdrs = None
  123. # if response_is_JSON:
  124. # # response_data = ((JSON_HDR, ), dumps(Messager.output_json(json_dic)))
  125. # response_data = dumps(Messager.output_json(json_dic))
  126. return HttpResponse(json.dumps(Messager.output_json(json_dic),ensure_ascii=False),content_type="application/json,charset=utf-8")
  127. home = login_required(Home.as_view())