repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
langloisjp/tstore
tstore/tstore.py
TStore.delete
python
def delete(self, cls, rid, user='undefined'): self.validate_record_type(cls) deletedcount = self.db.delete(cls, {ID: rid}) if deletedcount < 1: raise KeyError('No record {}/{}'.format(cls, rid))
Delete a record by id. `user` currently unused. Would be used with soft deletes. >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> len(s.list('tstoretest')) 1 >>> s.delete('tstoretest', '1') >>> len(s.list('tstoretest')) 0 >>> s.delete('tstoretest', '1') Traceback (most recent call last): ... KeyError: 'No record tstoretest/1'
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L248-L269
[ "def validate_record_type(self, cls):\n \"\"\"\n Validate given record is acceptable.\n\n >>> s = teststore()\n >>> s.validate_record_type('tstoretest')\n >>> s.validate_record_type('bad')\n Traceback (most recent call last):\n ...\n ValueError: Unsupported record type \"bad\"\n \"\"\"\n if self.record_types and cls not in self.record_types:\n raise ValueError('Unsupported record type \"' + cls + '\"')\n" ]
class TStore(object): """ A simple table-oriented storage class. Override validate_record for record validation. """ def __init__(self, dburl, record_types=None, schemafile=None, schemasql=None, encoder=JSONEncoder): """ Create new TStore object. - dburl: e.g. pg://user:pass@host/dbname Optional parameters: - record_types: list of acceptable record types - encoder: a custom JSON encoder if you use custom types - schemasql: string containing SQL to create schema - schemafile: file containing SQL to create schema (takes precendence over schemasql) >>> import getpass >>> s = TStore('pg://' + getpass.getuser() + ':@/test') """ self._db = None self.dburl = dburl self.record_types = record_types self.encoder = encoder if schemafile: # pragma: no cover schemasql = open(schemafile).read() if schemasql: self._create_schema(schemasql) @property def db(self): """Lazy init the DB (fork friendly)""" if not self._db: self._db = pgtablestorage.DB(dburl=self.dburl) return self._db def ping(self): """ Return 'ok' if DB is reachable. Otherwise raises error. >>> s = teststore() >>> s.ping() 'ok' """ return self.db.ping() def get(self, cls, rid): """Return record of given type with key `rid` >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['name'] 'Toto' >>> s.get('badcls', '1') Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.get('tstoretest', '2') Traceback (most recent call last): ... KeyError: 'No tstoretest record with id 2' """ self.validate_record_type(cls) rows = self.db.select(cls, where={ID: rid}, limit=1) if not rows: raise KeyError('No {} record with id {}'.format(cls, rid)) return rows[0] def create(self, cls, record, user='undefined'): """Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) """ self.validate_record(cls, record) record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr() record[CREATOR] = record[UPDATER] = user try: return self.db.insert(cls, record) except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: logging.warning("{} {}: {}".format( error.__class__.__name__, psycopg2.errorcodes.lookup(error.pgcode), error.pgerror)) if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, record[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad record ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def update(self, cls, rid, partialrecord, user='undefined'): """Update existing record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['age'] >>> s.update('tstoretest', '1', {'age': 25}) >>> r = s.get('tstoretest', '1') >>> r['age'] 25 >>> s.update('tstoretest', '1', {'age': 30}, user='jane') >>> r = s.get('tstoretest', '1') >>> r[UPDATER] 'jane' >>> s.update('tstoretest', '2', {'age': 25}) Traceback (most recent call last): ... KeyError: 'No such record' >>> s.create('tstoretest', {'id': '2', 'name': 'Joe'}) >>> s.update('tstoretest', '2', {'id': '1'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.update('tstoretest', '2', {'badcol': '1'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.update('tstoretest', '2', {'age': 'hello'}) Traceback (most recent call last): ... ValueError: Bad update (INVALID_TEXT_REPRESENTATION) """ self.validate_partial_record(cls, partialrecord) partialrecord[UPDATE_DATE] = self.nowstr() partialrecord[UPDATER] = user try: updatecount = self.db.update(cls, partialrecord, where={ID: rid}) if updatecount < 1: raise KeyError('No such record') except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, partialrecord[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad update ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def list(self, cls, criteria=None): """ Return list of matching records. criteria is a dict of {field: value} >>> s = teststore() >>> s.list('tstoretest') [] """ self.validate_criteria(cls, criteria) return self.db.select(cls, where=criteria) def validate_record_type(self, cls): """ Validate given record is acceptable. >>> s = teststore() >>> s.validate_record_type('tstoretest') >>> s.validate_record_type('bad') Traceback (most recent call last): ... ValueError: Unsupported record type "bad" """ if self.record_types and cls not in self.record_types: raise ValueError('Unsupported record type "' + cls + '"') def as_record(self, cls, content_type, strdata): """ Returns a record from serialized string representation. >>> s = teststore() >>> s.as_record('tstoretest', 'application/json', ... '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} """ self.validate_record_type(cls) parsedrecord = self.deserialize(content_type, strdata) return self.post_process_record(cls, parsedrecord) def serialize(self, cls, record): """ Serialize the record to JSON. cls unused in this implementation. >>> s = teststore() >>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'}) '{"id": "1", "name": "Toto"}' """ return json.dumps(record, cls=self.encoder) def deserialize(self, content_type, strdata): """Deserialize string of given content type. `self` unused in this implementation. >>> s = teststore() >>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} >>> s.deserialize('text/plain', 'id: 1, name: Toto') Traceback (most recent call last): ... ValueError: Unsupported content type "text/plain" """ if content_type != 'application/json': raise ValueError('Unsupported content type "' + content_type + '"') return json.loads(strdata) @staticmethod def nowstr(): """Return current UTC date/time string in ISO format""" return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") def _create_schema(self, sql): "Create DB schema. Called by constructor." self.db.execute(sql) def post_process_record(self, cls, parsedrecord): """Post process parsed record. For example, a date field can be parsed into a date object. This default implementation doesn't do anything. Override as needed. """ return parsedrecord def validate_record(self, cls, record): """Validate given record is proper. This default implementation only checks the record type. Override as needed. """ self.validate_record_type(cls) def validate_partial_record(self, cls, partialrecord): """Validate given partial record is proper. A partial record is used for updates. This default implementation doesn't check anything. Override as needed. """ pass def validate_criteria(self, cls, criteria): """Validate given criteria is proper for record type. This default implementation doesn't check anything. Override as needed. """ pass
langloisjp/tstore
tstore/tstore.py
TStore.validate_record_type
python
def validate_record_type(self, cls): if self.record_types and cls not in self.record_types: raise ValueError('Unsupported record type "' + cls + '"')
Validate given record is acceptable. >>> s = teststore() >>> s.validate_record_type('tstoretest') >>> s.validate_record_type('bad') Traceback (most recent call last): ... ValueError: Unsupported record type "bad"
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L271-L283
null
class TStore(object): """ A simple table-oriented storage class. Override validate_record for record validation. """ def __init__(self, dburl, record_types=None, schemafile=None, schemasql=None, encoder=JSONEncoder): """ Create new TStore object. - dburl: e.g. pg://user:pass@host/dbname Optional parameters: - record_types: list of acceptable record types - encoder: a custom JSON encoder if you use custom types - schemasql: string containing SQL to create schema - schemafile: file containing SQL to create schema (takes precendence over schemasql) >>> import getpass >>> s = TStore('pg://' + getpass.getuser() + ':@/test') """ self._db = None self.dburl = dburl self.record_types = record_types self.encoder = encoder if schemafile: # pragma: no cover schemasql = open(schemafile).read() if schemasql: self._create_schema(schemasql) @property def db(self): """Lazy init the DB (fork friendly)""" if not self._db: self._db = pgtablestorage.DB(dburl=self.dburl) return self._db def ping(self): """ Return 'ok' if DB is reachable. Otherwise raises error. >>> s = teststore() >>> s.ping() 'ok' """ return self.db.ping() def get(self, cls, rid): """Return record of given type with key `rid` >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['name'] 'Toto' >>> s.get('badcls', '1') Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.get('tstoretest', '2') Traceback (most recent call last): ... KeyError: 'No tstoretest record with id 2' """ self.validate_record_type(cls) rows = self.db.select(cls, where={ID: rid}, limit=1) if not rows: raise KeyError('No {} record with id {}'.format(cls, rid)) return rows[0] def create(self, cls, record, user='undefined'): """Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) """ self.validate_record(cls, record) record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr() record[CREATOR] = record[UPDATER] = user try: return self.db.insert(cls, record) except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: logging.warning("{} {}: {}".format( error.__class__.__name__, psycopg2.errorcodes.lookup(error.pgcode), error.pgerror)) if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, record[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad record ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def update(self, cls, rid, partialrecord, user='undefined'): """Update existing record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['age'] >>> s.update('tstoretest', '1', {'age': 25}) >>> r = s.get('tstoretest', '1') >>> r['age'] 25 >>> s.update('tstoretest', '1', {'age': 30}, user='jane') >>> r = s.get('tstoretest', '1') >>> r[UPDATER] 'jane' >>> s.update('tstoretest', '2', {'age': 25}) Traceback (most recent call last): ... KeyError: 'No such record' >>> s.create('tstoretest', {'id': '2', 'name': 'Joe'}) >>> s.update('tstoretest', '2', {'id': '1'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.update('tstoretest', '2', {'badcol': '1'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.update('tstoretest', '2', {'age': 'hello'}) Traceback (most recent call last): ... ValueError: Bad update (INVALID_TEXT_REPRESENTATION) """ self.validate_partial_record(cls, partialrecord) partialrecord[UPDATE_DATE] = self.nowstr() partialrecord[UPDATER] = user try: updatecount = self.db.update(cls, partialrecord, where={ID: rid}) if updatecount < 1: raise KeyError('No such record') except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, partialrecord[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad update ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def list(self, cls, criteria=None): """ Return list of matching records. criteria is a dict of {field: value} >>> s = teststore() >>> s.list('tstoretest') [] """ self.validate_criteria(cls, criteria) return self.db.select(cls, where=criteria) def delete(self, cls, rid, user='undefined'): """ Delete a record by id. `user` currently unused. Would be used with soft deletes. >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> len(s.list('tstoretest')) 1 >>> s.delete('tstoretest', '1') >>> len(s.list('tstoretest')) 0 >>> s.delete('tstoretest', '1') Traceback (most recent call last): ... KeyError: 'No record tstoretest/1' """ self.validate_record_type(cls) deletedcount = self.db.delete(cls, {ID: rid}) if deletedcount < 1: raise KeyError('No record {}/{}'.format(cls, rid)) def as_record(self, cls, content_type, strdata): """ Returns a record from serialized string representation. >>> s = teststore() >>> s.as_record('tstoretest', 'application/json', ... '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} """ self.validate_record_type(cls) parsedrecord = self.deserialize(content_type, strdata) return self.post_process_record(cls, parsedrecord) def serialize(self, cls, record): """ Serialize the record to JSON. cls unused in this implementation. >>> s = teststore() >>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'}) '{"id": "1", "name": "Toto"}' """ return json.dumps(record, cls=self.encoder) def deserialize(self, content_type, strdata): """Deserialize string of given content type. `self` unused in this implementation. >>> s = teststore() >>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} >>> s.deserialize('text/plain', 'id: 1, name: Toto') Traceback (most recent call last): ... ValueError: Unsupported content type "text/plain" """ if content_type != 'application/json': raise ValueError('Unsupported content type "' + content_type + '"') return json.loads(strdata) @staticmethod def nowstr(): """Return current UTC date/time string in ISO format""" return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") def _create_schema(self, sql): "Create DB schema. Called by constructor." self.db.execute(sql) def post_process_record(self, cls, parsedrecord): """Post process parsed record. For example, a date field can be parsed into a date object. This default implementation doesn't do anything. Override as needed. """ return parsedrecord def validate_record(self, cls, record): """Validate given record is proper. This default implementation only checks the record type. Override as needed. """ self.validate_record_type(cls) def validate_partial_record(self, cls, partialrecord): """Validate given partial record is proper. A partial record is used for updates. This default implementation doesn't check anything. Override as needed. """ pass def validate_criteria(self, cls, criteria): """Validate given criteria is proper for record type. This default implementation doesn't check anything. Override as needed. """ pass
langloisjp/tstore
tstore/tstore.py
TStore.as_record
python
def as_record(self, cls, content_type, strdata): self.validate_record_type(cls) parsedrecord = self.deserialize(content_type, strdata) return self.post_process_record(cls, parsedrecord)
Returns a record from serialized string representation. >>> s = teststore() >>> s.as_record('tstoretest', 'application/json', ... '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'}
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L285-L296
[ "def validate_record_type(self, cls):\n \"\"\"\n Validate given record is acceptable.\n\n >>> s = teststore()\n >>> s.validate_record_type('tstoretest')\n >>> s.validate_record_type('bad')\n Traceback (most recent call last):\n ...\n ValueError: Unsupported record type \"bad\"\n \"\"\"\n if self.record_types and cls not in self.record_types:\n raise ValueError('Unsupported record type \"' + cls + '\"')\n", "def deserialize(self, content_type, strdata):\n \"\"\"Deserialize string of given content type.\n\n `self` unused in this implementation.\n\n >>> s = teststore()\n >>> s.deserialize('application/json', '{\"id\": \"1\", \"name\": \"Toto\"}')\n {u'id': u'1', u'name': u'Toto'}\n >>> s.deserialize('text/plain', 'id: 1, name: Toto')\n Traceback (most recent call last):\n ...\n ValueError: Unsupported content type \"text/plain\"\n \"\"\"\n if content_type != 'application/json':\n raise ValueError('Unsupported content type \"' + content_type + '\"')\n return json.loads(strdata)\n", "def post_process_record(self, cls, parsedrecord):\n \"\"\"Post process parsed record. For example, a date field\n can be parsed into a date object.\n This default implementation doesn't do anything. Override\n as needed.\n \"\"\"\n return parsedrecord\n" ]
class TStore(object): """ A simple table-oriented storage class. Override validate_record for record validation. """ def __init__(self, dburl, record_types=None, schemafile=None, schemasql=None, encoder=JSONEncoder): """ Create new TStore object. - dburl: e.g. pg://user:pass@host/dbname Optional parameters: - record_types: list of acceptable record types - encoder: a custom JSON encoder if you use custom types - schemasql: string containing SQL to create schema - schemafile: file containing SQL to create schema (takes precendence over schemasql) >>> import getpass >>> s = TStore('pg://' + getpass.getuser() + ':@/test') """ self._db = None self.dburl = dburl self.record_types = record_types self.encoder = encoder if schemafile: # pragma: no cover schemasql = open(schemafile).read() if schemasql: self._create_schema(schemasql) @property def db(self): """Lazy init the DB (fork friendly)""" if not self._db: self._db = pgtablestorage.DB(dburl=self.dburl) return self._db def ping(self): """ Return 'ok' if DB is reachable. Otherwise raises error. >>> s = teststore() >>> s.ping() 'ok' """ return self.db.ping() def get(self, cls, rid): """Return record of given type with key `rid` >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['name'] 'Toto' >>> s.get('badcls', '1') Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.get('tstoretest', '2') Traceback (most recent call last): ... KeyError: 'No tstoretest record with id 2' """ self.validate_record_type(cls) rows = self.db.select(cls, where={ID: rid}, limit=1) if not rows: raise KeyError('No {} record with id {}'.format(cls, rid)) return rows[0] def create(self, cls, record, user='undefined'): """Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) """ self.validate_record(cls, record) record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr() record[CREATOR] = record[UPDATER] = user try: return self.db.insert(cls, record) except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: logging.warning("{} {}: {}".format( error.__class__.__name__, psycopg2.errorcodes.lookup(error.pgcode), error.pgerror)) if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, record[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad record ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def update(self, cls, rid, partialrecord, user='undefined'): """Update existing record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['age'] >>> s.update('tstoretest', '1', {'age': 25}) >>> r = s.get('tstoretest', '1') >>> r['age'] 25 >>> s.update('tstoretest', '1', {'age': 30}, user='jane') >>> r = s.get('tstoretest', '1') >>> r[UPDATER] 'jane' >>> s.update('tstoretest', '2', {'age': 25}) Traceback (most recent call last): ... KeyError: 'No such record' >>> s.create('tstoretest', {'id': '2', 'name': 'Joe'}) >>> s.update('tstoretest', '2', {'id': '1'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.update('tstoretest', '2', {'badcol': '1'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.update('tstoretest', '2', {'age': 'hello'}) Traceback (most recent call last): ... ValueError: Bad update (INVALID_TEXT_REPRESENTATION) """ self.validate_partial_record(cls, partialrecord) partialrecord[UPDATE_DATE] = self.nowstr() partialrecord[UPDATER] = user try: updatecount = self.db.update(cls, partialrecord, where={ID: rid}) if updatecount < 1: raise KeyError('No such record') except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, partialrecord[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad update ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def list(self, cls, criteria=None): """ Return list of matching records. criteria is a dict of {field: value} >>> s = teststore() >>> s.list('tstoretest') [] """ self.validate_criteria(cls, criteria) return self.db.select(cls, where=criteria) def delete(self, cls, rid, user='undefined'): """ Delete a record by id. `user` currently unused. Would be used with soft deletes. >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> len(s.list('tstoretest')) 1 >>> s.delete('tstoretest', '1') >>> len(s.list('tstoretest')) 0 >>> s.delete('tstoretest', '1') Traceback (most recent call last): ... KeyError: 'No record tstoretest/1' """ self.validate_record_type(cls) deletedcount = self.db.delete(cls, {ID: rid}) if deletedcount < 1: raise KeyError('No record {}/{}'.format(cls, rid)) def validate_record_type(self, cls): """ Validate given record is acceptable. >>> s = teststore() >>> s.validate_record_type('tstoretest') >>> s.validate_record_type('bad') Traceback (most recent call last): ... ValueError: Unsupported record type "bad" """ if self.record_types and cls not in self.record_types: raise ValueError('Unsupported record type "' + cls + '"') def serialize(self, cls, record): """ Serialize the record to JSON. cls unused in this implementation. >>> s = teststore() >>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'}) '{"id": "1", "name": "Toto"}' """ return json.dumps(record, cls=self.encoder) def deserialize(self, content_type, strdata): """Deserialize string of given content type. `self` unused in this implementation. >>> s = teststore() >>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} >>> s.deserialize('text/plain', 'id: 1, name: Toto') Traceback (most recent call last): ... ValueError: Unsupported content type "text/plain" """ if content_type != 'application/json': raise ValueError('Unsupported content type "' + content_type + '"') return json.loads(strdata) @staticmethod def nowstr(): """Return current UTC date/time string in ISO format""" return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") def _create_schema(self, sql): "Create DB schema. Called by constructor." self.db.execute(sql) def post_process_record(self, cls, parsedrecord): """Post process parsed record. For example, a date field can be parsed into a date object. This default implementation doesn't do anything. Override as needed. """ return parsedrecord def validate_record(self, cls, record): """Validate given record is proper. This default implementation only checks the record type. Override as needed. """ self.validate_record_type(cls) def validate_partial_record(self, cls, partialrecord): """Validate given partial record is proper. A partial record is used for updates. This default implementation doesn't check anything. Override as needed. """ pass def validate_criteria(self, cls, criteria): """Validate given criteria is proper for record type. This default implementation doesn't check anything. Override as needed. """ pass
langloisjp/tstore
tstore/tstore.py
TStore.serialize
python
def serialize(self, cls, record): return json.dumps(record, cls=self.encoder)
Serialize the record to JSON. cls unused in this implementation. >>> s = teststore() >>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'}) '{"id": "1", "name": "Toto"}'
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L298-L306
null
class TStore(object): """ A simple table-oriented storage class. Override validate_record for record validation. """ def __init__(self, dburl, record_types=None, schemafile=None, schemasql=None, encoder=JSONEncoder): """ Create new TStore object. - dburl: e.g. pg://user:pass@host/dbname Optional parameters: - record_types: list of acceptable record types - encoder: a custom JSON encoder if you use custom types - schemasql: string containing SQL to create schema - schemafile: file containing SQL to create schema (takes precendence over schemasql) >>> import getpass >>> s = TStore('pg://' + getpass.getuser() + ':@/test') """ self._db = None self.dburl = dburl self.record_types = record_types self.encoder = encoder if schemafile: # pragma: no cover schemasql = open(schemafile).read() if schemasql: self._create_schema(schemasql) @property def db(self): """Lazy init the DB (fork friendly)""" if not self._db: self._db = pgtablestorage.DB(dburl=self.dburl) return self._db def ping(self): """ Return 'ok' if DB is reachable. Otherwise raises error. >>> s = teststore() >>> s.ping() 'ok' """ return self.db.ping() def get(self, cls, rid): """Return record of given type with key `rid` >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['name'] 'Toto' >>> s.get('badcls', '1') Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.get('tstoretest', '2') Traceback (most recent call last): ... KeyError: 'No tstoretest record with id 2' """ self.validate_record_type(cls) rows = self.db.select(cls, where={ID: rid}, limit=1) if not rows: raise KeyError('No {} record with id {}'.format(cls, rid)) return rows[0] def create(self, cls, record, user='undefined'): """Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) """ self.validate_record(cls, record) record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr() record[CREATOR] = record[UPDATER] = user try: return self.db.insert(cls, record) except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: logging.warning("{} {}: {}".format( error.__class__.__name__, psycopg2.errorcodes.lookup(error.pgcode), error.pgerror)) if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, record[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad record ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def update(self, cls, rid, partialrecord, user='undefined'): """Update existing record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['age'] >>> s.update('tstoretest', '1', {'age': 25}) >>> r = s.get('tstoretest', '1') >>> r['age'] 25 >>> s.update('tstoretest', '1', {'age': 30}, user='jane') >>> r = s.get('tstoretest', '1') >>> r[UPDATER] 'jane' >>> s.update('tstoretest', '2', {'age': 25}) Traceback (most recent call last): ... KeyError: 'No such record' >>> s.create('tstoretest', {'id': '2', 'name': 'Joe'}) >>> s.update('tstoretest', '2', {'id': '1'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.update('tstoretest', '2', {'badcol': '1'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.update('tstoretest', '2', {'age': 'hello'}) Traceback (most recent call last): ... ValueError: Bad update (INVALID_TEXT_REPRESENTATION) """ self.validate_partial_record(cls, partialrecord) partialrecord[UPDATE_DATE] = self.nowstr() partialrecord[UPDATER] = user try: updatecount = self.db.update(cls, partialrecord, where={ID: rid}) if updatecount < 1: raise KeyError('No such record') except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, partialrecord[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad update ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def list(self, cls, criteria=None): """ Return list of matching records. criteria is a dict of {field: value} >>> s = teststore() >>> s.list('tstoretest') [] """ self.validate_criteria(cls, criteria) return self.db.select(cls, where=criteria) def delete(self, cls, rid, user='undefined'): """ Delete a record by id. `user` currently unused. Would be used with soft deletes. >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> len(s.list('tstoretest')) 1 >>> s.delete('tstoretest', '1') >>> len(s.list('tstoretest')) 0 >>> s.delete('tstoretest', '1') Traceback (most recent call last): ... KeyError: 'No record tstoretest/1' """ self.validate_record_type(cls) deletedcount = self.db.delete(cls, {ID: rid}) if deletedcount < 1: raise KeyError('No record {}/{}'.format(cls, rid)) def validate_record_type(self, cls): """ Validate given record is acceptable. >>> s = teststore() >>> s.validate_record_type('tstoretest') >>> s.validate_record_type('bad') Traceback (most recent call last): ... ValueError: Unsupported record type "bad" """ if self.record_types and cls not in self.record_types: raise ValueError('Unsupported record type "' + cls + '"') def as_record(self, cls, content_type, strdata): """ Returns a record from serialized string representation. >>> s = teststore() >>> s.as_record('tstoretest', 'application/json', ... '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} """ self.validate_record_type(cls) parsedrecord = self.deserialize(content_type, strdata) return self.post_process_record(cls, parsedrecord) def deserialize(self, content_type, strdata): """Deserialize string of given content type. `self` unused in this implementation. >>> s = teststore() >>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} >>> s.deserialize('text/plain', 'id: 1, name: Toto') Traceback (most recent call last): ... ValueError: Unsupported content type "text/plain" """ if content_type != 'application/json': raise ValueError('Unsupported content type "' + content_type + '"') return json.loads(strdata) @staticmethod def nowstr(): """Return current UTC date/time string in ISO format""" return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") def _create_schema(self, sql): "Create DB schema. Called by constructor." self.db.execute(sql) def post_process_record(self, cls, parsedrecord): """Post process parsed record. For example, a date field can be parsed into a date object. This default implementation doesn't do anything. Override as needed. """ return parsedrecord def validate_record(self, cls, record): """Validate given record is proper. This default implementation only checks the record type. Override as needed. """ self.validate_record_type(cls) def validate_partial_record(self, cls, partialrecord): """Validate given partial record is proper. A partial record is used for updates. This default implementation doesn't check anything. Override as needed. """ pass def validate_criteria(self, cls, criteria): """Validate given criteria is proper for record type. This default implementation doesn't check anything. Override as needed. """ pass
langloisjp/tstore
tstore/tstore.py
TStore.deserialize
python
def deserialize(self, content_type, strdata): if content_type != 'application/json': raise ValueError('Unsupported content type "' + content_type + '"') return json.loads(strdata)
Deserialize string of given content type. `self` unused in this implementation. >>> s = teststore() >>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} >>> s.deserialize('text/plain', 'id: 1, name: Toto') Traceback (most recent call last): ... ValueError: Unsupported content type "text/plain"
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/tstore.py#L308-L323
null
class TStore(object): """ A simple table-oriented storage class. Override validate_record for record validation. """ def __init__(self, dburl, record_types=None, schemafile=None, schemasql=None, encoder=JSONEncoder): """ Create new TStore object. - dburl: e.g. pg://user:pass@host/dbname Optional parameters: - record_types: list of acceptable record types - encoder: a custom JSON encoder if you use custom types - schemasql: string containing SQL to create schema - schemafile: file containing SQL to create schema (takes precendence over schemasql) >>> import getpass >>> s = TStore('pg://' + getpass.getuser() + ':@/test') """ self._db = None self.dburl = dburl self.record_types = record_types self.encoder = encoder if schemafile: # pragma: no cover schemasql = open(schemafile).read() if schemasql: self._create_schema(schemasql) @property def db(self): """Lazy init the DB (fork friendly)""" if not self._db: self._db = pgtablestorage.DB(dburl=self.dburl) return self._db def ping(self): """ Return 'ok' if DB is reachable. Otherwise raises error. >>> s = teststore() >>> s.ping() 'ok' """ return self.db.ping() def get(self, cls, rid): """Return record of given type with key `rid` >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['name'] 'Toto' >>> s.get('badcls', '1') Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.get('tstoretest', '2') Traceback (most recent call last): ... KeyError: 'No tstoretest record with id 2' """ self.validate_record_type(cls) rows = self.db.select(cls, where={ID: rid}, limit=1) if not rows: raise KeyError('No {} record with id {}'.format(cls, rid)) return rows[0] def create(self, cls, record, user='undefined'): """Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) """ self.validate_record(cls, record) record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr() record[CREATOR] = record[UPDATER] = user try: return self.db.insert(cls, record) except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: logging.warning("{} {}: {}".format( error.__class__.__name__, psycopg2.errorcodes.lookup(error.pgcode), error.pgerror)) if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, record[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad record ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def update(self, cls, rid, partialrecord, user='undefined'): """Update existing record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> r = s.get('tstoretest', '1') >>> r['age'] >>> s.update('tstoretest', '1', {'age': 25}) >>> r = s.get('tstoretest', '1') >>> r['age'] 25 >>> s.update('tstoretest', '1', {'age': 30}, user='jane') >>> r = s.get('tstoretest', '1') >>> r[UPDATER] 'jane' >>> s.update('tstoretest', '2', {'age': 25}) Traceback (most recent call last): ... KeyError: 'No such record' >>> s.create('tstoretest', {'id': '2', 'name': 'Joe'}) >>> s.update('tstoretest', '2', {'id': '1'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.update('tstoretest', '2', {'badcol': '1'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.update('tstoretest', '2', {'age': 'hello'}) Traceback (most recent call last): ... ValueError: Bad update (INVALID_TEXT_REPRESENTATION) """ self.validate_partial_record(cls, partialrecord) partialrecord[UPDATE_DATE] = self.nowstr() partialrecord[UPDATER] = user try: updatecount = self.db.update(cls, partialrecord, where={ID: rid}) if updatecount < 1: raise KeyError('No such record') except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, partialrecord[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad update ({})'.format( psycopg2.errorcodes.lookup(error.pgcode))) def list(self, cls, criteria=None): """ Return list of matching records. criteria is a dict of {field: value} >>> s = teststore() >>> s.list('tstoretest') [] """ self.validate_criteria(cls, criteria) return self.db.select(cls, where=criteria) def delete(self, cls, rid, user='undefined'): """ Delete a record by id. `user` currently unused. Would be used with soft deletes. >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> len(s.list('tstoretest')) 1 >>> s.delete('tstoretest', '1') >>> len(s.list('tstoretest')) 0 >>> s.delete('tstoretest', '1') Traceback (most recent call last): ... KeyError: 'No record tstoretest/1' """ self.validate_record_type(cls) deletedcount = self.db.delete(cls, {ID: rid}) if deletedcount < 1: raise KeyError('No record {}/{}'.format(cls, rid)) def validate_record_type(self, cls): """ Validate given record is acceptable. >>> s = teststore() >>> s.validate_record_type('tstoretest') >>> s.validate_record_type('bad') Traceback (most recent call last): ... ValueError: Unsupported record type "bad" """ if self.record_types and cls not in self.record_types: raise ValueError('Unsupported record type "' + cls + '"') def as_record(self, cls, content_type, strdata): """ Returns a record from serialized string representation. >>> s = teststore() >>> s.as_record('tstoretest', 'application/json', ... '{"id": "1", "name": "Toto"}') {u'id': u'1', u'name': u'Toto'} """ self.validate_record_type(cls) parsedrecord = self.deserialize(content_type, strdata) return self.post_process_record(cls, parsedrecord) def serialize(self, cls, record): """ Serialize the record to JSON. cls unused in this implementation. >>> s = teststore() >>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'}) '{"id": "1", "name": "Toto"}' """ return json.dumps(record, cls=self.encoder) @staticmethod def nowstr(): """Return current UTC date/time string in ISO format""" return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") def _create_schema(self, sql): "Create DB schema. Called by constructor." self.db.execute(sql) def post_process_record(self, cls, parsedrecord): """Post process parsed record. For example, a date field can be parsed into a date object. This default implementation doesn't do anything. Override as needed. """ return parsedrecord def validate_record(self, cls, record): """Validate given record is proper. This default implementation only checks the record type. Override as needed. """ self.validate_record_type(cls) def validate_partial_record(self, cls, partialrecord): """Validate given partial record is proper. A partial record is used for updates. This default implementation doesn't check anything. Override as needed. """ pass def validate_criteria(self, cls, criteria): """Validate given criteria is proper for record type. This default implementation doesn't check anything. Override as needed. """ pass
langloisjp/tstore
tstore/pgtablestorage.py
sqlselect
python
def sqlselect(table, fields=['*'], where=None, orderby=None, limit=None, offset=None): validate_name(table) if fields != ['*']: validate_names(fields) fieldspart = ', '.join(fields) sql = "select {} from {}".format(fieldspart, table) values = [] if where: (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause values = wherevalues if orderby: validate_names(orderby) sql = sql + " order by " + ', '.join(orderby) if limit: if not isinstance(limit, int): raise ValueError("Limit parameter must be an int") sql = sql + " limit {}".format(limit) if offset: if not isinstance(offset, int): raise ValueError("Offset parameter must be an int") sql = sql + " offset {}".format(offset) return (sql, values)
Generates SQL select ... Returns (sql, params) >>> sqlselect('t') ('select * from t', []) >>> sqlselect('t', fields=['name', 'address']) ('select name, address from t', []) >>> sqlselect('t', where={'name': 'Toto', 'country': 'US'}) ('select * from t where country=%s and name=%s', ['US', 'Toto']) >>> sqlselect('t', orderby=['lastname', 'firstname']) ('select * from t order by lastname, firstname', []) >>> sqlselect('t', limit=1) ('select * from t limit 1', []) >>> sqlselect('t', limit='yes') Traceback (most recent call last): ... ValueError: Limit parameter must be an int >>> sqlselect('t', offset=20) ('select * from t offset 20', []) >>> sqlselect('t', offset='yes') Traceback (most recent call last): ... ValueError: Offset parameter must be an int
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L304-L357
[ "def validate_name(name):\n \"\"\"Check that table/field name is valid. Raise ValueError otherwise.\n\n >>> validate_name('mytable')\n >>> validate_name('invalid!')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"invalid!\"\n >>> validate_name('in valid')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"in valid\"\n >>> validate_name('nope,nope')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"nope,nope\"\n \"\"\"\n if not VALID_NAME_RE.match(name):\n raise ValueError('Invalid name \"{}\"'.format(name))\n", "def validate_names(names):\n \"\"\"Validate list of names.\n\n >>> validate_names(['id', 'field'])\n >>> validate_names(['id', 'b#d'])\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"b#d\"\n \"\"\"\n for name in names:\n validate_name(name)\n", "def sqlwhere(criteria=None):\n \"\"\"Generates SQL where clause. Returns (sql, values).\n Criteria is a dictionary of {field: value}.\n\n >>> sqlwhere()\n ('', [])\n >>> sqlwhere({'id': 5})\n ('id=%s', [5])\n >>> sqlwhere({'id': 3, 'name': 'toto'})\n ('id=%s and name=%s', [3, 'toto'])\n >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'})\n ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto'])\n \"\"\"\n if not criteria:\n return ('', [])\n fields = sorted(criteria.keys())\n validate_names(fields)\n values = [criteria[field] for field in fields]\n parts = [field + '=%s' for field in fields]\n sql = ' and '.join(parts)\n return (sql, values)\n" ]
""" Table storage interface to postgesql Insert, select, update, delete rows from tables. Run tests with: python -m doctest pgtablestorage.py Make sure the current user has a 'test' DB with no password: createdb test >>> import getpass >>> user = getpass.getuser() >>> s = DB(dbname='test', user=user, host='localhost', password='') >>> s.execute('drop table if exists t1') >>> s.execute(''' ... create table t1 (id text not null primary key, name text, memo text) ... ''') >>> s.select('t1') [] >>> s.insert('t1', {'id': 'toto', 'name': 'Toto', 'memo': 'Toto memo'}) >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.insert('t1', {'id': 'tata', 'name': 'Tata', 'memo': 'Tata memo'}) >>> s.select('t1', ['id', 'name']) [{'id': 'toto', 'name': 'Toto'}, {'id': 'tata', 'name': 'Tata'}] >>> s.select('t1', where={'id': 'toto'}) [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.update('t1', {'memo': 'New memo'}, {'id': 'tata'}) 1 >>> s.select('t1', ['memo'], where={'id': 'tata'}) [{'memo': 'New memo'}] >>> s.delete('t1', {'name': 'Tata'}) 1 >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] Dependencies: - psycopg2 (`pip install psycopg2`) """ import logging import urlparse import psycopg2 import psycopg2.extras import re class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall() # SQL generation def sqlinsert(table, row): """Generates SQL insert into table ... Returns (sql, parameters) >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'}) ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto']) >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'}) ('insert into t2 (id, name) values (%s, %s)', [1, 'Toto']) """ validate_name(table) fields = sorted(row.keys()) validate_names(fields) values = [row[field] for field in fields] sql = "insert into {} ({}) values ({})".format( table, ', '.join(fields), ', '.join(['%s'] * len(fields))) return sql, values def sqlupdate(table, rowupdate, where): """Generates SQL update table set ... Returns (sql, parameters) >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5}) ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5]) """ validate_name(table) fields = sorted(rowupdate.keys()) validate_names(fields) values = [rowupdate[field] for field in fields] setparts = [field + '=%s' for field in fields] setclause = ', '.join(setparts) sql = "update {} set ".format(table) + setclause (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause return (sql, values + wherevalues) def sqldelete(table, where): """Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5]) """ validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues) def sqlwhere(criteria=None): """Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'}) ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto']) """ if not criteria: return ('', []) fields = sorted(criteria.keys()) validate_names(fields) values = [criteria[field] for field in fields] parts = [field + '=%s' for field in fields] sql = ' and '.join(parts) return (sql, values) VALID_NAME_RE = re.compile('^[a-zA-Z0-9_]+$') def validate_name(name): """Check that table/field name is valid. Raise ValueError otherwise. >>> validate_name('mytable') >>> validate_name('invalid!') Traceback (most recent call last): ... ValueError: Invalid name "invalid!" >>> validate_name('in valid') Traceback (most recent call last): ... ValueError: Invalid name "in valid" >>> validate_name('nope,nope') Traceback (most recent call last): ... ValueError: Invalid name "nope,nope" """ if not VALID_NAME_RE.match(name): raise ValueError('Invalid name "{}"'.format(name)) def validate_names(names): """Validate list of names. >>> validate_names(['id', 'field']) >>> validate_names(['id', 'b#d']) Traceback (most recent call last): ... ValueError: Invalid name "b#d" """ for name in names: validate_name(name) def parse_dburl(dburl): """Parse DB URL. Return (scheme, user, password, host, dbname) pg://user:pass@host/dbname >>> parse_dburl("pg://user:pass@host/name") ('pg', 'user', 'pass', 'host', 'name') >>> parse_dburl("dbm:///dbfile") ('dbm', '', '', '', 'dbfile') >>> parse_dburl("pg://user:@/name") ('pg', 'user', '', '', 'name') """ res = urlparse.urlparse(dburl) if '@' in res.netloc: (creds, host) = res.netloc.split('@') else: creds = ':' host = res.netloc (user, password) = creds.split(':') return (res.scheme, user, password, host, res.path[1:])
langloisjp/tstore
tstore/pgtablestorage.py
sqlinsert
python
def sqlinsert(table, row): validate_name(table) fields = sorted(row.keys()) validate_names(fields) values = [row[field] for field in fields] sql = "insert into {} ({}) values ({})".format( table, ', '.join(fields), ', '.join(['%s'] * len(fields))) return sql, values
Generates SQL insert into table ... Returns (sql, parameters) >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'}) ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto']) >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'}) ('insert into t2 (id, name) values (%s, %s)', [1, 'Toto'])
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L360-L375
[ "def validate_name(name):\n \"\"\"Check that table/field name is valid. Raise ValueError otherwise.\n\n >>> validate_name('mytable')\n >>> validate_name('invalid!')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"invalid!\"\n >>> validate_name('in valid')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"in valid\"\n >>> validate_name('nope,nope')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"nope,nope\"\n \"\"\"\n if not VALID_NAME_RE.match(name):\n raise ValueError('Invalid name \"{}\"'.format(name))\n", "def validate_names(names):\n \"\"\"Validate list of names.\n\n >>> validate_names(['id', 'field'])\n >>> validate_names(['id', 'b#d'])\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"b#d\"\n \"\"\"\n for name in names:\n validate_name(name)\n" ]
""" Table storage interface to postgesql Insert, select, update, delete rows from tables. Run tests with: python -m doctest pgtablestorage.py Make sure the current user has a 'test' DB with no password: createdb test >>> import getpass >>> user = getpass.getuser() >>> s = DB(dbname='test', user=user, host='localhost', password='') >>> s.execute('drop table if exists t1') >>> s.execute(''' ... create table t1 (id text not null primary key, name text, memo text) ... ''') >>> s.select('t1') [] >>> s.insert('t1', {'id': 'toto', 'name': 'Toto', 'memo': 'Toto memo'}) >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.insert('t1', {'id': 'tata', 'name': 'Tata', 'memo': 'Tata memo'}) >>> s.select('t1', ['id', 'name']) [{'id': 'toto', 'name': 'Toto'}, {'id': 'tata', 'name': 'Tata'}] >>> s.select('t1', where={'id': 'toto'}) [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.update('t1', {'memo': 'New memo'}, {'id': 'tata'}) 1 >>> s.select('t1', ['memo'], where={'id': 'tata'}) [{'memo': 'New memo'}] >>> s.delete('t1', {'name': 'Tata'}) 1 >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] Dependencies: - psycopg2 (`pip install psycopg2`) """ import logging import urlparse import psycopg2 import psycopg2.extras import re class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall() # SQL generation def sqlselect(table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """Generates SQL select ... Returns (sql, params) >>> sqlselect('t') ('select * from t', []) >>> sqlselect('t', fields=['name', 'address']) ('select name, address from t', []) >>> sqlselect('t', where={'name': 'Toto', 'country': 'US'}) ('select * from t where country=%s and name=%s', ['US', 'Toto']) >>> sqlselect('t', orderby=['lastname', 'firstname']) ('select * from t order by lastname, firstname', []) >>> sqlselect('t', limit=1) ('select * from t limit 1', []) >>> sqlselect('t', limit='yes') Traceback (most recent call last): ... ValueError: Limit parameter must be an int >>> sqlselect('t', offset=20) ('select * from t offset 20', []) >>> sqlselect('t', offset='yes') Traceback (most recent call last): ... ValueError: Offset parameter must be an int """ validate_name(table) if fields != ['*']: validate_names(fields) fieldspart = ', '.join(fields) sql = "select {} from {}".format(fieldspart, table) values = [] if where: (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause values = wherevalues if orderby: validate_names(orderby) sql = sql + " order by " + ', '.join(orderby) if limit: if not isinstance(limit, int): raise ValueError("Limit parameter must be an int") sql = sql + " limit {}".format(limit) if offset: if not isinstance(offset, int): raise ValueError("Offset parameter must be an int") sql = sql + " offset {}".format(offset) return (sql, values) def sqlupdate(table, rowupdate, where): """Generates SQL update table set ... Returns (sql, parameters) >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5}) ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5]) """ validate_name(table) fields = sorted(rowupdate.keys()) validate_names(fields) values = [rowupdate[field] for field in fields] setparts = [field + '=%s' for field in fields] setclause = ', '.join(setparts) sql = "update {} set ".format(table) + setclause (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause return (sql, values + wherevalues) def sqldelete(table, where): """Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5]) """ validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues) def sqlwhere(criteria=None): """Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'}) ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto']) """ if not criteria: return ('', []) fields = sorted(criteria.keys()) validate_names(fields) values = [criteria[field] for field in fields] parts = [field + '=%s' for field in fields] sql = ' and '.join(parts) return (sql, values) VALID_NAME_RE = re.compile('^[a-zA-Z0-9_]+$') def validate_name(name): """Check that table/field name is valid. Raise ValueError otherwise. >>> validate_name('mytable') >>> validate_name('invalid!') Traceback (most recent call last): ... ValueError: Invalid name "invalid!" >>> validate_name('in valid') Traceback (most recent call last): ... ValueError: Invalid name "in valid" >>> validate_name('nope,nope') Traceback (most recent call last): ... ValueError: Invalid name "nope,nope" """ if not VALID_NAME_RE.match(name): raise ValueError('Invalid name "{}"'.format(name)) def validate_names(names): """Validate list of names. >>> validate_names(['id', 'field']) >>> validate_names(['id', 'b#d']) Traceback (most recent call last): ... ValueError: Invalid name "b#d" """ for name in names: validate_name(name) def parse_dburl(dburl): """Parse DB URL. Return (scheme, user, password, host, dbname) pg://user:pass@host/dbname >>> parse_dburl("pg://user:pass@host/name") ('pg', 'user', 'pass', 'host', 'name') >>> parse_dburl("dbm:///dbfile") ('dbm', '', '', '', 'dbfile') >>> parse_dburl("pg://user:@/name") ('pg', 'user', '', '', 'name') """ res = urlparse.urlparse(dburl) if '@' in res.netloc: (creds, host) = res.netloc.split('@') else: creds = ':' host = res.netloc (user, password) = creds.split(':') return (res.scheme, user, password, host, res.path[1:])
langloisjp/tstore
tstore/pgtablestorage.py
sqlupdate
python
def sqlupdate(table, rowupdate, where): validate_name(table) fields = sorted(rowupdate.keys()) validate_names(fields) values = [rowupdate[field] for field in fields] setparts = [field + '=%s' for field in fields] setclause = ', '.join(setparts) sql = "update {} set ".format(table) + setclause (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause return (sql, values + wherevalues)
Generates SQL update table set ... Returns (sql, parameters) >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5}) ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5])
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L378-L395
[ "def validate_name(name):\n \"\"\"Check that table/field name is valid. Raise ValueError otherwise.\n\n >>> validate_name('mytable')\n >>> validate_name('invalid!')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"invalid!\"\n >>> validate_name('in valid')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"in valid\"\n >>> validate_name('nope,nope')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"nope,nope\"\n \"\"\"\n if not VALID_NAME_RE.match(name):\n raise ValueError('Invalid name \"{}\"'.format(name))\n", "def validate_names(names):\n \"\"\"Validate list of names.\n\n >>> validate_names(['id', 'field'])\n >>> validate_names(['id', 'b#d'])\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"b#d\"\n \"\"\"\n for name in names:\n validate_name(name)\n", "def sqlwhere(criteria=None):\n \"\"\"Generates SQL where clause. Returns (sql, values).\n Criteria is a dictionary of {field: value}.\n\n >>> sqlwhere()\n ('', [])\n >>> sqlwhere({'id': 5})\n ('id=%s', [5])\n >>> sqlwhere({'id': 3, 'name': 'toto'})\n ('id=%s and name=%s', [3, 'toto'])\n >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'})\n ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto'])\n \"\"\"\n if not criteria:\n return ('', [])\n fields = sorted(criteria.keys())\n validate_names(fields)\n values = [criteria[field] for field in fields]\n parts = [field + '=%s' for field in fields]\n sql = ' and '.join(parts)\n return (sql, values)\n" ]
""" Table storage interface to postgesql Insert, select, update, delete rows from tables. Run tests with: python -m doctest pgtablestorage.py Make sure the current user has a 'test' DB with no password: createdb test >>> import getpass >>> user = getpass.getuser() >>> s = DB(dbname='test', user=user, host='localhost', password='') >>> s.execute('drop table if exists t1') >>> s.execute(''' ... create table t1 (id text not null primary key, name text, memo text) ... ''') >>> s.select('t1') [] >>> s.insert('t1', {'id': 'toto', 'name': 'Toto', 'memo': 'Toto memo'}) >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.insert('t1', {'id': 'tata', 'name': 'Tata', 'memo': 'Tata memo'}) >>> s.select('t1', ['id', 'name']) [{'id': 'toto', 'name': 'Toto'}, {'id': 'tata', 'name': 'Tata'}] >>> s.select('t1', where={'id': 'toto'}) [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.update('t1', {'memo': 'New memo'}, {'id': 'tata'}) 1 >>> s.select('t1', ['memo'], where={'id': 'tata'}) [{'memo': 'New memo'}] >>> s.delete('t1', {'name': 'Tata'}) 1 >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] Dependencies: - psycopg2 (`pip install psycopg2`) """ import logging import urlparse import psycopg2 import psycopg2.extras import re class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall() # SQL generation def sqlselect(table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """Generates SQL select ... Returns (sql, params) >>> sqlselect('t') ('select * from t', []) >>> sqlselect('t', fields=['name', 'address']) ('select name, address from t', []) >>> sqlselect('t', where={'name': 'Toto', 'country': 'US'}) ('select * from t where country=%s and name=%s', ['US', 'Toto']) >>> sqlselect('t', orderby=['lastname', 'firstname']) ('select * from t order by lastname, firstname', []) >>> sqlselect('t', limit=1) ('select * from t limit 1', []) >>> sqlselect('t', limit='yes') Traceback (most recent call last): ... ValueError: Limit parameter must be an int >>> sqlselect('t', offset=20) ('select * from t offset 20', []) >>> sqlselect('t', offset='yes') Traceback (most recent call last): ... ValueError: Offset parameter must be an int """ validate_name(table) if fields != ['*']: validate_names(fields) fieldspart = ', '.join(fields) sql = "select {} from {}".format(fieldspart, table) values = [] if where: (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause values = wherevalues if orderby: validate_names(orderby) sql = sql + " order by " + ', '.join(orderby) if limit: if not isinstance(limit, int): raise ValueError("Limit parameter must be an int") sql = sql + " limit {}".format(limit) if offset: if not isinstance(offset, int): raise ValueError("Offset parameter must be an int") sql = sql + " offset {}".format(offset) return (sql, values) def sqlinsert(table, row): """Generates SQL insert into table ... Returns (sql, parameters) >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'}) ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto']) >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'}) ('insert into t2 (id, name) values (%s, %s)', [1, 'Toto']) """ validate_name(table) fields = sorted(row.keys()) validate_names(fields) values = [row[field] for field in fields] sql = "insert into {} ({}) values ({})".format( table, ', '.join(fields), ', '.join(['%s'] * len(fields))) return sql, values def sqldelete(table, where): """Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5]) """ validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues) def sqlwhere(criteria=None): """Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'}) ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto']) """ if not criteria: return ('', []) fields = sorted(criteria.keys()) validate_names(fields) values = [criteria[field] for field in fields] parts = [field + '=%s' for field in fields] sql = ' and '.join(parts) return (sql, values) VALID_NAME_RE = re.compile('^[a-zA-Z0-9_]+$') def validate_name(name): """Check that table/field name is valid. Raise ValueError otherwise. >>> validate_name('mytable') >>> validate_name('invalid!') Traceback (most recent call last): ... ValueError: Invalid name "invalid!" >>> validate_name('in valid') Traceback (most recent call last): ... ValueError: Invalid name "in valid" >>> validate_name('nope,nope') Traceback (most recent call last): ... ValueError: Invalid name "nope,nope" """ if not VALID_NAME_RE.match(name): raise ValueError('Invalid name "{}"'.format(name)) def validate_names(names): """Validate list of names. >>> validate_names(['id', 'field']) >>> validate_names(['id', 'b#d']) Traceback (most recent call last): ... ValueError: Invalid name "b#d" """ for name in names: validate_name(name) def parse_dburl(dburl): """Parse DB URL. Return (scheme, user, password, host, dbname) pg://user:pass@host/dbname >>> parse_dburl("pg://user:pass@host/name") ('pg', 'user', 'pass', 'host', 'name') >>> parse_dburl("dbm:///dbfile") ('dbm', '', '', '', 'dbfile') >>> parse_dburl("pg://user:@/name") ('pg', 'user', '', '', 'name') """ res = urlparse.urlparse(dburl) if '@' in res.netloc: (creds, host) = res.netloc.split('@') else: creds = ':' host = res.netloc (user, password) = creds.split(':') return (res.scheme, user, password, host, res.path[1:])
langloisjp/tstore
tstore/pgtablestorage.py
sqldelete
python
def sqldelete(table, where): validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues)
Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5])
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L398-L409
[ "def validate_name(name):\n \"\"\"Check that table/field name is valid. Raise ValueError otherwise.\n\n >>> validate_name('mytable')\n >>> validate_name('invalid!')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"invalid!\"\n >>> validate_name('in valid')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"in valid\"\n >>> validate_name('nope,nope')\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"nope,nope\"\n \"\"\"\n if not VALID_NAME_RE.match(name):\n raise ValueError('Invalid name \"{}\"'.format(name))\n", "def sqlwhere(criteria=None):\n \"\"\"Generates SQL where clause. Returns (sql, values).\n Criteria is a dictionary of {field: value}.\n\n >>> sqlwhere()\n ('', [])\n >>> sqlwhere({'id': 5})\n ('id=%s', [5])\n >>> sqlwhere({'id': 3, 'name': 'toto'})\n ('id=%s and name=%s', [3, 'toto'])\n >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'})\n ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto'])\n \"\"\"\n if not criteria:\n return ('', [])\n fields = sorted(criteria.keys())\n validate_names(fields)\n values = [criteria[field] for field in fields]\n parts = [field + '=%s' for field in fields]\n sql = ' and '.join(parts)\n return (sql, values)\n" ]
""" Table storage interface to postgesql Insert, select, update, delete rows from tables. Run tests with: python -m doctest pgtablestorage.py Make sure the current user has a 'test' DB with no password: createdb test >>> import getpass >>> user = getpass.getuser() >>> s = DB(dbname='test', user=user, host='localhost', password='') >>> s.execute('drop table if exists t1') >>> s.execute(''' ... create table t1 (id text not null primary key, name text, memo text) ... ''') >>> s.select('t1') [] >>> s.insert('t1', {'id': 'toto', 'name': 'Toto', 'memo': 'Toto memo'}) >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.insert('t1', {'id': 'tata', 'name': 'Tata', 'memo': 'Tata memo'}) >>> s.select('t1', ['id', 'name']) [{'id': 'toto', 'name': 'Toto'}, {'id': 'tata', 'name': 'Tata'}] >>> s.select('t1', where={'id': 'toto'}) [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.update('t1', {'memo': 'New memo'}, {'id': 'tata'}) 1 >>> s.select('t1', ['memo'], where={'id': 'tata'}) [{'memo': 'New memo'}] >>> s.delete('t1', {'name': 'Tata'}) 1 >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] Dependencies: - psycopg2 (`pip install psycopg2`) """ import logging import urlparse import psycopg2 import psycopg2.extras import re class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall() # SQL generation def sqlselect(table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """Generates SQL select ... Returns (sql, params) >>> sqlselect('t') ('select * from t', []) >>> sqlselect('t', fields=['name', 'address']) ('select name, address from t', []) >>> sqlselect('t', where={'name': 'Toto', 'country': 'US'}) ('select * from t where country=%s and name=%s', ['US', 'Toto']) >>> sqlselect('t', orderby=['lastname', 'firstname']) ('select * from t order by lastname, firstname', []) >>> sqlselect('t', limit=1) ('select * from t limit 1', []) >>> sqlselect('t', limit='yes') Traceback (most recent call last): ... ValueError: Limit parameter must be an int >>> sqlselect('t', offset=20) ('select * from t offset 20', []) >>> sqlselect('t', offset='yes') Traceback (most recent call last): ... ValueError: Offset parameter must be an int """ validate_name(table) if fields != ['*']: validate_names(fields) fieldspart = ', '.join(fields) sql = "select {} from {}".format(fieldspart, table) values = [] if where: (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause values = wherevalues if orderby: validate_names(orderby) sql = sql + " order by " + ', '.join(orderby) if limit: if not isinstance(limit, int): raise ValueError("Limit parameter must be an int") sql = sql + " limit {}".format(limit) if offset: if not isinstance(offset, int): raise ValueError("Offset parameter must be an int") sql = sql + " offset {}".format(offset) return (sql, values) def sqlinsert(table, row): """Generates SQL insert into table ... Returns (sql, parameters) >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'}) ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto']) >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'}) ('insert into t2 (id, name) values (%s, %s)', [1, 'Toto']) """ validate_name(table) fields = sorted(row.keys()) validate_names(fields) values = [row[field] for field in fields] sql = "insert into {} ({}) values ({})".format( table, ', '.join(fields), ', '.join(['%s'] * len(fields))) return sql, values def sqlupdate(table, rowupdate, where): """Generates SQL update table set ... Returns (sql, parameters) >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5}) ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5]) """ validate_name(table) fields = sorted(rowupdate.keys()) validate_names(fields) values = [rowupdate[field] for field in fields] setparts = [field + '=%s' for field in fields] setclause = ', '.join(setparts) sql = "update {} set ".format(table) + setclause (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause return (sql, values + wherevalues) def sqlwhere(criteria=None): """Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'}) ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto']) """ if not criteria: return ('', []) fields = sorted(criteria.keys()) validate_names(fields) values = [criteria[field] for field in fields] parts = [field + '=%s' for field in fields] sql = ' and '.join(parts) return (sql, values) VALID_NAME_RE = re.compile('^[a-zA-Z0-9_]+$') def validate_name(name): """Check that table/field name is valid. Raise ValueError otherwise. >>> validate_name('mytable') >>> validate_name('invalid!') Traceback (most recent call last): ... ValueError: Invalid name "invalid!" >>> validate_name('in valid') Traceback (most recent call last): ... ValueError: Invalid name "in valid" >>> validate_name('nope,nope') Traceback (most recent call last): ... ValueError: Invalid name "nope,nope" """ if not VALID_NAME_RE.match(name): raise ValueError('Invalid name "{}"'.format(name)) def validate_names(names): """Validate list of names. >>> validate_names(['id', 'field']) >>> validate_names(['id', 'b#d']) Traceback (most recent call last): ... ValueError: Invalid name "b#d" """ for name in names: validate_name(name) def parse_dburl(dburl): """Parse DB URL. Return (scheme, user, password, host, dbname) pg://user:pass@host/dbname >>> parse_dburl("pg://user:pass@host/name") ('pg', 'user', 'pass', 'host', 'name') >>> parse_dburl("dbm:///dbfile") ('dbm', '', '', '', 'dbfile') >>> parse_dburl("pg://user:@/name") ('pg', 'user', '', '', 'name') """ res = urlparse.urlparse(dburl) if '@' in res.netloc: (creds, host) = res.netloc.split('@') else: creds = ':' host = res.netloc (user, password) = creds.split(':') return (res.scheme, user, password, host, res.path[1:])
langloisjp/tstore
tstore/pgtablestorage.py
sqlwhere
python
def sqlwhere(criteria=None): if not criteria: return ('', []) fields = sorted(criteria.keys()) validate_names(fields) values = [criteria[field] for field in fields] parts = [field + '=%s' for field in fields] sql = ' and '.join(parts) return (sql, values)
Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'}) ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto'])
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L412-L432
[ "def validate_names(names):\n \"\"\"Validate list of names.\n\n >>> validate_names(['id', 'field'])\n >>> validate_names(['id', 'b#d'])\n Traceback (most recent call last):\n ...\n ValueError: Invalid name \"b#d\"\n \"\"\"\n for name in names:\n validate_name(name)\n" ]
""" Table storage interface to postgesql Insert, select, update, delete rows from tables. Run tests with: python -m doctest pgtablestorage.py Make sure the current user has a 'test' DB with no password: createdb test >>> import getpass >>> user = getpass.getuser() >>> s = DB(dbname='test', user=user, host='localhost', password='') >>> s.execute('drop table if exists t1') >>> s.execute(''' ... create table t1 (id text not null primary key, name text, memo text) ... ''') >>> s.select('t1') [] >>> s.insert('t1', {'id': 'toto', 'name': 'Toto', 'memo': 'Toto memo'}) >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.insert('t1', {'id': 'tata', 'name': 'Tata', 'memo': 'Tata memo'}) >>> s.select('t1', ['id', 'name']) [{'id': 'toto', 'name': 'Toto'}, {'id': 'tata', 'name': 'Tata'}] >>> s.select('t1', where={'id': 'toto'}) [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.update('t1', {'memo': 'New memo'}, {'id': 'tata'}) 1 >>> s.select('t1', ['memo'], where={'id': 'tata'}) [{'memo': 'New memo'}] >>> s.delete('t1', {'name': 'Tata'}) 1 >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] Dependencies: - psycopg2 (`pip install psycopg2`) """ import logging import urlparse import psycopg2 import psycopg2.extras import re class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall() # SQL generation def sqlselect(table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """Generates SQL select ... Returns (sql, params) >>> sqlselect('t') ('select * from t', []) >>> sqlselect('t', fields=['name', 'address']) ('select name, address from t', []) >>> sqlselect('t', where={'name': 'Toto', 'country': 'US'}) ('select * from t where country=%s and name=%s', ['US', 'Toto']) >>> sqlselect('t', orderby=['lastname', 'firstname']) ('select * from t order by lastname, firstname', []) >>> sqlselect('t', limit=1) ('select * from t limit 1', []) >>> sqlselect('t', limit='yes') Traceback (most recent call last): ... ValueError: Limit parameter must be an int >>> sqlselect('t', offset=20) ('select * from t offset 20', []) >>> sqlselect('t', offset='yes') Traceback (most recent call last): ... ValueError: Offset parameter must be an int """ validate_name(table) if fields != ['*']: validate_names(fields) fieldspart = ', '.join(fields) sql = "select {} from {}".format(fieldspart, table) values = [] if where: (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause values = wherevalues if orderby: validate_names(orderby) sql = sql + " order by " + ', '.join(orderby) if limit: if not isinstance(limit, int): raise ValueError("Limit parameter must be an int") sql = sql + " limit {}".format(limit) if offset: if not isinstance(offset, int): raise ValueError("Offset parameter must be an int") sql = sql + " offset {}".format(offset) return (sql, values) def sqlinsert(table, row): """Generates SQL insert into table ... Returns (sql, parameters) >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'}) ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto']) >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'}) ('insert into t2 (id, name) values (%s, %s)', [1, 'Toto']) """ validate_name(table) fields = sorted(row.keys()) validate_names(fields) values = [row[field] for field in fields] sql = "insert into {} ({}) values ({})".format( table, ', '.join(fields), ', '.join(['%s'] * len(fields))) return sql, values def sqlupdate(table, rowupdate, where): """Generates SQL update table set ... Returns (sql, parameters) >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5}) ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5]) """ validate_name(table) fields = sorted(rowupdate.keys()) validate_names(fields) values = [rowupdate[field] for field in fields] setparts = [field + '=%s' for field in fields] setclause = ', '.join(setparts) sql = "update {} set ".format(table) + setclause (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause return (sql, values + wherevalues) def sqldelete(table, where): """Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5]) """ validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues) VALID_NAME_RE = re.compile('^[a-zA-Z0-9_]+$') def validate_name(name): """Check that table/field name is valid. Raise ValueError otherwise. >>> validate_name('mytable') >>> validate_name('invalid!') Traceback (most recent call last): ... ValueError: Invalid name "invalid!" >>> validate_name('in valid') Traceback (most recent call last): ... ValueError: Invalid name "in valid" >>> validate_name('nope,nope') Traceback (most recent call last): ... ValueError: Invalid name "nope,nope" """ if not VALID_NAME_RE.match(name): raise ValueError('Invalid name "{}"'.format(name)) def validate_names(names): """Validate list of names. >>> validate_names(['id', 'field']) >>> validate_names(['id', 'b#d']) Traceback (most recent call last): ... ValueError: Invalid name "b#d" """ for name in names: validate_name(name) def parse_dburl(dburl): """Parse DB URL. Return (scheme, user, password, host, dbname) pg://user:pass@host/dbname >>> parse_dburl("pg://user:pass@host/name") ('pg', 'user', 'pass', 'host', 'name') >>> parse_dburl("dbm:///dbfile") ('dbm', '', '', '', 'dbfile') >>> parse_dburl("pg://user:@/name") ('pg', 'user', '', '', 'name') """ res = urlparse.urlparse(dburl) if '@' in res.netloc: (creds, host) = res.netloc.split('@') else: creds = ':' host = res.netloc (user, password) = creds.split(':') return (res.scheme, user, password, host, res.path[1:])
langloisjp/tstore
tstore/pgtablestorage.py
parse_dburl
python
def parse_dburl(dburl): res = urlparse.urlparse(dburl) if '@' in res.netloc: (creds, host) = res.netloc.split('@') else: creds = ':' host = res.netloc (user, password) = creds.split(':') return (res.scheme, user, password, host, res.path[1:])
Parse DB URL. Return (scheme, user, password, host, dbname) pg://user:pass@host/dbname >>> parse_dburl("pg://user:pass@host/name") ('pg', 'user', 'pass', 'host', 'name') >>> parse_dburl("dbm:///dbfile") ('dbm', '', '', '', 'dbfile') >>> parse_dburl("pg://user:@/name") ('pg', 'user', '', '', 'name')
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L472-L492
null
""" Table storage interface to postgesql Insert, select, update, delete rows from tables. Run tests with: python -m doctest pgtablestorage.py Make sure the current user has a 'test' DB with no password: createdb test >>> import getpass >>> user = getpass.getuser() >>> s = DB(dbname='test', user=user, host='localhost', password='') >>> s.execute('drop table if exists t1') >>> s.execute(''' ... create table t1 (id text not null primary key, name text, memo text) ... ''') >>> s.select('t1') [] >>> s.insert('t1', {'id': 'toto', 'name': 'Toto', 'memo': 'Toto memo'}) >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.insert('t1', {'id': 'tata', 'name': 'Tata', 'memo': 'Tata memo'}) >>> s.select('t1', ['id', 'name']) [{'id': 'toto', 'name': 'Toto'}, {'id': 'tata', 'name': 'Tata'}] >>> s.select('t1', where={'id': 'toto'}) [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] >>> s.update('t1', {'memo': 'New memo'}, {'id': 'tata'}) 1 >>> s.select('t1', ['memo'], where={'id': 'tata'}) [{'memo': 'New memo'}] >>> s.delete('t1', {'name': 'Tata'}) 1 >>> s.select('t1') [{'memo': 'Toto memo', 'id': 'toto', 'name': 'Toto'}] Dependencies: - psycopg2 (`pip install psycopg2`) """ import logging import urlparse import psycopg2 import psycopg2.extras import re class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall() # SQL generation def sqlselect(table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """Generates SQL select ... Returns (sql, params) >>> sqlselect('t') ('select * from t', []) >>> sqlselect('t', fields=['name', 'address']) ('select name, address from t', []) >>> sqlselect('t', where={'name': 'Toto', 'country': 'US'}) ('select * from t where country=%s and name=%s', ['US', 'Toto']) >>> sqlselect('t', orderby=['lastname', 'firstname']) ('select * from t order by lastname, firstname', []) >>> sqlselect('t', limit=1) ('select * from t limit 1', []) >>> sqlselect('t', limit='yes') Traceback (most recent call last): ... ValueError: Limit parameter must be an int >>> sqlselect('t', offset=20) ('select * from t offset 20', []) >>> sqlselect('t', offset='yes') Traceback (most recent call last): ... ValueError: Offset parameter must be an int """ validate_name(table) if fields != ['*']: validate_names(fields) fieldspart = ', '.join(fields) sql = "select {} from {}".format(fieldspart, table) values = [] if where: (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause values = wherevalues if orderby: validate_names(orderby) sql = sql + " order by " + ', '.join(orderby) if limit: if not isinstance(limit, int): raise ValueError("Limit parameter must be an int") sql = sql + " limit {}".format(limit) if offset: if not isinstance(offset, int): raise ValueError("Offset parameter must be an int") sql = sql + " offset {}".format(offset) return (sql, values) def sqlinsert(table, row): """Generates SQL insert into table ... Returns (sql, parameters) >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'}) ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto']) >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'}) ('insert into t2 (id, name) values (%s, %s)', [1, 'Toto']) """ validate_name(table) fields = sorted(row.keys()) validate_names(fields) values = [row[field] for field in fields] sql = "insert into {} ({}) values ({})".format( table, ', '.join(fields), ', '.join(['%s'] * len(fields))) return sql, values def sqlupdate(table, rowupdate, where): """Generates SQL update table set ... Returns (sql, parameters) >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5}) ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5]) """ validate_name(table) fields = sorted(rowupdate.keys()) validate_names(fields) values = [rowupdate[field] for field in fields] setparts = [field + '=%s' for field in fields] setclause = ', '.join(setparts) sql = "update {} set ".format(table) + setclause (whereclause, wherevalues) = sqlwhere(where) if whereclause: sql = sql + " where " + whereclause return (sql, values + wherevalues) def sqldelete(table, where): """Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5]) """ validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues) def sqlwhere(criteria=None): """Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2013-12-02'}) ('createdon=%s and id=%s and name=%s', ['2013-12-02', 3, 'toto']) """ if not criteria: return ('', []) fields = sorted(criteria.keys()) validate_names(fields) values = [criteria[field] for field in fields] parts = [field + '=%s' for field in fields] sql = ' and '.join(parts) return (sql, values) VALID_NAME_RE = re.compile('^[a-zA-Z0-9_]+$') def validate_name(name): """Check that table/field name is valid. Raise ValueError otherwise. >>> validate_name('mytable') >>> validate_name('invalid!') Traceback (most recent call last): ... ValueError: Invalid name "invalid!" >>> validate_name('in valid') Traceback (most recent call last): ... ValueError: Invalid name "in valid" >>> validate_name('nope,nope') Traceback (most recent call last): ... ValueError: Invalid name "nope,nope" """ if not VALID_NAME_RE.match(name): raise ValueError('Invalid name "{}"'.format(name)) def validate_names(names): """Validate list of names. >>> validate_names(['id', 'field']) >>> validate_names(['id', 'b#d']) Traceback (most recent call last): ... ValueError: Invalid name "b#d" """ for name in names: validate_name(name)
langloisjp/tstore
tstore/pgtablestorage.py
DB.select
python
def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall()
Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'}
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L98-L118
[ "def sqlselect(table, fields=['*'], where=None, orderby=None, limit=None,\n offset=None):\n \"\"\"Generates SQL select ...\n Returns (sql, params)\n\n >>> sqlselect('t')\n ('select * from t', [])\n >>> sqlselect('t', fields=['name', 'address'])\n ('select name, address from t', [])\n >>> sqlselect('t', where={'name': 'Toto', 'country': 'US'})\n ('select * from t where country=%s and name=%s', ['US', 'Toto'])\n >>> sqlselect('t', orderby=['lastname', 'firstname'])\n ('select * from t order by lastname, firstname', [])\n >>> sqlselect('t', limit=1)\n ('select * from t limit 1', [])\n >>> sqlselect('t', limit='yes')\n Traceback (most recent call last):\n ...\n ValueError: Limit parameter must be an int\n >>> sqlselect('t', offset=20)\n ('select * from t offset 20', [])\n >>> sqlselect('t', offset='yes')\n Traceback (most recent call last):\n ...\n ValueError: Offset parameter must be an int\n \"\"\"\n validate_name(table)\n if fields != ['*']:\n validate_names(fields)\n fieldspart = ', '.join(fields)\n sql = \"select {} from {}\".format(fieldspart, table)\n values = []\n\n if where:\n (whereclause, wherevalues) = sqlwhere(where)\n if whereclause:\n sql = sql + \" where \" + whereclause\n values = wherevalues\n\n if orderby:\n validate_names(orderby)\n sql = sql + \" order by \" + ', '.join(orderby)\n\n if limit:\n if not isinstance(limit, int):\n raise ValueError(\"Limit parameter must be an int\")\n sql = sql + \" limit {}\".format(limit)\n\n if offset:\n if not isinstance(offset, int):\n raise ValueError(\"Offset parameter must be an int\")\n sql = sql + \" offset {}\".format(offset)\n\n return (sql, values)\n", "def execute(self, sql, params=None):\n \"\"\"\n Execute given SQL.\n Calls `rollback` if there's a DB error and re-raises the exception.\n Calls `commit` if autocommit is True and there was no error.\n Returns number of rows affected (for commands that affect rows).\n\n >>> import getpass\n >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost',\n ... password='')\n >>> s.execute('drop table if exists t2')\n >>> s.execute('drop table t2')\n Traceback (most recent call last):\n ...\n ProgrammingError: table \"t2\" does not exist\n <BLANKLINE>\n \"\"\"\n logging.debug(sql)\n try:\n self._cursor.execute(sql, params)\n if self.autocommit:\n self._conn.commit()\n if self._cursor.rowcount > 0:\n return self._cursor.rowcount\n except psycopg2.Error, error:\n logging.debug('PG error ({}): {}'.format(\n error.pgcode, error.pgerror))\n self._conn.rollback()\n raise\n", "def fetchall(self):\n \"\"\"\n Fetch all rows from the current cursor.\n\n >>> import getpass\n >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost',\n ... password='')\n >>> s.execute('drop table if exists t2')\n >>> s.execute('create table t2 (id int, name text)')\n >>> s.insert('t2', {'id': 1, 'name': 'Toto'})\n >>> s.execute('select * from t2')\n 1\n >>> s.fetchall()\n [{'id': 1, 'name': 'Toto'}]\n >>> s.fetchall()\n []\n \"\"\"\n return self._cursor.fetchall()\n" ]
class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall()
langloisjp/tstore
tstore/pgtablestorage.py
DB.insert
python
def insert(self, table, row): (sql, values) = sqlinsert(table, row) self.execute(sql, values)
Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'}
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L120-L138
[ "def sqlinsert(table, row):\n \"\"\"Generates SQL insert into table ...\n Returns (sql, parameters)\n\n >>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'})\n ('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto'])\n >>> sqlinsert('t2', {'id': 1, 'name': 'Toto'})\n ('insert into t2 (id, name) values (%s, %s)', [1, 'Toto'])\n \"\"\"\n validate_name(table)\n fields = sorted(row.keys())\n validate_names(fields)\n values = [row[field] for field in fields]\n sql = \"insert into {} ({}) values ({})\".format(\n table, ', '.join(fields), ', '.join(['%s'] * len(fields)))\n return sql, values\n", "def execute(self, sql, params=None):\n \"\"\"\n Execute given SQL.\n Calls `rollback` if there's a DB error and re-raises the exception.\n Calls `commit` if autocommit is True and there was no error.\n Returns number of rows affected (for commands that affect rows).\n\n >>> import getpass\n >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost',\n ... password='')\n >>> s.execute('drop table if exists t2')\n >>> s.execute('drop table t2')\n Traceback (most recent call last):\n ...\n ProgrammingError: table \"t2\" does not exist\n <BLANKLINE>\n \"\"\"\n logging.debug(sql)\n try:\n self._cursor.execute(sql, params)\n if self.autocommit:\n self._conn.commit()\n if self._cursor.rowcount > 0:\n return self._cursor.rowcount\n except psycopg2.Error, error:\n logging.debug('PG error ({}): {}'.format(\n error.pgcode, error.pgerror))\n self._conn.rollback()\n raise\n" ]
class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall()
langloisjp/tstore
tstore/pgtablestorage.py
DB.update
python
def update(self, table, rowupdate, where): (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values)
Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}]
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L140-L162
[ "def sqlupdate(table, rowupdate, where):\n \"\"\"Generates SQL update table set ...\n Returns (sql, parameters)\n\n >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5})\n ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5])\n \"\"\"\n validate_name(table)\n fields = sorted(rowupdate.keys())\n validate_names(fields)\n values = [rowupdate[field] for field in fields]\n setparts = [field + '=%s' for field in fields]\n setclause = ', '.join(setparts)\n sql = \"update {} set \".format(table) + setclause\n (whereclause, wherevalues) = sqlwhere(where)\n if whereclause:\n sql = sql + \" where \" + whereclause\n return (sql, values + wherevalues)\n", "def execute(self, sql, params=None):\n \"\"\"\n Execute given SQL.\n Calls `rollback` if there's a DB error and re-raises the exception.\n Calls `commit` if autocommit is True and there was no error.\n Returns number of rows affected (for commands that affect rows).\n\n >>> import getpass\n >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost',\n ... password='')\n >>> s.execute('drop table if exists t2')\n >>> s.execute('drop table t2')\n Traceback (most recent call last):\n ...\n ProgrammingError: table \"t2\" does not exist\n <BLANKLINE>\n \"\"\"\n logging.debug(sql)\n try:\n self._cursor.execute(sql, params)\n if self.autocommit:\n self._conn.commit()\n if self._cursor.rowcount > 0:\n return self._cursor.rowcount\n except psycopg2.Error, error:\n logging.debug('PG error ({}): {}'.format(\n error.pgcode, error.pgerror))\n self._conn.rollback()\n raise\n" ]
class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def execute(self, sql, params=None): """ Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE> """ logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall()
langloisjp/tstore
tstore/pgtablestorage.py
DB.execute
python
def execute(self, sql, params=None): logging.debug(sql) try: self._cursor.execute(sql, params) if self.autocommit: self._conn.commit() if self._cursor.rowcount > 0: return self._cursor.rowcount except psycopg2.Error, error: logging.debug('PG error ({}): {}'.format( error.pgcode, error.pgerror)) self._conn.rollback() raise
Execute given SQL. Calls `rollback` if there's a DB error and re-raises the exception. Calls `commit` if autocommit is True and there was no error. Returns number of rows affected (for commands that affect rows). >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('drop table t2') Traceback (most recent call last): ... ProgrammingError: table "t2" does not exist <BLANKLINE>
train
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L189-L217
null
class DB(object): """PG DB interface""" def __init__(self, dburl=None, host=None, dbname=None, user=None, password=None, autocommit=True): """Instantiate a new DB object. Needs parameters dbname, user, host, and password. Or, specify a DB url of the form pg://user:password@host/dbname If host is None or not specified, PG driver will connect using the default unix socket. You can change db.autocommit after the object has been instantiated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser()) >>> s = DB(dburl='pg://' + getpass.getuser() + ':@/test') >>> s = DB(dburl='mysql://:@/test') Traceback (most recent call last): ... ValueError: Unsupported DB scheme "mysql" """ if dburl: (scheme, user, password, host, dbname) = parse_dburl(dburl) if scheme != 'pg': raise ValueError('Unsupported DB scheme "{}"'.format(scheme)) self._conn = psycopg2.connect(user=user, dbname=dbname, host=host, password=password) self._cursor = self._conn.cursor( cursor_factory=psycopg2.extras.RealDictCursor) self.autocommit = autocommit def ping(self): """ Return 'ok' if can ping db or raise exception >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.ping() 'ok' """ self.execute("SELECT 1") return 'ok' def select(self, table, fields=['*'], where=None, orderby=None, limit=None, offset=None): """ Query and return list of records. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlselect(table, fields, where, orderby, limit, offset) self.execute(sql, values) return self.fetchall() def insert(self, table, row): """ Add new row. Row must be a dict or implement the mapping interface. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> rows = s.select('t2') >>> len(rows) 1 >>> row = rows[0] >>> row {'id': 1, 'name': 'Toto'} """ (sql, values) = sqlinsert(table, row) self.execute(sql, values) def update(self, table, rowupdate, where): """ Update matching records. - rowupdate is a dict with updated fields, e.g. {'name': 'John'}. - See `sqlwhere` for where clause. Returns the number of rows updated. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> s.update('t2', {'name': 'Tata'}, {'id': 1}) 1 >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] """ (sql, values) = sqlupdate(table, rowupdate, where) return self.execute(sql, values) def delete(self, table, where): """ Delete matching records. Returns the number of rows deleted. See sqlwhere for where clause. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.insert('t2', {'id': 2, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}, {'id': 2, 'name': 'Tata'}] >>> s.delete('t2', {'id': 1}) 1 >>> s.select('t2') [{'id': 2, 'name': 'Tata'}] """ (sql, values) = sqldelete(table, where) return self.execute(sql, values) # Low-level methods def commit(self): """ Commit current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.select('t2') [{'id': 1, 'name': 'Toto'}] >>> # didn't commit that last one, another connection won't see it >>> s2 = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s2.select('t2') [] >>> s.commit() # now s2 should see it >>> s2.select('t2') [{'id': 1, 'name': 'Toto'}] """ self._conn.commit() def rollback(self): """ Rollback current transaction. >>> import getpass >>> s = DB(autocommit=False, dbname='test', user=getpass.getuser(), ... host='localhost', password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.commit() >>> s.select('t2') [] >>> s.insert('t2', {'id': 1, 'name': 'Tata'}) >>> s.select('t2') [{'id': 1, 'name': 'Tata'}] >>> s.rollback() >>> s.select('t2') [] """ self._conn.rollback() def fetchone(self): """ Fetch one row from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchone() {'id': 1, 'name': 'Toto'} >>> s.fetchone() """ return self._cursor.fetchone() def fetchall(self): """ Fetch all rows from the current cursor. >>> import getpass >>> s = DB(dbname='test', user=getpass.getuser(), host='localhost', ... password='') >>> s.execute('drop table if exists t2') >>> s.execute('create table t2 (id int, name text)') >>> s.insert('t2', {'id': 1, 'name': 'Toto'}) >>> s.execute('select * from t2') 1 >>> s.fetchall() [{'id': 1, 'name': 'Toto'}] >>> s.fetchall() [] """ return self._cursor.fetchall()
jonathansick/paperweight
paperweight/gitio.py
read_git_blob
python
def read_git_blob(commit_ref, path, repo_dir='.'): repo = git.Repo(repo_dir) tree = repo.tree(commit_ref) dirname, fname = os.path.split(path) text = None if dirname == '': text = _read_blob(tree, fname) else: components = path.split(os.sep) text = _read_blob_in_tree(tree, components) return text
Get text from a git blob. Parameters ---------- commit_ref : str Any SHA or git tag that can resolve into a commit in the git repository. path : str Path to the document in the git repository, relative to the root of the repository. repo_dir : str Path from current working directory to the root of the git repository. Returns ------- text : unicode The document text.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/gitio.py#L14-L42
[ "def _read_blob(tree, filename):\n for blb in tree.blobs:\n if blb.name == filename:\n txt = unicode(blb.data_stream.read(), 'utf-8')\n # txt = txt.encode('utf-8')\n return txt\n return None\n", "def _read_blob_in_tree(tree, components):\n \"\"\"Recursively open trees to ultimately read a blob\"\"\"\n if len(components) == 1:\n # Tree is direct parent of blob\n return _read_blob(tree, components[0])\n else:\n # Still trees to open\n dirname = components.pop(0)\n for t in tree.traverse():\n if t.name == dirname:\n return _read_blob_in_tree(t, components)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ Utilities for reading content in git repositories. """ import git import os __all__ = ['read_git_blob', 'absolute_git_root_dir'] def _read_blob_in_tree(tree, components): """Recursively open trees to ultimately read a blob""" if len(components) == 1: # Tree is direct parent of blob return _read_blob(tree, components[0]) else: # Still trees to open dirname = components.pop(0) for t in tree.traverse(): if t.name == dirname: return _read_blob_in_tree(t, components) def _read_blob(tree, filename): for blb in tree.blobs: if blb.name == filename: txt = unicode(blb.data_stream.read(), 'utf-8') # txt = txt.encode('utf-8') return txt return None def absolute_git_root_dir(fpath=""): """Absolute path to the git root directory containing a given file or directory. """ if len(fpath) == 0: dirname_str = os.getcwd() else: dirname_str = os.path.dirname(fpath) dirname_str = os.path.abspath(dirname_str) dirnames = dirname_str.split(os.sep) n = len(dirnames) for i in xrange(n): # is there a .git directory at this level? # FIXME hack basedir = "/" + os.path.join(*dirnames[0:n - i]) gitdir = os.path.join(basedir, ".git") if os.path.exists(gitdir): return basedir
jonathansick/paperweight
paperweight/gitio.py
_read_blob_in_tree
python
def _read_blob_in_tree(tree, components): if len(components) == 1: # Tree is direct parent of blob return _read_blob(tree, components[0]) else: # Still trees to open dirname = components.pop(0) for t in tree.traverse(): if t.name == dirname: return _read_blob_in_tree(t, components)
Recursively open trees to ultimately read a blob
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/gitio.py#L45-L55
null
#!/usr/bin/env python # encoding: utf-8 """ Utilities for reading content in git repositories. """ import git import os __all__ = ['read_git_blob', 'absolute_git_root_dir'] def read_git_blob(commit_ref, path, repo_dir='.'): """Get text from a git blob. Parameters ---------- commit_ref : str Any SHA or git tag that can resolve into a commit in the git repository. path : str Path to the document in the git repository, relative to the root of the repository. repo_dir : str Path from current working directory to the root of the git repository. Returns ------- text : unicode The document text. """ repo = git.Repo(repo_dir) tree = repo.tree(commit_ref) dirname, fname = os.path.split(path) text = None if dirname == '': text = _read_blob(tree, fname) else: components = path.split(os.sep) text = _read_blob_in_tree(tree, components) return text def _read_blob(tree, filename): for blb in tree.blobs: if blb.name == filename: txt = unicode(blb.data_stream.read(), 'utf-8') # txt = txt.encode('utf-8') return txt return None def absolute_git_root_dir(fpath=""): """Absolute path to the git root directory containing a given file or directory. """ if len(fpath) == 0: dirname_str = os.getcwd() else: dirname_str = os.path.dirname(fpath) dirname_str = os.path.abspath(dirname_str) dirnames = dirname_str.split(os.sep) n = len(dirnames) for i in xrange(n): # is there a .git directory at this level? # FIXME hack basedir = "/" + os.path.join(*dirnames[0:n - i]) gitdir = os.path.join(basedir, ".git") if os.path.exists(gitdir): return basedir
jonathansick/paperweight
paperweight/gitio.py
absolute_git_root_dir
python
def absolute_git_root_dir(fpath=""): if len(fpath) == 0: dirname_str = os.getcwd() else: dirname_str = os.path.dirname(fpath) dirname_str = os.path.abspath(dirname_str) dirnames = dirname_str.split(os.sep) n = len(dirnames) for i in xrange(n): # is there a .git directory at this level? # FIXME hack basedir = "/" + os.path.join(*dirnames[0:n - i]) gitdir = os.path.join(basedir, ".git") if os.path.exists(gitdir): return basedir
Absolute path to the git root directory containing a given file or directory.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/gitio.py#L67-L84
null
#!/usr/bin/env python # encoding: utf-8 """ Utilities for reading content in git repositories. """ import git import os __all__ = ['read_git_blob', 'absolute_git_root_dir'] def read_git_blob(commit_ref, path, repo_dir='.'): """Get text from a git blob. Parameters ---------- commit_ref : str Any SHA or git tag that can resolve into a commit in the git repository. path : str Path to the document in the git repository, relative to the root of the repository. repo_dir : str Path from current working directory to the root of the git repository. Returns ------- text : unicode The document text. """ repo = git.Repo(repo_dir) tree = repo.tree(commit_ref) dirname, fname = os.path.split(path) text = None if dirname == '': text = _read_blob(tree, fname) else: components = path.split(os.sep) text = _read_blob_in_tree(tree, components) return text def _read_blob_in_tree(tree, components): """Recursively open trees to ultimately read a blob""" if len(components) == 1: # Tree is direct parent of blob return _read_blob(tree, components[0]) else: # Still trees to open dirname = components.pop(0) for t in tree.traverse(): if t.name == dirname: return _read_blob_in_tree(t, components) def _read_blob(tree, filename): for blb in tree.blobs: if blb.name == filename: txt = unicode(blb.data_stream.read(), 'utf-8') # txt = txt.encode('utf-8') return txt return None
jonathansick/paperweight
paperweight/document.py
TexDocument.find_input_documents
python
def find_input_documents(self): paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths
Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document).
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L54-L73
null
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.sections
python
def sections(self): sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections
List with tuples of section names and positions. Positions of section names are measured by cumulative word count.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L76-L89
[ "def wordify(text):\n \"\"\"Generate a list of words given text, removing punctuation.\n\n Parameters\n ----------\n text : unicode\n A piece of english text.\n\n Returns\n -------\n words : list\n List of words.\n \"\"\"\n stopset = set(nltk.corpus.stopwords.words('english'))\n tokens = nltk.WordPunctTokenizer().tokenize(text)\n return [w for w in tokens if w not in stopset]\n" ]
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.bib_name
python
def bib_name(self): bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name
Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``).
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L92-L101
null
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.bib_path
python
def bib_path(self): bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None
Absolute file path to the .bib bibliography document.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L104-L115
null
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.remove_comments
python
def remove_comments(self, recursive=True): self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True)
Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``).
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L117-L128
[ "def remove_comments(tex):\n \"\"\"Delete latex comments from a manuscript.\n\n Parameters\n ----------\n tex : unicode\n The latex manuscript\n\n Returns\n -------\n tex : unicode\n The manuscript without comments.\n \"\"\"\n # Expression via http://stackoverflow.com/a/13365453\n return re.sub(ur'(?<!\\\\)%.*\\n', ur'', tex)\n" ]
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.bib_keys
python
def bib_keys(self): bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys
List of all bib keys in the document (and input documents).
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L131-L144
null
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.extract_citation_context
python
def extract_citation_context(self, n_words=20): bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys
Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L146-L210
[ "def wordify(text):\n \"\"\"Generate a list of words given text, removing punctuation.\n\n Parameters\n ----------\n text : unicode\n A piece of english text.\n\n Returns\n -------\n words : list\n List of words.\n \"\"\"\n stopset = set(nltk.corpus.stopwords.words('english'))\n tokens = nltk.WordPunctTokenizer().tokenize(text)\n return [w for w in tokens if w not in stopset]\n" ]
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.write
python
def write(self, path): with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text)
Write the document's text to a ``path`` on the filesystem.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L212-L215
null
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys @property def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
jonathansick/paperweight
paperweight/document.py
TexDocument.bibitems
python
def bibitems(self): bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
List of bibitem strings appearing in the document.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L218-L244
null
class TexDocument(object): """Baseclass for a tex document. Parameters ---------- text : unicode Unicode-encoded text of the latex document. Attributes ---------- text : unicode Text of the document as a unicode string. """ def __init__(self, text): super(TexDocument, self).__init__() self.text = text self.sections self._children = OrderedDict() def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths @property def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections @property def bib_name(self): """Name of the BibTeX bibliography file (e.g., ``'mybibliography.bib'``). """ bib_name = None for match in texutils.bib_pattern.finditer(self.text): bib_name = match.group(1) if not bib_name.endswith('.bib'): bib_name = ".".join((bib_name, "bib")) return bib_name @property def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None def remove_comments(self, recursive=True): """Remove latex comments from document (modifies document in place). Parameters ---------- recursive : bool Remove comments from all input LaTeX documents (default ``True``). """ self.text = texutils.remove_comments(self.text) if recursive: for path, document in self._children.iteritems(): document.remove_comments(recursive=True) @property def bib_keys(self): """List of all bib keys in the document (and input documents).""" bib_keys = [] # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): keys = match.group(5).split(',') bib_keys += keys # Recursion for path, document in self._children.iteritems(): bib_keys += document.bib_keys bib_keys = list(set(bib_keys)) return bib_keys def extract_citation_context(self, n_words=20): """Generate a dictionary of all bib keys in the document (and input documents), with rich of metadata about the context of each citation in the document. For example, suppose ``'Sick:2014'`` is cited twice within a document. Then the dictionary returned by this method will have a length-2 list under the ``'Sick:2014'`` key. Each item in this list will be a dictionary providing metadata of the context for that citation. Fields of this dictionary are: - ``position``: (int) the cumulative word count at which the citation occurs. - ``wordsbefore``: (unicode) text occuring before the citation. - ``wordsafter``: (unicode) text occuring after the citation. - ``section``: (unicode) name of the section in which the citation occurs. Parameters ---------- n_words : int Number of words before and after the citation to extract for context. Returns ------- bib_keys : dict Dictionary, keyed by BibTeX cite key, where entires are lists of instances of citations. See above for the format of the instance metadata. """ bib_keys = defaultdict(list) # Get bib keys in this document for match in texutils.cite_pattern.finditer(self.text): textbefore = self.text[0:match.start()] textafter = self.text[match.end():-1] wordsbefore = nlputils.wordify(textbefore) wordsafter = nlputils.wordify(textafter) numwordsbefore = len(wordsbefore) # numwordsafter = len(wordsafter) containing_section = None for (section_pos, section_name) in self._sections: if section_pos < numwordsbefore: containing_section = (section_pos, section_name) citebody = match.groups() keys = (citebody[-1].replace(" ", "")).split(',') for key in keys: cite_instance = { "position": numwordsbefore, "wordsbefore": (" ".join(wordsbefore[-n_words:])), "wordsafter": (" ".join(wordsafter[:n_words])), "section": containing_section} bib_keys[key] += [cite_instance] # Recursion for path, document in self._children.iteritems(): sub_bib_keys = document.rich_bib_keys(n_words=n_words) for k, cite_instances in sub_bib_keys.iteritems(): bib_keys[k] += cite_instances return bib_keys def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text) @property
jonathansick/paperweight
paperweight/document.py
FilesystemTexDocument.inline_bbl
python
def inline_bbl(self): bbl_path = os.path.splitext(self._filepath)[0] + ".bbl" try: with codecs.open(bbl_path, 'r', encoding='utf-8') as f: bbl_text = f.read() except IOError: print("Cannot open bibliography {0}".format(bbl_path)) self.text = texutils.inline_bbl(self.text, bbl_text)
Inline a compiled bibliography (.bbl) in place of a bibliography environment. The document is modified in place.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L274-L284
[ "def inline_bbl(root_tex, bbl_tex):\n \"\"\"Inline a compiled bibliography (.bbl) in place of a bibliography\n environment.\n\n Parameters\n ----------\n root_tex : unicode\n Text to process.\n bbl_tex : unicode\n Text of bibliography file.\n\n Returns\n -------\n txt : unicode\n Text with bibliography included.\n \"\"\"\n bbl_tex = bbl_tex.replace(u'\\\\', u'\\\\\\\\')\n result = bib_pattern.sub(bbl_tex, root_tex)\n return result\n" ]
class FilesystemTexDocument(TexDocument): """A TeX document derived from a file in the filesystem. Parameters ---------- filepath : unicode Path to the '.tex' on the filesystem. recursive : bool If `True` (default), then tex documents input by this root document will be opened. """ def __init__(self, path, recursive=True): # read the tex document self._filepath = os.path.abspath(path) with codecs.open(path, 'r', encoding='utf-8') as f: text = f.read() super(FilesystemTexDocument, self).__init__(text) if recursive: child_paths = self.find_input_documents() for path in child_paths: # FIXME may need to deal with path normalization here. self._children[path] = FilesystemTexDocument(path, recursive=True) def _file_exists(self, path): return os.path.exists(path) def inline_inputs(self): """Inline all input latex files references by this document. The inlining is accomplished recursively. The document is modified in place. """ self.text = texutils.inline(self.text, os.path.dirname(self._filepath)) # Remove children self._children = {}
jonathansick/paperweight
paperweight/document.py
FilesystemTexDocument.inline_inputs
python
def inline_inputs(self): self.text = texutils.inline(self.text, os.path.dirname(self._filepath)) # Remove children self._children = {}
Inline all input latex files references by this document. The inlining is accomplished recursively. The document is modified in place.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L286-L294
[ "def inline(root_text,\n base_dir=\"\",\n replacer=None,\n ifexists_replacer=None):\n \"\"\"Inline all input latex files.\n\n The inlining is accomplished recursively. All files are opened as UTF-8\n unicode files.\n\n Parameters\n ----------\n root_txt : unicode\n Text to process (and include in-lined files).\n base_dir : str\n Base directory of file containing ``root_text``. Defaults to the\n current working directory.\n replacer : function\n Function called by :func:`re.sub` to replace ``\\input`` expressions\n with a latex document. Changeable only for testing purposes.\n ifexists_replacer : function\n Function called by :func:`re.sub` to replace ``\\InputIfExists``\n expressions with a latex document. Changeable only for\n testing purposes.\n\n Returns\n -------\n txt : unicode\n Text with referenced files included.\n \"\"\"\n def _sub_line(match):\n \"\"\"Function to be used with re.sub to inline files for each match.\"\"\"\n fname = match.group(1)\n if not fname.endswith('.tex'):\n full_fname = \".\".join((fname, 'tex'))\n else:\n full_fname = fname\n full_path = os.path.abspath(os.path.join(base_dir, full_fname))\n try:\n with codecs.open(full_path, 'r', encoding='utf-8') as f:\n included_text = f.read()\n except IOError:\n # TODO actually do logging here\n print(\"Cannot open {0} for in-lining\".format(full_path))\n return u\"\"\n else:\n # Recursively inline files\n included_text = inline(included_text, base_dir=base_dir)\n return included_text\n\n def _sub_line_ifexists(match):\n \"\"\"Function to be used with re.sub for the input_ifexists_pattern.\"\"\"\n fname = match.group(1)\n if not fname.endswith('.tex'):\n full_fname = \".\".join((fname, 'tex'))\n else:\n full_fname = fname\n full_path = os.path.abspath(os.path.join(base_dir, full_fname))\n\n if os.path.exists(full_path):\n with codecs.open(full_path, 'r', encoding='utf-8') as f:\n included_text = f.read()\n # Append extra info after input\n included_text = \"\\n\".join((included_text, match.group(2)))\n else:\n # Use the fall-back clause in InputIfExists\n included_text = match.group(3)\n # Recursively inline files\n included_text = inline(included_text, base_dir=base_dir)\n return included_text\n\n # Text processing pipline\n result = remove_comments(root_text)\n result = input_pattern.sub(_sub_line, result)\n result = include_pattern.sub(_sub_line, result)\n result = input_ifexists_pattern.sub(_sub_line_ifexists, result)\n return result\n" ]
class FilesystemTexDocument(TexDocument): """A TeX document derived from a file in the filesystem. Parameters ---------- filepath : unicode Path to the '.tex' on the filesystem. recursive : bool If `True` (default), then tex documents input by this root document will be opened. """ def __init__(self, path, recursive=True): # read the tex document self._filepath = os.path.abspath(path) with codecs.open(path, 'r', encoding='utf-8') as f: text = f.read() super(FilesystemTexDocument, self).__init__(text) if recursive: child_paths = self.find_input_documents() for path in child_paths: # FIXME may need to deal with path normalization here. self._children[path] = FilesystemTexDocument(path, recursive=True) def _file_exists(self, path): return os.path.exists(path) def inline_bbl(self): """Inline a compiled bibliography (.bbl) in place of a bibliography environment. The document is modified in place. """ bbl_path = os.path.splitext(self._filepath)[0] + ".bbl" try: with codecs.open(bbl_path, 'r', encoding='utf-8') as f: bbl_text = f.read() except IOError: print("Cannot open bibliography {0}".format(bbl_path)) self.text = texutils.inline_bbl(self.text, bbl_text)
jonathansick/paperweight
paperweight/texutils.py
find_root_tex_document
python
def find_root_tex_document(base_dir="."): log = logging.getLogger(__name__) for tex_path in iter_tex_documents(base_dir=base_dir): with codecs.open(tex_path, 'r', encoding='utf-8') as f: text = f.read() if len(docclass_pattern.findall(text)) > 0: log.debug("Found root tex {0}".format(tex_path)) return tex_path log.warning("Could not find a root .tex file") raise RootNotFound
Find the tex article in the current directory that can be considered a root. We do this by searching contents for ``'\documentclass'``. Parameters ---------- base_dir : str Directory to search for LaTeX documents, relative to the current working directory. Returns ------- tex_path : str Path to the root tex document relative to the current working directory.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L30-L54
[ "def iter_tex_documents(base_dir=\".\"):\n \"\"\"Iterate through all .tex documents in the current directory.\"\"\"\n for path, dirlist, filelist in os.walk(base_dir):\n for name in fnmatch.filter(filelist, \"*.tex\"):\n yield os.path.join(path, name)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ Utilities for maniuplating latex documents. """ import os import re import codecs import fnmatch import logging from .gitio import read_git_blob __all__ = ['find_root_tex_document', 'iter_tex_documents', 'inline', 'inline_blob', 'inline_bbl', 'remove_comments'] # ? is non-greedy cite_pattern = re.compile(ur'\\cite((.*?)((\[.*?\])*)){(.*?)}', re.UNICODE) section_pattern = re.compile(ur'\\section{(.*?)}', re.UNICODE) bib_pattern = re.compile(ur'\\bibliography{(.*?)}', re.UNICODE) input_pattern = re.compile(ur'\\input{(.*?)}', re.UNICODE) include_pattern = re.compile(ur'\\include{(.*?)}', re.UNICODE) input_ifexists_pattern = re.compile( ur'\\InputIfFileExists{(.*)}{(.*)}{(.*)}', re.UNICODE) docclass_pattern = re.compile(ur'\\documentclass(.*?){(.*?)}', re.UNICODE) def iter_tex_documents(base_dir="."): """Iterate through all .tex documents in the current directory.""" for path, dirlist, filelist in os.walk(base_dir): for name in fnmatch.filter(filelist, "*.tex"): yield os.path.join(path, name) class RootNotFound(BaseException): pass def inline_bbl(root_tex, bbl_tex): """Inline a compiled bibliography (.bbl) in place of a bibliography environment. Parameters ---------- root_tex : unicode Text to process. bbl_tex : unicode Text of bibliography file. Returns ------- txt : unicode Text with bibliography included. """ bbl_tex = bbl_tex.replace(u'\\', u'\\\\') result = bib_pattern.sub(bbl_tex, root_tex) return result def inline(root_text, base_dir="", replacer=None, ifexists_replacer=None): """Inline all input latex files. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- root_txt : unicode Text to process (and include in-lined files). base_dir : str Base directory of file containing ``root_text``. Defaults to the current working directory. replacer : function Function called by :func:`re.sub` to replace ``\input`` expressions with a latex document. Changeable only for testing purposes. ifexists_replacer : function Function called by :func:`re.sub` to replace ``\InputIfExists`` expressions with a latex document. Changeable only for testing purposes. Returns ------- txt : unicode Text with referenced files included. """ def _sub_line(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) try: with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() except IOError: # TODO actually do logging here print("Cannot open {0} for in-lining".format(full_path)) return u"" else: # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text def _sub_line_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) if os.path.exists(full_path): with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() # Append extra info after input included_text = "\n".join((included_text, match.group(2))) else: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_line, result) result = include_pattern.sub(_sub_line, result) result = input_ifexists_pattern.sub(_sub_line_ifexists, result) return result def inline_blob(commit_ref, root_text, base_dir='.', repo_dir=""): """Inline all input latex files that exist as git blobs in a tree object. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- commit_ref : str String identifying a git commit/tag. root_text : unicode Text of tex document where referenced files will be inlined. base_dir : str Directory of the master tex document, relative to the repo_dir. repo_dir : str Directory of the containing git repository. Returns ------- txt : unicode Text with referenced files included. """ def _sub_blob(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname git_rel_path = os.path.relpath(full_fname, base_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is None: # perhaps file is not in VC # FIXME need to deal with possibility # it does not exist there either with codecs.open(full_fname, 'r', encoding='utf-8') as f: included_text = f.read() # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text def _sub_blob_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname # full_fname is relative to the root_path # Make path relative to git repo root git_rel_path = os.path.relpath( os.path.join(repo_dir, base_dir, full_fname), repo_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is not None: # Append extra info after input included_text = "\n".join((included_text, match.group(2))) if included_text is None: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_blob, result) result = include_pattern.sub(_sub_blob, result) result = input_ifexists_pattern.sub(_sub_blob_ifexists, result) return result def remove_comments(tex): """Delete latex comments from a manuscript. Parameters ---------- tex : unicode The latex manuscript Returns ------- tex : unicode The manuscript without comments. """ # Expression via http://stackoverflow.com/a/13365453 return re.sub(ur'(?<!\\)%.*\n', ur'', tex)
jonathansick/paperweight
paperweight/texutils.py
iter_tex_documents
python
def iter_tex_documents(base_dir="."): for path, dirlist, filelist in os.walk(base_dir): for name in fnmatch.filter(filelist, "*.tex"): yield os.path.join(path, name)
Iterate through all .tex documents in the current directory.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L57-L61
null
#!/usr/bin/env python # encoding: utf-8 """ Utilities for maniuplating latex documents. """ import os import re import codecs import fnmatch import logging from .gitio import read_git_blob __all__ = ['find_root_tex_document', 'iter_tex_documents', 'inline', 'inline_blob', 'inline_bbl', 'remove_comments'] # ? is non-greedy cite_pattern = re.compile(ur'\\cite((.*?)((\[.*?\])*)){(.*?)}', re.UNICODE) section_pattern = re.compile(ur'\\section{(.*?)}', re.UNICODE) bib_pattern = re.compile(ur'\\bibliography{(.*?)}', re.UNICODE) input_pattern = re.compile(ur'\\input{(.*?)}', re.UNICODE) include_pattern = re.compile(ur'\\include{(.*?)}', re.UNICODE) input_ifexists_pattern = re.compile( ur'\\InputIfFileExists{(.*)}{(.*)}{(.*)}', re.UNICODE) docclass_pattern = re.compile(ur'\\documentclass(.*?){(.*?)}', re.UNICODE) def find_root_tex_document(base_dir="."): """Find the tex article in the current directory that can be considered a root. We do this by searching contents for ``'\documentclass'``. Parameters ---------- base_dir : str Directory to search for LaTeX documents, relative to the current working directory. Returns ------- tex_path : str Path to the root tex document relative to the current working directory. """ log = logging.getLogger(__name__) for tex_path in iter_tex_documents(base_dir=base_dir): with codecs.open(tex_path, 'r', encoding='utf-8') as f: text = f.read() if len(docclass_pattern.findall(text)) > 0: log.debug("Found root tex {0}".format(tex_path)) return tex_path log.warning("Could not find a root .tex file") raise RootNotFound class RootNotFound(BaseException): pass def inline_bbl(root_tex, bbl_tex): """Inline a compiled bibliography (.bbl) in place of a bibliography environment. Parameters ---------- root_tex : unicode Text to process. bbl_tex : unicode Text of bibliography file. Returns ------- txt : unicode Text with bibliography included. """ bbl_tex = bbl_tex.replace(u'\\', u'\\\\') result = bib_pattern.sub(bbl_tex, root_tex) return result def inline(root_text, base_dir="", replacer=None, ifexists_replacer=None): """Inline all input latex files. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- root_txt : unicode Text to process (and include in-lined files). base_dir : str Base directory of file containing ``root_text``. Defaults to the current working directory. replacer : function Function called by :func:`re.sub` to replace ``\input`` expressions with a latex document. Changeable only for testing purposes. ifexists_replacer : function Function called by :func:`re.sub` to replace ``\InputIfExists`` expressions with a latex document. Changeable only for testing purposes. Returns ------- txt : unicode Text with referenced files included. """ def _sub_line(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) try: with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() except IOError: # TODO actually do logging here print("Cannot open {0} for in-lining".format(full_path)) return u"" else: # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text def _sub_line_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) if os.path.exists(full_path): with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() # Append extra info after input included_text = "\n".join((included_text, match.group(2))) else: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_line, result) result = include_pattern.sub(_sub_line, result) result = input_ifexists_pattern.sub(_sub_line_ifexists, result) return result def inline_blob(commit_ref, root_text, base_dir='.', repo_dir=""): """Inline all input latex files that exist as git blobs in a tree object. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- commit_ref : str String identifying a git commit/tag. root_text : unicode Text of tex document where referenced files will be inlined. base_dir : str Directory of the master tex document, relative to the repo_dir. repo_dir : str Directory of the containing git repository. Returns ------- txt : unicode Text with referenced files included. """ def _sub_blob(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname git_rel_path = os.path.relpath(full_fname, base_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is None: # perhaps file is not in VC # FIXME need to deal with possibility # it does not exist there either with codecs.open(full_fname, 'r', encoding='utf-8') as f: included_text = f.read() # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text def _sub_blob_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname # full_fname is relative to the root_path # Make path relative to git repo root git_rel_path = os.path.relpath( os.path.join(repo_dir, base_dir, full_fname), repo_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is not None: # Append extra info after input included_text = "\n".join((included_text, match.group(2))) if included_text is None: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_blob, result) result = include_pattern.sub(_sub_blob, result) result = input_ifexists_pattern.sub(_sub_blob_ifexists, result) return result def remove_comments(tex): """Delete latex comments from a manuscript. Parameters ---------- tex : unicode The latex manuscript Returns ------- tex : unicode The manuscript without comments. """ # Expression via http://stackoverflow.com/a/13365453 return re.sub(ur'(?<!\\)%.*\n', ur'', tex)
jonathansick/paperweight
paperweight/texutils.py
inline_bbl
python
def inline_bbl(root_tex, bbl_tex): bbl_tex = bbl_tex.replace(u'\\', u'\\\\') result = bib_pattern.sub(bbl_tex, root_tex) return result
Inline a compiled bibliography (.bbl) in place of a bibliography environment. Parameters ---------- root_tex : unicode Text to process. bbl_tex : unicode Text of bibliography file. Returns ------- txt : unicode Text with bibliography included.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L68-L86
null
#!/usr/bin/env python # encoding: utf-8 """ Utilities for maniuplating latex documents. """ import os import re import codecs import fnmatch import logging from .gitio import read_git_blob __all__ = ['find_root_tex_document', 'iter_tex_documents', 'inline', 'inline_blob', 'inline_bbl', 'remove_comments'] # ? is non-greedy cite_pattern = re.compile(ur'\\cite((.*?)((\[.*?\])*)){(.*?)}', re.UNICODE) section_pattern = re.compile(ur'\\section{(.*?)}', re.UNICODE) bib_pattern = re.compile(ur'\\bibliography{(.*?)}', re.UNICODE) input_pattern = re.compile(ur'\\input{(.*?)}', re.UNICODE) include_pattern = re.compile(ur'\\include{(.*?)}', re.UNICODE) input_ifexists_pattern = re.compile( ur'\\InputIfFileExists{(.*)}{(.*)}{(.*)}', re.UNICODE) docclass_pattern = re.compile(ur'\\documentclass(.*?){(.*?)}', re.UNICODE) def find_root_tex_document(base_dir="."): """Find the tex article in the current directory that can be considered a root. We do this by searching contents for ``'\documentclass'``. Parameters ---------- base_dir : str Directory to search for LaTeX documents, relative to the current working directory. Returns ------- tex_path : str Path to the root tex document relative to the current working directory. """ log = logging.getLogger(__name__) for tex_path in iter_tex_documents(base_dir=base_dir): with codecs.open(tex_path, 'r', encoding='utf-8') as f: text = f.read() if len(docclass_pattern.findall(text)) > 0: log.debug("Found root tex {0}".format(tex_path)) return tex_path log.warning("Could not find a root .tex file") raise RootNotFound def iter_tex_documents(base_dir="."): """Iterate through all .tex documents in the current directory.""" for path, dirlist, filelist in os.walk(base_dir): for name in fnmatch.filter(filelist, "*.tex"): yield os.path.join(path, name) class RootNotFound(BaseException): pass def inline(root_text, base_dir="", replacer=None, ifexists_replacer=None): """Inline all input latex files. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- root_txt : unicode Text to process (and include in-lined files). base_dir : str Base directory of file containing ``root_text``. Defaults to the current working directory. replacer : function Function called by :func:`re.sub` to replace ``\input`` expressions with a latex document. Changeable only for testing purposes. ifexists_replacer : function Function called by :func:`re.sub` to replace ``\InputIfExists`` expressions with a latex document. Changeable only for testing purposes. Returns ------- txt : unicode Text with referenced files included. """ def _sub_line(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) try: with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() except IOError: # TODO actually do logging here print("Cannot open {0} for in-lining".format(full_path)) return u"" else: # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text def _sub_line_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) if os.path.exists(full_path): with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() # Append extra info after input included_text = "\n".join((included_text, match.group(2))) else: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_line, result) result = include_pattern.sub(_sub_line, result) result = input_ifexists_pattern.sub(_sub_line_ifexists, result) return result def inline_blob(commit_ref, root_text, base_dir='.', repo_dir=""): """Inline all input latex files that exist as git blobs in a tree object. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- commit_ref : str String identifying a git commit/tag. root_text : unicode Text of tex document where referenced files will be inlined. base_dir : str Directory of the master tex document, relative to the repo_dir. repo_dir : str Directory of the containing git repository. Returns ------- txt : unicode Text with referenced files included. """ def _sub_blob(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname git_rel_path = os.path.relpath(full_fname, base_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is None: # perhaps file is not in VC # FIXME need to deal with possibility # it does not exist there either with codecs.open(full_fname, 'r', encoding='utf-8') as f: included_text = f.read() # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text def _sub_blob_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname # full_fname is relative to the root_path # Make path relative to git repo root git_rel_path = os.path.relpath( os.path.join(repo_dir, base_dir, full_fname), repo_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is not None: # Append extra info after input included_text = "\n".join((included_text, match.group(2))) if included_text is None: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_blob, result) result = include_pattern.sub(_sub_blob, result) result = input_ifexists_pattern.sub(_sub_blob_ifexists, result) return result def remove_comments(tex): """Delete latex comments from a manuscript. Parameters ---------- tex : unicode The latex manuscript Returns ------- tex : unicode The manuscript without comments. """ # Expression via http://stackoverflow.com/a/13365453 return re.sub(ur'(?<!\\)%.*\n', ur'', tex)
jonathansick/paperweight
paperweight/texutils.py
inline
python
def inline(root_text, base_dir="", replacer=None, ifexists_replacer=None): def _sub_line(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) try: with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() except IOError: # TODO actually do logging here print("Cannot open {0} for in-lining".format(full_path)) return u"" else: # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text def _sub_line_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) if os.path.exists(full_path): with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() # Append extra info after input included_text = "\n".join((included_text, match.group(2))) else: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_line, result) result = include_pattern.sub(_sub_line, result) result = input_ifexists_pattern.sub(_sub_line_ifexists, result) return result
Inline all input latex files. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- root_txt : unicode Text to process (and include in-lined files). base_dir : str Base directory of file containing ``root_text``. Defaults to the current working directory. replacer : function Function called by :func:`re.sub` to replace ``\input`` expressions with a latex document. Changeable only for testing purposes. ifexists_replacer : function Function called by :func:`re.sub` to replace ``\InputIfExists`` expressions with a latex document. Changeable only for testing purposes. Returns ------- txt : unicode Text with referenced files included.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L89-L164
[ "def remove_comments(tex):\n \"\"\"Delete latex comments from a manuscript.\n\n Parameters\n ----------\n tex : unicode\n The latex manuscript\n\n Returns\n -------\n tex : unicode\n The manuscript without comments.\n \"\"\"\n # Expression via http://stackoverflow.com/a/13365453\n return re.sub(ur'(?<!\\\\)%.*\\n', ur'', tex)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ Utilities for maniuplating latex documents. """ import os import re import codecs import fnmatch import logging from .gitio import read_git_blob __all__ = ['find_root_tex_document', 'iter_tex_documents', 'inline', 'inline_blob', 'inline_bbl', 'remove_comments'] # ? is non-greedy cite_pattern = re.compile(ur'\\cite((.*?)((\[.*?\])*)){(.*?)}', re.UNICODE) section_pattern = re.compile(ur'\\section{(.*?)}', re.UNICODE) bib_pattern = re.compile(ur'\\bibliography{(.*?)}', re.UNICODE) input_pattern = re.compile(ur'\\input{(.*?)}', re.UNICODE) include_pattern = re.compile(ur'\\include{(.*?)}', re.UNICODE) input_ifexists_pattern = re.compile( ur'\\InputIfFileExists{(.*)}{(.*)}{(.*)}', re.UNICODE) docclass_pattern = re.compile(ur'\\documentclass(.*?){(.*?)}', re.UNICODE) def find_root_tex_document(base_dir="."): """Find the tex article in the current directory that can be considered a root. We do this by searching contents for ``'\documentclass'``. Parameters ---------- base_dir : str Directory to search for LaTeX documents, relative to the current working directory. Returns ------- tex_path : str Path to the root tex document relative to the current working directory. """ log = logging.getLogger(__name__) for tex_path in iter_tex_documents(base_dir=base_dir): with codecs.open(tex_path, 'r', encoding='utf-8') as f: text = f.read() if len(docclass_pattern.findall(text)) > 0: log.debug("Found root tex {0}".format(tex_path)) return tex_path log.warning("Could not find a root .tex file") raise RootNotFound def iter_tex_documents(base_dir="."): """Iterate through all .tex documents in the current directory.""" for path, dirlist, filelist in os.walk(base_dir): for name in fnmatch.filter(filelist, "*.tex"): yield os.path.join(path, name) class RootNotFound(BaseException): pass def inline_bbl(root_tex, bbl_tex): """Inline a compiled bibliography (.bbl) in place of a bibliography environment. Parameters ---------- root_tex : unicode Text to process. bbl_tex : unicode Text of bibliography file. Returns ------- txt : unicode Text with bibliography included. """ bbl_tex = bbl_tex.replace(u'\\', u'\\\\') result = bib_pattern.sub(bbl_tex, root_tex) return result def inline_blob(commit_ref, root_text, base_dir='.', repo_dir=""): """Inline all input latex files that exist as git blobs in a tree object. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- commit_ref : str String identifying a git commit/tag. root_text : unicode Text of tex document where referenced files will be inlined. base_dir : str Directory of the master tex document, relative to the repo_dir. repo_dir : str Directory of the containing git repository. Returns ------- txt : unicode Text with referenced files included. """ def _sub_blob(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname git_rel_path = os.path.relpath(full_fname, base_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is None: # perhaps file is not in VC # FIXME need to deal with possibility # it does not exist there either with codecs.open(full_fname, 'r', encoding='utf-8') as f: included_text = f.read() # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text def _sub_blob_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname # full_fname is relative to the root_path # Make path relative to git repo root git_rel_path = os.path.relpath( os.path.join(repo_dir, base_dir, full_fname), repo_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is not None: # Append extra info after input included_text = "\n".join((included_text, match.group(2))) if included_text is None: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_blob, result) result = include_pattern.sub(_sub_blob, result) result = input_ifexists_pattern.sub(_sub_blob_ifexists, result) return result def remove_comments(tex): """Delete latex comments from a manuscript. Parameters ---------- tex : unicode The latex manuscript Returns ------- tex : unicode The manuscript without comments. """ # Expression via http://stackoverflow.com/a/13365453 return re.sub(ur'(?<!\\)%.*\n', ur'', tex)
jonathansick/paperweight
paperweight/texutils.py
inline_blob
python
def inline_blob(commit_ref, root_text, base_dir='.', repo_dir=""): def _sub_blob(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname git_rel_path = os.path.relpath(full_fname, base_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is None: # perhaps file is not in VC # FIXME need to deal with possibility # it does not exist there either with codecs.open(full_fname, 'r', encoding='utf-8') as f: included_text = f.read() # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text def _sub_blob_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname # full_fname is relative to the root_path # Make path relative to git repo root git_rel_path = os.path.relpath( os.path.join(repo_dir, base_dir, full_fname), repo_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is not None: # Append extra info after input included_text = "\n".join((included_text, match.group(2))) if included_text is None: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_blob, result) result = include_pattern.sub(_sub_blob, result) result = input_ifexists_pattern.sub(_sub_blob_ifexists, result) return result
Inline all input latex files that exist as git blobs in a tree object. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- commit_ref : str String identifying a git commit/tag. root_text : unicode Text of tex document where referenced files will be inlined. base_dir : str Directory of the master tex document, relative to the repo_dir. repo_dir : str Directory of the containing git repository. Returns ------- txt : unicode Text with referenced files included.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L167-L246
[ "def remove_comments(tex):\n \"\"\"Delete latex comments from a manuscript.\n\n Parameters\n ----------\n tex : unicode\n The latex manuscript\n\n Returns\n -------\n tex : unicode\n The manuscript without comments.\n \"\"\"\n # Expression via http://stackoverflow.com/a/13365453\n return re.sub(ur'(?<!\\\\)%.*\\n', ur'', tex)\n" ]
#!/usr/bin/env python # encoding: utf-8 """ Utilities for maniuplating latex documents. """ import os import re import codecs import fnmatch import logging from .gitio import read_git_blob __all__ = ['find_root_tex_document', 'iter_tex_documents', 'inline', 'inline_blob', 'inline_bbl', 'remove_comments'] # ? is non-greedy cite_pattern = re.compile(ur'\\cite((.*?)((\[.*?\])*)){(.*?)}', re.UNICODE) section_pattern = re.compile(ur'\\section{(.*?)}', re.UNICODE) bib_pattern = re.compile(ur'\\bibliography{(.*?)}', re.UNICODE) input_pattern = re.compile(ur'\\input{(.*?)}', re.UNICODE) include_pattern = re.compile(ur'\\include{(.*?)}', re.UNICODE) input_ifexists_pattern = re.compile( ur'\\InputIfFileExists{(.*)}{(.*)}{(.*)}', re.UNICODE) docclass_pattern = re.compile(ur'\\documentclass(.*?){(.*?)}', re.UNICODE) def find_root_tex_document(base_dir="."): """Find the tex article in the current directory that can be considered a root. We do this by searching contents for ``'\documentclass'``. Parameters ---------- base_dir : str Directory to search for LaTeX documents, relative to the current working directory. Returns ------- tex_path : str Path to the root tex document relative to the current working directory. """ log = logging.getLogger(__name__) for tex_path in iter_tex_documents(base_dir=base_dir): with codecs.open(tex_path, 'r', encoding='utf-8') as f: text = f.read() if len(docclass_pattern.findall(text)) > 0: log.debug("Found root tex {0}".format(tex_path)) return tex_path log.warning("Could not find a root .tex file") raise RootNotFound def iter_tex_documents(base_dir="."): """Iterate through all .tex documents in the current directory.""" for path, dirlist, filelist in os.walk(base_dir): for name in fnmatch.filter(filelist, "*.tex"): yield os.path.join(path, name) class RootNotFound(BaseException): pass def inline_bbl(root_tex, bbl_tex): """Inline a compiled bibliography (.bbl) in place of a bibliography environment. Parameters ---------- root_tex : unicode Text to process. bbl_tex : unicode Text of bibliography file. Returns ------- txt : unicode Text with bibliography included. """ bbl_tex = bbl_tex.replace(u'\\', u'\\\\') result = bib_pattern.sub(bbl_tex, root_tex) return result def inline(root_text, base_dir="", replacer=None, ifexists_replacer=None): """Inline all input latex files. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters ---------- root_txt : unicode Text to process (and include in-lined files). base_dir : str Base directory of file containing ``root_text``. Defaults to the current working directory. replacer : function Function called by :func:`re.sub` to replace ``\input`` expressions with a latex document. Changeable only for testing purposes. ifexists_replacer : function Function called by :func:`re.sub` to replace ``\InputIfExists`` expressions with a latex document. Changeable only for testing purposes. Returns ------- txt : unicode Text with referenced files included. """ def _sub_line(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) try: with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() except IOError: # TODO actually do logging here print("Cannot open {0} for in-lining".format(full_path)) return u"" else: # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text def _sub_line_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) if os.path.exists(full_path): with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() # Append extra info after input included_text = "\n".join((included_text, match.group(2))) else: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_line, result) result = include_pattern.sub(_sub_line, result) result = input_ifexists_pattern.sub(_sub_line_ifexists, result) return result def remove_comments(tex): """Delete latex comments from a manuscript. Parameters ---------- tex : unicode The latex manuscript Returns ------- tex : unicode The manuscript without comments. """ # Expression via http://stackoverflow.com/a/13365453 return re.sub(ur'(?<!\\)%.*\n', ur'', tex)
jonathansick/paperweight
paperweight/nlputils.py
wordify
python
def wordify(text): stopset = set(nltk.corpus.stopwords.words('english')) tokens = nltk.WordPunctTokenizer().tokenize(text) return [w for w in tokens if w not in stopset]
Generate a list of words given text, removing punctuation. Parameters ---------- text : unicode A piece of english text. Returns ------- words : list List of words.
train
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/nlputils.py#L10-L25
null
#!/usr/bin/env python # encoding: utf-8 """ Utility functions for working with NLTK """ import nltk
vingd/vingd-api-python
vingd/client.py
Vingd.request
python
def request(self, verb, subpath, data=''): if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code)
Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception.
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L57-L118
[ "def quote(url, safe='/=:%{}'):\n return base_quote(url, safe)\n", "def quote(url, safe='/=:%{}'):\n try:\n return ascii_quote(url.encode('utf-8'), safe).encode('ascii')\n except Exception as e:\n raise Exception(\"Malformed URL: '\" + url + \"'\")\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd._extract_id_from_batch_response
python
def _extract_id_from_batch_response(r, name='id'): names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id)
Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L121-L133
null
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.kvpath
python
def kvpath(self, base, *pa, **kw): def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts)
Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2").
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L135-L151
[ "def quote(url, safe='/=:%{}'):\n return base_quote(url, safe)\n", "def quote(url, safe='/=:%{}'):\n try:\n return ascii_quote(url.encode('utf-8'), safe).encode('ascii')\n except Exception as e:\n raise Exception(\"Malformed URL: '\" + url + \"'\")\n", "def fmt(vtuple):\n typ, val = vtuple\n if not val is None:\n return safeformat(\"{:%s}\"%typ, val)\n return None\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.create_object
python
def create_object(self, name, url): r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid')
CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L153-L177
[ "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n", "def _extract_id_from_batch_response(r, name='id'):\n \"\"\"Unholy, forward-compatible, mess for extraction of id/oid from a\n soon-to-be (deprecated) batch response.\"\"\"\n names = name + 's'\n if names in r:\n # soon-to-be deprecated batch reponse\n if 'errors' in r and r['errors']:\n raise GeneralException(r['errors'][0]['desc'])\n id = r[names][0]\n else:\n # new-style simplified api response\n id = r[name]\n return int(id)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.commit_purchase
python
def commit_purchase(self, purchaseid, transferid): return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) )
DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L236-L270
[ "def safeformat(format_string, *args):\n \"\"\"String formatter with type validation. Python `format`-alike.\n\n Examples::\n\n - implicit indexing:\n\n safeformat(\"Decimal {:int}, hexadecimal {1:hex}\", 2, \"abc\")\n --> \"Decimal 2, hexadecimal abc\"\n\n - reusable arguments:\n\n safeformat(\"{:hex}. item: {0:str}\", 13)\n --> \"13. item: 13\"\n\n - safe paths:\n\n safeformat(\"objects/{:int}/tokens/{:hex}\", 123, \"ab2e36d953e7b634\")\n --> \"objects/123/tokens/ab2e36d953e7b634\"\n\n Format pattern is `{[index]:type}`, where `index` is optional argument\n index, and `type` is one of the predefined typenames (currently: `int`,\n `hex`, `str`, `ident`, `iso`, `isobasic`).\n \"\"\"\n\n def hex(x):\n \"\"\"Allow hexadecimal digits.\"\"\"\n if re.match('^[a-fA-F\\d]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-hex digits in hex number.\")\n\n def identifier(x):\n \"\"\"Allow letters, digits, underscore and minus/dash.\"\"\"\n if re.match('^[-\\w]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-identifier characters in string.\")\n\n def iso(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.isoformat()\n\n def isobasic(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.strftime(\"%Y%m%dT%H%M%S%z\")\n\n converters = {\n 'int': int,\n 'hex': hex,\n 'str': str,\n 'ident': identifier,\n 'iso': iso,\n 'isobasic': isobasic\n }\n\n argidx = count(0)\n\n def replace(match):\n idx, typ = match.group('idx', 'typ')\n\n if idx is None:\n idx = next(argidx)\n else:\n try:\n idx = int(idx)\n except:\n raise ConversionError(\"Non-integer index: '%s'.\" % idx)\n\n try:\n arg = args[idx]\n except:\n raise ConversionError(\"Index out of bounds: %d.\" % idx)\n\n try:\n conv = converters[typ]\n except:\n raise ConversionError(\"Invalid converter/type: '%s'.\" % typ)\n\n try:\n val = conv(arg)\n except:\n raise ConversionError(\"Argument '%s' not of type '%s'.\" % (arg, typ))\n\n return str(val)\n\n return re.sub(\"{(?:(?P<idx>\\d+))?:(?P<typ>\\w+)}\", replace, format_string)\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.create_order
python
def create_order(self, oid, price, context=None, expires=None): expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } }
CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L272-L340
[ "def safeformat(format_string, *args):\n \"\"\"String formatter with type validation. Python `format`-alike.\n\n Examples::\n\n - implicit indexing:\n\n safeformat(\"Decimal {:int}, hexadecimal {1:hex}\", 2, \"abc\")\n --> \"Decimal 2, hexadecimal abc\"\n\n - reusable arguments:\n\n safeformat(\"{:hex}. item: {0:str}\", 13)\n --> \"13. item: 13\"\n\n - safe paths:\n\n safeformat(\"objects/{:int}/tokens/{:hex}\", 123, \"ab2e36d953e7b634\")\n --> \"objects/123/tokens/ab2e36d953e7b634\"\n\n Format pattern is `{[index]:type}`, where `index` is optional argument\n index, and `type` is one of the predefined typenames (currently: `int`,\n `hex`, `str`, `ident`, `iso`, `isobasic`).\n \"\"\"\n\n def hex(x):\n \"\"\"Allow hexadecimal digits.\"\"\"\n if re.match('^[a-fA-F\\d]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-hex digits in hex number.\")\n\n def identifier(x):\n \"\"\"Allow letters, digits, underscore and minus/dash.\"\"\"\n if re.match('^[-\\w]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-identifier characters in string.\")\n\n def iso(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.isoformat()\n\n def isobasic(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.strftime(\"%Y%m%dT%H%M%S%z\")\n\n converters = {\n 'int': int,\n 'hex': hex,\n 'str': str,\n 'ident': identifier,\n 'iso': iso,\n 'isobasic': isobasic\n }\n\n argidx = count(0)\n\n def replace(match):\n idx, typ = match.group('idx', 'typ')\n\n if idx is None:\n idx = next(argidx)\n else:\n try:\n idx = int(idx)\n except:\n raise ConversionError(\"Non-integer index: '%s'.\" % idx)\n\n try:\n arg = args[idx]\n except:\n raise ConversionError(\"Index out of bounds: %d.\" % idx)\n\n try:\n conv = converters[typ]\n except:\n raise ConversionError(\"Invalid converter/type: '%s'.\" % typ)\n\n try:\n val = conv(arg)\n except:\n raise ConversionError(\"Argument '%s' not of type '%s'.\" % (arg, typ))\n\n return str(val)\n\n return re.sub(\"{(?:(?P<idx>\\d+))?:(?P<typ>\\w+)}\", replace, format_string)\n", "def absdatetime(ts, default=None):\n \"\"\"Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``\n fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or\n `None` if `datetime` can not be derived from `ts`).\"\"\"\n if ts is None:\n ts = default\n if isinstance(ts, dict):\n ts = timedelta(**ts)\n if isinstance(ts, timedelta):\n ts = now() + ts\n if isinstance(ts, datetime):\n return ts\n return None\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n", "def _extract_id_from_batch_response(r, name='id'):\n \"\"\"Unholy, forward-compatible, mess for extraction of id/oid from a\n soon-to-be (deprecated) batch response.\"\"\"\n names = name + 's'\n if names in r:\n # soon-to-be deprecated batch reponse\n if 'errors' in r and r['errors']:\n raise GeneralException(r['errors'][0]['desc'])\n id = r[names][0]\n else:\n # new-style simplified api response\n id = r[name]\n return int(id)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.get_orders
python
def get_orders(self, oid=None, include_expired=False, orderid=None): return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) )
FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L342-L373
[ "def safeformat(format_string, *args):\n \"\"\"String formatter with type validation. Python `format`-alike.\n\n Examples::\n\n - implicit indexing:\n\n safeformat(\"Decimal {:int}, hexadecimal {1:hex}\", 2, \"abc\")\n --> \"Decimal 2, hexadecimal abc\"\n\n - reusable arguments:\n\n safeformat(\"{:hex}. item: {0:str}\", 13)\n --> \"13. item: 13\"\n\n - safe paths:\n\n safeformat(\"objects/{:int}/tokens/{:hex}\", 123, \"ab2e36d953e7b634\")\n --> \"objects/123/tokens/ab2e36d953e7b634\"\n\n Format pattern is `{[index]:type}`, where `index` is optional argument\n index, and `type` is one of the predefined typenames (currently: `int`,\n `hex`, `str`, `ident`, `iso`, `isobasic`).\n \"\"\"\n\n def hex(x):\n \"\"\"Allow hexadecimal digits.\"\"\"\n if re.match('^[a-fA-F\\d]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-hex digits in hex number.\")\n\n def identifier(x):\n \"\"\"Allow letters, digits, underscore and minus/dash.\"\"\"\n if re.match('^[-\\w]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-identifier characters in string.\")\n\n def iso(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.isoformat()\n\n def isobasic(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.strftime(\"%Y%m%dT%H%M%S%z\")\n\n converters = {\n 'int': int,\n 'hex': hex,\n 'str': str,\n 'ident': identifier,\n 'iso': iso,\n 'isobasic': isobasic\n }\n\n argidx = count(0)\n\n def replace(match):\n idx, typ = match.group('idx', 'typ')\n\n if idx is None:\n idx = next(argidx)\n else:\n try:\n idx = int(idx)\n except:\n raise ConversionError(\"Non-integer index: '%s'.\" % idx)\n\n try:\n arg = args[idx]\n except:\n raise ConversionError(\"Index out of bounds: %d.\" % idx)\n\n try:\n conv = converters[typ]\n except:\n raise ConversionError(\"Invalid converter/type: '%s'.\" % typ)\n\n try:\n val = conv(arg)\n except:\n raise ConversionError(\"Argument '%s' not of type '%s'.\" % (arg, typ))\n\n return str(val)\n\n return re.sub(\"{(?:(?P<idx>\\d+))?:(?P<typ>\\w+)}\", replace, format_string)\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.update_object
python
def update_object(self, oid, name, url): r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid')
UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L396-L427
[ "def safeformat(format_string, *args):\n \"\"\"String formatter with type validation. Python `format`-alike.\n\n Examples::\n\n - implicit indexing:\n\n safeformat(\"Decimal {:int}, hexadecimal {1:hex}\", 2, \"abc\")\n --> \"Decimal 2, hexadecimal abc\"\n\n - reusable arguments:\n\n safeformat(\"{:hex}. item: {0:str}\", 13)\n --> \"13. item: 13\"\n\n - safe paths:\n\n safeformat(\"objects/{:int}/tokens/{:hex}\", 123, \"ab2e36d953e7b634\")\n --> \"objects/123/tokens/ab2e36d953e7b634\"\n\n Format pattern is `{[index]:type}`, where `index` is optional argument\n index, and `type` is one of the predefined typenames (currently: `int`,\n `hex`, `str`, `ident`, `iso`, `isobasic`).\n \"\"\"\n\n def hex(x):\n \"\"\"Allow hexadecimal digits.\"\"\"\n if re.match('^[a-fA-F\\d]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-hex digits in hex number.\")\n\n def identifier(x):\n \"\"\"Allow letters, digits, underscore and minus/dash.\"\"\"\n if re.match('^[-\\w]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-identifier characters in string.\")\n\n def iso(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.isoformat()\n\n def isobasic(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.strftime(\"%Y%m%dT%H%M%S%z\")\n\n converters = {\n 'int': int,\n 'hex': hex,\n 'str': str,\n 'ident': identifier,\n 'iso': iso,\n 'isobasic': isobasic\n }\n\n argidx = count(0)\n\n def replace(match):\n idx, typ = match.group('idx', 'typ')\n\n if idx is None:\n idx = next(argidx)\n else:\n try:\n idx = int(idx)\n except:\n raise ConversionError(\"Non-integer index: '%s'.\" % idx)\n\n try:\n arg = args[idx]\n except:\n raise ConversionError(\"Index out of bounds: %d.\" % idx)\n\n try:\n conv = converters[typ]\n except:\n raise ConversionError(\"Invalid converter/type: '%s'.\" % typ)\n\n try:\n val = conv(arg)\n except:\n raise ConversionError(\"Argument '%s' not of type '%s'.\" % (arg, typ))\n\n return str(val)\n\n return re.sub(\"{(?:(?P<idx>\\d+))?:(?P<typ>\\w+)}\", replace, format_string)\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n", "def _extract_id_from_batch_response(r, name='id'):\n \"\"\"Unholy, forward-compatible, mess for extraction of id/oid from a\n soon-to-be (deprecated) batch response.\"\"\"\n names = name + 's'\n if names in r:\n # soon-to-be deprecated batch reponse\n if 'errors' in r and r['errors']:\n raise GeneralException(r['errors'][0]['desc'])\n id = r[names][0]\n else:\n # new-style simplified api response\n id = r[name]\n return int(id)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.get_objects
python
def get_objects(self, oid=None, since=None, until=None, last=None, first=None): resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource)
FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L429-L473
[ "def absdatetime(ts, default=None):\n \"\"\"Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``\n fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or\n `None` if `datetime` can not be derived from `ts`).\"\"\"\n if ts is None:\n ts = default\n if isinstance(ts, dict):\n ts = timedelta(**ts)\n if isinstance(ts, timedelta):\n ts = now() + ts\n if isinstance(ts, datetime):\n return ts\n return None\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n", "def kvpath(self, base, *pa, **kw):\n \"\"\"Key-value query url builder (of the form: \"base/v0/k1=v1/k2=v2\"). \"\"\"\n def fmt(vtuple):\n typ, val = vtuple\n if not val is None:\n return safeformat(\"{:%s}\"%typ, val)\n return None\n parts = [base]\n for v in pa:\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(fv))\n for k,v in kw.items():\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(k+\"=\"+fv))\n return \"/\".join(parts)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.authorized_get_account_balance
python
def authorized_get_account_balance(self, huid): acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance'])
FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance``
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L528-L541
[ "def safeformat(format_string, *args):\n \"\"\"String formatter with type validation. Python `format`-alike.\n\n Examples::\n\n - implicit indexing:\n\n safeformat(\"Decimal {:int}, hexadecimal {1:hex}\", 2, \"abc\")\n --> \"Decimal 2, hexadecimal abc\"\n\n - reusable arguments:\n\n safeformat(\"{:hex}. item: {0:str}\", 13)\n --> \"13. item: 13\"\n\n - safe paths:\n\n safeformat(\"objects/{:int}/tokens/{:hex}\", 123, \"ab2e36d953e7b634\")\n --> \"objects/123/tokens/ab2e36d953e7b634\"\n\n Format pattern is `{[index]:type}`, where `index` is optional argument\n index, and `type` is one of the predefined typenames (currently: `int`,\n `hex`, `str`, `ident`, `iso`, `isobasic`).\n \"\"\"\n\n def hex(x):\n \"\"\"Allow hexadecimal digits.\"\"\"\n if re.match('^[a-fA-F\\d]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-hex digits in hex number.\")\n\n def identifier(x):\n \"\"\"Allow letters, digits, underscore and minus/dash.\"\"\"\n if re.match('^[-\\w]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-identifier characters in string.\")\n\n def iso(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.isoformat()\n\n def isobasic(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.strftime(\"%Y%m%dT%H%M%S%z\")\n\n converters = {\n 'int': int,\n 'hex': hex,\n 'str': str,\n 'ident': identifier,\n 'iso': iso,\n 'isobasic': isobasic\n }\n\n argidx = count(0)\n\n def replace(match):\n idx, typ = match.group('idx', 'typ')\n\n if idx is None:\n idx = next(argidx)\n else:\n try:\n idx = int(idx)\n except:\n raise ConversionError(\"Non-integer index: '%s'.\" % idx)\n\n try:\n arg = args[idx]\n except:\n raise ConversionError(\"Index out of bounds: %d.\" % idx)\n\n try:\n conv = converters[typ]\n except:\n raise ConversionError(\"Invalid converter/type: '%s'.\" % typ)\n\n try:\n val = conv(arg)\n except:\n raise ConversionError(\"Argument '%s' not of type '%s'.\" % (arg, typ))\n\n return str(val)\n\n return re.sub(\"{(?:(?P<idx>\\d+))?:(?P<typ>\\w+)}\", replace, format_string)\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.authorized_purchase_object
python
def authorized_purchase_object(self, oid, price, huid): return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True }))
Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object``
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L543-L562
[ "def safeformat(format_string, *args):\n \"\"\"String formatter with type validation. Python `format`-alike.\n\n Examples::\n\n - implicit indexing:\n\n safeformat(\"Decimal {:int}, hexadecimal {1:hex}\", 2, \"abc\")\n --> \"Decimal 2, hexadecimal abc\"\n\n - reusable arguments:\n\n safeformat(\"{:hex}. item: {0:str}\", 13)\n --> \"13. item: 13\"\n\n - safe paths:\n\n safeformat(\"objects/{:int}/tokens/{:hex}\", 123, \"ab2e36d953e7b634\")\n --> \"objects/123/tokens/ab2e36d953e7b634\"\n\n Format pattern is `{[index]:type}`, where `index` is optional argument\n index, and `type` is one of the predefined typenames (currently: `int`,\n `hex`, `str`, `ident`, `iso`, `isobasic`).\n \"\"\"\n\n def hex(x):\n \"\"\"Allow hexadecimal digits.\"\"\"\n if re.match('^[a-fA-F\\d]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-hex digits in hex number.\")\n\n def identifier(x):\n \"\"\"Allow letters, digits, underscore and minus/dash.\"\"\"\n if re.match('^[-\\w]*$', str(x)):\n return str(x)\n raise ValueError(\"Non-identifier characters in string.\")\n\n def iso(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.isoformat()\n\n def isobasic(x):\n if not isinstance(x, datetime):\n raise ValueError(\"Datetime expected.\")\n return x.strftime(\"%Y%m%dT%H%M%S%z\")\n\n converters = {\n 'int': int,\n 'hex': hex,\n 'str': str,\n 'ident': identifier,\n 'iso': iso,\n 'isobasic': isobasic\n }\n\n argidx = count(0)\n\n def replace(match):\n idx, typ = match.group('idx', 'typ')\n\n if idx is None:\n idx = next(argidx)\n else:\n try:\n idx = int(idx)\n except:\n raise ConversionError(\"Non-integer index: '%s'.\" % idx)\n\n try:\n arg = args[idx]\n except:\n raise ConversionError(\"Index out of bounds: %d.\" % idx)\n\n try:\n conv = converters[typ]\n except:\n raise ConversionError(\"Invalid converter/type: '%s'.\" % typ)\n\n try:\n val = conv(arg)\n except:\n raise ConversionError(\"Argument '%s' not of type '%s'.\" % (arg, typ))\n\n return str(val)\n\n return re.sub(\"{(?:(?P<idx>\\d+))?:(?P<typ>\\w+)}\", replace, format_string)\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.authorized_create_user
python
def authorized_create_user(self, identities=None, primary=None, permissions=None): return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions }))
Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create``
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L564-L593
[ "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.reward_user
python
def reward_user(self, huid_to, amount, description=None): return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description }))
PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L595-L625
[ "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.create_voucher
python
def create_voucher(self, amount, expires=None, message='', gid=None): expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } }
CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L627-L691
[ "def absdatetime(ts, default=None):\n \"\"\"Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``\n fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or\n `None` if `datetime` can not be derived from `ts`).\"\"\"\n if ts is None:\n ts = default\n if isinstance(ts, dict):\n ts = timedelta(**ts)\n if isinstance(ts, timedelta):\n ts = now() + ts\n if isinstance(ts, datetime):\n return ts\n return None\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.get_vouchers
python
def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource)
FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L693-L761
[ "def absdatetime(ts, default=None):\n \"\"\"Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``\n fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or\n `None` if `datetime` can not be derived from `ts`).\"\"\"\n if ts is None:\n ts = default\n if isinstance(ts, dict):\n ts = timedelta(**ts)\n if isinstance(ts, timedelta):\n ts = now() + ts\n if isinstance(ts, datetime):\n return ts\n return None\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n", "def kvpath(self, base, *pa, **kw):\n \"\"\"Key-value query url builder (of the form: \"base/v0/k1=v1/k2=v2\"). \"\"\"\n def fmt(vtuple):\n typ, val = vtuple\n if not val is None:\n return safeformat(\"{:%s}\"%typ, val)\n return None\n parts = [base]\n for v in pa:\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(fv))\n for k,v in kw.items():\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(k+\"=\"+fv))\n return \"/\".join(parts)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.get_vouchers_history
python
def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource)
FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L763-L851
[ "def absdatetime(ts, default=None):\n \"\"\"Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``\n fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or\n `None` if `datetime` can not be derived from `ts`).\"\"\"\n if ts is None:\n ts = default\n if isinstance(ts, dict):\n ts = timedelta(**ts)\n if isinstance(ts, timedelta):\n ts = now() + ts\n if isinstance(ts, datetime):\n return ts\n return None\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n", "def kvpath(self, base, *pa, **kw):\n \"\"\"Key-value query url builder (of the form: \"base/v0/k1=v1/k2=v2\"). \"\"\"\n def fmt(vtuple):\n typ, val = vtuple\n if not val is None:\n return safeformat(\"{:%s}\"%typ, val)\n return None\n parts = [base]\n for v in pa:\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(fv))\n for k,v in kw.items():\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(k+\"=\"+fv))\n return \"/\".join(parts)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/client.py
Vingd.revoke_vouchers
python
def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``)
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/client.py#L853-L925
[ "def absdatetime(ts, default=None):\n \"\"\"Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict``\n fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or\n `None` if `datetime` can not be derived from `ts`).\"\"\"\n if ts is None:\n ts = default\n if isinstance(ts, dict):\n ts = timedelta(**ts)\n if isinstance(ts, timedelta):\n ts = now() + ts\n if isinstance(ts, datetime):\n return ts\n return None\n", "def request(self, verb, subpath, data=''):\n \"\"\"\n Generic Vingd-backend authenticated request (currently HTTP Basic Auth\n over HTTPS, but OAuth1 in the future).\n\n :returns: Data ``dict``, or raises exception.\n \"\"\"\n if not self.api_key or not self.api_secret:\n raise Exception(\"Vingd authentication credentials undefined.\")\n\n endpoint = urlparse(self.api_endpoint)\n if endpoint.scheme != 'https':\n raise Exception(\"Invalid Vingd endpoint URL (non-https).\")\n\n host = endpoint.netloc.split(':')[0]\n port = 443\n path = urljoin(endpoint.path+'/', subpath)\n\n creds = \"%s:%s\" % (self.api_key, self.api_secret)\n headers = {\n 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')),\n 'User-Agent': self.USER_AGENT\n }\n try:\n conn = httplib.HTTPSConnection(host, port)\n conn.request(verb.upper(), quote(path), data, headers)\n r = conn.getresponse()\n content = r.read().decode('ascii')\n code = r.status\n conn.close()\n except httplib.HTTPException as e:\n raise InternalError('HTTP request failed! (Network error? Installation error?)')\n\n try:\n content = json.loads(content)\n except:\n raise GeneralException(content, 'Non-JSON server response', code)\n\n if 200 <= code <= 299:\n try:\n return content['data']\n except:\n raise InvalidData('Invalid server DATA response format!')\n\n try:\n message = content['message']\n context = content['context']\n except:\n raise InvalidData('Invalid server ERROR response format!')\n\n if code == Codes.BAD_REQUEST:\n raise InvalidData(message, context)\n elif code == Codes.FORBIDDEN:\n raise Forbidden(message, context)\n elif code == Codes.NOT_FOUND:\n raise NotFound(message, context)\n elif code == Codes.INTERNAL_SERVER_ERROR:\n raise InternalError(message, context)\n elif code == Codes.CONFLICT:\n raise GeneralException(message, context)\n\n raise GeneralException(message, context, code)\n", "def kvpath(self, base, *pa, **kw):\n \"\"\"Key-value query url builder (of the form: \"base/v0/k1=v1/k2=v2\"). \"\"\"\n def fmt(vtuple):\n typ, val = vtuple\n if not val is None:\n return safeformat(\"{:%s}\"%typ, val)\n return None\n parts = [base]\n for v in pa:\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(fv))\n for k,v in kw.items():\n fv = fmt(v)\n if not fv is None:\n parts.append(quote(k+\"=\"+fv))\n return \"/\".join(parts)\n" ]
class Vingd: # production urls URL_ENDPOINT = "https://api.vingd.com/broker/v1" URL_FRONTEND = "https://www.vingd.com" # sandbox urls URL_ENDPOINT_SANDBOX = "https://api.vingd.com/sandbox/broker/v1" URL_FRONTEND_SANDBOX = "https://www.sandbox.vingd.com" EXP_ORDER = {'minutes': 15} EXP_VOUCHER = {'days': 7} USER_AGENT = 'vingd-api-python/'+__version__ api_key = None api_secret = None api_endpoint = URL_ENDPOINT usr_frontend = URL_FRONTEND def __init__(self, key=None, secret=None, endpoint=None, frontend=None, username=None, password=None): # `key`, `secret` are forward compatible arguments (we'll switch to oauth soon) self.api_key = key or username self.api_secret = secret or hash(password) if not self.api_key or not self.api_secret: raise Exception("API key/username and/or API secret/password undefined.") if endpoint: self.api_endpoint = endpoint if frontend: self.usr_frontend = frontend def request(self, verb, subpath, data=''): """ Generic Vingd-backend authenticated request (currently HTTP Basic Auth over HTTPS, but OAuth1 in the future). :returns: Data ``dict``, or raises exception. """ if not self.api_key or not self.api_secret: raise Exception("Vingd authentication credentials undefined.") endpoint = urlparse(self.api_endpoint) if endpoint.scheme != 'https': raise Exception("Invalid Vingd endpoint URL (non-https).") host = endpoint.netloc.split(':')[0] port = 443 path = urljoin(endpoint.path+'/', subpath) creds = "%s:%s" % (self.api_key, self.api_secret) headers = { 'Authorization': b'Basic ' + base64.b64encode(creds.encode('ascii')), 'User-Agent': self.USER_AGENT } try: conn = httplib.HTTPSConnection(host, port) conn.request(verb.upper(), quote(path), data, headers) r = conn.getresponse() content = r.read().decode('ascii') code = r.status conn.close() except httplib.HTTPException as e: raise InternalError('HTTP request failed! (Network error? Installation error?)') try: content = json.loads(content) except: raise GeneralException(content, 'Non-JSON server response', code) if 200 <= code <= 299: try: return content['data'] except: raise InvalidData('Invalid server DATA response format!') try: message = content['message'] context = content['context'] except: raise InvalidData('Invalid server ERROR response format!') if code == Codes.BAD_REQUEST: raise InvalidData(message, context) elif code == Codes.FORBIDDEN: raise Forbidden(message, context) elif code == Codes.NOT_FOUND: raise NotFound(message, context) elif code == Codes.INTERNAL_SERVER_ERROR: raise InternalError(message, context) elif code == Codes.CONFLICT: raise GeneralException(message, context) raise GeneralException(message, context, code) @staticmethod def _extract_id_from_batch_response(r, name='id'): """Unholy, forward-compatible, mess for extraction of id/oid from a soon-to-be (deprecated) batch response.""" names = name + 's' if names in r: # soon-to-be deprecated batch reponse if 'errors' in r and r['errors']: raise GeneralException(r['errors'][0]['desc']) id = r[names][0] else: # new-style simplified api response id = r[name] return int(id) def kvpath(self, base, *pa, **kw): """Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2"). """ def fmt(vtuple): typ, val = vtuple if not val is None: return safeformat("{:%s}"%typ, val) return None parts = [base] for v in pa: fv = fmt(v) if not fv is None: parts.append(quote(fv)) for k,v in kw.items(): fv = fmt(v) if not fv is None: parts.append(quote(k+"="+fv)) return "/".join(parts) def create_object(self, name, url): """ CREATES a single object in Vingd Object registry. :type name: ``string`` :param name: Object's name. :type url: ``string`` :param url: Callback URL (object's resource location - on your server). :rtype: `bigint` :returns: Object ID for the newly created object. :raises GeneralException:s :resource: ``registry/objects/`` :access: authorized users """ r = self.request('post', 'registry/objects/', json.dumps({ 'description': { 'name': name, 'url': url } })) return self._extract_id_from_batch_response(r, 'oid') def verify_purchase(self, oid, tid): """ VERIFIES token ``tid`` and returns token data associated with ``tid`` and bound to object ``oid``. At the same time decrements entitlement validity counter for ``oid`` and ``uid`` bound to this token. :type oid: ``bigint`` :param oid: Object ID. :type tid: ``alphanumeric(40)`` :param tid: Token ID. :rtype: ``dict`` :returns: A single token data dictionary:: token = { "object": <object_name>, "huid": <hashed_user_id_bound_to_seller> / None, "context": <order_context> / None, ... } where: * ``object`` is object's name, as stored in object's ``description['name']`` Registry entry, at the time of token creation/purchase (i.e. if object changes its name in the meantime, ``object`` field will hold the old/obsolete name). * ``huid`` is Hashed User ID - The unique ID for a user, bound to the object owner/seller. Each user/buyer of the ``oid`` gets an arbitrary (random) identification alphanumeric handle associated with her, such that ``huid`` is unique in the set of all buyers (users) of all of the seller's objects. In other words, each seller can treat a retrieved ``huid`` as unique in his little microcosm of all of his users. On the other hand, that same ``huid`` has absolutely no meaning to anyone else -- and user's privacy is guaranteed. Also, note that the value of ``huid`` **will be** ``null`` iff buyer chose anonymous purchase. * ``context`` is an arbitrary purchase context defined when creating order. :raises GeneralException: :raises Forbidden: User no longer entitled to ``oid`` (count-wise). :see: `commit_purchase`. :resource: ``objects/<oid>/tokens/<tid>`` :access: authenticated user MUST be the object's owner """ return self.request( 'get', safeformat('objects/{:int}/tokens/{:hex}', oid, tid) ) def commit_purchase(self, purchaseid, transferid): """ DECLARES a purchase defined with ``purchaseid`` (bound to vingd transfer referenced by ``transferid``) as finished, with user being granted the access to the service or goods. If seller fails to commit the purchase, the user (buyer) shall be refunded full amount paid (reserved). :type purchaseid: ``bigint`` :param purchaseid: Purchase ID, as returned in purchase description, upon token/purchase verification. :type transferid: ``bigint`` :param transferid: Transfer ID, as returned in purchase description, upon token/purchase verification. :rtype: ``dict`` :returns: ``{'ok': <boolean>}``. :raises InvalidData: invalid format of input parameters :raises NotFound: non-existing order/purchase/transfer :raises GeneralException: depends on details of error :raises InternalError: Vingd internal error (network, server, app) :see: `verify_purchase`. :resource: ``purchases/<purchaseid>`` :access: authorized users (ACL flag: ``type.business``) """ return self.request( 'put', safeformat('purchases/{:int}', purchaseid), json.dumps({'transferid': transferid}) ) def create_order(self, oid, price, context=None, expires=None): """ CREATES a single order for object ``oid``, with price set to ``price`` and validity until ``expires``. :type oid: ``bigint`` :param oid: Object ID. :type price: ``bigint`` :param price: Vingd amount (in cents) the user/buyer shall be charged upon successful purchase. :type context: ``string`` :param context: Purchase (order-related) context. Retrieved upon purchase verification. :type expires: ``datetime``/``dict`` :param expires: Order expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_ORDER`. :rtype: ``dict`` :returns: Order dictionary:: order = { 'id': <order_id>, 'expires': <order_expiry>, 'context': <purchase_context>, 'object': { 'id': <oid>, 'price': <amount_in_cents> }, 'urls': { 'redirect': <url_for_failsafe_redirect_purchase_mode>, 'popup': <url_for_popup_purchase_mode> } } :raises GeneralException: :resource: ``objects/<oid>/orders/`` :access: authorized users """ expires = absdatetime(expires, default=self.EXP_ORDER) orders = self.request( 'post', safeformat('objects/{:int}/orders/', oid), json.dumps({ 'price': price, 'order_expires': expires.isoformat(), 'context': context })) orderid = self._extract_id_from_batch_response(orders) return { 'id': orderid, 'expires': expires, 'context': context, 'object': { 'id': oid, 'price': price }, 'urls': { 'redirect': urljoin(self.usr_frontend, '/orders/%d/add/' % orderid), 'popup': urljoin(self.usr_frontend, '/popup/orders/%d/add/' % orderid) } } def get_orders(self, oid=None, include_expired=False, orderid=None): """ FETCHES filtered orders. All arguments are optional. :type oid: ``bigint`` :param oid: Object ID. :type include_expired: ``boolean`` :param include_expired: Fetch also expired orders. :type orderid: ``bigint`` :param orderid: Order ID. If specified, exactly one order shall be returned, or `NotFound` exception raised. Otherwise, a LIST of orders is returned. :rtype: ``list``/``dict`` :returns: (A list of) order(s) description dictionary(ies). :raises GeneralException: :resource: ``[objects/<oid>/]orders/[<all>/]<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.request( 'get', '%sorders/%s%s' % ( safeformat('objects/{:int}/', oid) if oid else "", "all/" if include_expired else "", safeformat('{:int}', orderid) if orderid else "" ) ) def get_order(self, orderid): """ FETCHES a single order defined with ``orderid``, or fails if order is non-existing (with `NotFound`). :type orderid: ``bigint`` :param orderid: Order ID :rtype: ``dict`` :returns: The order description dictionary. :raises GeneralException: :see: `get_orders` ``(orderid=...)`` :resource: ``orders/<orderid>`` :access: authorized users (authenticated user MUST be the object/order owner) """ return self.get_orders(orderid=orderid) def update_object(self, oid, name, url): """ UPDATES a single object in Vingd Object registry. :type oid: ``bigint`` :param oid: Object ID of the object being updated. :type name: ``string`` :param name: New object's name. :type url: ``string`` :param url: New callback URL (object's resource location). :rtype: `bigint` :returns: Object ID of the updated object. :raises GeneralException: :resource: ``registry/objects/<oid>/`` :access: authorized user MUST be the object owner """ r = self.request( 'put', safeformat('registry/objects/{:int}/', oid), json.dumps({ 'description': { 'name': name, 'url': url } }) ) return self._extract_id_from_batch_response(r, 'oid') def get_objects(self, oid=None, since=None, until=None, last=None, first=None): """ FETCHES a filtered collection of objects created by the authenticated user. :type oid: ``bigint`` :param oid: Object ID :type since: ``datetime``/``dict`` :param since: Object has to be newer than this timestamp (absolute ``datetime``, or relative ``dict``). Valid keys for relative `since` timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type until: ``datetime``/``dict`` :param until: Object has to be older than this timestamp (for format, see the `since` parameter above). :type last: ``bigint`` :param last: The number of newest objects (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest objects (that satisfy all other criteria) to return. :rtype: ``list``/``dict`` :returns: A list of object description dictionaries. If ``oid`` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``registry/objects[/<oid>]`` ``[/since=<since>][/until=<until>][/last=<last>][/first=<first>]`` :access: authorized users (only objects owned by the authenticated user are returned) """ resource = self.kvpath('registry/objects', ('int', oid), since=('isobasic', absdatetime(since)), until=('isobasic', absdatetime(until)), first=('int', first), last=('int', last)) return self.request('get', resource) def get_object(self, oid): """ FETCHES a single object, referenced by its ``oid``. :type oid: ``bigint`` :param oid: Object ID :rtype: ``dict`` :returns: The object description dictionary. :raises GeneralException: :note: `get_objects` can be used instead, but then specifying any other (conflicting) constraint (except ``oid``) yields a non-existing resource exception (`NotFound`). :resource: ``registry/objects/<oid>`` :access: authorized users (only objects owned by the authenticated user are returned) """ return self.request('get', safeformat('registry/objects/{:int}', oid)) def get_user_profile(self): """ FETCHES profile dictionary of the authenticated user. :rtype: ``dict`` :returns: A single user description dictionary. :raises GeneralException: :resource: ``/id/users/<uid>`` :access: authorized users; only authenticated user's metadata can be fetched (UID is automatically set to the authenticated user's UID) """ return self.request('get', 'id/users') def get_account_balance(self): """ FETCHES the account balance for the authenticated user. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/`` :access: authorized users; authenticated user's account data will be fetched """ return int(self.request('get', 'fort/accounts')['balance']) def authorized_get_account_balance(self, huid): """ FETCHES the account balance for the user defined with `huid`. :rtype: ``bigint`` :returns: ``<amount_in_cents>`` :raises GeneralException: :resource: ``fort/accounts/<huid>`` :access: authorized users; delegate permission required for the requester to read user's balance: ``get.account.balance`` """ acc = self.request('get', safeformat('fort/accounts/{:hex}', huid)) return int(acc['balance']) def authorized_purchase_object(self, oid, price, huid): """Does delegated (pre-authorized) purchase of `oid` in the name of `huid`, at price `price` (vingd transferred from `huid` to consumer's acc). :raises GeneralException: :resource: ``objects/<oid>/purchases`` :access: authorized users with ACL flag ``purchase.object.authorize`` + delegate permission required for the requester to charge the user: ``purchase.object`` """ return self.request( 'post', safeformat('objects/{:int}/purchases', oid), json.dumps({ 'price': price, 'huid': huid, 'autocommit': True })) def authorized_create_user(self, identities=None, primary=None, permissions=None): """Creates Vingd user (profile & account), links it with the provided identities (to be verified later), and sets the delegate-user permissions (creator being the delegate). Returns Vingd user's `huid` (hashed user id). Example:: vingd.authorized_create_user( identities={"facebook": "12312312", "mail": "user@example.com"}, primary="facebook", permissions=["get.account.balance", "purchase.object"] ) If `identities` and `primary` are unspecified, a "zombie" ("headless") account is created (i.e. account with no identities associated, user-unreachable). :rtype: ``dict`` :returns: ``{'huid': <huid>}`` :raises GeneralException: :resource: ``id/objects/<oid>/purchases`` :access: authorized users with ACL flag ``user.create`` """ return self.request('post', 'id/users/', json.dumps({ 'identities': identities, 'primary_identity': primary, 'delegate_permissions': permissions })) def reward_user(self, huid_to, amount, description=None): """ PERFORMS a single reward. User defined with `huid_to` is rewarded with `amount` cents, transfered from the account of the authenticated user. :type huid_to: ``alphanumeric(40)`` :param huid_to: Hashed User ID, bound to account of the authenticated user (doing the request). :type amount: ``integer`` :param amount: Amount in cents. :type description: ``string`` :param description: Transaction description (optional). :rtype: ``dict`` :returns: ``{'transfer_id': <transfer_id>}`` Fort Transfer ID packed inside a dict. :raises Forbidden: consumer has to have ``transfer.outbound`` ACL flag set. :raises GeneralException: :raises NotFound: :resource: ``rewards/`` :access: authorized users (ACL flag: ``transfer.outbound``) """ return self.request('post', 'rewards', json.dumps({ 'huid_to': huid_to, 'amount': amount, 'description': description })) def create_voucher(self, amount, expires=None, message='', gid=None): """ CREATES a new preallocated voucher with ``amount`` vingd cents reserved until ``expires``. :type amount: ``bigint`` :param amount: Voucher amount in vingd cents. :type expires: ``datetime``/``dict`` :param expires: Voucher expiry timestamp, absolute (``datetime``) or relative (``dict``). Valid keys for relative expiry timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). Default: `Vingd.EXP_VOUCHER`. :type message: ``string`` :param message: Short message displayed to user when she redeems the voucher on Vingd frontend. :type gid: ``alphanum(32)`` :param gid: Voucher group id. An user can redeem only one voucher per group. :rtype: ``dict`` :returns: Created voucher description:: voucher = { 'vid': <voucher_integer_id>, 'vid_encoded': <voucher_string_id>, 'amount_allocated': <int_cents | None if not allocated>, 'amount_vouched': <int_cents>, 'id_fort_transfer': <id_of_allocating_transfer | None if not allocated>, 'fee': <int_cents>, 'uid_from': <source_account_uid>, 'uid_proxy': <broker_id>, 'uid_to': <destination_account_id | None if not given>, 'gid': <voucher_group_id | None if undefined>, 'ts_valid_until': <iso8601_timestamp_absolute>, 'description': <string | None>, 'message': <string | None> } combined with voucher redeem urls on Vingd frontend. :raises GeneralException: :resource: ``vouchers/`` :access: authorized users (ACL flag: ``voucher.add``) """ expires = absdatetime(expires, default=self.EXP_VOUCHER).isoformat() voucher = self.request('post', 'vouchers/', json.dumps({ 'amount': amount, 'until': expires, 'message': message, 'gid': gid })) return { 'raw': voucher, 'urls': { 'redirect': urljoin(self.usr_frontend, '/vouchers/%s' % voucher['vid_encoded']), 'popup': urljoin(self.usr_frontend, '/popup/vouchers/%s' % voucher['vid_encoded']) } } def get_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `vid_encoded`. :rtype: ``list``/``dict`` :returns: A list of voucher description dictionaries. If `vid_encoded` is specified, a single dictionary is returned instead of a list. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.get``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def get_vouchers_history(self, vid_encoded=None, vid=None, action=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, create_after=None, create_before=None, last=None, first=None): """ FETCHES a filtered list of vouchers log entries. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type vid: ``bigint`` :param vid: Voucher ID. :type action: ``string`` (add | use | revoke | expire) :param action: Filter only these actions on vouchers. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type create_after: ``datetime``/``dict`` :param create_after: Voucher has to be created after this timestamp (for format, see the `valid_after` above). :type create_before: ``datetime``/``dict`` :param create_before: Voucher was created until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest voucher entries (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest voucher entries (that satisfy all other criteria) to return. :note: If `first` or `last` are used, the vouchers list is sorted by time created, otherwise it is sorted alphabetically by `id`. :rtype: ``list``/``dict`` :returns: A list of voucher log description dictionaries. :raises GeneralException: :resource: ``vouchers/history[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/vid=<vid>][/action=<action>][/last=<last>][/first=<first>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/create_after=<create_after>][/create_before=<create_before>]`` ``[/gid=<group_id>]`` :access: authorized users (ACL flag: ``voucher.history``) """ resource = self.kvpath( 'vouchers/history', ('ident', vid_encoded), **{ 'vid': ('int', vid), 'action': ('ident', action), 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'create_after': ('isobasic', absdatetime(create_after)), 'create_before': ('isobasic', absdatetime(create_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('get', resource) def revoke_vouchers(self, vid_encoded=None, uid_from=None, uid_to=None, gid=None, valid_after=None, valid_before=None, last=None, first=None): """ REVOKES/INVALIDATES a filtered list of vouchers. :type vid_encoded: ``alphanumeric(64)`` :param vid_encoded: Voucher ID, as a string with CRC. :type uid_from: ``bigint`` :param uid_from: Filter by source account UID. :type uid_to: ``bigint`` :param uid_to: Filter by destination account UID. :type gid: ``alphanumeric(32)`` :param gid: Filter by voucher Group ID. GID is localized to `uid_from`. :type valid_after: ``datetime``/``dict`` :param valid_after: Voucher has to be valid after this timestamp. Absolute (``datetime``) or relative (``dict``) timestamps are accepted. Valid keys for relative timestamp dictionary are same as keyword arguments for `datetime.timedelta` (``days``, ``seconds``, ``minutes``, ``hours``, ``weeks``). :type valid_before: ``datetime``/``dict`` :param valid_before: Voucher was valid until this timestamp (for format, see the `valid_after` above). :type last: ``bigint`` :param last: The number of newest vouchers (that satisfy all other criteria) to return. :type first: ``bigint`` :param first: The number of oldest vouchers (that satisfy all other criteria) to return. :note: As with `get_vouchers`, filters are restrictive, narrowing down the set of vouchers, which initially includes complete voucher collection. That means, in turn, that a naive empty-handed `revoke_vouchers()` call shall revoke **all** un-used vouchers (both valid and expired)! :rtype: ``dict`` :returns: A dictionary of successfully revoked vouchers, i.e. a map ``vid_encoded``: ``refund_transfer_id`` for all successfully revoked vouchers. :raises GeneralException: :resource: ``vouchers[/<vid_encoded>][/from=<uid_from>][/to=<uid_to>]`` ``[/valid_after=<valid_after>][/valid_before=<valid_before>]`` ``[/last=<last>][/first=<first>]`` :access: authorized users (ACL flag: ``voucher.revoke``) """ resource = self.kvpath( 'vouchers', ('ident', vid_encoded), **{ 'from': ('int', uid_from), 'to': ('int', uid_to), 'gid': ('ident', gid), 'valid_after': ('isobasic', absdatetime(valid_after)), 'valid_before': ('isobasic', absdatetime(valid_before)), 'first': ('int', first), 'last': ('int', last) } ) return self.request('delete', resource, json.dumps({'revoke': True}))
vingd/vingd-api-python
vingd/util.py
absdatetime
python
def absdatetime(ts, default=None): if ts is None: ts = default if isinstance(ts, dict): ts = timedelta(**ts) if isinstance(ts, timedelta): ts = now() + ts if isinstance(ts, datetime): return ts return None
Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict`` fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or `None` if `datetime` can not be derived from `ts`).
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/util.py#L49-L61
null
import re from hashlib import sha1 from datetime import datetime, timedelta, tzinfo from itertools import count try: from urllib.parse import quote as base_quote def quote(url, safe='/=:%{}'): return base_quote(url, safe) except ImportError: # python2 sucks at unicoding from urllib import quote as ascii_quote def quote(url, safe='/=:%{}'): try: return ascii_quote(url.encode('utf-8'), safe).encode('ascii') except Exception as e: raise Exception("Malformed URL: '" + url + "'") def hash(msg): return sha1(msg.encode('utf-8')).hexdigest() if msg else None class tzutc(tzinfo): '''UTC time zone info.''' def utcoffset(self, dt): return timedelta(0) def dst(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def localnow(): """Local time without time zone (local time @ local time zone).""" return datetime.now() def utcnow(): """Current UTC/GMT time without time zone (local time @ UTC).""" return datetime.utcnow() def now(): """Current UTC/GMT time with time zone.""" return datetime.now(tzutc()) def parse_duration(string): ''' Parses duration/period stamp expressed in a subset of ISO8601 duration specification formats and returns a dictionary of time components (as integers). Accepted formats are: * ``PnYnMnDTnHnMnS`` Note: n is positive integer! Floats are NOT supported. Any component (nX) is optional, but if any time component is specified, ``T`` spearator is mandatory. Also, ``P`` is always mandatory. * ``PnW`` Note: n is positive integer representing number of weeks. * ``P<date>T<time>`` Note: This format is basically standard ISO8601 timestamp format, without the time zone and with ``P`` prepended. We support both basic and extended format, which translates into following two subformats: - ``PYYYYMMDDThhmmss`` for basic, and - ``PYYYY-MM-DDThh:mm:ss`` for extended format. Note that all subfields are mandatory. Note: whitespaces are ignored. Examples:: from datetime import datetime from dateutil.relativedelta import relativedelta rel = parse_duration('P1m') # +1 month rel = parse_duration('P 1y 1m T 2m 1s') rel = parse_duration('P12w') # +12 weeks rel = parse_duration('P 0001-02-03 T 03:02:01') rel = parse_duration('P00010203T030201') future = datetime.now() + relativedelta(**rel) Returns: dictionary with (some of the) fields: ``years``, ``months``, ``weeks``, ``days``, ``hours``, ``minutes`` or ``seconds``. If nothing is matched, an empty dict is returned. ''' string = string.replace(' ', '').upper() # try `PnYnMnDTnHnMnS` form match = re.match( "^P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?)?" \ "(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `PnW` form match = re.match( "^P(?P<weeks>\d+)W$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `P<date>T<time>` form, subforms `PYYYYMMDDThhmmss` and `PYYYY-MM-DDThh:mm:ss` match = re.match( "^P(?P<years>\d{4})(-)?(?P<months>\d{2})(?(2)-)(?P<days>\d{2})T(?P<hours>\d{2})(?(2):)(?P<minutes>\d{2})(?(2):)(?P<seconds>\d{2})$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) return {} class ConversionError(TypeError): """Raised by `safeformat` when argument can't be cast to the type proscribed with `format_string`.""" def safeformat(format_string, *args): """String formatter with type validation. Python `format`-alike. Examples:: - implicit indexing: safeformat("Decimal {:int}, hexadecimal {1:hex}", 2, "abc") --> "Decimal 2, hexadecimal abc" - reusable arguments: safeformat("{:hex}. item: {0:str}", 13) --> "13. item: 13" - safe paths: safeformat("objects/{:int}/tokens/{:hex}", 123, "ab2e36d953e7b634") --> "objects/123/tokens/ab2e36d953e7b634" Format pattern is `{[index]:type}`, where `index` is optional argument index, and `type` is one of the predefined typenames (currently: `int`, `hex`, `str`, `ident`, `iso`, `isobasic`). """ def hex(x): """Allow hexadecimal digits.""" if re.match('^[a-fA-F\d]*$', str(x)): return str(x) raise ValueError("Non-hex digits in hex number.") def identifier(x): """Allow letters, digits, underscore and minus/dash.""" if re.match('^[-\w]*$', str(x)): return str(x) raise ValueError("Non-identifier characters in string.") def iso(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.isoformat() def isobasic(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.strftime("%Y%m%dT%H%M%S%z") converters = { 'int': int, 'hex': hex, 'str': str, 'ident': identifier, 'iso': iso, 'isobasic': isobasic } argidx = count(0) def replace(match): idx, typ = match.group('idx', 'typ') if idx is None: idx = next(argidx) else: try: idx = int(idx) except: raise ConversionError("Non-integer index: '%s'." % idx) try: arg = args[idx] except: raise ConversionError("Index out of bounds: %d." % idx) try: conv = converters[typ] except: raise ConversionError("Invalid converter/type: '%s'." % typ) try: val = conv(arg) except: raise ConversionError("Argument '%s' not of type '%s'." % (arg, typ)) return str(val) return re.sub("{(?:(?P<idx>\d+))?:(?P<typ>\w+)}", replace, format_string)
vingd/vingd-api-python
vingd/util.py
parse_duration
python
def parse_duration(string): ''' Parses duration/period stamp expressed in a subset of ISO8601 duration specification formats and returns a dictionary of time components (as integers). Accepted formats are: * ``PnYnMnDTnHnMnS`` Note: n is positive integer! Floats are NOT supported. Any component (nX) is optional, but if any time component is specified, ``T`` spearator is mandatory. Also, ``P`` is always mandatory. * ``PnW`` Note: n is positive integer representing number of weeks. * ``P<date>T<time>`` Note: This format is basically standard ISO8601 timestamp format, without the time zone and with ``P`` prepended. We support both basic and extended format, which translates into following two subformats: - ``PYYYYMMDDThhmmss`` for basic, and - ``PYYYY-MM-DDThh:mm:ss`` for extended format. Note that all subfields are mandatory. Note: whitespaces are ignored. Examples:: from datetime import datetime from dateutil.relativedelta import relativedelta rel = parse_duration('P1m') # +1 month rel = parse_duration('P 1y 1m T 2m 1s') rel = parse_duration('P12w') # +12 weeks rel = parse_duration('P 0001-02-03 T 03:02:01') rel = parse_duration('P00010203T030201') future = datetime.now() + relativedelta(**rel) Returns: dictionary with (some of the) fields: ``years``, ``months``, ``weeks``, ``days``, ``hours``, ``minutes`` or ``seconds``. If nothing is matched, an empty dict is returned. ''' string = string.replace(' ', '').upper() # try `PnYnMnDTnHnMnS` form match = re.match( "^P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?)?" \ "(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `PnW` form match = re.match( "^P(?P<weeks>\d+)W$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `P<date>T<time>` form, subforms `PYYYYMMDDThhmmss` and `PYYYY-MM-DDThh:mm:ss` match = re.match( "^P(?P<years>\d{4})(-)?(?P<months>\d{2})(?(2)-)(?P<days>\d{2})T(?P<hours>\d{2})(?(2):)(?P<minutes>\d{2})(?(2):)(?P<seconds>\d{2})$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) return {}
Parses duration/period stamp expressed in a subset of ISO8601 duration specification formats and returns a dictionary of time components (as integers). Accepted formats are: * ``PnYnMnDTnHnMnS`` Note: n is positive integer! Floats are NOT supported. Any component (nX) is optional, but if any time component is specified, ``T`` spearator is mandatory. Also, ``P`` is always mandatory. * ``PnW`` Note: n is positive integer representing number of weeks. * ``P<date>T<time>`` Note: This format is basically standard ISO8601 timestamp format, without the time zone and with ``P`` prepended. We support both basic and extended format, which translates into following two subformats: - ``PYYYYMMDDThhmmss`` for basic, and - ``PYYYY-MM-DDThh:mm:ss`` for extended format. Note that all subfields are mandatory. Note: whitespaces are ignored. Examples:: from datetime import datetime from dateutil.relativedelta import relativedelta rel = parse_duration('P1m') # +1 month rel = parse_duration('P 1y 1m T 2m 1s') rel = parse_duration('P12w') # +12 weeks rel = parse_duration('P 0001-02-03 T 03:02:01') rel = parse_duration('P00010203T030201') future = datetime.now() + relativedelta(**rel) Returns: dictionary with (some of the) fields: ``years``, ``months``, ``weeks``, ``days``, ``hours``, ``minutes`` or ``seconds``. If nothing is matched, an empty dict is returned.
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/util.py#L64-L141
null
import re from hashlib import sha1 from datetime import datetime, timedelta, tzinfo from itertools import count try: from urllib.parse import quote as base_quote def quote(url, safe='/=:%{}'): return base_quote(url, safe) except ImportError: # python2 sucks at unicoding from urllib import quote as ascii_quote def quote(url, safe='/=:%{}'): try: return ascii_quote(url.encode('utf-8'), safe).encode('ascii') except Exception as e: raise Exception("Malformed URL: '" + url + "'") def hash(msg): return sha1(msg.encode('utf-8')).hexdigest() if msg else None class tzutc(tzinfo): '''UTC time zone info.''' def utcoffset(self, dt): return timedelta(0) def dst(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def localnow(): """Local time without time zone (local time @ local time zone).""" return datetime.now() def utcnow(): """Current UTC/GMT time without time zone (local time @ UTC).""" return datetime.utcnow() def now(): """Current UTC/GMT time with time zone.""" return datetime.now(tzutc()) def absdatetime(ts, default=None): """Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict`` fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or `None` if `datetime` can not be derived from `ts`).""" if ts is None: ts = default if isinstance(ts, dict): ts = timedelta(**ts) if isinstance(ts, timedelta): ts = now() + ts if isinstance(ts, datetime): return ts return None def parse_duration(string): ''' Parses duration/period stamp expressed in a subset of ISO8601 duration specification formats and returns a dictionary of time components (as integers). Accepted formats are: * ``PnYnMnDTnHnMnS`` Note: n is positive integer! Floats are NOT supported. Any component (nX) is optional, but if any time component is specified, ``T`` spearator is mandatory. Also, ``P`` is always mandatory. * ``PnW`` Note: n is positive integer representing number of weeks. * ``P<date>T<time>`` Note: This format is basically standard ISO8601 timestamp format, without the time zone and with ``P`` prepended. We support both basic and extended format, which translates into following two subformats: - ``PYYYYMMDDThhmmss`` for basic, and - ``PYYYY-MM-DDThh:mm:ss`` for extended format. Note that all subfields are mandatory. Note: whitespaces are ignored. Examples:: from datetime import datetime from dateutil.relativedelta import relativedelta rel = parse_duration('P1m') # +1 month rel = parse_duration('P 1y 1m T 2m 1s') rel = parse_duration('P12w') # +12 weeks rel = parse_duration('P 0001-02-03 T 03:02:01') rel = parse_duration('P00010203T030201') future = datetime.now() + relativedelta(**rel) Returns: dictionary with (some of the) fields: ``years``, ``months``, ``weeks``, ``days``, ``hours``, ``minutes`` or ``seconds``. If nothing is matched, an empty dict is returned. ''' string = string.replace(' ', '').upper() # try `PnYnMnDTnHnMnS` form match = re.match( "^P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?)?" \ "(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `PnW` form match = re.match( "^P(?P<weeks>\d+)W$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `P<date>T<time>` form, subforms `PYYYYMMDDThhmmss` and `PYYYY-MM-DDThh:mm:ss` match = re.match( "^P(?P<years>\d{4})(-)?(?P<months>\d{2})(?(2)-)(?P<days>\d{2})T(?P<hours>\d{2})(?(2):)(?P<minutes>\d{2})(?(2):)(?P<seconds>\d{2})$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) return {} class ConversionError(TypeError): """Raised by `safeformat` when argument can't be cast to the type proscribed with `format_string`.""" def safeformat(format_string, *args): """String formatter with type validation. Python `format`-alike. Examples:: - implicit indexing: safeformat("Decimal {:int}, hexadecimal {1:hex}", 2, "abc") --> "Decimal 2, hexadecimal abc" - reusable arguments: safeformat("{:hex}. item: {0:str}", 13) --> "13. item: 13" - safe paths: safeformat("objects/{:int}/tokens/{:hex}", 123, "ab2e36d953e7b634") --> "objects/123/tokens/ab2e36d953e7b634" Format pattern is `{[index]:type}`, where `index` is optional argument index, and `type` is one of the predefined typenames (currently: `int`, `hex`, `str`, `ident`, `iso`, `isobasic`). """ def hex(x): """Allow hexadecimal digits.""" if re.match('^[a-fA-F\d]*$', str(x)): return str(x) raise ValueError("Non-hex digits in hex number.") def identifier(x): """Allow letters, digits, underscore and minus/dash.""" if re.match('^[-\w]*$', str(x)): return str(x) raise ValueError("Non-identifier characters in string.") def iso(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.isoformat() def isobasic(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.strftime("%Y%m%dT%H%M%S%z") converters = { 'int': int, 'hex': hex, 'str': str, 'ident': identifier, 'iso': iso, 'isobasic': isobasic } argidx = count(0) def replace(match): idx, typ = match.group('idx', 'typ') if idx is None: idx = next(argidx) else: try: idx = int(idx) except: raise ConversionError("Non-integer index: '%s'." % idx) try: arg = args[idx] except: raise ConversionError("Index out of bounds: %d." % idx) try: conv = converters[typ] except: raise ConversionError("Invalid converter/type: '%s'." % typ) try: val = conv(arg) except: raise ConversionError("Argument '%s' not of type '%s'." % (arg, typ)) return str(val) return re.sub("{(?:(?P<idx>\d+))?:(?P<typ>\w+)}", replace, format_string)
vingd/vingd-api-python
vingd/util.py
safeformat
python
def safeformat(format_string, *args): def hex(x): """Allow hexadecimal digits.""" if re.match('^[a-fA-F\d]*$', str(x)): return str(x) raise ValueError("Non-hex digits in hex number.") def identifier(x): """Allow letters, digits, underscore and minus/dash.""" if re.match('^[-\w]*$', str(x)): return str(x) raise ValueError("Non-identifier characters in string.") def iso(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.isoformat() def isobasic(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.strftime("%Y%m%dT%H%M%S%z") converters = { 'int': int, 'hex': hex, 'str': str, 'ident': identifier, 'iso': iso, 'isobasic': isobasic } argidx = count(0) def replace(match): idx, typ = match.group('idx', 'typ') if idx is None: idx = next(argidx) else: try: idx = int(idx) except: raise ConversionError("Non-integer index: '%s'." % idx) try: arg = args[idx] except: raise ConversionError("Index out of bounds: %d." % idx) try: conv = converters[typ] except: raise ConversionError("Invalid converter/type: '%s'." % typ) try: val = conv(arg) except: raise ConversionError("Argument '%s' not of type '%s'." % (arg, typ)) return str(val) return re.sub("{(?:(?P<idx>\d+))?:(?P<typ>\w+)}", replace, format_string)
String formatter with type validation. Python `format`-alike. Examples:: - implicit indexing: safeformat("Decimal {:int}, hexadecimal {1:hex}", 2, "abc") --> "Decimal 2, hexadecimal abc" - reusable arguments: safeformat("{:hex}. item: {0:str}", 13) --> "13. item: 13" - safe paths: safeformat("objects/{:int}/tokens/{:hex}", 123, "ab2e36d953e7b634") --> "objects/123/tokens/ab2e36d953e7b634" Format pattern is `{[index]:type}`, where `index` is optional argument index, and `type` is one of the predefined typenames (currently: `int`, `hex`, `str`, `ident`, `iso`, `isobasic`).
train
https://github.com/vingd/vingd-api-python/blob/7548a49973a472f7277c8ef847563faa7b6f3706/vingd/util.py#L149-L235
null
import re from hashlib import sha1 from datetime import datetime, timedelta, tzinfo from itertools import count try: from urllib.parse import quote as base_quote def quote(url, safe='/=:%{}'): return base_quote(url, safe) except ImportError: # python2 sucks at unicoding from urllib import quote as ascii_quote def quote(url, safe='/=:%{}'): try: return ascii_quote(url.encode('utf-8'), safe).encode('ascii') except Exception as e: raise Exception("Malformed URL: '" + url + "'") def hash(msg): return sha1(msg.encode('utf-8')).hexdigest() if msg else None class tzutc(tzinfo): '''UTC time zone info.''' def utcoffset(self, dt): return timedelta(0) def dst(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def localnow(): """Local time without time zone (local time @ local time zone).""" return datetime.now() def utcnow(): """Current UTC/GMT time without time zone (local time @ UTC).""" return datetime.utcnow() def now(): """Current UTC/GMT time with time zone.""" return datetime.now(tzutc()) def absdatetime(ts, default=None): """Accepts relative timestamp (`timedelta` or `timedelta`-supported ``dict`` fmt), absolute `datetime`, or failbacks to `default`. Returns `datetime` (or `None` if `datetime` can not be derived from `ts`).""" if ts is None: ts = default if isinstance(ts, dict): ts = timedelta(**ts) if isinstance(ts, timedelta): ts = now() + ts if isinstance(ts, datetime): return ts return None def parse_duration(string): ''' Parses duration/period stamp expressed in a subset of ISO8601 duration specification formats and returns a dictionary of time components (as integers). Accepted formats are: * ``PnYnMnDTnHnMnS`` Note: n is positive integer! Floats are NOT supported. Any component (nX) is optional, but if any time component is specified, ``T`` spearator is mandatory. Also, ``P`` is always mandatory. * ``PnW`` Note: n is positive integer representing number of weeks. * ``P<date>T<time>`` Note: This format is basically standard ISO8601 timestamp format, without the time zone and with ``P`` prepended. We support both basic and extended format, which translates into following two subformats: - ``PYYYYMMDDThhmmss`` for basic, and - ``PYYYY-MM-DDThh:mm:ss`` for extended format. Note that all subfields are mandatory. Note: whitespaces are ignored. Examples:: from datetime import datetime from dateutil.relativedelta import relativedelta rel = parse_duration('P1m') # +1 month rel = parse_duration('P 1y 1m T 2m 1s') rel = parse_duration('P12w') # +12 weeks rel = parse_duration('P 0001-02-03 T 03:02:01') rel = parse_duration('P00010203T030201') future = datetime.now() + relativedelta(**rel) Returns: dictionary with (some of the) fields: ``years``, ``months``, ``weeks``, ``days``, ``hours``, ``minutes`` or ``seconds``. If nothing is matched, an empty dict is returned. ''' string = string.replace(' ', '').upper() # try `PnYnMnDTnHnMnS` form match = re.match( "^P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?)?" \ "(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `PnW` form match = re.match( "^P(?P<weeks>\d+)W$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) # try `P<date>T<time>` form, subforms `PYYYYMMDDThhmmss` and `PYYYY-MM-DDThh:mm:ss` match = re.match( "^P(?P<years>\d{4})(-)?(?P<months>\d{2})(?(2)-)(?P<days>\d{2})T(?P<hours>\d{2})(?(2):)(?P<minutes>\d{2})(?(2):)(?P<seconds>\d{2})$", string ) if match: d = match.groupdict(0) return dict(zip(d.keys(), map(int, d.values()))) return {} class ConversionError(TypeError): """Raised by `safeformat` when argument can't be cast to the type proscribed with `format_string`.""" def safeformat(format_string, *args): """String formatter with type validation. Python `format`-alike. Examples:: - implicit indexing: safeformat("Decimal {:int}, hexadecimal {1:hex}", 2, "abc") --> "Decimal 2, hexadecimal abc" - reusable arguments: safeformat("{:hex}. item: {0:str}", 13) --> "13. item: 13" - safe paths: safeformat("objects/{:int}/tokens/{:hex}", 123, "ab2e36d953e7b634") --> "objects/123/tokens/ab2e36d953e7b634" Format pattern is `{[index]:type}`, where `index` is optional argument index, and `type` is one of the predefined typenames (currently: `int`, `hex`, `str`, `ident`, `iso`, `isobasic`). """ def hex(x): """Allow hexadecimal digits.""" if re.match('^[a-fA-F\d]*$', str(x)): return str(x) raise ValueError("Non-hex digits in hex number.") def identifier(x): """Allow letters, digits, underscore and minus/dash.""" if re.match('^[-\w]*$', str(x)): return str(x) raise ValueError("Non-identifier characters in string.") def iso(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.isoformat() def isobasic(x): if not isinstance(x, datetime): raise ValueError("Datetime expected.") return x.strftime("%Y%m%dT%H%M%S%z") converters = { 'int': int, 'hex': hex, 'str': str, 'ident': identifier, 'iso': iso, 'isobasic': isobasic } argidx = count(0) def replace(match): idx, typ = match.group('idx', 'typ') if idx is None: idx = next(argidx) else: try: idx = int(idx) except: raise ConversionError("Non-integer index: '%s'." % idx) try: arg = args[idx] except: raise ConversionError("Index out of bounds: %d." % idx) try: conv = converters[typ] except: raise ConversionError("Invalid converter/type: '%s'." % typ) try: val = conv(arg) except: raise ConversionError("Argument '%s' not of type '%s'." % (arg, typ)) return str(val) return re.sub("{(?:(?P<idx>\d+))?:(?P<typ>\w+)}", replace, format_string)
davidmiller/letter
letter/sms.py
TwillioPostie.send
python
def send(self, to, from_, body): try: msg = self.client.sms.messages.create( body=body, to=to, from_=from_ ) print msg.sid except twilio.TwilioRestException as e: raise
Send BODY to TO from FROM as an SMS!
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/sms.py#L14-L26
null
class TwillioPostie(object): """ Render messages from templates and handle deliery. """ def __init__(self, sid=None, token=None): self.client = TwilioRestClient(sid, token)
davidmiller/letter
letter/__main__.py
main
python
def main(): description = 'Letter - a commandline interface' parser = argparse.ArgumentParser(description=description) parser.add_argument('--gmail', action='store_true', help='Send via Gmail', ) args = parser.parse_args() to = raw_input('To address > ') subject = raw_input('Subject > ') body = raw_input('Your Message > ') if args.gmail: user = fromaddr = raw_input('Gmail Address > ') pw = getpass.getpass() postie = letter.GmailPostman(user=user, pw=pw) else: postie = letter.Postman() # Unauthorized SMTP, localhost:25 fromaddr = raw_input('From address > ') class Message(letter.Letter): Postie = postie From = fromaddr To = to Subject = subject Body = body return 0
Do the things! Return: 0 Exceptions:
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__main__.py#L10-L44
null
""" Commandline module interface. """ import argparse import getpass import sys import letter if __name__ == '__main__': sys.exit(main())
davidmiller/letter
letter/contrib/contact.py
EmailForm.send_email
python
def send_email(self, to): body = self.body() subject = self.subject() import letter class Message(letter.Letter): Postie = letter.DjangoPostman() From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com') To = to Subject = subject Body = body if hasattr(self, 'reply_to'): Message.ReplyTo = self.reply_to() Message.send() return
Do work.
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L24-L45
[ "def send(klass):\n to = klass.To\n subject = getattr(klass, 'Subject', '')\n\n if stringy(to):\n to = [to]\n if getattr(klass, 'Body', None):\n klass.Postie.send(\n klass.From,\n to,\n subject,\n klass.Body,\n cc=getattr(klass, 'Cc', None),\n bcc=getattr(klass, 'Bcc', None),\n replyto=getattr(klass, 'ReplyTo', None),\n attach=getattr(klass, 'Attach', None),\n )\n return\n\n with klass.Postie.template(klass.Template):\n klass.Postie.send(\n klass.From,\n to,\n subject,\n cc=getattr(klass, 'Cc', None),\n bcc=getattr(klass, 'Bcc', None),\n replyto=getattr(klass, 'ReplyTo', None),\n attach=getattr(klass, 'Attach', None),\n **getattr(klass, 'Context', {})\n )\n" ]
class EmailForm(forms.Form): name = forms.CharField() email = forms.EmailField() message = forms.CharField(widget=forms.Textarea)
davidmiller/letter
letter/contrib/contact.py
EmailView.form_valid
python
def form_valid(self, form): form.send_email(to=self.to_addr) return super(EmailView, self).form_valid(form)
Praise be, someone has spammed us.
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L87-L92
null
class EmailView(FormView): """ Base class for views that will send an email. Subclasses should specify the following properties: * template_name * form_class * success_url """ to_addr = getattr(settings, 'CONTACT_EMAIL', 'contact@example.com')
davidmiller/letter
letter/social.py
TwitterPostie.send
python
def send(self, to, from_, body, dm=False): tweet = '@{0} {1}'.format(to, body) if from_ not in self.accounts: raise AccountNotFoundError() if len(tweet) > 140: raise TweetTooLongError() self.auth.set_access_token(*self.accounts.get(from_)) api = tweepy.API(self.auth) if dm: api.send_direct_message(screen_name=to, text=body) else: api.update_status(tweet) return
Send BODY as an @message from FROM to TO If we don't have the access tokens for FROM, raise AccountNotFoundError. If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars raise TweetTooLongError. If we want to send this message as a DM, do so. Arguments: - `to`: str - `from_`: str - `body`: str - `dm`: [optional] bool Return: None Exceptions: AccountNotFoundError TweetTooLongError
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/social.py#L31-L64
null
class TwitterPostie(object): """ Deliver messages via twitter """ def __init__(self, consumer_key='', consumer_secret='', accounts={}): self.auth = tweepy.OAuthHandler(consumer_key, consumer_secret) self.accounts = accounts
davidmiller/letter
letter/__init__.py
_stringlist
python
def _stringlist(*args): return list(itertools.chain.from_iterable(itertools.repeat(x,1) if stringy(x) else x for x in args if x))
Take a lists of strings or strings and flatten these into a list of strings. Arguments: - `*args`: "" or [""...] Return: [""...] Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L51-L62
null
""" Send letters electronically. We assume you're likely to want to send emails from templates. Let's make that as easy as possible. """ from letter._version import __version__ import contextlib import email from email import encoders from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage import itertools import mimetypes import smtplib import types import ffs from ffs.contrib import mold from six import u, string_types, text_type __all__ = [ '__version__', 'Postman', 'DjangoPostman', 'GmailPostman', 'setup_test_environment', 'teardown_test_environment' ] flatten = lambda x: [item for sublist in x for item in sublist] stringy = lambda x: isinstance(x, string_types) listy = lambda x: isinstance(x, (list, tuple)) OUTBOX = [] SMTP = None class Error(Exception): pass class NoTemplateError(Error): pass class NoContentError(Error): pass def ensure_unicode(s): if isinstance(s, text_type): return s return u(s) class Attachment(object): """ A file we're attaching to an email. """ def __init__(self, path): self.path = ffs.Path(path) def as_msg(self): """ Convert ourself to be a message part of the appropriate MIME type. Return: MIMEBase Exceptions: None """ # Based upon http://docs.python.org/2/library/email-examples.html # with minimal tweaking # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(str(self.path)) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(self.path.read(), _subtype=subtype) elif maintype == 'image': fp = self.path.open('rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = self.path.open('rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = self.path.open('rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) filename = str(self.path[-1]) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg class BaseMailer(object): """ Mailers either handle the construction and delivery of message objects once we have determined the contents etc. """ def tolist(self, to): """ Make sure that our addressees are a unicoded list Arguments: - `to`: str or list Return: [u, ...] Exceptions: None """ return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)]) def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None): """ Sanity check the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str Return: None Exceptions: NoContentError """ if not plain and not html: raise NoContentError() class BaseSMTPMailer(BaseMailer): """ Construct the message """ def send(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None, replyto=None, attach=None): """ Send the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `attach`: str or [str] Return: None Exceptions: NoContentError """ self.sanity_check(sender, to, subject, plain=plain, html=html) # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('mixed') msg['Subject'] = u(subject) msg['From'] = u(sender) msg['To'] = self.tolist(to) if cc: msg['Cc'] = self.tolist(cc) recipients = _stringlist(to, cc, bcc) if replyto: msg.add_header('reply-to', replyto) # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. if plain: msg.attach(MIMEText(u(plain), 'plain')) if html: msg.attach(MIMEText(u(html), 'html')) # Deal with attachments. if attach: for p in _stringlist(attach): msg.attach(Attachment(p).as_msg()) self.deliver(msg, recipients) class SMTPMailer(BaseSMTPMailer): """ Use SMTP to deliver our message. """ def __init__(self, host, port): """ Store vars """ self.host = host self.port = port def deliver(self, message, to): """ Deliver our message Arguments: - `message`: MIMEMultipart Return: None Exceptions: None """ # Send the message via local SMTP server. s = smtplib.SMTP(self.host, self.port) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(message['From'], to, message.as_string()) s.quit() return class SMTPAuthenticatedMailer(BaseSMTPMailer): """ Use authenticated SMTP to deliver our message """ def __init__(self, host, port, user, pw): self.host = host self.port = port self.user = user self.pw = pw def deliver(self, message, to): """ Deliver our message Arguments: - `message`: MIMEMultipart Return: None Exceptions: None """ # Send the message via local SMTP server. s = smtplib.SMTP(self.host, self.port) s.ehlo() s.starttls() s.login(self.user, self.pw) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(message['From'], to, message.as_string()) s.quit() return class DjangoMailer(BaseMailer): """ Send email using whatever is configured in our Django project's email settings etc etc """ def send(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None, attach=None, replyto=None): """ Send the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str - `attach`: str or iterable of str - `replyto`: str Return: None Exceptions: NoContentError """ headers = {} if attach: raise NotImplementedError('Attachments not implemented for Django yet!') if replyto: headers['Reply-To'] = replyto self.sanity_check(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc) if not cc: cc = [] if not bcc: bcc = [] # This comes straight from the docs at # https://docs.djangoproject.com/en/dev/topics/email/ from django.core.mail import EmailMultiAlternatives if not plain: plain = '' msg = EmailMultiAlternatives(u(subject), u(plain), u(sender), _stringlist(to), bcc=bcc, cc=cc, headers=headers) if html: msg.attach_alternative(ensure_unicode(html), "text/html") msg.send() return class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """ found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found def _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """ return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html') def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): """ Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None """ self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return send = _send def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """ plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return def body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """ text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content @contextlib.contextmanager def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send class SMTPPostman(BasePostman): """ The SMTP Postman is a utility class for using SMTP as a delivery method for our messages. """ def __init__(self, templatedir=None, host='localhost', port=25): super(SMTPPostman, self).__init__(templatedir) self.mailer = SMTPMailer(host, port) class SMTPAuthenticatedPostman(BasePostman): """ The SMTP Postman is a utility class for using SMTP as a delivery method for our messages. """ def __init__(self, templatedir=None, host='localhost', port=25, user=None, pw=None): super(SMTPAuthenticatedPostman, self).__init__(templatedir) self.mailer = SMTPAuthenticatedMailer(host, port, user, pw) class Postman(SMTPPostman): """ The Postman is your main entrypoint to sending Electronic Mail. Set up an SMTP mailer at HOST:PORT using TEMPLATEDIR as the place to look for templates. If BLOCKING is True, use the blocking mailer. Arguments: - `templatedir`: str - `host`: str - `port`: int Return: None Exceptions: None """ class DjangoPostman(BasePostman): """ Postman for use with Django's mail framework. """ def __init__(self): """ Do Django imports... """ self.html, self.plain = None, None from django.conf import settings from django.utils.functional import empty if settings._wrapped is empty: settings.configure() self.settings = settings super(DjangoPostman, self).__init__(settings.TEMPLATE_DIRS) self.mailer = DjangoMailer() class GmailPostman(SMTPAuthenticatedPostman): """ OK, so we're sending emails via Google's SMTP servers. >>> postie = GmailPostman('.', user='username', pw='password') """ def __init__(self, templatedir='.', user=None, pw=None): super(GmailPostman, self).__init__(templatedir=templatedir, host='smtp.gmail.com', port=587, user=user, pw=pw) class Letter(object): """ An individual Letter """ @classmethod def send(klass): to = klass.To subject = getattr(klass, 'Subject', '') if stringy(to): to = [to] if getattr(klass, 'Body', None): klass.Postie.send( klass.From, to, subject, klass.Body, cc=getattr(klass, 'Cc', None), bcc=getattr(klass, 'Bcc', None), replyto=getattr(klass, 'ReplyTo', None), attach=getattr(klass, 'Attach', None), ) return with klass.Postie.template(klass.Template): klass.Postie.send( klass.From, to, subject, cc=getattr(klass, 'Cc', None), bcc=getattr(klass, 'Bcc', None), replyto=getattr(klass, 'ReplyTo', None), attach=getattr(klass, 'Attach', None), **getattr(klass, 'Context', {}) ) """ Testing utilities start here. """ def _parse_outgoing_mail(sender, to, msgstring): """ Parse an outgoing mail and put it into the OUTBOX. Arguments: - `sender`: str - `to`: str - `msgstring`: str Return: None Exceptions: None """ global OUTBOX OUTBOX.append(email.message_from_string(msgstring)) return def setup_test_environment(): """ Set up our environment to test the sending of email with letter. We return an outbox for you, into which all emails will be delivered. Requires the Mock library. Return: list Exceptions: None """ import mock global OUTBOX, SMTP SMTP = smtplib.SMTP mock_smtp = mock.MagicMock(name='Mock SMTP') mock_smtp.return_value.sendmail.side_effect = _parse_outgoing_mail smtplib.SMTP = mock_smtp return OUTBOX def teardown_test_environment(): """ Tear down utilities for the testing of mail sent with letter. Return: None Exceptions: None """ global OUTBOX, SMTP smtplib.SMTP = SMTP OUTBOX = [] return
davidmiller/letter
letter/__init__.py
_parse_outgoing_mail
python
def _parse_outgoing_mail(sender, to, msgstring): global OUTBOX OUTBOX.append(email.message_from_string(msgstring)) return
Parse an outgoing mail and put it into the OUTBOX. Arguments: - `sender`: str - `to`: str - `msgstring`: str Return: None Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L581-L596
null
""" Send letters electronically. We assume you're likely to want to send emails from templates. Let's make that as easy as possible. """ from letter._version import __version__ import contextlib import email from email import encoders from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage import itertools import mimetypes import smtplib import types import ffs from ffs.contrib import mold from six import u, string_types, text_type __all__ = [ '__version__', 'Postman', 'DjangoPostman', 'GmailPostman', 'setup_test_environment', 'teardown_test_environment' ] flatten = lambda x: [item for sublist in x for item in sublist] stringy = lambda x: isinstance(x, string_types) listy = lambda x: isinstance(x, (list, tuple)) OUTBOX = [] SMTP = None class Error(Exception): pass class NoTemplateError(Error): pass class NoContentError(Error): pass def ensure_unicode(s): if isinstance(s, text_type): return s return u(s) def _stringlist(*args): """ Take a lists of strings or strings and flatten these into a list of strings. Arguments: - `*args`: "" or [""...] Return: [""...] Exceptions: None """ return list(itertools.chain.from_iterable(itertools.repeat(x,1) if stringy(x) else x for x in args if x)) class Attachment(object): """ A file we're attaching to an email. """ def __init__(self, path): self.path = ffs.Path(path) def as_msg(self): """ Convert ourself to be a message part of the appropriate MIME type. Return: MIMEBase Exceptions: None """ # Based upon http://docs.python.org/2/library/email-examples.html # with minimal tweaking # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(str(self.path)) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(self.path.read(), _subtype=subtype) elif maintype == 'image': fp = self.path.open('rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = self.path.open('rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = self.path.open('rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) filename = str(self.path[-1]) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg class BaseMailer(object): """ Mailers either handle the construction and delivery of message objects once we have determined the contents etc. """ def tolist(self, to): """ Make sure that our addressees are a unicoded list Arguments: - `to`: str or list Return: [u, ...] Exceptions: None """ return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)]) def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None): """ Sanity check the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str Return: None Exceptions: NoContentError """ if not plain and not html: raise NoContentError() class BaseSMTPMailer(BaseMailer): """ Construct the message """ def send(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None, replyto=None, attach=None): """ Send the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `attach`: str or [str] Return: None Exceptions: NoContentError """ self.sanity_check(sender, to, subject, plain=plain, html=html) # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('mixed') msg['Subject'] = u(subject) msg['From'] = u(sender) msg['To'] = self.tolist(to) if cc: msg['Cc'] = self.tolist(cc) recipients = _stringlist(to, cc, bcc) if replyto: msg.add_header('reply-to', replyto) # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. if plain: msg.attach(MIMEText(u(plain), 'plain')) if html: msg.attach(MIMEText(u(html), 'html')) # Deal with attachments. if attach: for p in _stringlist(attach): msg.attach(Attachment(p).as_msg()) self.deliver(msg, recipients) class SMTPMailer(BaseSMTPMailer): """ Use SMTP to deliver our message. """ def __init__(self, host, port): """ Store vars """ self.host = host self.port = port def deliver(self, message, to): """ Deliver our message Arguments: - `message`: MIMEMultipart Return: None Exceptions: None """ # Send the message via local SMTP server. s = smtplib.SMTP(self.host, self.port) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(message['From'], to, message.as_string()) s.quit() return class SMTPAuthenticatedMailer(BaseSMTPMailer): """ Use authenticated SMTP to deliver our message """ def __init__(self, host, port, user, pw): self.host = host self.port = port self.user = user self.pw = pw def deliver(self, message, to): """ Deliver our message Arguments: - `message`: MIMEMultipart Return: None Exceptions: None """ # Send the message via local SMTP server. s = smtplib.SMTP(self.host, self.port) s.ehlo() s.starttls() s.login(self.user, self.pw) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(message['From'], to, message.as_string()) s.quit() return class DjangoMailer(BaseMailer): """ Send email using whatever is configured in our Django project's email settings etc etc """ def send(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None, attach=None, replyto=None): """ Send the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str - `attach`: str or iterable of str - `replyto`: str Return: None Exceptions: NoContentError """ headers = {} if attach: raise NotImplementedError('Attachments not implemented for Django yet!') if replyto: headers['Reply-To'] = replyto self.sanity_check(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc) if not cc: cc = [] if not bcc: bcc = [] # This comes straight from the docs at # https://docs.djangoproject.com/en/dev/topics/email/ from django.core.mail import EmailMultiAlternatives if not plain: plain = '' msg = EmailMultiAlternatives(u(subject), u(plain), u(sender), _stringlist(to), bcc=bcc, cc=cc, headers=headers) if html: msg.attach_alternative(ensure_unicode(html), "text/html") msg.send() return class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """ found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found def _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """ return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html') def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): """ Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None """ self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return send = _send def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """ plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return def body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """ text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content @contextlib.contextmanager def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send class SMTPPostman(BasePostman): """ The SMTP Postman is a utility class for using SMTP as a delivery method for our messages. """ def __init__(self, templatedir=None, host='localhost', port=25): super(SMTPPostman, self).__init__(templatedir) self.mailer = SMTPMailer(host, port) class SMTPAuthenticatedPostman(BasePostman): """ The SMTP Postman is a utility class for using SMTP as a delivery method for our messages. """ def __init__(self, templatedir=None, host='localhost', port=25, user=None, pw=None): super(SMTPAuthenticatedPostman, self).__init__(templatedir) self.mailer = SMTPAuthenticatedMailer(host, port, user, pw) class Postman(SMTPPostman): """ The Postman is your main entrypoint to sending Electronic Mail. Set up an SMTP mailer at HOST:PORT using TEMPLATEDIR as the place to look for templates. If BLOCKING is True, use the blocking mailer. Arguments: - `templatedir`: str - `host`: str - `port`: int Return: None Exceptions: None """ class DjangoPostman(BasePostman): """ Postman for use with Django's mail framework. """ def __init__(self): """ Do Django imports... """ self.html, self.plain = None, None from django.conf import settings from django.utils.functional import empty if settings._wrapped is empty: settings.configure() self.settings = settings super(DjangoPostman, self).__init__(settings.TEMPLATE_DIRS) self.mailer = DjangoMailer() class GmailPostman(SMTPAuthenticatedPostman): """ OK, so we're sending emails via Google's SMTP servers. >>> postie = GmailPostman('.', user='username', pw='password') """ def __init__(self, templatedir='.', user=None, pw=None): super(GmailPostman, self).__init__(templatedir=templatedir, host='smtp.gmail.com', port=587, user=user, pw=pw) class Letter(object): """ An individual Letter """ @classmethod def send(klass): to = klass.To subject = getattr(klass, 'Subject', '') if stringy(to): to = [to] if getattr(klass, 'Body', None): klass.Postie.send( klass.From, to, subject, klass.Body, cc=getattr(klass, 'Cc', None), bcc=getattr(klass, 'Bcc', None), replyto=getattr(klass, 'ReplyTo', None), attach=getattr(klass, 'Attach', None), ) return with klass.Postie.template(klass.Template): klass.Postie.send( klass.From, to, subject, cc=getattr(klass, 'Cc', None), bcc=getattr(klass, 'Bcc', None), replyto=getattr(klass, 'ReplyTo', None), attach=getattr(klass, 'Attach', None), **getattr(klass, 'Context', {}) ) """ Testing utilities start here. """ def setup_test_environment(): """ Set up our environment to test the sending of email with letter. We return an outbox for you, into which all emails will be delivered. Requires the Mock library. Return: list Exceptions: None """ import mock global OUTBOX, SMTP SMTP = smtplib.SMTP mock_smtp = mock.MagicMock(name='Mock SMTP') mock_smtp.return_value.sendmail.side_effect = _parse_outgoing_mail smtplib.SMTP = mock_smtp return OUTBOX def teardown_test_environment(): """ Tear down utilities for the testing of mail sent with letter. Return: None Exceptions: None """ global OUTBOX, SMTP smtplib.SMTP = SMTP OUTBOX = [] return
davidmiller/letter
letter/__init__.py
Attachment.as_msg
python
def as_msg(self): # Based upon http://docs.python.org/2/library/email-examples.html # with minimal tweaking # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(str(self.path)) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(self.path.read(), _subtype=subtype) elif maintype == 'image': fp = self.path.open('rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = self.path.open('rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = self.path.open('rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) filename = str(self.path[-1]) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
Convert ourself to be a message part of the appropriate MIME type. Return: MIMEBase Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L72-L113
null
class Attachment(object): """ A file we're attaching to an email. """ def __init__(self, path): self.path = ffs.Path(path)
davidmiller/letter
letter/__init__.py
BaseMailer.tolist
python
def tolist(self, to): return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)])
Make sure that our addressees are a unicoded list Arguments: - `to`: str or list Return: [u, ...] Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L122-L132
null
class BaseMailer(object): """ Mailers either handle the construction and delivery of message objects once we have determined the contents etc. """ def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None): """ Sanity check the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str Return: None Exceptions: NoContentError """ if not plain and not html: raise NoContentError()
davidmiller/letter
letter/__init__.py
BaseMailer.sanity_check
python
def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None): if not plain and not html: raise NoContentError()
Sanity check the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str Return: None Exceptions: NoContentError
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L134-L154
null
class BaseMailer(object): """ Mailers either handle the construction and delivery of message objects once we have determined the contents etc. """ def tolist(self, to): """ Make sure that our addressees are a unicoded list Arguments: - `to`: str or list Return: [u, ...] Exceptions: None """ return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)])
davidmiller/letter
letter/__init__.py
BaseSMTPMailer.send
python
def send(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None, replyto=None, attach=None): self.sanity_check(sender, to, subject, plain=plain, html=html) # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('mixed') msg['Subject'] = u(subject) msg['From'] = u(sender) msg['To'] = self.tolist(to) if cc: msg['Cc'] = self.tolist(cc) recipients = _stringlist(to, cc, bcc) if replyto: msg.add_header('reply-to', replyto) # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. if plain: msg.attach(MIMEText(u(plain), 'plain')) if html: msg.attach(MIMEText(u(html), 'html')) # Deal with attachments. if attach: for p in _stringlist(attach): msg.attach(Attachment(p).as_msg()) self.deliver(msg, recipients)
Send the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `attach`: str or [str] Return: None Exceptions: NoContentError
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L162-L213
[ "def _stringlist(*args):\n \"\"\"\n Take a lists of strings or strings and flatten these into\n a list of strings.\n\n Arguments:\n - `*args`: \"\" or [\"\"...]\n\n Return: [\"\"...]\n Exceptions: None\n \"\"\"\n return list(itertools.chain.from_iterable(itertools.repeat(x,1) if stringy(x) else x for x in args if x))\n", "def as_msg(self):\n \"\"\"\n Convert ourself to be a message part of the appropriate\n MIME type.\n\n Return: MIMEBase\n Exceptions: None\n \"\"\"\n # Based upon http://docs.python.org/2/library/email-examples.html\n # with minimal tweaking\n\n # Guess the content type based on the file's extension. Encoding\n # will be ignored, although we should check for simple things like\n # gzip'd or compressed files.\n ctype, encoding = mimetypes.guess_type(str(self.path))\n if ctype is None or encoding is not None:\n # No guess could be made, or the file is encoded (compressed), so\n # use a generic bag-of-bits type.\n ctype = 'application/octet-stream'\n maintype, subtype = ctype.split('/', 1)\n if maintype == 'text':\n # Note: we should handle calculating the charset\n msg = MIMEText(self.path.read(), _subtype=subtype)\n elif maintype == 'image':\n fp = self.path.open('rb')\n msg = MIMEImage(fp.read(), _subtype=subtype)\n fp.close()\n elif maintype == 'audio':\n fp = self.path.open('rb')\n msg = MIMEAudio(fp.read(), _subtype=subtype)\n fp.close()\n else:\n fp = self.path.open('rb')\n msg = MIMEBase(maintype, subtype)\n msg.set_payload(fp.read())\n fp.close()\n # Encode the payload using Base64\n encoders.encode_base64(msg)\n\n filename = str(self.path[-1])\n msg.add_header('Content-Disposition', 'attachment', filename=filename)\n return msg\n", "def tolist(self, to):\n \"\"\"\n Make sure that our addressees are a unicoded list\n\n Arguments:\n - `to`: str or list\n\n Return: [u, ...]\n Exceptions: None\n \"\"\"\n return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)])\n", "def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None):\n \"\"\"\n Sanity check the message.\n\n If we have PLAIN and HTML versions, send a multipart alternative\n MIME message, else send whichever we do have.\n\n If we have neither, raise NoContentError\n\n Arguments:\n - `sender`: str\n - `to`: list\n - `subject`: str\n - `plain`: str\n - `html`: str\n\n Return: None\n Exceptions: NoContentError\n \"\"\"\n if not plain and not html:\n raise NoContentError()\n" ]
class BaseSMTPMailer(BaseMailer): """ Construct the message """
davidmiller/letter
letter/__init__.py
SMTPMailer.deliver
python
def deliver(self, message, to): # Send the message via local SMTP server. s = smtplib.SMTP(self.host, self.port) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(message['From'], to, message.as_string()) s.quit() return
Deliver our message Arguments: - `message`: MIMEMultipart Return: None Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L228-L244
null
class SMTPMailer(BaseSMTPMailer): """ Use SMTP to deliver our message. """ def __init__(self, host, port): """ Store vars """ self.host = host self.port = port
davidmiller/letter
letter/__init__.py
SMTPAuthenticatedMailer.deliver
python
def deliver(self, message, to): # Send the message via local SMTP server. s = smtplib.SMTP(self.host, self.port) s.ehlo() s.starttls() s.login(self.user, self.pw) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(message['From'], to, message.as_string()) s.quit() return
Deliver our message Arguments: - `message`: MIMEMultipart Return: None Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L258-L277
null
class SMTPAuthenticatedMailer(BaseSMTPMailer): """ Use authenticated SMTP to deliver our message """ def __init__(self, host, port, user, pw): self.host = host self.port = port self.user = user self.pw = pw
davidmiller/letter
letter/__init__.py
DjangoMailer.send
python
def send(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None, attach=None, replyto=None): headers = {} if attach: raise NotImplementedError('Attachments not implemented for Django yet!') if replyto: headers['Reply-To'] = replyto self.sanity_check(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc) if not cc: cc = [] if not bcc: bcc = [] # This comes straight from the docs at # https://docs.djangoproject.com/en/dev/topics/email/ from django.core.mail import EmailMultiAlternatives if not plain: plain = '' msg = EmailMultiAlternatives(u(subject), u(plain), u(sender), _stringlist(to), bcc=bcc, cc=cc, headers=headers) if html: msg.attach_alternative(ensure_unicode(html), "text/html") msg.send() return
Send the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str - `attach`: str or iterable of str - `replyto`: str Return: None Exceptions: NoContentError
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L286-L336
[ "def ensure_unicode(s):\n if isinstance(s, text_type):\n return s\n return u(s)\n", "def _stringlist(*args):\n \"\"\"\n Take a lists of strings or strings and flatten these into\n a list of strings.\n\n Arguments:\n - `*args`: \"\" or [\"\"...]\n\n Return: [\"\"...]\n Exceptions: None\n \"\"\"\n return list(itertools.chain.from_iterable(itertools.repeat(x,1) if stringy(x) else x for x in args if x))\n", "def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None):\n \"\"\"\n Sanity check the message.\n\n If we have PLAIN and HTML versions, send a multipart alternative\n MIME message, else send whichever we do have.\n\n If we have neither, raise NoContentError\n\n Arguments:\n - `sender`: str\n - `to`: list\n - `subject`: str\n - `plain`: str\n - `html`: str\n\n Return: None\n Exceptions: NoContentError\n \"\"\"\n if not plain and not html:\n raise NoContentError()\n" ]
class DjangoMailer(BaseMailer): """ Send email using whatever is configured in our Django project's email settings etc etc """
davidmiller/letter
letter/__init__.py
BasePostman._find_tpl
python
def _find_tpl(self, name, extension='.jinja2'): found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found
Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L354-L376
null
class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """ return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html') def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): """ Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None """ self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return send = _send def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """ plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return def body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """ text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content @contextlib.contextmanager def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send
davidmiller/letter
letter/__init__.py
BasePostman._find_tpls
python
def _find_tpls(self, name): return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html')
Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L378-L388
[ "def _find_tpl(self, name, extension='.jinja2'):\n \"\"\"\n Return a Path object representing the Template we're after,\n searching SELF.tpls or None\n\n Arguments:\n - `name`: str\n\n Return: Path or None\n Exceptions: None\n \"\"\"\n found = None\n for loc in self.tpls:\n if not loc:\n continue\n contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)]\n if contents:\n found = contents[0]\n break\n exact = loc + (name + extension)\n if exact.is_file:\n found = exact\n return found\n" ]
class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """ found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): """ Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None """ self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return send = _send def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """ plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return def body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """ text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content @contextlib.contextmanager def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send
davidmiller/letter
letter/__init__.py
BasePostman._send
python
def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return
Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L390-L407
null
class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """ found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found def _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """ return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html') send = _send def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """ plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return def body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """ text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content @contextlib.contextmanager def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send
davidmiller/letter
letter/__init__.py
BasePostman._sendtpl
python
def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return
Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L411-L431
null
class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """ found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found def _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """ return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html') def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): """ Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None """ self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return send = _send def body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """ text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content @contextlib.contextmanager def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send
davidmiller/letter
letter/__init__.py
BasePostman.body
python
def body(self, **kwargs): text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content
Return the plain and html versions of our contents. Return: tuple Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L433-L445
null
class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """ found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found def _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """ return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html') def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): """ Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None """ self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return send = _send def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """ plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return @contextlib.contextmanager def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send
davidmiller/letter
letter/__init__.py
BasePostman.template
python
def template(self, name): self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send
Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None
train
https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/__init__.py#L448-L468
[ "def _find_tpl(self, name, extension='.jinja2'):\n \"\"\"\n Return a Path object representing the Template we're after,\n searching SELF.tpls or None\n\n Arguments:\n - `name`: str\n\n Return: Path or None\n Exceptions: None\n \"\"\"\n found = None\n for loc in self.tpls:\n if not loc:\n continue\n contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)]\n if contents:\n found = contents[0]\n break\n exact = loc + (name + extension)\n if exact.is_file:\n found = exact\n return found\n", "def _find_tpls(self, name):\n \"\"\"\n Return plain, html templates for NAME\n\n Arguments:\n - `name`: str\n\n Return: tuple\n Exceptions: None\n \"\"\"\n return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html')\n" ]
class BasePostman(object): """ Implement common postman-esque methods """ def __init__(self, templatedir): """ Set template locations """ if isinstance(templatedir, (list, tuple)): self.tpls = [ffs.Path(t) for t in templatedir] else: self.tpls = [ffs.Path(templatedir)] return def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """ found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact return found def _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """ return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html') def _send(self, sender, to, subject, message, cc=None, bcc=None, attach=None, replyto=None): """ Send a Letter (MESSAGE) from SENDER to TO, with the subject SUBJECT Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `message`: unicode - `cc`: str or [str] - `bcc`: str or [str] ` `replyto`: str Return: None Exceptions: None """ self.mailer.send(sender, to, subject, plain=message, cc=cc, bcc=bcc, attach=attach, replyto=replyto) return send = _send def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """ plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) return def body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """ text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_content @contextlib.contextmanager
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.pathNames
python
def pathNames(self) -> [str]: return [f.pathName for f in list(self._files.values())]
Path Names @return: A list of path + name of each file, relative to the root directory.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L141-L148
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.paths
python
def paths(self) -> [str]: return set([f.path for f in list(self._files.values())])
Paths @return: A list of the paths, effectively a list of relative directory names.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L151-L158
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.getFile
python
def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName)
Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L160-L177
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.createFile
python
def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file
Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L179-L196
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.createTempFile
python
def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file
Create File Creates a new file within the directory with a temporary file like name. @return: Created file.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L198-L218
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.createHiddenFolder
python
def createHiddenFolder(self) -> 'File': if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".")
Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L220-L231
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory._listFilesWin
python
def _listFilesWin(self) -> ['File']: output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output
List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L233-L248
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory._listFilesPosix
python
def _listFilesPosix(self) -> ['File']: find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output
List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L250-L262
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.scan
python
def scan(self) -> ['File']: self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files
Scan Scan the directory for files and folders and update the file dictionary. @return: List of files
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L264-L283
[ "def _listFilesWin(self) -> ['File']:\n \"\"\" List Files for Windows OS\n\n Search and list the files and folder in the current directory for the\n Windows file system.\n\n @return: List of directory files and folders.\n \"\"\"\n\n output = []\n for dirname, dirnames, filenames in os.walk(self._path):\n for subdirname in dirnames:\n output.append(os.path.join(dirname, subdirname))\n for filename in filenames:\n output.append(os.path.join(dirname, filename))\n return output\n", "def _listFilesPosix(self) -> ['File']:\n \"\"\" List Files for POSIX\n\n Search and list the files and folder in the current directory for the\n POSIX file system.\n\n @return: List of directory files and folders.\n \"\"\"\n\n find = \"find %s -type f\" % self._path\n output = check_output(args=find.split()).strip().decode().split(\n '\\n')\n return output\n" ]
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory.clone
python
def clone(self, autoDelete: bool = True) -> 'Directory': d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d
Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L285-L301
[ "def scan(self) -> ['File']:\n \"\"\" Scan\n\n Scan the directory for files and folders and update the file dictionary.\n\n @return: List of files\n \"\"\"\n\n self._files = {}\n output = self._listFilesWin() if isWindows else self._listFilesPosix()\n output = [line for line in output if \"__MACOSX\" not in line]\n for pathName in output:\n if not pathName: # Sometimes we get empty lines\n continue\n\n pathName = pathName[len(self._path) + 1:]\n file = File(self, pathName=pathName, exists=True)\n self._files[file.pathName] = file\n\n return self.files\n" ]
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName) def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ self._files.pop(oldPathName) self._files[file.pathName] = file
Synerty/pytmpdir
pytmpdir/Directory.py
Directory._fileMoved
python
def _fileMoved(self, oldPathName: str, file: 'File'): self._files.pop(oldPathName) self._files[file.pathName] = file
File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L314-L326
null
class Directory(object): """ Directory Functions as a directory object to extract, archive and pass around code. Auto deletes when the directory falls out of scope. """ def __init__(self, initWithDir: bool = None, autoDelete: bool = True, inDir: str = None): """ Directory Initialise Creates a temporary directory if the directory doesn't exist. @param initWithDir: Force creation of temporary directory. @param autoDelete: Remove temporary files and folders. Default as True. @param inDir: Current directory. @type initWithDir: Boolean @type autoDelete: Boolean @type inDir: String """ self._files = {} self._autoDelete = autoDelete if initWithDir: self._path = initWithDir self.scan() else: if (os.path.isdir(inDir if inDir else DirSettings.tmpDirPath) is False): os.mkdir(inDir if inDir else DirSettings.tmpDirPath) self._path = tempfile.mkdtemp(dir=(inDir if inDir else DirSettings.tmpDirPath)) closurePath = self._path def cleanup(me): """ Cleanup Recursively delete a directory tree of the created path. """ if autoDelete: shutil.rmtree(closurePath) self.__cleanupRef = weakref.ref(self, cleanup) @property def path(self) -> str: """ Path :return The absolute path of this directory """ return self._path @property def delete(self) -> bool: """ Delete :return True if this directory will delete it's self when it falls out of scope. """ return self._autoDelete @property def files(self) -> ['File']: """ Files @return: A list of the Directory.File objects. """ return list(self._files.values()) @property def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())] @property def paths(self) -> [str]: """ Paths @return: A list of the paths, effectively a list of relative directory names. """ return set([f.path for f in list(self._files.values())]) def getFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Get File Get File name corresponding to a path name. @param path: File path. Default as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Specific file from dictionary. """ assert (name or pathName) pathName = (pathName if pathName else os.path.join(path, name)) return self._files.get(pathName) def createFile(self, path: str = '', name: str = None, pathName: str = None) -> 'File': """ Create File Creates a new file and updates file dictionary. @param path: File path. Defaults as empty string. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @type path: String @type name: String @type pathName: String @return: Created file. """ file = File(self, path=path, name=name, pathName=pathName) self._files[file.pathName] = file return file def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File': """ Create File Creates a new file within the directory with a temporary file like name. @return: Created file. """ if not secure: raise NotImplementedError("We only support secure files at this point") # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False) newFileNum, newFileRealPath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=self._path) os.close(newFileNum) relativePath = os.path.relpath(newFileRealPath, self.path) file = File(self, pathName=relativePath, exists=True) self._files[file.pathName] = file return file def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ if not self._autoDelete: raise Exception("Hidden folders can only be created within" " an autoDelete directory") return tempfile.mkdtemp(dir=self._path, prefix=".") def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @return: List of directory files and folders. """ output = [] for dirname, dirnames, filenames in os.walk(self._path): for subdirname in dirnames: output.append(os.path.join(dirname, subdirname)) for filename in filenames: output.append(os.path.join(dirname, filename)) return output def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: List of directory files and folders. """ find = "find %s -type f" % self._path output = check_output(args=find.split()).strip().decode().split( '\n') return output def scan(self) -> ['File']: """ Scan Scan the directory for files and folders and update the file dictionary. @return: List of files """ self._files = {} output = self._listFilesWin() if isWindows else self._listFilesPosix() output = [line for line in output if "__MACOSX" not in line] for pathName in output: if not pathName: # Sometimes we get empty lines continue pathName = pathName[len(self._path) + 1:] file = File(self, pathName=pathName, exists=True) self._files[file.pathName] = file return self.files def clone(self, autoDelete: bool = True) -> 'Directory': """ Clone Recursively copy a directory tree. Removes the destination directory as the destination directory must not already exist. @param autoDelete: Used to clean up files on completion. Default as True. @type autoDelete: Boolean @return: The cloned directory. """ d = Directory(autoDelete=autoDelete) os.rmdir(d._path) # shutil doesn't like it existing shutil.copytree(self._path, d._path) d.scan() return d def _fileDeleted(self, file: 'File'): """ File Deleted Drop the file name from dictionary. @param file: File name. @type file: File """ self._files.pop(file.pathName)
Synerty/pytmpdir
pytmpdir/Directory.py
File.path
python
def path(self, path: str): path = path if path else '' self.pathName = os.path.join(path, self.name)
Path Setter Set path with passed in variable. @param path: New path string. @type path: String
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L472-L482
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName) def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File.name
python
def name(self, name: str): self.pathName = os.path.join(self.path, name)
Name Setter Set name with passed in variable. @param name: New name string. @type name: String
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L496-L505
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName) def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File.pathName
python
def pathName(self, pathName: str): if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self)
Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L519-L547
[ "def _realPath(self, newPathName: str = None) -> str:\n \"\"\" Private Real Path\n\n Get path name.\n\n @param newPathName: variable for new path name if passed argument.\n @type newPathName: String\n @return: Path Name as string.\n \"\"\"\n\n directory = self._directory()\n assert directory\n return os.path.join(directory.path,\n newPathName if newPathName else self._pathName)\n", "def sanitise(self, pathName: str) -> str:\n \"\"\" Sanitise\n\n Clean unwanted characters from the pathName string.\n\n @param pathName: Path name variable.\n @type pathName: String\n @return: Path name as string.\n \"\"\"\n\n assert isinstance(pathName, str)\n assert '..' not in pathName\n assert not pathName.endswith(os.sep)\n\n while pathName.startswith(os.sep):\n pathName = pathName[1:]\n\n return pathName\n" ]
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName) def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File.open
python
def open(self, append: bool = False, write: bool = False): flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag)
Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L549-L572
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName) def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File.namedTempFileReader
python
def namedTempFileReader(self) -> NamedTempFileReader: # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self)
Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L574-L590
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName) def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File.delete
python
def delete(self): directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self)
Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L592-L606
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName) def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File.remove
python
def remove(self): directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self)
Remove Removes the file from the Directory object, file on file system remains on disk.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L608-L617
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName) def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File._realPath
python
def _realPath(self, newPathName: str = None) -> str: directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName)
Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L664-L677
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def sanitise(self, pathName: str) -> str: """ Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string. """ assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Synerty/pytmpdir
pytmpdir/Directory.py
File.sanitise
python
def sanitise(self, pathName: str) -> str: assert isinstance(pathName, str) assert '..' not in pathName assert not pathName.endswith(os.sep) while pathName.startswith(os.sep): pathName = pathName[1:] return pathName
Sanitise Clean unwanted characters from the pathName string. @param pathName: Path name variable. @type pathName: String @return: Path name as string.
train
https://github.com/Synerty/pytmpdir/blob/8f21d7a0b28d4f5c3a0ed91f9660ac5310773605/pytmpdir/Directory.py#L679-L696
null
class File(object): def __init__(self, directory: Directory, path: str = '', name: str = None, pathName: str = None, exists: bool = False): """ File Test whether a path exists. Set the access and modified time of path. Change the access permissions of a file. @param directory: Directory instance. Default as empty string. @param path: File path. @param name: File name to be used if passed. @param pathName: Joined file name and path to be used if passed. @param exists: Passed argument. Default as False. @type directory: Directory @type path: String @type name: String @type pathName: String @type exists: Boolean """ assert (isinstance(directory, Directory)) assert (name or pathName) self._directory = weakref.ref(directory) if name: path = path if path else '' self._pathName = os.path.join(path, name) elif pathName: self._pathName = pathName self._pathName = self.sanitise(self._pathName) if not exists and os.path.exists(self.realPath): raise FileClobberError(self.realPath) if exists and not os.path.exists(self.realPath): raise FileDisappearedError(self.realPath) if not os.path.exists(self.realPath): with self.open(append=True): os.utime(self.realPath, None) os.chmod(self.realPath, 0o600) # ----- Name and Path setters @property def path(self) -> str: """ Path Determines directory name. @return: Path as string. """ return os.path.dirname(self.pathName) @path.setter def path(self, path: str): """ Path Setter Set path with passed in variable. @param path: New path string. @type path: String """ path = path if path else '' self.pathName = os.path.join(path, self.name) @property def name(self) -> str: """ Name Determines working directory. @return: Directory name as string. """ return os.path.basename(self.pathName) @name.setter def name(self, name: str): """ Name Setter Set name with passed in variable. @param name: New name string. @type name: String """ self.pathName = os.path.join(self.path, name) @property def pathName(self) -> str: """ Path Name Returns stored path name. @return: Path Name as string. """ return self._pathName @pathName.setter def pathName(self, pathName: str): """ Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new path name. @param pathName: New path name string. @type pathName: String """ if self.pathName == pathName: return pathName = self.sanitise(pathName) before = self.realPath after = self._realPath(pathName) assert (not os.path.exists(after)) newRealDir = os.path.dirname(after) if not os.path.exists(newRealDir): os.makedirs(newRealDir, DirSettings.defaultDirChmod) shutil.move(before, after) oldPathName = self._pathName self._pathName = pathName self._directory()._fileMoved(oldPathName, self) def open(self, append: bool = False, write: bool = False): """ Open Pass arguments and return open file. @param append: Open for writing, appending to the end of the file if it exists. Default as False. @param write: Open for writing, truncating the file first. Default as False. @type append: Boolean @type write: Boolean @return: Open file function. """ flag = {(False, False): 'r', (True, False): 'a', (True, True): 'a', (False, True): 'w'}[(append, write)] realPath = self.realPath realDir = os.path.dirname(realPath) if not os.path.exists(realDir): os.makedirs(realDir, DirSettings.defaultDirChmod) return open(self.realPath, flag) def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being written to """ # Get the weak ref directory = self._directory() assert isinstance(directory, Directory), ( "Expected Directory, receieved %s" % directory) # Return the object return NamedTempFileReader(directory, self) def delete(self): """ Delete Deletes directory and drops the file name from dictionary. File on file system removed on disk. """ directory = self._directory() assert isinstance(directory, Directory) realPath = self.realPath assert (os.path.exists(realPath)) os.remove(realPath) directory._fileDeleted(self) def remove(self): """ Remove Removes the file from the Directory object, file on file system remains on disk. """ directory = self._directory() assert isinstance(directory, Directory) directory._fileDeleted(self) @property def size(self) -> str: """ Size Determines size of directory. @return: Total size, in bytes. """ return os.stat(self.realPath).st_size @property def mTime(self) -> str: """ mTime Return the last modification time of a file, reported by os.stat(). @return: Time as string. """ return os.path.getmtime(self.realPath) @property def isContentText(self): """ Is Content Text Determine if the file contains text. @return: True if file contains text. """ with self.open() as f: return not is_binary_string(self.open().read(40000)) @property def realPath(self) -> str: """ Real Path Get path name. @return: Path Name as string. """ return self._realPath() def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert directory return os.path.join(directory.path, newPathName if newPathName else self._pathName)
xtream1101/web-wrapper
web_wrapper/web.py
Web.get_image_dimension
python
def get_image_dimension(self, url): w_h = (None, None) try: if url.startswith('//'): url = 'http:' + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Error getting image size {}".format(url), exc_info=True) return w_h
Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/web.py#L64-L81
null
class Web: """ Web related functions Need to be on its own that way each profile can have its own instance of it for proxy support """ def __init__(self, headers={}, cookies={}, proxy=None, **driver_args): self.scraper = None self.driver = None self.driver_args = driver_args self.current_proxy = proxy # Number of times to re-try a url self._num_retries = 3 if headers is not None: self.current_headers = headers else: self.current_headers = {} if cookies is not None: self.current_cookies = cookies else: self.current_cookies = {} # Set the default response values self._reset_response() def _reset_response(self): """ Vars to track per request made Run before ever get_site to clear previous values """ self.status_code = None self.url = None self.response = None def get_soup(self, raw_content, input_type='html'): rdata = None if input_type == 'html': rdata = BeautifulSoup(raw_content, 'html.parser') # Other option: html5lib elif input_type == 'xml': rdata = BeautifulSoup(raw_content, 'lxml') return rdata def screenshot(self, save_path, element=None, delay=0): """ This can be used no matter what driver that is being used * ^ Soon requests support will be added Save screenshot to local dir with uuid as filename then move the file to `filename` (path must be part of the file name) Return the filepath of the image """ if save_path is None: logger.error("save_path cannot be None") return None save_location = cutil.norm_path(save_path) cutil.create_path(save_location) logger.info("Taking screenshot: {filename}".format(filename=save_location)) if not self.driver_type.startswith('selenium'): logger.debug("Create tmp phantomjs web driver for screenshot") # Create a tmp phantom driver to take the screenshot for us from web_wrapper import DriverSeleniumPhantomJS headers = self.get_headers() # Get headers to pass to the driver proxy = self.get_proxy() # Get the current proxy being used if any # TODO: ^ Do the same thing for cookies screenshot_web = DriverSeleniumPhantomJS(headers=headers, proxy=proxy) screenshot_web.get_site(self.url, page_format='raw') screenshot_driver = screenshot_web.driver else: screenshot_driver = self.driver # If a background color does need to be set # self.driver.execute_script('document.body.style.background = "{}"'.format('white')) # Take screenshot # Give the page some extra time to load time.sleep(delay) if self.driver_type == 'selenium_chrome': # Need to do this for chrome to get a fullpage screenshot self.chrome_fullpage_screenshot(save_location, delay) else: screenshot_driver.get_screenshot_as_file(save_location) # Use .png extenstion for users save file if not save_location.endswith('.png'): save_location += '.png' # If an element was passed, just get that element so crop the screenshot if element is not None: logger.debug("Crop screenshot") # Crop the image el_location = element.location el_size = element.size try: cutil.crop_image(save_location, output_file=save_location, width=int(el_size['width']), height=int(el_size['height']), x=int(el_location['x']), y=int(el_location['y']), ) except Exception as e: raise e.with_traceback(sys.exc_info()[2]) if not self.driver_type.startswith('selenium'): # Quit the tmp driver created to take the screenshot screenshot_web.quit() return save_location def new_proxy(self): raise NotImplementedError def new_headers(self): raise NotImplementedError def _try_new_proxy(self): try: new_proxy = self.new_proxy() self.set_proxy(new_proxy) except NotImplementedError: logger.warning("No function new_proxy() found, not changing proxy") except Exception: logger.exception("Something went wrong when getting a new proxy") def _try_new_headers(self): try: new_headers = self.new_headers() self.set_headers(new_headers) except NotImplementedError: logger.warning("No function new_headers() found, not changing headers") except Exception: logger.exception("Something went wrong when getting a new header") def new_profile(self): logger.info("Create a new profile to use") self._try_new_proxy() self._try_new_headers() ########################################################################### # Get/load page ########################################################################### def get_site(self, url, cookies={}, page_format='html', return_on_error=[], retry_enabled=True, num_tries=0, num_apikey_tries=0, headers={}, api=False, track_stat=True, timeout=30, force_requests=False, driver_args=(), driver_kwargs={}, parser='beautifulsoup', custom_source_checks=[]): """ headers & cookies - Will update to the current headers/cookies and just be for this request driver_args & driver_kwargs - Gets passed and expanded out to the driver """ self._reset_response() num_tries += 1 # Save args and kwargs so they can be used for trying the function again tmp_args = locals().copy() get_site_args = [tmp_args['url']] # Remove keys that dont belong to the keywords passed in del tmp_args['url'] del tmp_args['self'] get_site_kwargs = tmp_args # Check driver_kwargs for anything that we already set kwargs_cannot_be = ['headers', 'cookies', 'timeout'] for key_name in kwargs_cannot_be: if driver_kwargs.get(key_name) is not None: del driver_kwargs[key_name] logger.warning("Cannot pass `{key}` in driver_kwargs to get_site(). `{key}` is already set by default" .format(key=key_name)) # Check if a url is being passed in if url is None: logger.error("Url cannot be None") return None ## # url must start with http.... ## prepend = '' if url.startswith('//'): prepend = 'http:' elif not url.startswith('http'): prepend = 'http://' url = prepend + url ## # Try and get the page ## rdata = None try: source_text = self._get_site(url, headers, cookies, timeout, driver_args, driver_kwargs) if custom_source_checks: # Check if there are any custom check to run for re_text, status_code in custom_source_checks: if re.search(re_text, source_text): if self.response is None: # This is needed when using selenium and we still need to pass in the 'response' self.response = type('', (), {})() self.response.status_code = status_code self.status_code = status_code raise requests.exceptions.HTTPError("Custom matched status code", response=self.response) rdata = self.parse_source(source_text, page_format, parser) ## # Exceptions from Selenium ## # Nothing yet ## # Exceptions from Requests ## except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: """ Try again with a new profile (do not get new apikey) Wait n seconds before trying again """ e_name = type(e).__name__ if num_tries < self._num_retries and retry_enabled is True: logger.info("{} [get_site]: try #{} on {} Error {}".format(e_name, num_tries, url, e)) time.sleep(2) self.new_profile() return self.get_site(*get_site_args, **get_site_kwargs) else: logger.error("{} [get_site]: try #{} on{}".format(e_name, num_tries, url)) except requests.exceptions.TooManyRedirects as e: logger.exception("TooManyRedirects [get_site]: {}".format(url)) ## # Exceptions shared by Selenium and Requests ## except (requests.exceptions.HTTPError, SeleniumHTTPError) as e: """ Check the status code returned to see what should be done """ status_code = str(e.response.status_code) # If the client wants to handle the error send it to them if int(status_code) in return_on_error: raise e.with_traceback(sys.exc_info()[2]) try_again = self._get_site_status_code(url, status_code, api, num_tries, num_apikey_tries) if try_again is True and retry_enabled is True: # If True then try request again return self.get_site(*get_site_args, **get_site_kwargs) # Every other exceptions that were not caught except Exception: logger.exception("Unknown Exception [get_site]: {url}".format(url=url)) return rdata def _get_site_status_code(self, url, status_code, api, num_tries, num_apikey_tries): """ Check the http status code and num_tries/num_apikey_tries to see if it should try again or not Log any data as needed """ # Make status code an int try: status_code = int(status_code) except ValueError: logger.exception("Incorrect status code passed in") return None # TODO: Try with the same api key 3 times, then try with with a new apikey the same way for 3 times as well # try_profile_again = False # if api is True and num_apikey_tries < self._num_retries: # # Try with the same apikey/profile again after a short wait # try_profile_again = True # Retry for any status code in the 400's or greater if status_code >= 400 and num_tries < self._num_retries: # Fail after 3 tries logger.info("HTTP error, try #{}, Status: {} on url: {}".format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) time.sleep(.5) self.new_profile() return True else: logger.warning("HTTPError [get_site]\n\t# of Tries: {}\n\tCode: {} - {}" .format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) return None def parse_source(self, source, page_format, parser): rdata = None if page_format == 'html': if parser == 'beautifulsoup': rdata = self.get_soup(source, input_type='html') elif parser == 'parsel': rdata = Selector(text=source) else: logger.error("No parser passed for parsing html") elif page_format == 'json': if self.driver_type == 'requests': rdata = json.loads(source) else: rdata = json.loads(self.driver.find_element_by_tag_name('body').text) elif page_format == 'xml': rdata = self.get_soup(source, input_type='xml') elif page_format == 'raw': # Return unparsed html rdata = source return rdata def download(self, url, save_path, header={}, redownload=False): """ Currently does not use the proxied driver TODO: Be able to use cookies just like headers is used here :return: the path of the file that was saved """ if save_path is None: logger.error("save_path cannot be None") return None # Get headers of current web driver header = self.get_headers() if len(header) > 0: # Add more headers if needed header.update(header) logger.debug("Download {url} to {save_path}".format(url=url, save_path=save_path)) save_location = cutil.norm_path(save_path) if redownload is False: # See if we already have the file if os.path.isfile(save_location): logger.debug("File {save_location} already exists".format(save_location=save_location)) return save_location # Create the dir path on disk cutil.create_path(save_location) if url.startswith('//'): url = "http:" + url try: with urllib.request.urlopen(urllib.request.Request(url, headers=header)) as response,\ open(save_location, 'wb') as out_file: data = response.read() out_file.write(data) except urllib.error.HTTPError as e: save_location = None # We do not need to show the user 404 errors if e.code != 404: logger.exception("Download Http Error {url}".format(url=url)) except Exception: save_location = None logger.exception("Download Error: {url}".format(url=url)) return save_location
xtream1101/web-wrapper
web_wrapper/web.py
Web.screenshot
python
def screenshot(self, save_path, element=None, delay=0): if save_path is None: logger.error("save_path cannot be None") return None save_location = cutil.norm_path(save_path) cutil.create_path(save_location) logger.info("Taking screenshot: {filename}".format(filename=save_location)) if not self.driver_type.startswith('selenium'): logger.debug("Create tmp phantomjs web driver for screenshot") # Create a tmp phantom driver to take the screenshot for us from web_wrapper import DriverSeleniumPhantomJS headers = self.get_headers() # Get headers to pass to the driver proxy = self.get_proxy() # Get the current proxy being used if any # TODO: ^ Do the same thing for cookies screenshot_web = DriverSeleniumPhantomJS(headers=headers, proxy=proxy) screenshot_web.get_site(self.url, page_format='raw') screenshot_driver = screenshot_web.driver else: screenshot_driver = self.driver # If a background color does need to be set # self.driver.execute_script('document.body.style.background = "{}"'.format('white')) # Take screenshot # Give the page some extra time to load time.sleep(delay) if self.driver_type == 'selenium_chrome': # Need to do this for chrome to get a fullpage screenshot self.chrome_fullpage_screenshot(save_location, delay) else: screenshot_driver.get_screenshot_as_file(save_location) # Use .png extenstion for users save file if not save_location.endswith('.png'): save_location += '.png' # If an element was passed, just get that element so crop the screenshot if element is not None: logger.debug("Crop screenshot") # Crop the image el_location = element.location el_size = element.size try: cutil.crop_image(save_location, output_file=save_location, width=int(el_size['width']), height=int(el_size['height']), x=int(el_location['x']), y=int(el_location['y']), ) except Exception as e: raise e.with_traceback(sys.exc_info()[2]) if not self.driver_type.startswith('selenium'): # Quit the tmp driver created to take the screenshot screenshot_web.quit() return save_location
This can be used no matter what driver that is being used * ^ Soon requests support will be added Save screenshot to local dir with uuid as filename then move the file to `filename` (path must be part of the file name) Return the filepath of the image
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/web.py#L91-L159
[ "def get_site(self, url, cookies={}, page_format='html', return_on_error=[], retry_enabled=True,\n num_tries=0, num_apikey_tries=0, headers={}, api=False, track_stat=True, timeout=30,\n force_requests=False, driver_args=(), driver_kwargs={}, parser='beautifulsoup',\n custom_source_checks=[]):\n \"\"\"\n headers & cookies - Will update to the current headers/cookies and just be for this request\n driver_args & driver_kwargs - Gets passed and expanded out to the driver\n \"\"\"\n self._reset_response()\n\n num_tries += 1\n # Save args and kwargs so they can be used for trying the function again\n tmp_args = locals().copy()\n get_site_args = [tmp_args['url']]\n # Remove keys that dont belong to the keywords passed in\n del tmp_args['url']\n del tmp_args['self']\n get_site_kwargs = tmp_args\n\n # Check driver_kwargs for anything that we already set\n kwargs_cannot_be = ['headers', 'cookies', 'timeout']\n for key_name in kwargs_cannot_be:\n if driver_kwargs.get(key_name) is not None:\n del driver_kwargs[key_name]\n logger.warning(\"Cannot pass `{key}` in driver_kwargs to get_site(). `{key}` is already set by default\"\n .format(key=key_name))\n\n # Check if a url is being passed in\n if url is None:\n logger.error(\"Url cannot be None\")\n return None\n\n ##\n # url must start with http....\n ##\n prepend = ''\n if url.startswith('//'):\n prepend = 'http:'\n\n elif not url.startswith('http'):\n prepend = 'http://'\n\n url = prepend + url\n\n ##\n # Try and get the page\n ##\n rdata = None\n try:\n source_text = self._get_site(url, headers, cookies, timeout, driver_args, driver_kwargs)\n if custom_source_checks:\n # Check if there are any custom check to run\n for re_text, status_code in custom_source_checks:\n if re.search(re_text, source_text):\n if self.response is None:\n # This is needed when using selenium and we still need to pass in the 'response'\n self.response = type('', (), {})()\n self.response.status_code = status_code\n self.status_code = status_code\n raise requests.exceptions.HTTPError(\"Custom matched status code\", response=self.response)\n\n rdata = self.parse_source(source_text, page_format, parser)\n\n ##\n # Exceptions from Selenium\n ##\n # Nothing yet\n\n ##\n # Exceptions from Requests\n ##\n except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:\n \"\"\"\n Try again with a new profile (do not get new apikey)\n Wait n seconds before trying again\n \"\"\"\n e_name = type(e).__name__\n if num_tries < self._num_retries and retry_enabled is True:\n logger.info(\"{} [get_site]: try #{} on {} Error {}\".format(e_name, num_tries, url, e))\n time.sleep(2)\n self.new_profile()\n return self.get_site(*get_site_args, **get_site_kwargs)\n\n else:\n logger.error(\"{} [get_site]: try #{} on{}\".format(e_name, num_tries, url))\n\n except requests.exceptions.TooManyRedirects as e:\n logger.exception(\"TooManyRedirects [get_site]: {}\".format(url))\n\n ##\n # Exceptions shared by Selenium and Requests\n ##\n except (requests.exceptions.HTTPError, SeleniumHTTPError) as e:\n \"\"\"\n Check the status code returned to see what should be done\n \"\"\"\n status_code = str(e.response.status_code)\n # If the client wants to handle the error send it to them\n if int(status_code) in return_on_error:\n raise e.with_traceback(sys.exc_info()[2])\n\n try_again = self._get_site_status_code(url, status_code, api, num_tries, num_apikey_tries)\n if try_again is True and retry_enabled is True:\n # If True then try request again\n return self.get_site(*get_site_args, **get_site_kwargs)\n\n # Every other exceptions that were not caught\n except Exception:\n logger.exception(\"Unknown Exception [get_site]: {url}\".format(url=url))\n\n return rdata\n" ]
class Web: """ Web related functions Need to be on its own that way each profile can have its own instance of it for proxy support """ def __init__(self, headers={}, cookies={}, proxy=None, **driver_args): self.scraper = None self.driver = None self.driver_args = driver_args self.current_proxy = proxy # Number of times to re-try a url self._num_retries = 3 if headers is not None: self.current_headers = headers else: self.current_headers = {} if cookies is not None: self.current_cookies = cookies else: self.current_cookies = {} # Set the default response values self._reset_response() def _reset_response(self): """ Vars to track per request made Run before ever get_site to clear previous values """ self.status_code = None self.url = None self.response = None def get_image_dimension(self, url): """ Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values """ w_h = (None, None) try: if url.startswith('//'): url = 'http:' + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Error getting image size {}".format(url), exc_info=True) return w_h def get_soup(self, raw_content, input_type='html'): rdata = None if input_type == 'html': rdata = BeautifulSoup(raw_content, 'html.parser') # Other option: html5lib elif input_type == 'xml': rdata = BeautifulSoup(raw_content, 'lxml') return rdata def new_proxy(self): raise NotImplementedError def new_headers(self): raise NotImplementedError def _try_new_proxy(self): try: new_proxy = self.new_proxy() self.set_proxy(new_proxy) except NotImplementedError: logger.warning("No function new_proxy() found, not changing proxy") except Exception: logger.exception("Something went wrong when getting a new proxy") def _try_new_headers(self): try: new_headers = self.new_headers() self.set_headers(new_headers) except NotImplementedError: logger.warning("No function new_headers() found, not changing headers") except Exception: logger.exception("Something went wrong when getting a new header") def new_profile(self): logger.info("Create a new profile to use") self._try_new_proxy() self._try_new_headers() ########################################################################### # Get/load page ########################################################################### def get_site(self, url, cookies={}, page_format='html', return_on_error=[], retry_enabled=True, num_tries=0, num_apikey_tries=0, headers={}, api=False, track_stat=True, timeout=30, force_requests=False, driver_args=(), driver_kwargs={}, parser='beautifulsoup', custom_source_checks=[]): """ headers & cookies - Will update to the current headers/cookies and just be for this request driver_args & driver_kwargs - Gets passed and expanded out to the driver """ self._reset_response() num_tries += 1 # Save args and kwargs so they can be used for trying the function again tmp_args = locals().copy() get_site_args = [tmp_args['url']] # Remove keys that dont belong to the keywords passed in del tmp_args['url'] del tmp_args['self'] get_site_kwargs = tmp_args # Check driver_kwargs for anything that we already set kwargs_cannot_be = ['headers', 'cookies', 'timeout'] for key_name in kwargs_cannot_be: if driver_kwargs.get(key_name) is not None: del driver_kwargs[key_name] logger.warning("Cannot pass `{key}` in driver_kwargs to get_site(). `{key}` is already set by default" .format(key=key_name)) # Check if a url is being passed in if url is None: logger.error("Url cannot be None") return None ## # url must start with http.... ## prepend = '' if url.startswith('//'): prepend = 'http:' elif not url.startswith('http'): prepend = 'http://' url = prepend + url ## # Try and get the page ## rdata = None try: source_text = self._get_site(url, headers, cookies, timeout, driver_args, driver_kwargs) if custom_source_checks: # Check if there are any custom check to run for re_text, status_code in custom_source_checks: if re.search(re_text, source_text): if self.response is None: # This is needed when using selenium and we still need to pass in the 'response' self.response = type('', (), {})() self.response.status_code = status_code self.status_code = status_code raise requests.exceptions.HTTPError("Custom matched status code", response=self.response) rdata = self.parse_source(source_text, page_format, parser) ## # Exceptions from Selenium ## # Nothing yet ## # Exceptions from Requests ## except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: """ Try again with a new profile (do not get new apikey) Wait n seconds before trying again """ e_name = type(e).__name__ if num_tries < self._num_retries and retry_enabled is True: logger.info("{} [get_site]: try #{} on {} Error {}".format(e_name, num_tries, url, e)) time.sleep(2) self.new_profile() return self.get_site(*get_site_args, **get_site_kwargs) else: logger.error("{} [get_site]: try #{} on{}".format(e_name, num_tries, url)) except requests.exceptions.TooManyRedirects as e: logger.exception("TooManyRedirects [get_site]: {}".format(url)) ## # Exceptions shared by Selenium and Requests ## except (requests.exceptions.HTTPError, SeleniumHTTPError) as e: """ Check the status code returned to see what should be done """ status_code = str(e.response.status_code) # If the client wants to handle the error send it to them if int(status_code) in return_on_error: raise e.with_traceback(sys.exc_info()[2]) try_again = self._get_site_status_code(url, status_code, api, num_tries, num_apikey_tries) if try_again is True and retry_enabled is True: # If True then try request again return self.get_site(*get_site_args, **get_site_kwargs) # Every other exceptions that were not caught except Exception: logger.exception("Unknown Exception [get_site]: {url}".format(url=url)) return rdata def _get_site_status_code(self, url, status_code, api, num_tries, num_apikey_tries): """ Check the http status code and num_tries/num_apikey_tries to see if it should try again or not Log any data as needed """ # Make status code an int try: status_code = int(status_code) except ValueError: logger.exception("Incorrect status code passed in") return None # TODO: Try with the same api key 3 times, then try with with a new apikey the same way for 3 times as well # try_profile_again = False # if api is True and num_apikey_tries < self._num_retries: # # Try with the same apikey/profile again after a short wait # try_profile_again = True # Retry for any status code in the 400's or greater if status_code >= 400 and num_tries < self._num_retries: # Fail after 3 tries logger.info("HTTP error, try #{}, Status: {} on url: {}".format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) time.sleep(.5) self.new_profile() return True else: logger.warning("HTTPError [get_site]\n\t# of Tries: {}\n\tCode: {} - {}" .format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) return None def parse_source(self, source, page_format, parser): rdata = None if page_format == 'html': if parser == 'beautifulsoup': rdata = self.get_soup(source, input_type='html') elif parser == 'parsel': rdata = Selector(text=source) else: logger.error("No parser passed for parsing html") elif page_format == 'json': if self.driver_type == 'requests': rdata = json.loads(source) else: rdata = json.loads(self.driver.find_element_by_tag_name('body').text) elif page_format == 'xml': rdata = self.get_soup(source, input_type='xml') elif page_format == 'raw': # Return unparsed html rdata = source return rdata def download(self, url, save_path, header={}, redownload=False): """ Currently does not use the proxied driver TODO: Be able to use cookies just like headers is used here :return: the path of the file that was saved """ if save_path is None: logger.error("save_path cannot be None") return None # Get headers of current web driver header = self.get_headers() if len(header) > 0: # Add more headers if needed header.update(header) logger.debug("Download {url} to {save_path}".format(url=url, save_path=save_path)) save_location = cutil.norm_path(save_path) if redownload is False: # See if we already have the file if os.path.isfile(save_location): logger.debug("File {save_location} already exists".format(save_location=save_location)) return save_location # Create the dir path on disk cutil.create_path(save_location) if url.startswith('//'): url = "http:" + url try: with urllib.request.urlopen(urllib.request.Request(url, headers=header)) as response,\ open(save_location, 'wb') as out_file: data = response.read() out_file.write(data) except urllib.error.HTTPError as e: save_location = None # We do not need to show the user 404 errors if e.code != 404: logger.exception("Download Http Error {url}".format(url=url)) except Exception: save_location = None logger.exception("Download Error: {url}".format(url=url)) return save_location
xtream1101/web-wrapper
web_wrapper/web.py
Web.get_site
python
def get_site(self, url, cookies={}, page_format='html', return_on_error=[], retry_enabled=True, num_tries=0, num_apikey_tries=0, headers={}, api=False, track_stat=True, timeout=30, force_requests=False, driver_args=(), driver_kwargs={}, parser='beautifulsoup', custom_source_checks=[]): self._reset_response() num_tries += 1 # Save args and kwargs so they can be used for trying the function again tmp_args = locals().copy() get_site_args = [tmp_args['url']] # Remove keys that dont belong to the keywords passed in del tmp_args['url'] del tmp_args['self'] get_site_kwargs = tmp_args # Check driver_kwargs for anything that we already set kwargs_cannot_be = ['headers', 'cookies', 'timeout'] for key_name in kwargs_cannot_be: if driver_kwargs.get(key_name) is not None: del driver_kwargs[key_name] logger.warning("Cannot pass `{key}` in driver_kwargs to get_site(). `{key}` is already set by default" .format(key=key_name)) # Check if a url is being passed in if url is None: logger.error("Url cannot be None") return None ## # url must start with http.... ## prepend = '' if url.startswith('//'): prepend = 'http:' elif not url.startswith('http'): prepend = 'http://' url = prepend + url ## # Try and get the page ## rdata = None try: source_text = self._get_site(url, headers, cookies, timeout, driver_args, driver_kwargs) if custom_source_checks: # Check if there are any custom check to run for re_text, status_code in custom_source_checks: if re.search(re_text, source_text): if self.response is None: # This is needed when using selenium and we still need to pass in the 'response' self.response = type('', (), {})() self.response.status_code = status_code self.status_code = status_code raise requests.exceptions.HTTPError("Custom matched status code", response=self.response) rdata = self.parse_source(source_text, page_format, parser) ## # Exceptions from Selenium ## # Nothing yet ## # Exceptions from Requests ## except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: """ Try again with a new profile (do not get new apikey) Wait n seconds before trying again """ e_name = type(e).__name__ if num_tries < self._num_retries and retry_enabled is True: logger.info("{} [get_site]: try #{} on {} Error {}".format(e_name, num_tries, url, e)) time.sleep(2) self.new_profile() return self.get_site(*get_site_args, **get_site_kwargs) else: logger.error("{} [get_site]: try #{} on{}".format(e_name, num_tries, url)) except requests.exceptions.TooManyRedirects as e: logger.exception("TooManyRedirects [get_site]: {}".format(url)) ## # Exceptions shared by Selenium and Requests ## except (requests.exceptions.HTTPError, SeleniumHTTPError) as e: """ Check the status code returned to see what should be done """ status_code = str(e.response.status_code) # If the client wants to handle the error send it to them if int(status_code) in return_on_error: raise e.with_traceback(sys.exc_info()[2]) try_again = self._get_site_status_code(url, status_code, api, num_tries, num_apikey_tries) if try_again is True and retry_enabled is True: # If True then try request again return self.get_site(*get_site_args, **get_site_kwargs) # Every other exceptions that were not caught except Exception: logger.exception("Unknown Exception [get_site]: {url}".format(url=url)) return rdata
headers & cookies - Will update to the current headers/cookies and just be for this request driver_args & driver_kwargs - Gets passed and expanded out to the driver
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/web.py#L193-L303
[ "def _reset_response(self):\n \"\"\"\n Vars to track per request made\n Run before ever get_site to clear previous values\n \"\"\"\n self.status_code = None\n self.url = None\n self.response = None\n", "def new_profile(self):\n logger.info(\"Create a new profile to use\")\n self._try_new_proxy()\n self._try_new_headers()\n", "def get_site(self, url, cookies={}, page_format='html', return_on_error=[], retry_enabled=True,\n num_tries=0, num_apikey_tries=0, headers={}, api=False, track_stat=True, timeout=30,\n force_requests=False, driver_args=(), driver_kwargs={}, parser='beautifulsoup',\n custom_source_checks=[]):\n \"\"\"\n headers & cookies - Will update to the current headers/cookies and just be for this request\n driver_args & driver_kwargs - Gets passed and expanded out to the driver\n \"\"\"\n self._reset_response()\n\n num_tries += 1\n # Save args and kwargs so they can be used for trying the function again\n tmp_args = locals().copy()\n get_site_args = [tmp_args['url']]\n # Remove keys that dont belong to the keywords passed in\n del tmp_args['url']\n del tmp_args['self']\n get_site_kwargs = tmp_args\n\n # Check driver_kwargs for anything that we already set\n kwargs_cannot_be = ['headers', 'cookies', 'timeout']\n for key_name in kwargs_cannot_be:\n if driver_kwargs.get(key_name) is not None:\n del driver_kwargs[key_name]\n logger.warning(\"Cannot pass `{key}` in driver_kwargs to get_site(). `{key}` is already set by default\"\n .format(key=key_name))\n\n # Check if a url is being passed in\n if url is None:\n logger.error(\"Url cannot be None\")\n return None\n\n ##\n # url must start with http....\n ##\n prepend = ''\n if url.startswith('//'):\n prepend = 'http:'\n\n elif not url.startswith('http'):\n prepend = 'http://'\n\n url = prepend + url\n\n ##\n # Try and get the page\n ##\n rdata = None\n try:\n source_text = self._get_site(url, headers, cookies, timeout, driver_args, driver_kwargs)\n if custom_source_checks:\n # Check if there are any custom check to run\n for re_text, status_code in custom_source_checks:\n if re.search(re_text, source_text):\n if self.response is None:\n # This is needed when using selenium and we still need to pass in the 'response'\n self.response = type('', (), {})()\n self.response.status_code = status_code\n self.status_code = status_code\n raise requests.exceptions.HTTPError(\"Custom matched status code\", response=self.response)\n\n rdata = self.parse_source(source_text, page_format, parser)\n\n ##\n # Exceptions from Selenium\n ##\n # Nothing yet\n\n ##\n # Exceptions from Requests\n ##\n except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:\n \"\"\"\n Try again with a new profile (do not get new apikey)\n Wait n seconds before trying again\n \"\"\"\n e_name = type(e).__name__\n if num_tries < self._num_retries and retry_enabled is True:\n logger.info(\"{} [get_site]: try #{} on {} Error {}\".format(e_name, num_tries, url, e))\n time.sleep(2)\n self.new_profile()\n return self.get_site(*get_site_args, **get_site_kwargs)\n\n else:\n logger.error(\"{} [get_site]: try #{} on{}\".format(e_name, num_tries, url))\n\n except requests.exceptions.TooManyRedirects as e:\n logger.exception(\"TooManyRedirects [get_site]: {}\".format(url))\n\n ##\n # Exceptions shared by Selenium and Requests\n ##\n except (requests.exceptions.HTTPError, SeleniumHTTPError) as e:\n \"\"\"\n Check the status code returned to see what should be done\n \"\"\"\n status_code = str(e.response.status_code)\n # If the client wants to handle the error send it to them\n if int(status_code) in return_on_error:\n raise e.with_traceback(sys.exc_info()[2])\n\n try_again = self._get_site_status_code(url, status_code, api, num_tries, num_apikey_tries)\n if try_again is True and retry_enabled is True:\n # If True then try request again\n return self.get_site(*get_site_args, **get_site_kwargs)\n\n # Every other exceptions that were not caught\n except Exception:\n logger.exception(\"Unknown Exception [get_site]: {url}\".format(url=url))\n\n return rdata\n", "def _get_site_status_code(self, url, status_code, api, num_tries, num_apikey_tries):\n \"\"\"\n Check the http status code and num_tries/num_apikey_tries to see if it should try again or not\n Log any data as needed\n \"\"\"\n # Make status code an int\n try:\n status_code = int(status_code)\n except ValueError:\n logger.exception(\"Incorrect status code passed in\")\n return None\n # TODO: Try with the same api key 3 times, then try with with a new apikey the same way for 3 times as well\n # try_profile_again = False\n # if api is True and num_apikey_tries < self._num_retries:\n # # Try with the same apikey/profile again after a short wait\n # try_profile_again = True\n\n # Retry for any status code in the 400's or greater\n if status_code >= 400 and num_tries < self._num_retries:\n # Fail after 3 tries\n logger.info(\"HTTP error, try #{}, Status: {} on url: {}\".format(num_tries, status_code, url),\n extra={'status_code': status_code,\n 'num_tries': num_tries,\n 'url': url})\n time.sleep(.5)\n self.new_profile()\n return True\n\n else:\n logger.warning(\"HTTPError [get_site]\\n\\t# of Tries: {}\\n\\tCode: {} - {}\"\n .format(num_tries, status_code, url),\n extra={'status_code': status_code,\n 'num_tries': num_tries,\n 'url': url})\n\n return None\n", "def parse_source(self, source, page_format, parser):\n rdata = None\n if page_format == 'html':\n if parser == 'beautifulsoup':\n rdata = self.get_soup(source, input_type='html')\n elif parser == 'parsel':\n rdata = Selector(text=source)\n else:\n logger.error(\"No parser passed for parsing html\")\n\n elif page_format == 'json':\n if self.driver_type == 'requests':\n rdata = json.loads(source)\n else:\n rdata = json.loads(self.driver.find_element_by_tag_name('body').text)\n\n elif page_format == 'xml':\n rdata = self.get_soup(source, input_type='xml')\n\n elif page_format == 'raw':\n # Return unparsed html\n rdata = source\n\n return rdata\n" ]
class Web: """ Web related functions Need to be on its own that way each profile can have its own instance of it for proxy support """ def __init__(self, headers={}, cookies={}, proxy=None, **driver_args): self.scraper = None self.driver = None self.driver_args = driver_args self.current_proxy = proxy # Number of times to re-try a url self._num_retries = 3 if headers is not None: self.current_headers = headers else: self.current_headers = {} if cookies is not None: self.current_cookies = cookies else: self.current_cookies = {} # Set the default response values self._reset_response() def _reset_response(self): """ Vars to track per request made Run before ever get_site to clear previous values """ self.status_code = None self.url = None self.response = None def get_image_dimension(self, url): """ Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values """ w_h = (None, None) try: if url.startswith('//'): url = 'http:' + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Error getting image size {}".format(url), exc_info=True) return w_h def get_soup(self, raw_content, input_type='html'): rdata = None if input_type == 'html': rdata = BeautifulSoup(raw_content, 'html.parser') # Other option: html5lib elif input_type == 'xml': rdata = BeautifulSoup(raw_content, 'lxml') return rdata def screenshot(self, save_path, element=None, delay=0): """ This can be used no matter what driver that is being used * ^ Soon requests support will be added Save screenshot to local dir with uuid as filename then move the file to `filename` (path must be part of the file name) Return the filepath of the image """ if save_path is None: logger.error("save_path cannot be None") return None save_location = cutil.norm_path(save_path) cutil.create_path(save_location) logger.info("Taking screenshot: {filename}".format(filename=save_location)) if not self.driver_type.startswith('selenium'): logger.debug("Create tmp phantomjs web driver for screenshot") # Create a tmp phantom driver to take the screenshot for us from web_wrapper import DriverSeleniumPhantomJS headers = self.get_headers() # Get headers to pass to the driver proxy = self.get_proxy() # Get the current proxy being used if any # TODO: ^ Do the same thing for cookies screenshot_web = DriverSeleniumPhantomJS(headers=headers, proxy=proxy) screenshot_web.get_site(self.url, page_format='raw') screenshot_driver = screenshot_web.driver else: screenshot_driver = self.driver # If a background color does need to be set # self.driver.execute_script('document.body.style.background = "{}"'.format('white')) # Take screenshot # Give the page some extra time to load time.sleep(delay) if self.driver_type == 'selenium_chrome': # Need to do this for chrome to get a fullpage screenshot self.chrome_fullpage_screenshot(save_location, delay) else: screenshot_driver.get_screenshot_as_file(save_location) # Use .png extenstion for users save file if not save_location.endswith('.png'): save_location += '.png' # If an element was passed, just get that element so crop the screenshot if element is not None: logger.debug("Crop screenshot") # Crop the image el_location = element.location el_size = element.size try: cutil.crop_image(save_location, output_file=save_location, width=int(el_size['width']), height=int(el_size['height']), x=int(el_location['x']), y=int(el_location['y']), ) except Exception as e: raise e.with_traceback(sys.exc_info()[2]) if not self.driver_type.startswith('selenium'): # Quit the tmp driver created to take the screenshot screenshot_web.quit() return save_location def new_proxy(self): raise NotImplementedError def new_headers(self): raise NotImplementedError def _try_new_proxy(self): try: new_proxy = self.new_proxy() self.set_proxy(new_proxy) except NotImplementedError: logger.warning("No function new_proxy() found, not changing proxy") except Exception: logger.exception("Something went wrong when getting a new proxy") def _try_new_headers(self): try: new_headers = self.new_headers() self.set_headers(new_headers) except NotImplementedError: logger.warning("No function new_headers() found, not changing headers") except Exception: logger.exception("Something went wrong when getting a new header") def new_profile(self): logger.info("Create a new profile to use") self._try_new_proxy() self._try_new_headers() ########################################################################### # Get/load page ########################################################################### def _get_site_status_code(self, url, status_code, api, num_tries, num_apikey_tries): """ Check the http status code and num_tries/num_apikey_tries to see if it should try again or not Log any data as needed """ # Make status code an int try: status_code = int(status_code) except ValueError: logger.exception("Incorrect status code passed in") return None # TODO: Try with the same api key 3 times, then try with with a new apikey the same way for 3 times as well # try_profile_again = False # if api is True and num_apikey_tries < self._num_retries: # # Try with the same apikey/profile again after a short wait # try_profile_again = True # Retry for any status code in the 400's or greater if status_code >= 400 and num_tries < self._num_retries: # Fail after 3 tries logger.info("HTTP error, try #{}, Status: {} on url: {}".format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) time.sleep(.5) self.new_profile() return True else: logger.warning("HTTPError [get_site]\n\t# of Tries: {}\n\tCode: {} - {}" .format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) return None def parse_source(self, source, page_format, parser): rdata = None if page_format == 'html': if parser == 'beautifulsoup': rdata = self.get_soup(source, input_type='html') elif parser == 'parsel': rdata = Selector(text=source) else: logger.error("No parser passed for parsing html") elif page_format == 'json': if self.driver_type == 'requests': rdata = json.loads(source) else: rdata = json.loads(self.driver.find_element_by_tag_name('body').text) elif page_format == 'xml': rdata = self.get_soup(source, input_type='xml') elif page_format == 'raw': # Return unparsed html rdata = source return rdata def download(self, url, save_path, header={}, redownload=False): """ Currently does not use the proxied driver TODO: Be able to use cookies just like headers is used here :return: the path of the file that was saved """ if save_path is None: logger.error("save_path cannot be None") return None # Get headers of current web driver header = self.get_headers() if len(header) > 0: # Add more headers if needed header.update(header) logger.debug("Download {url} to {save_path}".format(url=url, save_path=save_path)) save_location = cutil.norm_path(save_path) if redownload is False: # See if we already have the file if os.path.isfile(save_location): logger.debug("File {save_location} already exists".format(save_location=save_location)) return save_location # Create the dir path on disk cutil.create_path(save_location) if url.startswith('//'): url = "http:" + url try: with urllib.request.urlopen(urllib.request.Request(url, headers=header)) as response,\ open(save_location, 'wb') as out_file: data = response.read() out_file.write(data) except urllib.error.HTTPError as e: save_location = None # We do not need to show the user 404 errors if e.code != 404: logger.exception("Download Http Error {url}".format(url=url)) except Exception: save_location = None logger.exception("Download Error: {url}".format(url=url)) return save_location
xtream1101/web-wrapper
web_wrapper/web.py
Web._get_site_status_code
python
def _get_site_status_code(self, url, status_code, api, num_tries, num_apikey_tries): # Make status code an int try: status_code = int(status_code) except ValueError: logger.exception("Incorrect status code passed in") return None # TODO: Try with the same api key 3 times, then try with with a new apikey the same way for 3 times as well # try_profile_again = False # if api is True and num_apikey_tries < self._num_retries: # # Try with the same apikey/profile again after a short wait # try_profile_again = True # Retry for any status code in the 400's or greater if status_code >= 400 and num_tries < self._num_retries: # Fail after 3 tries logger.info("HTTP error, try #{}, Status: {} on url: {}".format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) time.sleep(.5) self.new_profile() return True else: logger.warning("HTTPError [get_site]\n\t# of Tries: {}\n\tCode: {} - {}" .format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) return None
Check the http status code and num_tries/num_apikey_tries to see if it should try again or not Log any data as needed
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/web.py#L305-L340
null
class Web: """ Web related functions Need to be on its own that way each profile can have its own instance of it for proxy support """ def __init__(self, headers={}, cookies={}, proxy=None, **driver_args): self.scraper = None self.driver = None self.driver_args = driver_args self.current_proxy = proxy # Number of times to re-try a url self._num_retries = 3 if headers is not None: self.current_headers = headers else: self.current_headers = {} if cookies is not None: self.current_cookies = cookies else: self.current_cookies = {} # Set the default response values self._reset_response() def _reset_response(self): """ Vars to track per request made Run before ever get_site to clear previous values """ self.status_code = None self.url = None self.response = None def get_image_dimension(self, url): """ Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values """ w_h = (None, None) try: if url.startswith('//'): url = 'http:' + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Error getting image size {}".format(url), exc_info=True) return w_h def get_soup(self, raw_content, input_type='html'): rdata = None if input_type == 'html': rdata = BeautifulSoup(raw_content, 'html.parser') # Other option: html5lib elif input_type == 'xml': rdata = BeautifulSoup(raw_content, 'lxml') return rdata def screenshot(self, save_path, element=None, delay=0): """ This can be used no matter what driver that is being used * ^ Soon requests support will be added Save screenshot to local dir with uuid as filename then move the file to `filename` (path must be part of the file name) Return the filepath of the image """ if save_path is None: logger.error("save_path cannot be None") return None save_location = cutil.norm_path(save_path) cutil.create_path(save_location) logger.info("Taking screenshot: {filename}".format(filename=save_location)) if not self.driver_type.startswith('selenium'): logger.debug("Create tmp phantomjs web driver for screenshot") # Create a tmp phantom driver to take the screenshot for us from web_wrapper import DriverSeleniumPhantomJS headers = self.get_headers() # Get headers to pass to the driver proxy = self.get_proxy() # Get the current proxy being used if any # TODO: ^ Do the same thing for cookies screenshot_web = DriverSeleniumPhantomJS(headers=headers, proxy=proxy) screenshot_web.get_site(self.url, page_format='raw') screenshot_driver = screenshot_web.driver else: screenshot_driver = self.driver # If a background color does need to be set # self.driver.execute_script('document.body.style.background = "{}"'.format('white')) # Take screenshot # Give the page some extra time to load time.sleep(delay) if self.driver_type == 'selenium_chrome': # Need to do this for chrome to get a fullpage screenshot self.chrome_fullpage_screenshot(save_location, delay) else: screenshot_driver.get_screenshot_as_file(save_location) # Use .png extenstion for users save file if not save_location.endswith('.png'): save_location += '.png' # If an element was passed, just get that element so crop the screenshot if element is not None: logger.debug("Crop screenshot") # Crop the image el_location = element.location el_size = element.size try: cutil.crop_image(save_location, output_file=save_location, width=int(el_size['width']), height=int(el_size['height']), x=int(el_location['x']), y=int(el_location['y']), ) except Exception as e: raise e.with_traceback(sys.exc_info()[2]) if not self.driver_type.startswith('selenium'): # Quit the tmp driver created to take the screenshot screenshot_web.quit() return save_location def new_proxy(self): raise NotImplementedError def new_headers(self): raise NotImplementedError def _try_new_proxy(self): try: new_proxy = self.new_proxy() self.set_proxy(new_proxy) except NotImplementedError: logger.warning("No function new_proxy() found, not changing proxy") except Exception: logger.exception("Something went wrong when getting a new proxy") def _try_new_headers(self): try: new_headers = self.new_headers() self.set_headers(new_headers) except NotImplementedError: logger.warning("No function new_headers() found, not changing headers") except Exception: logger.exception("Something went wrong when getting a new header") def new_profile(self): logger.info("Create a new profile to use") self._try_new_proxy() self._try_new_headers() ########################################################################### # Get/load page ########################################################################### def get_site(self, url, cookies={}, page_format='html', return_on_error=[], retry_enabled=True, num_tries=0, num_apikey_tries=0, headers={}, api=False, track_stat=True, timeout=30, force_requests=False, driver_args=(), driver_kwargs={}, parser='beautifulsoup', custom_source_checks=[]): """ headers & cookies - Will update to the current headers/cookies and just be for this request driver_args & driver_kwargs - Gets passed and expanded out to the driver """ self._reset_response() num_tries += 1 # Save args and kwargs so they can be used for trying the function again tmp_args = locals().copy() get_site_args = [tmp_args['url']] # Remove keys that dont belong to the keywords passed in del tmp_args['url'] del tmp_args['self'] get_site_kwargs = tmp_args # Check driver_kwargs for anything that we already set kwargs_cannot_be = ['headers', 'cookies', 'timeout'] for key_name in kwargs_cannot_be: if driver_kwargs.get(key_name) is not None: del driver_kwargs[key_name] logger.warning("Cannot pass `{key}` in driver_kwargs to get_site(). `{key}` is already set by default" .format(key=key_name)) # Check if a url is being passed in if url is None: logger.error("Url cannot be None") return None ## # url must start with http.... ## prepend = '' if url.startswith('//'): prepend = 'http:' elif not url.startswith('http'): prepend = 'http://' url = prepend + url ## # Try and get the page ## rdata = None try: source_text = self._get_site(url, headers, cookies, timeout, driver_args, driver_kwargs) if custom_source_checks: # Check if there are any custom check to run for re_text, status_code in custom_source_checks: if re.search(re_text, source_text): if self.response is None: # This is needed when using selenium and we still need to pass in the 'response' self.response = type('', (), {})() self.response.status_code = status_code self.status_code = status_code raise requests.exceptions.HTTPError("Custom matched status code", response=self.response) rdata = self.parse_source(source_text, page_format, parser) ## # Exceptions from Selenium ## # Nothing yet ## # Exceptions from Requests ## except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: """ Try again with a new profile (do not get new apikey) Wait n seconds before trying again """ e_name = type(e).__name__ if num_tries < self._num_retries and retry_enabled is True: logger.info("{} [get_site]: try #{} on {} Error {}".format(e_name, num_tries, url, e)) time.sleep(2) self.new_profile() return self.get_site(*get_site_args, **get_site_kwargs) else: logger.error("{} [get_site]: try #{} on{}".format(e_name, num_tries, url)) except requests.exceptions.TooManyRedirects as e: logger.exception("TooManyRedirects [get_site]: {}".format(url)) ## # Exceptions shared by Selenium and Requests ## except (requests.exceptions.HTTPError, SeleniumHTTPError) as e: """ Check the status code returned to see what should be done """ status_code = str(e.response.status_code) # If the client wants to handle the error send it to them if int(status_code) in return_on_error: raise e.with_traceback(sys.exc_info()[2]) try_again = self._get_site_status_code(url, status_code, api, num_tries, num_apikey_tries) if try_again is True and retry_enabled is True: # If True then try request again return self.get_site(*get_site_args, **get_site_kwargs) # Every other exceptions that were not caught except Exception: logger.exception("Unknown Exception [get_site]: {url}".format(url=url)) return rdata def parse_source(self, source, page_format, parser): rdata = None if page_format == 'html': if parser == 'beautifulsoup': rdata = self.get_soup(source, input_type='html') elif parser == 'parsel': rdata = Selector(text=source) else: logger.error("No parser passed for parsing html") elif page_format == 'json': if self.driver_type == 'requests': rdata = json.loads(source) else: rdata = json.loads(self.driver.find_element_by_tag_name('body').text) elif page_format == 'xml': rdata = self.get_soup(source, input_type='xml') elif page_format == 'raw': # Return unparsed html rdata = source return rdata def download(self, url, save_path, header={}, redownload=False): """ Currently does not use the proxied driver TODO: Be able to use cookies just like headers is used here :return: the path of the file that was saved """ if save_path is None: logger.error("save_path cannot be None") return None # Get headers of current web driver header = self.get_headers() if len(header) > 0: # Add more headers if needed header.update(header) logger.debug("Download {url} to {save_path}".format(url=url, save_path=save_path)) save_location = cutil.norm_path(save_path) if redownload is False: # See if we already have the file if os.path.isfile(save_location): logger.debug("File {save_location} already exists".format(save_location=save_location)) return save_location # Create the dir path on disk cutil.create_path(save_location) if url.startswith('//'): url = "http:" + url try: with urllib.request.urlopen(urllib.request.Request(url, headers=header)) as response,\ open(save_location, 'wb') as out_file: data = response.read() out_file.write(data) except urllib.error.HTTPError as e: save_location = None # We do not need to show the user 404 errors if e.code != 404: logger.exception("Download Http Error {url}".format(url=url)) except Exception: save_location = None logger.exception("Download Error: {url}".format(url=url)) return save_location
xtream1101/web-wrapper
web_wrapper/web.py
Web.download
python
def download(self, url, save_path, header={}, redownload=False): if save_path is None: logger.error("save_path cannot be None") return None # Get headers of current web driver header = self.get_headers() if len(header) > 0: # Add more headers if needed header.update(header) logger.debug("Download {url} to {save_path}".format(url=url, save_path=save_path)) save_location = cutil.norm_path(save_path) if redownload is False: # See if we already have the file if os.path.isfile(save_location): logger.debug("File {save_location} already exists".format(save_location=save_location)) return save_location # Create the dir path on disk cutil.create_path(save_location) if url.startswith('//'): url = "http:" + url try: with urllib.request.urlopen(urllib.request.Request(url, headers=header)) as response,\ open(save_location, 'wb') as out_file: data = response.read() out_file.write(data) except urllib.error.HTTPError as e: save_location = None # We do not need to show the user 404 errors if e.code != 404: logger.exception("Download Http Error {url}".format(url=url)) except Exception: save_location = None logger.exception("Download Error: {url}".format(url=url)) return save_location
Currently does not use the proxied driver TODO: Be able to use cookies just like headers is used here :return: the path of the file that was saved
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/web.py#L367-L413
null
class Web: """ Web related functions Need to be on its own that way each profile can have its own instance of it for proxy support """ def __init__(self, headers={}, cookies={}, proxy=None, **driver_args): self.scraper = None self.driver = None self.driver_args = driver_args self.current_proxy = proxy # Number of times to re-try a url self._num_retries = 3 if headers is not None: self.current_headers = headers else: self.current_headers = {} if cookies is not None: self.current_cookies = cookies else: self.current_cookies = {} # Set the default response values self._reset_response() def _reset_response(self): """ Vars to track per request made Run before ever get_site to clear previous values """ self.status_code = None self.url = None self.response = None def get_image_dimension(self, url): """ Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values """ w_h = (None, None) try: if url.startswith('//'): url = 'http:' + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Error getting image size {}".format(url), exc_info=True) return w_h def get_soup(self, raw_content, input_type='html'): rdata = None if input_type == 'html': rdata = BeautifulSoup(raw_content, 'html.parser') # Other option: html5lib elif input_type == 'xml': rdata = BeautifulSoup(raw_content, 'lxml') return rdata def screenshot(self, save_path, element=None, delay=0): """ This can be used no matter what driver that is being used * ^ Soon requests support will be added Save screenshot to local dir with uuid as filename then move the file to `filename` (path must be part of the file name) Return the filepath of the image """ if save_path is None: logger.error("save_path cannot be None") return None save_location = cutil.norm_path(save_path) cutil.create_path(save_location) logger.info("Taking screenshot: {filename}".format(filename=save_location)) if not self.driver_type.startswith('selenium'): logger.debug("Create tmp phantomjs web driver for screenshot") # Create a tmp phantom driver to take the screenshot for us from web_wrapper import DriverSeleniumPhantomJS headers = self.get_headers() # Get headers to pass to the driver proxy = self.get_proxy() # Get the current proxy being used if any # TODO: ^ Do the same thing for cookies screenshot_web = DriverSeleniumPhantomJS(headers=headers, proxy=proxy) screenshot_web.get_site(self.url, page_format='raw') screenshot_driver = screenshot_web.driver else: screenshot_driver = self.driver # If a background color does need to be set # self.driver.execute_script('document.body.style.background = "{}"'.format('white')) # Take screenshot # Give the page some extra time to load time.sleep(delay) if self.driver_type == 'selenium_chrome': # Need to do this for chrome to get a fullpage screenshot self.chrome_fullpage_screenshot(save_location, delay) else: screenshot_driver.get_screenshot_as_file(save_location) # Use .png extenstion for users save file if not save_location.endswith('.png'): save_location += '.png' # If an element was passed, just get that element so crop the screenshot if element is not None: logger.debug("Crop screenshot") # Crop the image el_location = element.location el_size = element.size try: cutil.crop_image(save_location, output_file=save_location, width=int(el_size['width']), height=int(el_size['height']), x=int(el_location['x']), y=int(el_location['y']), ) except Exception as e: raise e.with_traceback(sys.exc_info()[2]) if not self.driver_type.startswith('selenium'): # Quit the tmp driver created to take the screenshot screenshot_web.quit() return save_location def new_proxy(self): raise NotImplementedError def new_headers(self): raise NotImplementedError def _try_new_proxy(self): try: new_proxy = self.new_proxy() self.set_proxy(new_proxy) except NotImplementedError: logger.warning("No function new_proxy() found, not changing proxy") except Exception: logger.exception("Something went wrong when getting a new proxy") def _try_new_headers(self): try: new_headers = self.new_headers() self.set_headers(new_headers) except NotImplementedError: logger.warning("No function new_headers() found, not changing headers") except Exception: logger.exception("Something went wrong when getting a new header") def new_profile(self): logger.info("Create a new profile to use") self._try_new_proxy() self._try_new_headers() ########################################################################### # Get/load page ########################################################################### def get_site(self, url, cookies={}, page_format='html', return_on_error=[], retry_enabled=True, num_tries=0, num_apikey_tries=0, headers={}, api=False, track_stat=True, timeout=30, force_requests=False, driver_args=(), driver_kwargs={}, parser='beautifulsoup', custom_source_checks=[]): """ headers & cookies - Will update to the current headers/cookies and just be for this request driver_args & driver_kwargs - Gets passed and expanded out to the driver """ self._reset_response() num_tries += 1 # Save args and kwargs so they can be used for trying the function again tmp_args = locals().copy() get_site_args = [tmp_args['url']] # Remove keys that dont belong to the keywords passed in del tmp_args['url'] del tmp_args['self'] get_site_kwargs = tmp_args # Check driver_kwargs for anything that we already set kwargs_cannot_be = ['headers', 'cookies', 'timeout'] for key_name in kwargs_cannot_be: if driver_kwargs.get(key_name) is not None: del driver_kwargs[key_name] logger.warning("Cannot pass `{key}` in driver_kwargs to get_site(). `{key}` is already set by default" .format(key=key_name)) # Check if a url is being passed in if url is None: logger.error("Url cannot be None") return None ## # url must start with http.... ## prepend = '' if url.startswith('//'): prepend = 'http:' elif not url.startswith('http'): prepend = 'http://' url = prepend + url ## # Try and get the page ## rdata = None try: source_text = self._get_site(url, headers, cookies, timeout, driver_args, driver_kwargs) if custom_source_checks: # Check if there are any custom check to run for re_text, status_code in custom_source_checks: if re.search(re_text, source_text): if self.response is None: # This is needed when using selenium and we still need to pass in the 'response' self.response = type('', (), {})() self.response.status_code = status_code self.status_code = status_code raise requests.exceptions.HTTPError("Custom matched status code", response=self.response) rdata = self.parse_source(source_text, page_format, parser) ## # Exceptions from Selenium ## # Nothing yet ## # Exceptions from Requests ## except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: """ Try again with a new profile (do not get new apikey) Wait n seconds before trying again """ e_name = type(e).__name__ if num_tries < self._num_retries and retry_enabled is True: logger.info("{} [get_site]: try #{} on {} Error {}".format(e_name, num_tries, url, e)) time.sleep(2) self.new_profile() return self.get_site(*get_site_args, **get_site_kwargs) else: logger.error("{} [get_site]: try #{} on{}".format(e_name, num_tries, url)) except requests.exceptions.TooManyRedirects as e: logger.exception("TooManyRedirects [get_site]: {}".format(url)) ## # Exceptions shared by Selenium and Requests ## except (requests.exceptions.HTTPError, SeleniumHTTPError) as e: """ Check the status code returned to see what should be done """ status_code = str(e.response.status_code) # If the client wants to handle the error send it to them if int(status_code) in return_on_error: raise e.with_traceback(sys.exc_info()[2]) try_again = self._get_site_status_code(url, status_code, api, num_tries, num_apikey_tries) if try_again is True and retry_enabled is True: # If True then try request again return self.get_site(*get_site_args, **get_site_kwargs) # Every other exceptions that were not caught except Exception: logger.exception("Unknown Exception [get_site]: {url}".format(url=url)) return rdata def _get_site_status_code(self, url, status_code, api, num_tries, num_apikey_tries): """ Check the http status code and num_tries/num_apikey_tries to see if it should try again or not Log any data as needed """ # Make status code an int try: status_code = int(status_code) except ValueError: logger.exception("Incorrect status code passed in") return None # TODO: Try with the same api key 3 times, then try with with a new apikey the same way for 3 times as well # try_profile_again = False # if api is True and num_apikey_tries < self._num_retries: # # Try with the same apikey/profile again after a short wait # try_profile_again = True # Retry for any status code in the 400's or greater if status_code >= 400 and num_tries < self._num_retries: # Fail after 3 tries logger.info("HTTP error, try #{}, Status: {} on url: {}".format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) time.sleep(.5) self.new_profile() return True else: logger.warning("HTTPError [get_site]\n\t# of Tries: {}\n\tCode: {} - {}" .format(num_tries, status_code, url), extra={'status_code': status_code, 'num_tries': num_tries, 'url': url}) return None def parse_source(self, source, page_format, parser): rdata = None if page_format == 'html': if parser == 'beautifulsoup': rdata = self.get_soup(source, input_type='html') elif parser == 'parsel': rdata = Selector(text=source) else: logger.error("No parser passed for parsing html") elif page_format == 'json': if self.driver_type == 'requests': rdata = json.loads(source) else: rdata = json.loads(self.driver.find_element_by_tag_name('body').text) elif page_format == 'xml': rdata = self.get_soup(source, input_type='xml') elif page_format == 'raw': # Return unparsed html rdata = source return rdata