models.py 3.46 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1
2
3
from __future__ import print_function
from six import string_types

4
5
import json
import os
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
6
7
import logging

8
from collections import defaultdict
9
from pyld import jsonld
10
from flask import Response as FlaskResponse
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
11

12

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
13
class Response(object):
14

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
15
16
17
18
19
    @property
    def context(self):
        if not hasattr(self, '_context'):
            self._context = None
        return self._context
20

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
21
22
23
24
25
26
27
28
29
    @staticmethod
    def get_context(context):
        if isinstance(context, list):
            contexts = []
            for c in context:
                contexts.append(Response.get_context(c))
            return contexts
        elif isinstance(context, dict):
            return context
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30
        elif isinstance(context, string_types):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
31
32
33
34
35
            try:
                with open(context) as f:
                    return json.loads(f.read())
            except IOError:
                return context
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
36
37
        else:
            raise AttributeError('Please, provide a valid context')                
38

39
40
41
42
    def jsonld(self, frame=None, options=None,
               context=None, removeContext=None):
        if removeContext is None:
            removeContext = Response._context  # Loop?
43
44
45
        if frame is None:
            frame = self._frame
        if context is None:
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
            context = self.context
        else:
            context = self.get_context(context)
        # For some reason, this causes errors with pyld
        # if options is None:
            # options = {"expandContext": context.copy() }
        js = self
        if frame:
            logging.debug("Framing: %s", json.dumps(self, indent=4))
            logging.debug("Framing with %s", json.dumps(frame, indent=4))
            js = jsonld.frame(js, frame, options)
            logging.debug("Result: %s", json.dumps(js, indent=4))
            logging.debug("Compacting with %s", json.dumps(context, indent=4))
            js = jsonld.compact(js, context, options)
            logging.debug("Result: %s", json.dumps(js, indent=4))
        if removeContext == context:
            del js["@context"]
        return js

    def to_JSON(self, removeContext=None):
        return json.dumps(self.jsonld(removeContext=removeContext),
67
68
69
                          default=lambda o: o.__dict__,
                          sort_keys=True, indent=4)

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    def flask(self,
              in_headers=False,
              url="http://demos.gsi.dit.upm.es/senpy/senpy.jsonld"):
        """
        Return the values and error to be used in flask
        """
        js = self.jsonld()
        headers = None
        if in_headers:
            ctx = js["@context"]
            headers = {
                "Link": ('<%s>;'
                         'rel="http://www.w3.org/ns/json-ld#context";'
                         ' type="application/ld+json"' % url)
            }
            del js["@context"]
86
        return FlaskResponse(json.dumps(js, indent=4),
87
88
89
                             status=self.get("status", 200),
                             headers=headers,
                             mimetype="application/json")
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
90
91
92
    
class Entry(JSONLD):
    pass
93

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
94

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
95
96
class Sentiment(JSONLD):
    pass
97

98

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
99
100
class EmotionSet(JSONLD):
    pass
101

102

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
103
104
105
class Emotion(JSONLD):
    pass

106

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
107
108
class Suggestion(JSONLD):
    pass
109

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
110
class Error(BaseException, JSONLD):
111
    # A better pattern would be this:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
112
    # htp://flask.pocoo.org/docs/0.10/patterns/apierrors/
113
114
115
    _frame = {}
    _context = {}

116
    def __init__(self, *args, **kwargs):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
117
118
        self.message = kwargs.get('message', None)
        super(Error, self).__init__(*args)