Exemplo n.º 1
0
 def submit(self, redirect_limit=0, product=None, **response_kwargs):
     """ Submit this request and return a
     :py:class:`Response <httpstream.Response>` object.
     """
     uri = URI(self.uri)
     headers = dict(self.headers)
     headers.setdefault("User-Agent", user_agent(product))
     while True:
         http, rs = submit(self.method, uri, self.body, headers)
         status_class = rs.status // 100
         if status_class == 3:
             redirection = Redirection(http, uri, self, rs,
                                       **response_kwargs)
             if redirect_limit:
                 redirect_limit -= 1
                 location = URI.resolve(uri, rs.getheader("Location"))
                 if location == uri:
                     raise RedirectionError("Circular redirection")
                 if rs.status in (MOVED_PERMANENTLY, PERMANENT_REDIRECT):
                     redirects[uri] = location
                 uri = location
                 redirection.close()
             else:
                 return redirection
         elif status_class == 4:
             raise ClientError(http, uri, self, rs, **response_kwargs)
         elif status_class == 5:
             raise ServerError(http, uri, self, rs, **response_kwargs)
         else:
             return Response(http, uri, self, rs, **response_kwargs)
Exemplo n.º 2
0
 def submit(self, redirect_limit=0, product=None, **response_kwargs):
     """ Submit this request and return a
     :py:class:`Response <httpstream.Response>` object.
     """
     uri = URI(self.uri)
     headers = dict(self.headers)
     headers.setdefault("User-Agent", user_agent(product))
     while True:
         http, rs = submit(self.method, uri, self.body, headers)
         status_class = rs.status // 100
         if status_class == 3:
             redirection = Redirection(http, uri, self, rs,
                                       **response_kwargs)
             if redirect_limit:
                 redirect_limit -= 1
                 location = URI.resolve(uri, rs.getheader("Location"))
                 if location == uri:
                     raise RedirectionError("Circular redirection")
                 if rs.status in (MOVED_PERMANENTLY, PERMANENT_REDIRECT):
                     redirects[uri] = location
                 uri = location
                 redirection.close()
             else:
                 return redirection
         elif status_class == 4:
             raise ClientError(http, uri, self, rs, **response_kwargs)
         elif status_class == 5:
             raise ServerError(http, uri, self, rs, **response_kwargs)
         else:
             return Response(http, uri, self, rs, **response_kwargs)
Exemplo n.º 3
0
def get_graph_db():
	if not hasattr(app, 'gdb_client'):
		app.logger.info('get_graph_db(): try to ESTABLISH neo4j connection')
		try:
			gdb_url = app.config['GRAPHENEDB_URL']			
			service_root = neo4j.ServiceRoot(URI(gdb_url).resolve('/'))
			app.gdb_client = service_root.graph_db
			app.logger.info('neo4j: ' + str(service_root.graph_db))
			return app.gdb_client
		except:
			app.logger.error('neo4j: problems acquring graph db')
	else:
		app.logger.info('get_graph_db(): neo4j connection EXISTS')
Exemplo n.º 4
0
 def __init__(self, uri=None):
     self._uri = URI(uri or DEFAULT_URI)
     if self._uri.user_info:
         service_root_uri = "{0}://{1}@{2}:{3}/".format(self._uri.scheme, self._uri.user_info, self._uri.host, self._uri.port)
     else:
         service_root_uri = "{0}://{1}:{2}/".format(self._uri.scheme, self._uri.host, self._uri.port)
     self._service_root = ServiceRoot(service_root_uri)
     self._graph = self._service_root.graph
     try:
         self._transaction_uri = self._graph.resource.metadata["transaction"]
     except KeyError:
         raise NotImplementedError("Cypher transactions are not supported "
                                   "by this server version")
Exemplo n.º 5
0
 def __init__(self, http, uri, request, response, **kwargs):
     self._http = http
     self._uri = URI(uri)
     self._request = request
     self._response = response
     self._reason = kwargs.get("reason")
     self.__headers = KeyValueList(self._response.getheaders())
     #: Default chunk size for this response
     self.chunk_size = kwargs.get("chunk_size", default_chunk_size)
     log.info("<<< {0}".format(self))
     if __debug__:
         for key, value in self._response.getheaders():
             log.debug("<<< {0}: {1}".format(key, value))
Exemplo n.º 6
0
 def __init__(self,
              batch_id,
              uri,
              status_code=None,
              body=None,
              location=None):
     self.batch_id = batch_id
     self.uri = URI(uri)
     self.status_code = status_code or 200
     self.body = body
     self.location = location
     if __debug__:
         batch_log.debug("<<< {{{0}}} {1} {2}".format(
             self.batch_id, self.status_code, self.body, self.location))
Exemplo n.º 7
0
    def add(self, key, value, entity):
        """ Add an entity to this index under the `key`:`value` pair supplied::

            # create a node and obtain a reference to the "People" node index
            alice, = graph.create({"name": "Alice Smith"})
            people = graph.get_or_create_index(neo4j.Node, "People")

            # add the node to the index
            people.add("family_name", "Smith", alice)

        Note that while Neo4j indexes allow multiple entities to be added under
        a particular key:value, the same entity may only be represented once;
        this method is therefore idempotent.
        """
        self.resource.post({
            "key": key,
            "value": value,
            "uri": str(URI(entity))
        })
        return entity
Exemplo n.º 8
0
 def __init__(self, http, uri, request, response, **kwargs):
     self.__http = http
     if isinstance(uri, URI):
         self.__uri = uri
     else:
         self.__uri = URI(uri)
     self.__request = request
     self.__response = response
     self.__consumed = False
     if kwargs.get("cache"):
         self.__cached = bytearray()
     else:
         self.__cached = None
     self.__reason = kwargs.get("reason")
     self.__headers = KeyValueList(self.__response.getheaders())
     #: Default chunk size for this response
     self.chunk_size = kwargs.get("chunk_size", default_chunk_size)
     log.info("<<< {0}".format(self))
     if __debug__:
         for key, value in self.__response.getheaders():
             log.debug("<<< {0}: {1}".format(key, value))
Exemplo n.º 9
0
    def add_if_none(self, key, value, entity):
        """ Add an entity to this index under the `key`:`value` pair
        supplied if no entry already exists at that point::

            # obtain a reference to the "Rooms" node index and
            # add node `alice` to room 100 if empty
            rooms = graph.get_or_create_index(neo4j.Node, "Rooms")
            rooms.add_if_none("room", 100, alice)

        If added, this method returns the entity, otherwise :py:const:`None`
        is returned.
        """
        rs = self._get_or_create.post({
            "key": key,
            "value": value,
            "uri": str(URI(entity))
        })
        if rs.status_code == CREATED:
            return entity
        else:
            return None
Exemplo n.º 10
0
    def remove(self, key=None, value=None, entity=None):
        """ Remove any entries from the index which match the parameters
        supplied. The allowed parameter combinations are:

        `key`, `value`, `entity`
            remove a specific entity indexed under a given key-value pair

        `key`, `value`
            remove all entities indexed under a given key-value pair

        `key`, `entity`
            remove a specific entity indexed against a given key but with
            any value

        `entity`
            remove all occurrences of a specific entity regardless of
            key and value

        """
        if key and value and entity:
            t = ResourceTemplate(self.resource.uri.string +
                                 "/{key}/{value}/{entity}")
            t.expand(key=key, value=value, entity=entity._id).delete()
        elif key and value:
            uris = [
                URI(entity.resource.metadata["indexed"])
                for entity in self.get(key, value)
            ]
            batch = LegacyWriteBatch(self.graph)
            for uri in uris:
                batch.append_delete(uri)
            batch.run()
        elif key and entity:
            t = ResourceTemplate(self.resource.uri.string + "/{key}/{entity}")
            t.expand(key=key, entity=entity._id).delete()
        elif entity:
            t = ResourceTemplate(self.resource.uri.string + "/{entity}")
            t.expand(entity=entity._id).delete()
        else:
            raise TypeError("Illegal parameter combination for index removal")
Exemplo n.º 11
0
 def __init__(self, uri):
     self._uri = URI(uri)
Exemplo n.º 12
0
class Resource(object):
    """ A web resource identified by a URI.
    """
    def __init__(self, uri):
        self._uri = URI(uri)

    def __str__(self):
        return "<{0}>".format(str(self._uri))

    def __repr__(self):
        return "{0}({1})".format(self.__class__.__name__,
                                 repr(self._uri.string))

    def __eq__(self, other):
        """ Determine equality of two objects based on URI.
        """
        return self._uri == other._uri

    def __ne__(self, other):
        """ Determine inequality of two objects based on URI.
        """
        return self._uri != other._uri

    def __bool__(self):
        return bool(self._uri)

    def __nonzero__(self):
        return bool(self._uri)

    @property
    def __uri__(self):
        return self._uri

    @property
    def uri(self):
        """ The URI of this resource.
        """
        return self._uri

    def resolve(self, reference, strict=True):
        """ Resolve a URI reference against the URI for this resource,
        returning a new resource represented by the new target URI.
        """
        return Resource(self._uri.resolve(reference, strict))

    def get(self, headers=None, redirect_limit=5, **kwargs):
        """ Issue a ``GET`` request to this resource.

        :param headers: headers to be included in the request (optional)
        :type headers: dict
        :param redirect_limit: maximum number of redirects to be handled
            automatically (optional, default=5)
        :param product: name or (name, version) tuple for the client product to
            be listed in the ``User-Agent`` header (optional)
        :param chunk_size: number of bytes to retrieve per chunk (optional,
            default=4096)
        :return: file-like :py:class:`Response <httpstream.http.Response>`
            object from which content can be read
        """
        rq = Request("GET", self._uri, None, headers)
        return rq.submit(redirect_limit=redirect_limit, **kwargs)

    def put(self, body=None, headers=None, **kwargs):
        """ Issue a ``PUT`` request to this resource.
        """
        rq = Request("PUT", self._uri, body, headers)
        return rq.submit(**kwargs)

    def post(self, body=None, headers=None, **kwargs):
        """ Issue a ``POST`` request to this resource.
        """
        rq = Request("POST", self._uri, body, headers)
        return rq.submit(**kwargs)

    def delete(self, headers=None, **kwargs):
        """ Issue a ``DELETE`` request to this resource.
        """
        rq = Request("DELETE", self._uri, None, headers)
        return rq.submit(**kwargs)

    def head(self, headers=None, redirect_limit=5, **kwargs):
        """ Issue a ``HEAD`` request to this resource.
        """
        rq = Request("HEAD", self._uri, None, headers)
        return rq.submit(redirect_limit=redirect_limit, **kwargs)
Exemplo n.º 13
0
 def uri(self, value):
     self._uri = URI(value)
Exemplo n.º 14
0
def submit(method, uri, body, headers):
    """ Submit one HTTP request.
    """
    uri = URI(uri)
    headers["Host"] = uri.host_port
    if uri.user_info:
        credentials = uri.user_info.encode("UTF-8")
        value = "Basic " + b64encode(credentials).decode("ASCII")
        headers["Authorization"] = value
    try:
        http = ConnectionPool.acquire(uri.scheme, uri.host_port)
    except KeyError:
        raise ValueError("Unsupported URI scheme " + repr(uri.scheme))

    def send(reconnect=None):
        if reconnect:
            log.debug("<~> Reconnecting ({0})".format(reconnect))
            http.close()
            http.connect()
        if method in ("GET", "DELETE") and not body:
            log.info(">>> {0} {1}".format(method, uri))
        elif body:
            log.info(">>> {0} {1} [{2}]".format(method, uri, len(body)))
        else:
            log.info(">>> {0} {1} [0]".format(method, uri))
        if __debug__:
            for key, value in headers.items():
                log.debug(">>> {0}: {1}".format(key, value))
        http.request(method, uri.absolute_path_reference, body, headers)
        if supports_buffering:
            return http.getresponse(buffering=True)
        else:
            return http.getresponse()

    try:
        try:
            response = send()
        except BadStatusLine as err:
            if err.line == "''":
                response = send("peer closed connection")
            else:
                raise
        except ResponseNotReady:
            response = send("response not ready")
        except timeout:
            response = send("timeout")
        except error as err:
            if isinstance(err.args[0], tuple):
                code = err.args[0][0]
            else:
                code = err.args[0]
            if code in retry_codes:
                response = send(retry_codes[code])
            else:
                raise
    except (gaierror, herror) as err:
        raise NetworkAddressError(err.args[1], host_port=uri.host_port)
    except error as err:
        if isinstance(err.args[0], tuple):
            code, description = err.args[0]
        elif isinstance(err.args[0], int):
            code = err.args[0]
            try:
                description = strerror(code)
            except ValueError:
                description = None
        else:
            code, description = None, err.args[0]
        if code == 2:
            # Workaround for Linux bug with incorrect error message on
            # host resolution
            # ----
            # https://bugs.launchpad.net/ubuntu/+source/eglibc/+bug/1154599
            raise NetworkAddressError("Name or service not known",
                                      host_port=uri.host_port)
        else:
            raise SocketError(code, description, host_port=uri.host_port)
    else:
        return http, response
Exemplo n.º 15
0
 def __init__(self, uri):
     if isinstance(uri, URI):
         self._uri = uri
     else:
         self._uri = URI(uri)
Exemplo n.º 16
0
 def __repr__(self):
     return "{0}({1}, {2})".format(self.__class__.__name__,
                                   self._content_type.__name__,
                                   repr(URI(self).string))
Exemplo n.º 17
0
 def __init__(self, uri):
     self._uri = URI(uri)
Exemplo n.º 18
0
 def __init__(self, uri):
     if isinstance(uri, URI):
         self._uri = uri
     else:
         self._uri = URI(uri)
Exemplo n.º 19
0
class Resource(object):
    """ A web resource identified by a URI.
    """

    def __init__(self, uri):
        if isinstance(uri, URI):
            self._uri = uri
        else:
            self._uri = URI(uri)

    def __str__(self):
        return "<{0}>".format(str(self._uri))

    def __repr__(self):
        return "{0}({1})".format(self.__class__.__name__,
                                 repr(self._uri.string))

    def __eq__(self, other):
        """ Determine equality of two objects based on URI.
        """
        return self._uri == other._uri

    def __ne__(self, other):
        """ Determine inequality of two objects based on URI.
        """
        return self._uri != other._uri

    def __bool__(self):
        return bool(self._uri)

    def __nonzero__(self):
        return bool(self._uri)

    @property
    def __uri__(self):
        return self._uri

    @property
    def uri(self):
        """ The URI of this resource.
        """
        return self._uri

    def resolve(self, reference, strict=True):
        """ Resolve a URI reference against the URI for this resource,
        returning a new resource represented by the new target URI.
        """
        return Resource(self._uri.resolve(reference, strict))

    def get(self, headers=None, redirect_limit=5, **kwargs):
        """ Issue a ``GET`` request to this resource.

        :param headers: headers to be included in the request (optional)
        :type headers: dict
        :param redirect_limit: maximum number of redirects to be handled
            automatically (optional, default=5)
        :param product: name or (name, version) tuple for the client product to
            be listed in the ``User-Agent`` header (optional)
        :param chunk_size: number of bytes to retrieve per chunk (optional,
            default=4096)
        :return: file-like :py:class:`Response <httpstream.http.Response>`
            object from which content can be read
        """
        rq = Request("GET", self._uri, None, headers)
        return rq.submit(redirect_limit=redirect_limit, **kwargs)

    def put(self, body=None, headers=None, **kwargs):
        """ Issue a ``PUT`` request to this resource.
        """
        rq = Request("PUT", self._uri, body, headers)
        return rq.submit(**kwargs)

    def post(self, body=None, headers=None, **kwargs):
        """ Issue a ``POST`` request to this resource.
        """
        rq = Request("POST", self._uri, body, headers)
        return rq.submit(**kwargs)

    def delete(self, headers=None, **kwargs):
        """ Issue a ``DELETE`` request to this resource.
        """
        rq = Request("DELETE", self._uri, None, headers)
        return rq.submit(**kwargs)

    def head(self, headers=None, redirect_limit=5, **kwargs):
        """ Issue a ``HEAD`` request to this resource.
        """
        rq = Request("HEAD", self._uri, None, headers)
        return rq.submit(redirect_limit=redirect_limit, **kwargs)
Exemplo n.º 20
0
__author__ = 'chris'

import time, datetime
from py2neo import rel, node, neo4j, cypher
from py2neo import packages

#import redis
# conectarse a graphene service
import os
from py2neo.packages.urimagic import URI
GRAPHENEDB_URL = "http://*****:*****@app35846518.sb05.stations.graphenedb.com:24789"
graphenedb_url = os.environ.get("GRAPHENEDB_URL", "http://localhost:7474/")
service_root = neo4j.ServiceRoot(URI(graphenedb_url).resolve("/"))
graph_db = service_root.graph_db

#local  ne4j
#graph_db = graph_db = neo4j.GraphDatabaseService()


class Nodo(object):
    def __init__(self):
        self.created = str(datetime.datetime.now())

    def create_nodo(self, **kwargs):
        d = {"created": self.created}
        for item in kwargs.items():
            d.update({item[0]: item[1]})

        print "$$$$$$$$$$Diccionario para creacion de nodo$$$$$$$"
        print d
        if d["element_type"] == "person":