INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Retrieve information about a purchase using the system s unique ID or a client s ID
def get_purchase(self, purchase_id, purchase_key='sid'): """ Retrieve information about a purchase using the system's unique ID or a client's ID @param id_: a string that represents a unique_id or an extid. @param key: a string that is either 'sid' or 'extid'. """ data = ...
Retrieve information about your subscriber counts on a particular list on a particular day. http:// docs. sailthru. com/ api/ stat
def stats_list(self, list=None, date=None, headers=None): """ Retrieve information about your subscriber counts on a particular list, on a particular day. http://docs.sailthru.com/api/stat """ data = {'stat': 'list'} if list is not None: data['list'] = list ...
Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range. http:// docs. sailthru. com/ api/ stat
def stats_blast(self, blast_id=None, start_date=None, end_date=None, options=None): """ Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range. http://docs.sailthru.com/api/stat """ options = options or {} da...
Retrieve information about a particular transactional or aggregated information from transactionals from that template over a specified date range. http:// docs. sailthru. com/ api/ stat
def stats_send(self, template, start_date, end_date, options=None): """ Retrieve information about a particular transactional or aggregated information from transactionals from that template over a specified date range. http://docs.sailthru.com/api/stat """ options = opti...
Returns true if the incoming request is an authenticated verify post.
def receive_verify_post(self, post_params): """ Returns true if the incoming request is an authenticated verify post. """ if isinstance(post_params, dict): required_params = ['action', 'email', 'send_id', 'sig'] if not self.check_for_valid_postback_actions(requir...
Update postbacks
def receive_update_post(self, post_params): """ Update postbacks """ if isinstance(post_params, dict): required_params = ['action', 'email', 'sig'] if not self.check_for_valid_postback_actions(required_params, post_params): return False el...
Hard bounce postbacks
def receive_hardbounce_post(self, post_params): """ Hard bounce postbacks """ if isinstance(post_params, dict): required_params = ['action', 'email', 'sig'] if not self.check_for_valid_postback_actions(required_params, post_params): return False ...
checks if post_params contain required keys
def check_for_valid_postback_actions(self, required_keys, post_params): """ checks if post_params contain required keys """ for key in required_keys: if key not in post_params: return False return True
Perform an HTTP GET request using the shared - secret auth hash.
def api_get(self, action, data, headers=None): """ Perform an HTTP GET request, using the shared-secret auth hash. @param action: API action call @param data: dictionary values """ return self._api_request(action, data, 'GET', headers)
Perform an HTTP POST request using the shared - secret auth hash.
def api_post(self, action, data, binary_data_param=None): """ Perform an HTTP POST request, using the shared-secret auth hash. @param action: API action call @param data: dictionary values """ binary_data_param = binary_data_param or [] if binary_data_param: ...
Perform an HTTP Multipart POST request using the shared - secret auth hash.
def api_post_multipart(self, action, data, binary_data_param): """ Perform an HTTP Multipart POST request, using the shared-secret auth hash. @param action: API action call @param data: dictionary values @param: binary_data_params: array of multipart keys """ bina...
Make Request to Sailthru API with given data and api key format and signature hash
def _api_request(self, action, data, request_type, headers=None): """ Make Request to Sailthru API with given data and api key, format and signature hash """ if 'file' in data: file_data = {'file': open(data['file'], 'rb')} else: file_data = None ...
Get rate limit information for last API call: param action: API endpoint: param method: Http method GET POST or DELETE: return: dict|None
def get_last_rate_limit_info(self, action, method): """ Get rate limit information for last API call :param action: API endpoint :param method: Http method, GET, POST or DELETE :return: dict|None """ method = method.upper() if (action in self.last_rate_lim...
When having foreign key or m2m relationships between models A and B ( B has foreign key to A named parent ) we want to have a form that sits on A s viewset but creates/ edits B and sets it relationship to A automatically.
def linked_form(viewset, form_id=None, link=None, link_id=None, method=None): """ When having foreign key or m2m relationships between models A and B (B has foreign key to A named parent), we want to have a form that sits on A's viewset but creates/edits B and sets it relationship to A automatically. ...
Mint record identifiers.
def oaiid_minter(record_uuid, data): """Mint record identifiers. :param record_uuid: The record UUID. :param data: The record data. :returns: A :class:`invenio_pidstore.models.PersistentIdentifier` instance. """ pid_value = data.get('_oai', {}).get('id') if pid_value is None: fetche...
Return formatter validation error.
def validation_error(exception): """Return formatter validation error.""" messages = getattr(exception, 'messages', None) if messages is None: messages = getattr(exception, 'data', {'messages': None})['messages'] def extract_errors(): """Extract errors from exception.""" if isin...
Response endpoint.
def response(args): """Response endpoint.""" e_tree = getattr(xml, args['verb'].lower())(**args) response = make_response(etree.tostring( e_tree, pretty_print=True, xml_declaration=True, encoding='UTF-8', )) response.headers['Content-Type'] = 'text/xml' return re...
Create a new record identifier.
def create(cls, object_type=None, object_uuid=None, **kwargs): """Create a new record identifier. :param object_type: The object type. (Default: ``None``) :param object_uuid: The object UUID. (Default: ``None``) """ assert 'pid_value' in kwargs kwargs.setdefault('status...
Update mappings with the percolator field.
def _create_percolator_mapping(index, doc_type): """Update mappings with the percolator field. .. note:: This is only needed from ElasticSearch v5 onwards, because percolators are now just a special type of field inside mappings. """ if ES_VERSION[0] >= 5: current_search_client...
Get results for a percolate query.
def _percolate_query(index, doc_type, percolator_doc_type, document): """Get results for a percolate query.""" if ES_VERSION[0] in (2, 5): results = current_search_client.percolate( index=index, doc_type=doc_type, allow_no_indices=True, ignore_unavailable=True, body={'doc': docum...
Create new percolator associated with the new set.
def _new_percolator(spec, search_pattern): """Create new percolator associated with the new set.""" if spec and search_pattern: query = query_string_parser(search_pattern=search_pattern).to_dict() for index in current_search.mappings.keys(): # Create the percolator doc_type in the ex...
Delete percolator associated with the new oaiset.
def _delete_percolator(spec, search_pattern): """Delete percolator associated with the new oaiset.""" if spec: for index in current_search.mappings.keys(): # Create the percolator doc_type in the existing index for >= ES5 percolator_doc_type = _get_percolator_doc_type(index) ...
Build sets cache.
def _build_cache(): """Build sets cache.""" sets = current_oaiserver.sets if sets is None: # build sets cache sets = current_oaiserver.sets = [ oaiset.spec for oaiset in OAISet.query.filter( OAISet.search_pattern.is_(None)).all()] return sets
Find matching sets.
def get_record_sets(record): """Find matching sets.""" # get lists of sets with search_pattern equals to None but already in the # set list inside the record record_sets = set(record.get('_oai', {}).get('sets', [])) for spec in _build_cache(): if spec in record_sets: yield spec ...
Commit all records.
def _records_commit(record_ids): """Commit all records.""" for record_id in record_ids: record = Record.get_record(record_id) record.commit()
Update all affected records by OAISet change.
def update_affected_records(spec=None, search_pattern=None): """Update all affected records by OAISet change. :param spec: The record spec. :param search_pattern: The search pattern. """ chunk_size = current_app.config['OAISERVER_CELERY_TASK_CHUNK_SIZE'] record_ids = get_affected_records(spec=s...
Create OAI - PMH envelope for response.
def envelope(**kwargs): """Create OAI-PMH envelope for response.""" e_oaipmh = Element(etree.QName(NS_OAIPMH, 'OAI-PMH'), nsmap=NSMAP) e_oaipmh.set(etree.QName(NS_XSI, 'schemaLocation'), '{0} {1}'.format(NS_OAIPMH, NS_OAIPMH_XSD)) e_tree = ElementTree(element=e_oaipmh) if current_a...
Create error element.
def error(errors): """Create error element.""" e_tree, e_oaipmh = envelope() for code, message in errors: e_error = SubElement(e_oaipmh, etree.QName(NS_OAIPMH, 'error')) e_error.set('code', code) e_error.text = message return e_tree
Create OAI - PMH envelope for response with verb.
def verb(**kwargs): """Create OAI-PMH envelope for response with verb.""" e_tree, e_oaipmh = envelope(**kwargs) e_element = SubElement(e_oaipmh, etree.QName(NS_OAIPMH, kwargs['verb'])) return e_tree, e_element
Create OAI - PMH response for verb Identify.
def identify(**kwargs): """Create OAI-PMH response for verb Identify.""" cfg = current_app.config e_tree, e_identify = verb(**kwargs) e_repositoryName = SubElement( e_identify, etree.QName(NS_OAIPMH, 'repositoryName')) e_repositoryName.text = cfg['OAISERVER_REPOSITORY_NAME'] e_baseURL...
Attach resumption token element to a parent.
def resumption_token(parent, pagination, **kwargs): """Attach resumption token element to a parent.""" # Do not add resumptionToken if all results fit to the first page. if pagination.page == 1 and not pagination.has_next: return token = serialize(pagination, **kwargs) e_resumptionToken = S...
Create OAI - PMH response for ListSets verb.
def listsets(**kwargs): """Create OAI-PMH response for ListSets verb.""" e_tree, e_listsets = verb(**kwargs) page = kwargs.get('resumptionToken', {}).get('page', 1) size = current_app.config['OAISERVER_PAGE_SIZE'] oai_sets = OAISet.query.paginate(page=page, per_page=size, error_out=False) for ...
Create OAI - PMH response for ListMetadataFormats verb.
def listmetadataformats(**kwargs): """Create OAI-PMH response for ListMetadataFormats verb.""" cfg = current_app.config e_tree, e_listmetadataformats = verb(**kwargs) if 'identifier' in kwargs: # test if record exists OAIIDProvider.get(pid_value=kwargs['identifier']) for prefix, me...
Attach <header/ > element to a parent.
def header(parent, identifier, datestamp, sets=None, deleted=False): """Attach ``<header/>`` element to a parent.""" e_header = SubElement(parent, etree.QName(NS_OAIPMH, 'header')) if deleted: e_header.set('status', 'deleted') e_identifier = SubElement(e_header, etree.QName(NS_OAIPMH, 'identifie...
Create OAI - PMH response for verb Identify.
def getrecord(**kwargs): """Create OAI-PMH response for verb Identify.""" record_dumper = serializer(kwargs['metadataPrefix']) pid = OAIIDProvider.get(pid_value=kwargs['identifier']).pid record = Record.get_record(pid.object_uuid) e_tree, e_getrecord = verb(**kwargs) e_record = SubElement(e_get...
Create OAI - PMH response for verb ListIdentifiers.
def listidentifiers(**kwargs): """Create OAI-PMH response for verb ListIdentifiers.""" e_tree, e_listidentifiers = verb(**kwargs) result = get_records(**kwargs) for record in result.items: pid = oaiid_fetcher(record['id'], record['json']['_source']) header( e_listidentifiers...
Create OAI - PMH response for verb ListRecords.
def listrecords(**kwargs): """Create OAI-PMH response for verb ListRecords.""" record_dumper = serializer(kwargs['metadataPrefix']) e_tree, e_listrecords = verb(**kwargs) result = get_records(**kwargs) for record in result.items: pid = oaiid_fetcher(record['id'], record['json']['_source'])...
Fetch a record s identifier.
def oaiid_fetcher(record_uuid, data): """Fetch a record's identifier. :param record_uuid: The record UUID. :param data: The record data. :returns: A :class:`invenio_pidstore.fetchers.FetchedPID` instance. """ pid_value = data.get('_oai', {}).get('id') if pid_value is None: raise Per...
Forbit updates of set identifier.
def validate_spec(self, key, value): """Forbit updates of set identifier.""" if self.spec and self.spec != value: raise OAISetSpecUpdateError("Updating spec is not allowed.") return value
Add a record to the OAISet.
def add_record(self, record): """Add a record to the OAISet. :param record: Record to be added. :type record: `invenio_records.api.Record` or derivative. """ record.setdefault('_oai', {}).setdefault('sets', []) assert not self.has_record(record) record['_oai'][...
Remove a record from the OAISet.
def remove_record(self, record): """Remove a record from the OAISet. :param record: Record to be removed. :type record: `invenio_records.api.Record` or derivative. """ assert self.has_record(record) record['_oai']['sets'] = [ s for s in record['_oai']['sets'...
Initialize OAI - PMH server.
def oaiserver(sets, records): """Initialize OAI-PMH server.""" from invenio_db import db from invenio_oaiserver.models import OAISet from invenio_records.api import Record # create a OAI Set with db.session.begin_nested(): for i in range(sets): db.session.add(OAISet( ...
Return etree_dumper instances.
def serializer(metadata_prefix): """Return etree_dumper instances. :param metadata_prefix: One of the metadata identifiers configured in ``OAISERVER_METADATA_FORMATS``. """ metadataFormats = current_app.config['OAISERVER_METADATA_FORMATS'] serializer_ = metadataFormats[metadata_prefix]['ser...
Dump MARC21 compatible record.
def dumps_etree(pid, record, **kwargs): """Dump MARC21 compatible record. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The :class:`invenio_records.api.Record` instance. :returns: A LXML Element instance. """ from dojson.contrib.to_marc21...
Generate the eprints element for the identify response.
def eprints_description(metadataPolicy, dataPolicy, submissionPolicy=None, content=None): """Generate the eprints element for the identify response. The eprints container is used by the e-print community to describe the content and policies of repositories. For the full specific...
Generate the oai - identifier element for the identify response.
def oai_identifier_description(scheme, repositoryIdentifier, delimiter, sampleIdentifier): """Generate the oai-identifier element for the identify response. The OAI identifier format is intended to provide persistent resource identifiers for items in repositories that impleme...
Generate the friends element for the identify response.
def friends_description(baseURLs): """Generate the friends element for the identify response. The friends container is recommended for use by repositories to list confederate repositories. For the schema definition visit: http://www.openarchives.org/OAI/2.0/guidelines-friends.htm """ friend...
Update records on OAISet insertion.
def after_insert_oai_set(mapper, connection, target): """Update records on OAISet insertion.""" _new_percolator(spec=target.spec, search_pattern=target.search_pattern) sleep(2) update_affected_records.delay( search_pattern=target.search_pattern )
Update records on OAISet update.
def after_update_oai_set(mapper, connection, target): """Update records on OAISet update.""" _delete_percolator(spec=target.spec, search_pattern=target.search_pattern) _new_percolator(spec=target.spec, search_pattern=target.search_pattern) sleep(2) update_affected_records.delay( spec=target....
Update records on OAISet deletion.
def after_delete_oai_set(mapper, connection, target): """Update records on OAISet deletion.""" _delete_percolator(spec=target.spec, search_pattern=target.search_pattern) sleep(2) update_affected_records.delay( spec=target.spec )
Elasticsearch query string parser.
def query_string_parser(search_pattern): """Elasticsearch query string parser.""" if not hasattr(current_oaiserver, 'query_parser'): query_parser = current_app.config['OAISERVER_QUERY_PARSER'] if isinstance(query_parser, six.string_types): query_parser = import_string(query_parser) ...
Get list of affected records.
def get_affected_records(spec=None, search_pattern=None): """Get list of affected records. :param spec: The record spec. :param search_pattern: The search pattern. :returns: An iterator to lazily find results. """ # spec pattern query # ---------- ---------- ------- # None ...
Get records paginated.
def get_records(**kwargs): """Get records paginated.""" page_ = kwargs.get('resumptionToken', {}).get('page', 1) size_ = current_app.config['OAISERVER_PAGE_SIZE'] scroll = current_app.config['OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME'] scroll_id = kwargs.get('resumptionToken', {}).get('scroll_id') ...
Look for an existing path matching filename. Try to resolve relative to the module location if the path cannot by found using normal resolution.
def get_file_path(filename, local=True, relative_to_module=None, my_dir=my_dir): """ Look for an existing path matching filename. Try to resolve relative to the module location if the path cannot by found using "normal" resolution. """ # override my_dir if module is provided if relative_to_m...
Load a javascript file to the Jupyter notebook context unless it was already loaded.
def load_if_not_loaded(widget, filenames, verbose=False, delay=0.1, force=False, local=True, evaluator=None): """ Load a javascript file to the Jupyter notebook context, unless it was already loaded. """ if evaluator is None: evaluator = EVALUATOR # default if not specified. for filenam...
Proxy to set a property of the widget element.
def _set(self, name, value): "Proxy to set a property of the widget element." return self.widget(self.widget_element._set(name, value))
Strips the outer tag if text starts with a tag. Not entity aware ; designed to quickly strip outer tags from lxml cleaner output. Only checks for <p > and <div > outer tags.
def strip_outer_tag(text): """Strips the outer tag, if text starts with a tag. Not entity aware; designed to quickly strip outer tags from lxml cleaner output. Only checks for <p> and <div> outer tags.""" if not text or not isinstance(text, basestring): return text stripped = text.strip() ...
If an author contains an email and a name in it make sure it is in the format: name ( email ).
def munge_author(author): """If an author contains an email and a name in it, make sure it is in the format: "name (email)".""" # this loveliness is from feedparser but was not usable as a function if '@' in author: emailmatch = re.search(r"(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-...
Determine the base url for a root element.
def base_url(root): """Determine the base url for a root element.""" for attr, value in root.attrib.iteritems(): if attr.endswith('base') and 'http' in value: return value return None
Return a tag and its namespace separately.
def clean_ns(tag): """Return a tag and its namespace separately.""" if '}' in tag: split = tag.split('}') return split[0].strip('{'), split[-1] return '', tag
A safe xpath that only uses namespaces if available.
def xpath(node, query, namespaces={}): """A safe xpath that only uses namespaces if available.""" if namespaces and 'None' not in namespaces: return node.xpath(query, namespaces=namespaces) return node.xpath(query)
Return the inner text of a node. If a node has no sub elements this is just node. text. Otherwise it s node. text + sub - element - text + node. tail.
def innertext(node): """Return the inner text of a node. If a node has no sub elements, this is just node.text. Otherwise, it's node.text + sub-element-text + node.tail.""" if not len(node): return node.text return (node.text or '') + ''.join([etree.tostring(c) for c in node]) + (node.tai...
Parse a document and return a feedparser dictionary with attr key access. If clean_html is False the html in the feed will not be cleaned. If clean_html is True a sane version of lxml. html. clean. Cleaner will be used. If it is a Cleaner object that cleaner will be used. If unix_timestamp is True the date information ...
def parse(document, clean_html=True, unix_timestamp=False, encoding=None): """Parse a document and return a feedparser dictionary with attr key access. If clean_html is False, the html in the feed will not be cleaned. If clean_html is True, a sane version of lxml.html.clean.Cleaner will be used. If it ...
An attempt to parse pieces of an entry out w/ o xpath by looping over the entry root s children and slotting them into the right places. This is going to be way messier than SpeedParserEntries and maybe less cleanly usable but it should be faster.
def parse_entry(self, entry): """An attempt to parse pieces of an entry out w/o xpath, by looping over the entry root's children and slotting them into the right places. This is going to be way messier than SpeedParserEntries, and maybe less cleanly usable, but it should be faster.""" ...
Find any changed path and update all changed modification times.
def changed_path(self): "Find any changed path and update all changed modification times." result = None # default for path in self.paths_to_modification_times: lastmod = self.paths_to_modification_times[path] mod = os.path.getmtime(path) if mod > lastmod: ...
Parse a variety of ISO - 8601 - compatible formats like 20040105
def _parse_date_iso8601(dateString): '''Parse a variety of ISO-8601-compatible formats like 20040105''' m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = ...
Parse a string according to the OnBlog 8 - bit date format
def _parse_date_onblog(dateString): '''Parse a string according to the OnBlog 8-bit date format''' m = _korean_onblog_date_re.match(dateString) if not m: return w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \ {'year': m.group(1), 'month': m...
Parse a string according to the Nate 8 - bit date format
def _parse_date_nate(dateString): '''Parse a string according to the Nate 8-bit date format''' m = _korean_nate_date_re.match(dateString) if not m: return hour = int(m.group(5)) ampm = m.group(4) if (ampm == _korean_pm): hour += 12 hour = str(hour) if len(hour) == 1: ...
Parse a string according to a Greek 8 - bit date format.
def _parse_date_greek(dateString): '''Parse a string according to a Greek 8-bit date format.''' m = _greek_date_format_re.match(dateString) if not m: return wday = _greek_wdays[m.group(1)] month = _greek_months[m.group(3)] rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(min...
Parse a string according to a Hungarian 8 - bit date format.
def _parse_date_hungarian(dateString): '''Parse a string according to a Hungarian 8-bit date format.''' m = _hungarian_date_format_re.match(dateString) if not m or m.group(2) not in _hungarian_months: return None month = _hungarian_months[m.group(2)] day = m.group(3) if len(day) == 1: ...
Parse an RFC822 RFC1123 RFC2822 or asctime - style date
def _parse_date_rfc822(dateString): '''Parse an RFC822, RFC1123, RFC2822, or asctime-style date''' data = dateString.split() if not data: return None if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames: del data[0] if len(data) == 4: s = data[3] i = s....
parse a date in yyyy/ mm/ dd hh: mm: ss TTT format
def _parse_date_perforce(aDateString): """parse a date in yyyy/mm/dd hh:mm:ss TTT format""" # Fri, 2006/09/15 08:19:53 EDT _my_date_pattern = re.compile( \ r'(\w{,3}), (\d{,4})/(\d{,2})/(\d{2}) (\d{,2}):(\d{2}):(\d{2}) (\w{,3})') m = _my_date_pattern.search(aDateString) if m is None: ...
Parses a variety of date formats into a 9 - tuple in GMT
def parse_date(dateString): '''Parses a variety of date formats into a 9-tuple in GMT''' if not dateString: return None for handler in _date_handlers: try: date9tuple = handler(dateString) except (KeyError, OverflowError, ValueError): continue if not d...
wrapper to allow output redirects for handle_chunk.
def handle_chunk_wrapper(self, status, name, content, file_info): """wrapper to allow output redirects for handle_chunk.""" out = self.output if out is not None: with out: print("handling chunk " + repr(type(content))) self.handle_chunk(status, name, c...
Handle one chunk of the file. Override this method for peicewise delivery or error handling.
def handle_chunk(self, status, name, content, file_info): "Handle one chunk of the file. Override this method for peicewise delivery or error handling." if status == "error": msg = repr(file_info.get("message")) exc = JavaScriptError(msg) exc.file_info = file_info ...
Return a URL for a user to login/ register with ORCID.
def get_login_url(self, scope, redirect_uri, state=None, family_names=None, given_names=None, email=None, lang=None, show_login=None): """Return a URL for a user to login/register with ORCID. Parameters ---------- :param scope: string or itera...
Search the ORCID database.
def search(self, query, method="lucene", start=None, rows=None, access_token=None): """Search the ORCID database. Parameters ---------- :param query: string Query in line with the chosen method. :param method: string One of 'lucene', 'edism...
Search the ORCID database with a generator.
def search_generator(self, query, method="lucene", pagination=10, access_token=None): """Search the ORCID database with a generator. The generator will yield every result. Parameters ---------- :param query: string Query in line with the cho...
Get a token for searching ORCID records.
def get_search_token_from_orcid(self, scope='/read-public'): """Get a token for searching ORCID records. Parameters ---------- :param scope: string /read-public or /read-member Returns ------- :returns: string The token. """ ...
Get the token.
def get_token(self, user_id, password, redirect_uri, scope='/read-limited'): """Get the token. Parameters ---------- :param user_id: string The id of the user used for authentication. :param password: string The user password. :p...
Like get_token but using an OAuth 2 authorization code.
def get_token_from_authorization_code(self, authorization_code, redirect_uri): """Like `get_token`, but using an OAuth 2 authorization code. Use this method if you run a webserver that serves as an endpoint for the redirect URI. The webserver can retrie...
Get the public info about the researcher.
def read_record_public(self, orcid_id, request_type, token, put_code=None, accept_type='application/orcid+json'): """Get the public info about the researcher. Parameters ---------- :param orcid_id: string Id of the queried author. :param re...
Add a record to a profile.
def add_record(self, orcid_id, token, request_type, data, content_type='application/orcid+json'): """Add a record to a profile. Parameters ---------- :param orcid_id: string Id of the author. :param token: string Token received from OAu...
Get the token.
def get_token(self, user_id, password, redirect_uri, scope='/activities/update'): """Get the token. Parameters ---------- :param user_id: string The id of the user used for authentication. :param password: string The user password. ...
Get the user orcid from authentication process.
def get_user_orcid(self, user_id, password, redirect_uri): """Get the user orcid from authentication process. Parameters ---------- :param user_id: string The id of the user used for authentication. :param password: string The user password. :para...
Get the member info about the researcher.
def read_record_member(self, orcid_id, request_type, token, put_code=None, accept_type='application/orcid+json'): """Get the member info about the researcher. Parameters ---------- :param orcid_id: string Id of the queried author. :param re...
Add a record to a profile.
def remove_record(self, orcid_id, token, request_type, put_code): """Add a record to a profile. Parameters ---------- :param orcid_id: string Id of the author. :param token: string Token received from OAuth 2 3-legged authorization. :param request...
Add a record to a profile.
def update_record(self, orcid_id, token, request_type, data, put_code, content_type='application/orcid+json'): """Add a record to a profile. Parameters ---------- :param orcid_id: string Id of the author. :param token: string Token r...
Remove any duplicates from the entity relationship table: param apps:: param schema_editor:: return:
def remove_duplicates(apps, schema_editor): """ Remove any duplicates from the entity relationship table :param apps: :param schema_editor: :return: """ # Get the model EntityRelationship = apps.get_model('entity', 'EntityRelationship') # Find the duplicates duplicates = Entity...
From the authorization code get the access token and the refresh token from Box.
def get_access_tokens(self, authorization_code): """From the authorization code, get the "access token" and the "refresh token" from Box. Args: authorization_code (str). Authorisation code emitted by Box at the url provided by the function :func:`get_authorization_url`. Returns: ...
Called to unpack a STOMP message into a dictionary.
def unpack_frame(message): """Called to unpack a STOMP message into a dictionary. returned = { # STOMP Command: 'cmd' : '...', # Headers e.g. 'headers' : { 'destination' : 'xyz', 'message-id' : 'some event', : etc, } ...
STOMP acknowledge command.
def ack(messageid, transactionid=None): """STOMP acknowledge command. Acknowledge receipt of a specific message from the server. messageid: This is the id of the message we are acknowledging, what else could it be? ;) transactionid: This is the id that all actions in this tran...
STOMP send command.
def send(dest, msg, transactionid=None): """STOMP send command. dest: This is the channel we wish to subscribe to msg: This is the message body to be sent. transactionid: This is an optional field and is not needed by default. """ transheader = '' if tran...
Check the cmd is valid FrameError will be raised if its not.
def setCmd(self, cmd): """Check the cmd is valid, FrameError will be raised if its not.""" cmd = cmd.upper() if cmd not in VALID_COMMANDS: raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % ( cmd, VALID_COMMANDS, STOMP_VERSION) ...
Called to create a STOMP message from the internal values.
def pack(self): """Called to create a STOMP message from the internal values. """ headers = ''.join( ['%s:%s\n' % (f, v) for f, v in sorted(self.headers.items())] ) stomp_message = "%s\n%s\n%s%s\n" % (self._cmd, headers, self.body, NULL) # import pprint # ...
Called to extract a STOMP message into this instance.
def unpack(self, message): """Called to extract a STOMP message into this instance. message: This is a text string representing a valid STOMP (v1.0) message. This method uses unpack_frame(...) to extract the information, before it is assigned internally. ...
Called to provide a response to a message if needed.
def react(self, msg): """Called to provide a response to a message if needed. msg: This is a dictionary as returned by unpack_frame(...) or it can be a straight STOMP message. This function will attempt to determine which an deal with it. returned: ...
Called to handle an error message received from the server.
def error(self, msg): """Called to handle an error message received from the server. This method just logs the error message returned: NO_RESPONSE_NEEDED """ body = msg['body'].replace(NULL, '') brief_msg = "" if 'message' in msg['headers']: ...
Called to handle a receipt message received from the server.
def receipt(self, msg): """Called to handle a receipt message received from the server. This method just logs the receipt message returned: NO_RESPONSE_NEEDED """ body = msg['body'].replace(NULL, '') brief_msg = "" if 'receipt-id' in msg['headers']...
Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing.
def log_init(level): """Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing. """ log = logging.getLogger() hdlr = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') hdlr.se...