text stringlengths 81 112k |
|---|
Get list of sets.
def sets(self):
"""Get list of sets."""
if self.cache:
return self.cache.get(
self.app.config['OAISERVER_CACHE_KEY']) |
Set list of sets.
def sets(self, values):
"""Set list of sets."""
# if cache server is configured, save sets list
if self.cache:
self.cache.set(self.app.config['OAISERVER_CACHE_KEY'], values) |
Register signals.
def register_signals(self):
"""Register signals."""
from .receivers import OAIServerUpdater
# Register Record signals to update OAI informations
self.update_function = OAIServerUpdater()
records_signals.before_record_insert.connect(self.update_function,
... |
Register OAISet signals to update records.
def register_signals_oaiset(self):
"""Register OAISet signals to update records."""
from .models import OAISet
from .receivers import after_insert_oai_set, \
after_update_oai_set, after_delete_oai_set
listen(OAISet, 'after_insert', ... |
Unregister signals.
def unregister_signals(self):
"""Unregister signals."""
# Unregister Record signals
if hasattr(self, 'update_function'):
records_signals.before_record_insert.disconnect(
self.update_function)
records_signals.before_record_update.discon... |
Unregister signals oaiset.
def unregister_signals_oaiset(self):
"""Unregister signals oaiset."""
from .models import OAISet
from .receivers import after_insert_oai_set, \
after_update_oai_set, after_delete_oai_set
if contains(OAISet, 'after_insert', after_insert_oai_set):
... |
Initialize configuration.
:param app: An instance of :class:`flask.Flask`.
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`flask.Flask`.
"""
app.config.setdefault(
'OAISERVER_BASE_TEMPLATE',
app.config.get('BA... |
Extracts the values of a set of parameters, recursing into nested dictionaries.
def extract_params(params):
"""
Extracts the values of a set of parameters, recursing into nested dictionaries.
"""
values = []
if isinstance(params, dict):
for key, value in params.items():
values.e... |
Returns the unhashed signature string (secret + sorted list of param values) for an API call.
@param params: dictionary values to generate signature string
@param secret: secret string
def get_signature_string(params, secret):
"""
Returns the unhashed signature string (secret + sorted list of param val... |
Remotely send an email template to a single email address.
http://docs.sailthru.com/api/send
@param template: template string
@param email: Email value
@param _vars: a key/value hash of the replacement vars to use in the send. Each var may be referenced as {varname} within the template i... |
Remotely send an email template to multiple email addresses.
http://docs.sailthru.com/api/send
@param template: template string
@param emails: List with email values or comma separated email string
@param _vars: a key/value hash of the replacement vars to use in the send. Each var may be... |
DEPRECATED!
Update information about one of your users, including adding and removing the user from lists.
http://docs.sailthru.com/api/email
def set_email(self, email, _vars=None, lists=None, templates=None, verified=0, optout=None, send=None, send_vars=None):
"""
DEPRECATED!
U... |
get user by a given id
http://getstarted.sailthru.com/api/user
def get_user(self, idvalue, options=None):
"""
get user by a given id
http://getstarted.sailthru.com/api/user
"""
options = options or {}
data = options.copy()
data['id'] = idvalue
ret... |
save user by a given id
http://getstarted.sailthru.com/api/user
def save_user(self, idvalue, options=None):
"""
save user by a given id
http://getstarted.sailthru.com/api/user
"""
options = options or {}
data = options.copy()
data['id'] = idvalue
... |
Schedule a mass mail blast
http://docs.sailthru.com/api/blast
@param name: name to give to this new blast
@param list: mailing list name to send to
@param schedule_time: when the blast should send. Dates in the past will be scheduled for immediate delivery. Any English textual datetime ... |
Schedule a mass mail blast from template
http://docs.sailthru.com/api/blast
@param template: template to copy from
@param list_name: list to send to
@param schedule_time
@param options: additional optional params
def schedule_blast_from_template(self, template, list_name, schedu... |
Schedule a mass mail blast from previous blast
http://docs.sailthru.com/api/blast
@param blast_id: blast_id to copy from
@param schedule_time
@param options: additional optional params
def schedule_blast_from_blast(self, blast_id, schedule_time, options=None):
"""
Schedu... |
Get detailed metadata information about a list.
def get_list(self, list_name, options=None):
"""
Get detailed metadata information about a list.
"""
options = options or {}
data = {'list': list_name}
data.update(options)
return self.api_get('list', data) |
Upload a list. The list import job is queued and will happen shortly after the API request.
http://docs.sailthru.com/api/list
@param list: list name
@param emails: List of email values or comma separated string
def save_list(self, list_name, emails):
"""
Upload a list. The list ... |
Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail.
def import_contacts(self, email, password, include_name=False):
"""
Fetch email contacts from a user's address book on one of the major email websites. Currently ... |
Push a new piece of content to Sailthru.
Expected names for the `images` argument's map are "full" and "thumb"
Expected format for `location` should be [longitude,latitude]
@param title: title string for the content
@param url: URL string for the content
@param images: map of i... |
Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly).
http://docs.sailthru.com/api/alert
Usage:
email = 'praj@sailthru.com'
type = 'weekly'
template = 'default'
when = '+5 hours'
alert_options = {'match': ... |
delete user alert
def delete_alert(self, email, alert_id):
"""
delete user alert
"""
data = {'email': email,
'alert_id': alert_id}
return self.api_delete('alert', data) |
Record that a user has made a purchase, or has added items to their purchase total.
http://docs.sailthru.com/api/purchase
@param email: Email string
@param items: list of item dictionary with keys: id, title, price, qty, and url
@param message_id: message_id string
@param extid: ... |
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'.
def get_purchase(self, purchase_id, purchase_key='sid'):
"""
Retrieve information about... |
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:... |
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 aggr... |
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 part... |
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',... |
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):
retur... |
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):
... |
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.
@param action: API action call
@param data: dictionary values
def api_get(self, action, data, headers=None):
"""
Perform an HTTP GET request, using the shared-secret auth hash.
@param action: API action call
... |
Perform an HTTP POST request, using the shared-secret auth hash.
@param action: API action call
@param data: dictionary values
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... |
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
def api_post_multipart(self, action, data, binary_data_param):
"""
Perform an HTTP Multipa... |
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 = {'... |
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
... |
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.
In order to do so, define linked_forms on A's viewset containing a call to linked_form ... |
Mint record identifiers.
:param record_uuid: The record UUID.
:param data: The record data.
:returns: A :class:`invenio_pidstore.models.PersistentIdentifier` instance.
def oaiid_minter(record_uuid, data):
"""Mint record identifiers.
:param record_uuid: The record UUID.
:param data: The record... |
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 error... |
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'] = 'tex... |
Create a new record identifier.
:param object_type: The object type. (Default: ``None``)
:param object_uuid: The object UUID. (Default: ``None``)
def create(cls, object_type=None, object_uuid=None, **kwargs):
"""Create a new record identifier.
:param object_type: The object type. (Def... |
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.
def _create_percolator_mapping(index, doc_type):
"""Update mappings with the percolator field.
.. note::
... |
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_... |
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():
... |
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
percola... |
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 set... |
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:
... |
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.
:param spec: The record spec.
:param search_pattern: The search pattern.
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 patt... |
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 = ElementT... |
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... |
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(p... |
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=pag... |
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.... |
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(... |
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 = ve... |
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']['_sour... |
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_f... |
Fetch a record's identifier.
:param record_uuid: The record UUID.
:param data: The record data.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` instance.
def oaiid_fetcher(record_uuid, data):
"""Fetch a record's identifier.
:param record_uuid: The record UUID.
:param data: The recor... |
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.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative.
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.
... |
Remove a record from the OAISet.
:param record: Record to be removed.
:type record: `invenio_records.api.Record` or derivative.
def remove_record(self, record):
"""Remove a record from the OAISet.
:param record: Record to be removed.
:type record: `invenio_records.api.Record` ... |
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... |
Return etree_dumper instances.
:param metadata_prefix: One of the metadata identifiers configured in
``OAISERVER_METADATA_FORMATS``.
def serializer(metadata_prefix):
"""Return etree_dumper instances.
:param metadata_prefix: One of the metadata identifiers configured in
``OAISERVER_METADAT... |
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.
def dumps_etree(pid, record, **kwargs):
"""Dump MARC21 compatible record.
:par... |
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 specification and schema definition visit:
http://www.openarchives.org/OAI/2.0/guidelines-eprints.htm
def eprints_descriptio... |
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 implement OAI-PMH.
For the full specification and schema definition visit:
http://www.openarchives.org/OAI/2.0/guidelines-oai-id... |
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
def friends_description(baseURLs):
"""Generate the frie... |
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_r... |
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_pa... |
Get list of affected records.
:param spec: The record spec.
:param search_pattern: The search pattern.
:returns: An iterator to lazily find results.
def get_affected_records(spec=None, search_pattern=None):
"""Get list of affected records.
:param spec: The record spec.
:param search_pattern: ... |
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', {... |
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 relativ... |
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 ev... |
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... |
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 '@... |
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-t... |
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, th... |
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 a... |
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]
... |
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:
... |
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%(zoned... |
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):
hou... |
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)]
rfc822dat... |
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_mont... |
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]... |
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_patt... |
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, OverflowE... |
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... |
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.... |
Return a URL for a user to login/register with ORCID.
Parameters
----------
:param scope: string or iterable of strings
The scope(s) of the authorization request.
For example '/authenticate'
:param redirect_uri: string
The URI to which the user's brow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.