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):
elif req.method == 'GET':
indict = req.args
raise ValueError("Invalid data")
raise Error(message="Invalid data")
outdict = {}
wrong_params = {}
......@@ -82,7 +82,7 @@ def get_params(req, params=BASIC_PARAMS):
"errors": {param: error for param, error in
raise ValueError(message)
raise Error(message=message)
return outdict
......@@ -124,7 +124,7 @@ def api():
response = current_app.senpy.analyse(**params)
in_headers = params["inHeaders"] != "0"
return response.flask(in_headers=in_headers)
except ValueError as ex:
except Error as ex:
return ex.message.flask()
from __future__ import print_function
from six import string_types
import json
import os
import logging
from builtins import str
from collections import defaultdict
from pyld import jsonld
from flask import Response as FlaskResponse
class Leaf(dict):
_prefix = None
_frame = {}
_context = {}
class Response(object):
def __init__(self,
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 = id
def __getattr__(self, key):
return object.__getattr__(self, key)
except AttributeError:
return super(Leaf, self).__getitem__(self._get_key(key))
except KeyError:
raise AttributeError()
def __setattr__(self, key, value):
object.__getattr__(self, key)
object.__setattr__(self, key, value)
except AttributeError:
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)
if value is None:
super(Leaf, self).__delitem__(key)
except KeyError:
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)
return id
def __delattr__(self, key):
if key in self.__dict__:
del self.__dict__[key]
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)
return key
def context(self):
if not hasattr(self, '_context'):
self._context = None
return self._context
def get_context(context):
......@@ -95,22 +27,14 @@ class Leaf(dict):
return contexts
elif isinstance(context, dict):
return context
elif isinstance(context, str):
elif isinstance(context, string_types):
with open(context) as f:
return json.loads(
except IOError:
return context
def compact(self):
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)
raise AttributeError('Please, provide a valid context')
def jsonld(self, frame=None, options=None,
context=None, removeContext=None):
......@@ -163,92 +87,32 @@ class Leaf(dict):
status=self.get("status", 200),
class Entry(JSONLD):
class Response(Leaf):
_context = Leaf.get_context("{}/context.jsonld".format(
_frame = {
"@context": _context,
"analysis": {
"@explicit": True,
"maxPolarityValue": {},
"minPolarityValue": {},
"name": {},
"version": {},
"entries": {}
class Sentiment(JSONLD):
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,
class Entry(Leaf):
_context = {
"@vocab": (""
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):
_context = {
"@vocab": ""
def __init__(self, polarityValue=None, hasPolarity=None, *args, **kwargs):
super(Opinion, self).__init__(*args,
if polarityValue is not None:
self.hasPolarityValue = polarityValue
if hasPolarity is not None:
self.hasPolarity = hasPolarity
class EmotionSet(Leaf):
_context = {}
def __init__(self, emotions=None, *args, **kwargs):
if not emotions:
emotions = []
super(EmotionSet, self).__init__(context=EmotionSet._context,
self.emotions = emotions or []
class EmotionSet(JSONLD):
class Emotion(Leaf):
_context = {}
class Emotion(JSONLD):
class Suggestion(JSONLD):
class Error(Leaf):
class Error(BaseException, JSONLD):
# A better pattern would be this:
# htp://
_frame = {}
_context = {}
def __init__(self, *args, **kwargs):
super(Error, self).__init__(*args, **kwargs)
self.message = kwargs.get('message', None)
super(Error, self).__init__(*args)
......@@ -72,8 +72,8 @@ class SenpyPlugin(Leaf):
def __init__(self, info=None):
if not info:
raise ValueError(("You need to provide configuration"
"information for the plugin."))
raise Error(message=("You need to provide configuration"
"information for the plugin."))
logger.debug("Initialising {}".format(info))
super(SenpyPlugin, self).__init__() = info["name"]
......@@ -137,7 +137,7 @@ class ShelfMixin(object):
def sh(self):
if not hasattr(self, '_sh') or not self._sh:
if not hasattr(self, '_sh') or self._sh is None:
self._sh =, writeback=True)
return self._sh
from __future__ import print_function
import os
import logging
......@@ -31,7 +32,7 @@ class ExtensionsTest(TestCase):
""" Discovery of plugins in given folders. """
# noinspection PyProtectedMember
assert self.dir in self.senpy._search_folders
print self.senpy.plugins
assert "Dummy" in self.senpy.plugins
def test_enabling(self):
......@@ -59,7 +59,7 @@ class ModelsTest(TestCase):
assert("entries" in js)
assert("analysis" in js)
resp = r6.flask()
received = json.loads(
received = json.loads(
logging.debug("Response: %s", js)
assert(received["entries"][0]["text"] == "Just testing")
Supports Markdown
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