123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 |
- from django.shortcuts import render
- import json
- from collections import defaultdict
- from os.path import join as path_join
- from django.db.models import Q
- from django.contrib import messages
- from django.contrib.auth.decorators import login_required
- from django.core.urlresolvers import reverse
- from django.shortcuts import get_object_or_404, render_to_response, redirect
- from django.utils.decorators import method_decorator
- from django.utils import formats
- from django.views.generic.base import TemplateView
- from django.http import HttpResponse, HttpResponseBadRequest
- # Create your views here.
- from iepy.webui.brat.src import dispatch
- JSON_HDR = ('Content-Type', 'application/json')
- class Home(TemplateView):
- template_name = 'brat/index.html'
- def get_context_data(self, **kwargs):
- context = super().get_context_data(**kwargs)
- # context["relations"] = Relation.objects.all()
- #
- # segments_to_tag = SegmentToTag.objects.filter(done=False)
- # relation_ids_to_tag = list(set(segments_to_tag.values_list("relation", flat=True)))
- # relations_to_tag = Relation.objects.filter(id__in=relation_ids_to_tag)
- # context["iepy_runs"] = relations_to_tag
- return context
- def _convert_log_level(log_level):
- import config
- import logging
- if log_level == config.LL_DEBUG:
- return logging.DEBUG
- elif log_level == config.LL_INFO:
- return logging.INFO
- elif log_level == config.LL_WARNING:
- return logging.WARNING
- elif log_level == config.LL_ERROR:
- return logging.ERROR
- elif log_level == config.LL_CRITICAL:
- return logging.CRITICAL
- else:
- assert False, 'Should not happen'
- class DefaultNoneDict(dict):
- def __missing__(self, key):
- return None
- def ajax_dispatch(request):
- # print("1111")
- # print(request.POST["action"])
- cookie_data = ', '.join(
- [_f for _f in request.COOKIES if _f])
- # print(cookie_data)
- # Note: Only logging imports here
- from config import WORK_DIR
- from logging import basicConfig as log_basic_config
- # Enable logging
- try:
- from config import LOG_LEVEL
- log_level = _convert_log_level(LOG_LEVEL)
- except ImportError:
- from logging import WARNING as LOG_LEVEL_WARNING
- log_level = LOG_LEVEL_WARNING
- log_basic_config(filename=path_join(WORK_DIR, 'server.log'),
- level=log_level)
- # Do the necessary imports after enabling the logging, order critical
- try:
- from common import ProtocolError, ProtocolArgumentError, NoPrintJSONError
- from dispatch import dispatch
- from jsonwrap import dumps
- from message import Messager
- # from session import get_session, init_session,init_session_iepy, close_session, NoSessionError, SessionStoreError
- except ImportError:
- # Note: Heisenbug trap for #612, remove after resolved
- from logging import critical as log_critical
- from sys import path as sys_path
- log_critical('Heisenbug trap reports: ' + str(sys_path))
- raise
- client_ip = request.META.get("REMOTE_ADDR",'')
- client_hostname = request.META.get("REMOTE_HOST",'')
- # init_session(client_ip, cookie_data=cookie_data)
- # init_session_iepy(request)
- response_is_JSON = True
- params = request.POST
- try:
- # Unpack the arguments into something less obscure than the
- # Python FieldStorage object (part dictonary, part list, part FUBAR)
- http_args = DefaultNoneDict()
- http_args["request"] = request
- for k in params:
- # Also take the opportunity to convert Strings into Unicode,
- # according to HTTP they should be UTF-8
- try:
- http_args[k] = params[k]
- except TypeError as e:
- # Messager.error(e)
- Messager.error(
- 'protocol argument error: expected string argument %s, got %s' %
- (k, type(
- params.params[k])))
- raise ProtocolArgumentError
- # Dispatch the request
- json_dic = dispatch(http_args, client_ip, client_hostname)
- except ProtocolError as e:
- # Internal error, only reported to client not to log
- json_dic = {}
- e.json(json_dic)
- # Add a human-readable version of the error
- err_str = str(e)
- if err_str != '':
- Messager.error(err_str, duration=-1)
- except NoPrintJSONError as e:
- # Terrible hack to serve other things than JSON
- response_data = (e.hdrs, e.data)
- response_is_JSON = False
- # Get the potential cookie headers and close the session (if any)
- # try:
- # # cookie_hdrs = get_session().cookie.hdrs()
- # close_session()
- # except SessionStoreError:
- # Messager.error(
- # "Failed to store cookie (missing write permission to brat work directory)?", -1)
- # except NoSessionError:
- # cookie_hdrs = None
- # if response_is_JSON:
- # # response_data = ((JSON_HDR, ), dumps(Messager.output_json(json_dic)))
- # response_data = dumps(Messager.output_json(json_dic))
- return HttpResponse(json.dumps(Messager.output_json(json_dic),ensure_ascii=False),content_type="application/json,charset=utf-8")
- home = login_required(Home.as_view())
|