Commit a79df7a3 authored by J. Fernando Sánchez's avatar J. Fernando Sánchez
Browse files

Closer to py3

parent ecc2a831
...@@ -55,7 +55,7 @@ def get_params(req, params=BASIC_PARAMS): ...@@ -55,7 +55,7 @@ def get_params(req, params=BASIC_PARAMS):
elif req.method == 'GET': elif req.method == 'GET':
indict = req.args indict = req.args
else: else:
raise ValueError("Invalid data") raise Error(message="Invalid data")
outdict = {} outdict = {}
wrong_params = {} wrong_params = {}
...@@ -82,7 +82,7 @@ def get_params(req, params=BASIC_PARAMS): ...@@ -82,7 +82,7 @@ def get_params(req, params=BASIC_PARAMS):
"errors": {param: error for param, error in "errors": {param: error for param, error in
iteritems(wrong_params)} iteritems(wrong_params)}
}) })
raise ValueError(message) raise Error(message=message)
return outdict return outdict
...@@ -124,7 +124,7 @@ def api(): ...@@ -124,7 +124,7 @@ def api():
response = current_app.senpy.analyse(**params) response = current_app.senpy.analyse(**params)
in_headers = params["inHeaders"] != "0" in_headers = params["inHeaders"] != "0"
return response.flask(in_headers=in_headers) return response.flask(in_headers=in_headers)
except ValueError as ex: except Error as ex:
return ex.message.flask() return ex.message.flask()
......
from __future__ import print_function
from six import string_types
import json import json
import os import os
import logging import logging
from builtins import str
from collections import defaultdict from collections import defaultdict
from pyld import jsonld from pyld import jsonld
from flask import Response as FlaskResponse from flask import Response as FlaskResponse
class Leaf(dict): class Response(object):
_prefix = None
_frame = {}
_context = {}
def __init__(self,
*args,
**kwargs):
id = kwargs.pop("id", None)
context = kwargs.pop("context", self._context)
vocab = kwargs.pop("vocab", None)
prefix = kwargs.pop("prefix", None)
frame = kwargs.pop("frame", None)
super(Leaf, self).__init__(*args, **kwargs)
if context is not None:
self.context = context
if frame is not None:
self._frame = frame
self._prefix = prefix
self.id = id
def __getattr__(self, key):
try:
return object.__getattr__(self, key)
except AttributeError:
try:
return super(Leaf, self).__getitem__(self._get_key(key))
except KeyError:
raise AttributeError()
def __setattr__(self, key, value): @property
try: def context(self):
object.__getattr__(self, key) if not hasattr(self, '_context'):
object.__setattr__(self, key, value) self._context = None
except AttributeError: return self._context
key = self._get_key(key)
if key == "@context":
value = self.get_context(value)
elif key == "@id":
value = self.get_id(value)
if key[0] == "_":
object.__setattr__(self, key, value)
else:
if value is None:
try:
super(Leaf, self).__delitem__(key)
except KeyError:
pass
else:
super(Leaf, self).__setitem__(key, value)
def get_id(self, id):
"""
Get id, dealing with prefixes
"""
# This is not the most elegant solution to change the @id attribute,
# but it is the quickest way to have it included in the dictionary
# without extra boilerplate.
if id and self._prefix and ":" not in id:
return "{}{}".format(self._prefix, id)
else:
return id
def __delattr__(self, key):
if key in self.__dict__:
del self.__dict__[key]
else:
super(Leaf, self).__delitem__(self._get_key(key))
def _get_key(self, key):
if key[0] == "_":
return key
elif key in ["context", "id"]:
return "@{}".format(key)
else:
return key
@staticmethod @staticmethod
def get_context(context): def get_context(context):
...@@ -95,22 +27,14 @@ class Leaf(dict): ...@@ -95,22 +27,14 @@ class Leaf(dict):
return contexts return contexts
elif isinstance(context, dict): elif isinstance(context, dict):
return context return context
elif isinstance(context, str): elif isinstance(context, string_types):
try: try:
with open(context) as f: with open(context) as f:
return json.loads(f.read()) return json.loads(f.read())
except IOError: except IOError:
return context return context
else:
def compact(self): raise AttributeError('Please, provide a valid context')
return jsonld.compact(self, self.get_context(self.context))
def frame(self, frame=None, options=None):
if frame is None:
frame = self._frame
if options is None:
options = {}
return jsonld.frame(self, frame, options)
def jsonld(self, frame=None, options=None, def jsonld(self, frame=None, options=None,
context=None, removeContext=None): context=None, removeContext=None):
...@@ -164,91 +88,31 @@ class Leaf(dict): ...@@ -164,91 +88,31 @@ class Leaf(dict):
headers=headers, headers=headers,
mimetype="application/json") mimetype="application/json")
class Entry(JSONLD):
class Response(Leaf): pass
_context = Leaf.get_context("{}/context.jsonld".format(
os.path.dirname(os.path.realpath(__file__))))
_frame = {
"@context": _context,
"analysis": {
"@explicit": True,
"maxPolarityValue": {},
"minPolarityValue": {},
"name": {},
"version": {},
},
"entries": {}
}
def __init__(self, *args, **kwargs):
context = kwargs.pop("context", None)
frame = kwargs.pop("frame", None)
if context is None:
context = self._context
self.context = context
super(Response, self).__init__(
*args, context=context, frame=frame, **kwargs)
if self._frame is not None and "entries" in self._frame:
self.analysis = []
self.entries = []
def jsonld(self, frame=None, options=None, context=None, removeContext={}):
return super(Response, self).jsonld(frame,
options,
context,
removeContext)
class Entry(Leaf):
_context = {
"@vocab": ("http://persistence.uni-leipzig.org/"
"nlp2rdf/ontologies/nif-core#")
}
def __init__(self, text=None, emotion_sets=None, opinions=None, **kwargs):
super(Entry, self).__init__(**kwargs)
if text:
self.text = text
self.emotionSets = emotion_sets if emotion_sets else []
self.opinions = opinions if opinions else []
class Opinion(Leaf): class Sentiment(JSONLD):
_context = { pass
"@vocab": "http://www.gsi.dit.upm.es/ontologies/marl/ns#"
}
def __init__(self, polarityValue=None, hasPolarity=None, *args, **kwargs):
super(Opinion, self).__init__(*args,
**kwargs)
if polarityValue is not None:
self.hasPolarityValue = polarityValue
if hasPolarity is not None:
self.hasPolarity = hasPolarity
class EmotionSet(Leaf): class EmotionSet(JSONLD):
_context = {} pass
def __init__(self, emotions=None, *args, **kwargs):
if not emotions:
emotions = []
super(EmotionSet, self).__init__(context=EmotionSet._context,
*args,
**kwargs)
self.emotions = emotions or []
class Emotion(JSONLD):
pass
class Emotion(Leaf):
_context = {}
class Suggestion(JSONLD):
pass
class Error(Leaf): class Error(BaseException, JSONLD):
# A better pattern would be this: # A better pattern would be this:
# http://flask.pocoo.org/docs/0.10/patterns/apierrors/ # htp://flask.pocoo.org/docs/0.10/patterns/apierrors/
_frame = {} _frame = {}
_context = {} _context = {}
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(Error, self).__init__(*args, **kwargs) self.message = kwargs.get('message', None)
super(Error, self).__init__(*args)
...@@ -72,7 +72,7 @@ class SenpyPlugin(Leaf): ...@@ -72,7 +72,7 @@ class SenpyPlugin(Leaf):
def __init__(self, info=None): def __init__(self, info=None):
if not info: if not info:
raise ValueError(("You need to provide configuration" raise Error(message=("You need to provide configuration"
"information for the plugin.")) "information for the plugin."))
logger.debug("Initialising {}".format(info)) logger.debug("Initialising {}".format(info))
super(SenpyPlugin, self).__init__() super(SenpyPlugin, self).__init__()
...@@ -137,7 +137,7 @@ class ShelfMixin(object): ...@@ -137,7 +137,7 @@ class ShelfMixin(object):
@property @property
def sh(self): def sh(self):
if not hasattr(self, '_sh') or not self._sh: if not hasattr(self, '_sh') or self._sh is None:
self._sh = shelve.open(self.shelf_file, writeback=True) self._sh = shelve.open(self.shelf_file, writeback=True)
return self._sh return self._sh
......
from __future__ import print_function
import os import os
import logging import logging
...@@ -31,7 +32,7 @@ class ExtensionsTest(TestCase): ...@@ -31,7 +32,7 @@ class ExtensionsTest(TestCase):
""" Discovery of plugins in given folders. """ """ Discovery of plugins in given folders. """
# noinspection PyProtectedMember # noinspection PyProtectedMember
assert self.dir in self.senpy._search_folders assert self.dir in self.senpy._search_folders
print self.senpy.plugins print(self.senpy.plugins)
assert "Dummy" in self.senpy.plugins assert "Dummy" in self.senpy.plugins
def test_enabling(self): def test_enabling(self):
......
...@@ -59,7 +59,7 @@ class ModelsTest(TestCase): ...@@ -59,7 +59,7 @@ class ModelsTest(TestCase):
assert("entries" in js) assert("entries" in js)
assert("analysis" in js) assert("analysis" in js)
resp = r6.flask() resp = r6.flask()
received = json.loads(resp.data) received = json.loads(resp.data.decode())
logging.debug("Response: %s", js) logging.debug("Response: %s", js)
assert(received["entries"]) assert(received["entries"])
assert(received["entries"][0]["text"] == "Just testing") assert(received["entries"][0]["text"] == "Just testing")
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment