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, @property
*args, def context(self):
**kwargs): if not hasattr(self, '_context'):
self._context = None
id = kwargs.pop("id", None) return self._context
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
@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( return json.loads(
except IOError: except IOError:
return context return context
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):
...@@ -163,92 +87,32 @@ class Leaf(dict): ...@@ -163,92 +87,32 @@ class Leaf(dict):
status=self.get("status", 200), status=self.get("status", 200),
headers=headers, headers=headers,
mimetype="application/json") mimetype="application/json")
class Entry(JSONLD):
class Response(Leaf): class Sentiment(JSONLD):
_context = Leaf.get_context("{}/context.jsonld".format( pass
_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,
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): class EmotionSet(JSONLD):
if not emotions: pass
emotions = []
super(EmotionSet, self).__init__(context=EmotionSet._context,
self.emotions = emotions or []
class Emotion(Leaf): class Emotion(JSONLD):
_context = {} pass
class Suggestion(JSONLD):
class Error(Leaf): class Error(BaseException, JSONLD):
# A better pattern would be this: # A better pattern would be this:
# # htp://
_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,8 +72,8 @@ class SenpyPlugin(Leaf): ...@@ -72,8 +72,8 @@ 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__() = info["name"] = info["name"]
...@@ -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 =, writeback=True) self._sh =, 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( received = json.loads(
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