INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return fields from schema :param Schema schema: A marshmallow Schema instance or a class object :param bool exclude_dump_only: whether to filter fields in Meta.dump_only :rtype: dict, of field name field object pairs
def get_fields(schema, exclude_dump_only=False): """Return fields from schema :param Schema schema: A marshmallow Schema instance or a class object :param bool exclude_dump_only: whether to filter fields in Meta.dump_only :rtype: dict, of field name field object pairs """ if hasattr(schema, "fi...
Warns user that fields defined in Meta.fields or Meta.additional will be ignored :param dict fields: A dictionary of fields name field object pairs :param Meta: the schema's Meta class
def warn_if_fields_defined_in_meta(fields, Meta): """Warns user that fields defined in Meta.fields or Meta.additional will be ignored :param dict fields: A dictionary of fields name field object pairs :param Meta: the schema's Meta class """ if getattr(Meta, "fields", None) or getattr(Meta, "ad...
Filter fields that should be ignored in the OpenAPI spec :param dict fields: A dictionary of fields name field object pairs :param Meta: the schema's Meta class :param bool exclude_dump_only: whether to filter fields in Meta.dump_only
def filter_excluded_fields(fields, Meta, exclude_dump_only): """Filter fields that should be ignored in the OpenAPI spec :param dict fields: A dictionary of fields name field object pairs :param Meta: the schema's Meta class :param bool exclude_dump_only: whether to filter fields in Meta.dump_only ...
Function to generate a unique name based on the provided name and names already in the spec. Will append a number to the name to make it unique if the name is already in the spec. :param Components components: instance of the components of the spec :param string name: the name to use as a basis for th...
def get_unique_schema_name(components, name, counter=0): """Function to generate a unique name based on the provided name and names already in the spec. Will append a number to the name to make it unique if the name is already in the spec. :param Components components: instance of the components of th...
Return path to reference :param str component_type: Component type (schema, parameter, response, security_scheme) :param int openapi_major_version: OpenAPI major version (2 or 3) :param str component_name: Name of component to reference
def build_reference(component_type, openapi_major_version, component_name): """Return path to reference :param str component_type: Component type (schema, parameter, response, security_scheme) :param int openapi_major_version: OpenAPI major version (2 or 3) :param str component_name: Name of component ...
Validate the output of an :class:`APISpec` object against the OpenAPI specification. Note: Requires installing apispec with the ``[validation]`` extras. :: pip install 'apispec[validation]' :raise: apispec.exceptions.OpenAPIError if validation fails.
def validate_spec(spec): """Validate the output of an :class:`APISpec` object against the OpenAPI specification. Note: Requires installing apispec with the ``[validation]`` extras. :: pip install 'apispec[validation]' :raise: apispec.exceptions.OpenAPIError if validation fails. """ ...
Uniformly trims leading/trailing whitespace from docstrings. Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation
def trim_docstring(docstring): """Uniformly trims leading/trailing whitespace from docstrings. Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation """ if not docstring or not docstring.strip(): return "" # Convert tabs to spaces and split into lines lines = ...
Recursively update a dict. Subdict's won't be overwritten but also updated.
def deepupdate(original, update): """Recursively update a dict. Subdict's won't be overwritten but also updated. """ for key, value in original.items(): if key not in update: update[key] = value elif isinstance(value, dict): deepupdate(value, update[key]) ret...
Adjust field name to reflect `dump_to` and `load_from` attributes. :param Field field: A marshmallow field. :param str name: Field name :rtype: str
def _observed_name(field, name): """Adjust field name to reflect `dump_to` and `load_from` attributes. :param Field field: A marshmallow field. :param str name: Field name :rtype: str """ if MARSHMALLOW_VERSION_INFO[0] < 3: # use getattr in case we're running...
Decorator to set mapping for custom fields. ``*args`` can be: - a pair of the form ``(type, format)`` - a core marshmallow field type (in which case we reuse that type's mapping)
def map_to_openapi_type(self, *args): """Decorator to set mapping for custom fields. ``*args`` can be: - a pair of the form ``(type, format)`` - a core marshmallow field type (in which case we reuse that type's mapping) """ if len(args) == 1 and args[0] in self.field_ma...
Return the dictionary of OpenAPI type and format based on the field type :param Field field: A marshmallow field. :rtype: dict
def field2type_and_format(self, field): """Return the dictionary of OpenAPI type and format based on the field type :param Field field: A marshmallow field. :rtype: dict """ # If this type isn't directly in the field mapping then check the # hierarchy until we fi...
Return the dictionary containing the field's default value Will first look for a `doc_default` key in the field's metadata and then fall back on the field's `missing` parameter. A callable passed to the field's missing parameter will be ignored. :param Field field: A marshmallow field....
def field2default(self, field): """Return the dictionary containing the field's default value Will first look for a `doc_default` key in the field's metadata and then fall back on the field's `missing` parameter. A callable passed to the field's missing parameter will be ignored. ...
Return the dictionary of OpenAPI field attributes for valid choices definition :param Field field: A marshmallow field. :rtype: dict
def field2choices(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for valid choices definition :param Field field: A marshmallow field. :rtype: dict """ attributes = {} comparable = [ validator.comparable for validato...
Return the dictionary of OpenAPI field attributes for a dump_only field. :param Field field: A marshmallow field. :rtype: dict
def field2read_only(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for a dump_only field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.dump_only: attributes["readOnly"] = True return ...
Return the dictionary of OpenAPI field attributes for a load_only field. :param Field field: A marshmallow field. :rtype: dict
def field2write_only(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for a load_only field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.load_only and self.openapi_version.major >= 3: attribut...
Return the dictionary of OpenAPI field attributes for a nullable field. :param Field field: A marshmallow field. :rtype: dict
def field2nullable(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for a nullable field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.allow_none: attributes[ "x-nullable" if se...
Return the dictionary of OpenAPI field attributes for a set of :class:`Range <marshmallow.validators.Range>` validators. :param Field field: A marshmallow field. :rtype: dict
def field2range(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for a set of :class:`Range <marshmallow.validators.Range>` validators. :param Field field: A marshmallow field. :rtype: dict """ validators = [ validator ...
Return the dictionary of OpenAPI field attributes for a set of :class:`Length <marshmallow.validators.Length>` validators. :param Field field: A marshmallow field. :rtype: dict
def field2length(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for a set of :class:`Length <marshmallow.validators.Length>` validators. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} validators = [ ...
Return the dictionary of OpenAPI field attributes for a set of :class:`Range <marshmallow.validators.Regexp>` validators. :param Field field: A marshmallow field. :rtype: dict
def field2pattern(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for a set of :class:`Range <marshmallow.validators.Regexp>` validators. :param Field field: A marshmallow field. :rtype: dict """ regex_validators = ( v ...
Return a dictionary of properties extracted from field Metadata Will include field metadata that are valid properties of `OpenAPI schema objects <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_ (e.g. “description”, “enum”, “example”). ...
def metadata2properties(self, field): """Return a dictionary of properties extracted from field Metadata Will include field metadata that are valid properties of `OpenAPI schema objects <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject>`_ (...
Return the JSON Schema property definition given a marshmallow :class:`Field <marshmallow.fields.Field>`. Will include field metadata that are valid properties of OpenAPI schema objects (e.g. "description", "enum", "example"). https://github.com/OAI/OpenAPI-Specification/blob/master/ve...
def field2property(self, field): """Return the JSON Schema property definition given a marshmallow :class:`Field <marshmallow.fields.Field>`. Will include field metadata that are valid properties of OpenAPI schema objects (e.g. "description", "enum", "example"). https://github....
Return the Open API representation of a marshmallow Schema. Adds the schema to the spec if it isn't already present. Typically will return a dictionary with the reference to the schema's path in the spec unless the `schema_name_resolver` returns `None`, in which case the returned dicto...
def resolve_nested_schema(self, schema): """Return the Open API representation of a marshmallow Schema. Adds the schema to the spec if it isn't already present. Typically will return a dictionary with the reference to the schema's path in the spec unless the `schema_name_resolver` retu...
Return an array of OpenAPI parameters given a given marshmallow :class:`Schema <marshmallow.Schema>`. If `default_in` is "body", then return an array of a single parameter; else return an array of a parameter for each included field in the :class:`Schema <marshmallow.Schema>`. https://g...
def schema2parameters( self, schema, default_in="body", name="body", required=False, description=None ): """Return an array of OpenAPI parameters given a given marshmallow :class:`Schema <marshmallow.Schema>`. If `default_in` is "body", then return an array of a single parameter; els...
Return an array of OpenAPI parameters given a mapping between field names and :class:`Field <marshmallow.Field>` objects. If `default_in` is "body", then return an array of a single parameter; else return an array of a parameter for each included field in the :class:`Schema <marshmallow.Schema>`...
def fields2parameters(self, fields, default_in="body"): """Return an array of OpenAPI parameters given a mapping between field names and :class:`Field <marshmallow.Field>` objects. If `default_in` is "body", then return an array of a single parameter; else return an array of a parameter for each...
Return an OpenAPI parameter as a `dict`, given a marshmallow :class:`Field <marshmallow.Field>`. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
def field2parameter(self, field, name="body", default_in="body"): """Return an OpenAPI parameter as a `dict`, given a marshmallow :class:`Field <marshmallow.Field>`. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject """ location = field.m...
Return the Parameter Object definition for a JSON Schema property. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject :param dict prop: JSON Schema property :param str name: Field name :param bool required: Parameter is required :param bo...
def property2parameter( self, prop, name="body", required=False, multiple=False, location=None, default_in="body", ): """Return the Parameter Object definition for a JSON Schema property. https://github.com/OAI/OpenAPI-Specification/blob/maste...
Return the JSON Schema Object for a given marshmallow :class:`Schema <marshmallow.Schema>` instance. Schema may optionally provide the ``title`` and ``description`` class Meta options. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject Example: :: ...
def schema2jsonschema(self, schema): """Return the JSON Schema Object for a given marshmallow :class:`Schema <marshmallow.Schema>` instance. Schema may optionally provide the ``title`` and ``description`` class Meta options. https://github.com/OAI/OpenAPI-Specification/blob/master/versi...
Return the JSON Schema Object given a mapping between field names and :class:`Field <marshmallow.Field>` objects. :param dict fields: A dictionary of field name field object pairs :param bool ordered: Whether to preserve the order in which fields were declared :param bool|tuple partial:...
def fields2jsonschema(self, fields, ordered=False, partial=None): """Return the JSON Schema Object given a mapping between field names and :class:`Field <marshmallow.Field>` objects. :param dict fields: A dictionary of field name field object pairs :param bool ordered: Whether to preser...
Method to create a dictionary containing a JSON reference to the schema in the spec
def get_ref_dict(self, schema): """Method to create a dictionary containing a JSON reference to the schema in the spec """ schema_key = make_schema_key(schema) ref_schema = build_reference( "schema", self.openapi_version.major, self.refs[schema_key] ) ...
Ensure that all parameters with "in" equal to "path" are also required as required by the OpenAPI specification, as well as normalizing any references to global parameters. Also checks for invalid HTTP methods. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject. ...
def clean_operations(operations, openapi_major_version): """Ensure that all parameters with "in" equal to "path" are also required as required by the OpenAPI specification, as well as normalizing any references to global parameters. Also checks for invalid HTTP methods. See https://github.com/OAI/OpenA...
Add a new schema to the spec. :param str name: identifier by which schema may be referenced. :param dict component: schema definition. .. note:: If you are using `apispec.ext.marshmallow`, you can pass fields' metadata as additional keyword arguments. For ...
def schema(self, name, component=None, **kwargs): """Add a new schema to the spec. :param str name: identifier by which schema may be referenced. :param dict component: schema definition. .. note:: If you are using `apispec.ext.marshmallow`, you can pass fields' metadata a...
Add a parameter which can be referenced. :param str param_id: identifier by which parameter may be referenced. :param str location: location of the parameter. :param dict component: parameter fields. :param dict kwargs: plugin-specific arguments
def parameter(self, component_id, location, component=None, **kwargs): """ Add a parameter which can be referenced. :param str param_id: identifier by which parameter may be referenced. :param str location: location of the parameter. :param dict component: parameter fields. :par...
Add a response which can be referenced. :param str component_id: ref_id to use as reference :param dict component: response fields :param dict kwargs: plugin-specific arguments
def response(self, component_id, component=None, **kwargs): """Add a response which can be referenced. :param str component_id: ref_id to use as reference :param dict component: response fields :param dict kwargs: plugin-specific arguments """ if component_id in self._re...
Add a security scheme which can be referenced. :param str component_id: component_id to use as reference :param dict kwargs: security scheme fields
def security_scheme(self, component_id, component): """Add a security scheme which can be referenced. :param str component_id: component_id to use as reference :param dict kwargs: security scheme fields """ if component_id in self._security_schemes: raise DuplicateCo...
Add a new path object to the spec. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object :param str|None path: URL path component :param dict|None operations: describes the http methods and options for `path` :param str summary: short summary relev...
def path( self, path=None, operations=None, summary=None, description=None, **kwargs ): """Add a new path object to the spec. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object :param str|None path: URL path component :param dict|Non...
Default implementation of a schema name resolver function
def resolver(schema): """Default implementation of a schema name resolver function """ name = schema.__name__ if name.endswith("Schema"): return name[:-6] or name return name
Function to resolve a schema in a requestBody object - modifies then response dict to convert Marshmallow Schema object or class into dict
def resolve_schema_in_request_body(self, request_body): """Function to resolve a schema in a requestBody object - modifies then response dict to convert Marshmallow Schema object or class into dict """ content = request_body["content"] for content_type in content: sch...
Function to resolve a schema in a parameter or response - modifies the corresponding dict to convert Marshmallow Schema object or class into dict :param APISpec spec: `APISpec` containing refs. :param dict|str data: either a parameter or response dictionary that may contain a schema...
def resolve_schema(self, data): """Function to resolve a schema in a parameter or response - modifies the corresponding dict to convert Marshmallow Schema object or class into dict :param APISpec spec: `APISpec` containing refs. :param dict|str data: either a parameter or response dicti...
Definition helper that allows using a marshmallow :class:`Schema <marshmallow.Schema>` to provide OpenAPI metadata. :param type|Schema schema: A marshmallow Schema class or instance.
def schema_helper(self, name, _, schema=None, **kwargs): """Definition helper that allows using a marshmallow :class:`Schema <marshmallow.Schema>` to provide OpenAPI metadata. :param type|Schema schema: A marshmallow Schema class or instance. """ if schema is None: ...
Response component helper that allows using a marshmallow :class:`Schema <marshmallow.Schema>` in response definition. :param dict parameter: response fields. May contain a marshmallow Schema class or instance.
def response_helper(self, response, **kwargs): """Response component helper that allows using a marshmallow :class:`Schema <marshmallow.Schema>` in response definition. :param dict parameter: response fields. May contain a marshmallow Schema class or instance. """ se...
Method to warn the user if the schema has already been added to the spec.
def warn_if_schema_already_in_spec(self, schema_key): """Method to warn the user if the schema has already been added to the spec. """ if schema_key in self.openapi.refs: warnings.warn( "{} has already been added to the spec. Adding it twice may " ...
Returns the size in bytes from strings such as '5 mb' into 5242880. >>> size_in_bytes('1m') 1048576 >>> size_in_bytes('1.5m') 1572864 >>> size_in_bytes('2g') 2147483648 >>> size_in_bytes(None) Traceback (most recent call last): raise ValueError('no string specified') ValueEr...
def size_in_bytes(insize): """ Returns the size in bytes from strings such as '5 mb' into 5242880. >>> size_in_bytes('1m') 1048576 >>> size_in_bytes('1.5m') 1572864 >>> size_in_bytes('2g') 2147483648 >>> size_in_bytes(None) Traceback (most recent call last): raise ValueE...
Main function, parses the URL from command line arguments
def main(): """ Main function, parses the URL from command line arguments """ signal.signal(signal.SIGINT, signal_handler) global offset global arguments # Parse argument arguments = docopt(__doc__, version=__version__) if arguments['--debug']: logger.level = logging.DEBUG ...
Reads the music download filepath from scdl.cfg
def get_config(): """ Reads the music download filepath from scdl.cfg """ global token config = configparser.ConfigParser() config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg')) try: token = config['scdl']['auth_token'] path = config['scdl']['path'] ...
Fetches metadata for a track or playlist
def get_item(track_url, client_id=CLIENT_ID): """ Fetches metadata for a track or playlist """ try: item_url = url['resolve'].format(track_url) r = requests.get(item_url, params={'client_id': client_id}) logger.debug(r.url) if r.status_code == 403: return get...
Detects if a URL is a track or a playlist, and parses the track(s) to the track downloader
def parse_url(track_url): """ Detects if a URL is a track or a playlist, and parses the track(s) to the track downloader """ global arguments item = get_item(track_url) logger.debug(item) if not item: return elif item['kind'] == 'track': logger.info('Found a track') ...
Display username from current token and check for validity
def who_am_i(): """ Display username from current token and check for validity """ me = url['me'].format(token) r = requests.get(me, params={'client_id': CLIENT_ID}) r.raise_for_status() current_user = r.json() logger.debug(me) logger.info('Hello {0}!'.format(current_user['username'...
Removes any pre-existing tracks that were not just downloaded
def remove_files(): """ Removes any pre-existing tracks that were not just downloaded """ logger.info("Removing local track files that were not downloaded...") files = [f for f in os.listdir('.') if os.path.isfile(f)] for f in files: if f not in fileToKeep: os.remove(f)
Fetches track info from Soundcloud, given a track_id
def get_track_info(track_id): """ Fetches track info from Soundcloud, given a track_id """ logger.info('Retrieving more info on the track') info_url = url["trackinfo"].format(track_id) r = requests.get(info_url, params={'client_id': CLIENT_ID}, stream=True) item = r.json() logger.debug(i...
Download user items of dl_type (ie. all, playlists, liked, commented, etc.)
def download(user, dl_type, name): """ Download user items of dl_type (ie. all, playlists, liked, commented, etc.) """ username = user['username'] user_id = user['id'] logger.info( 'Retrieving all {0} of user {1}...'.format(name, username) ) dl_url = url[dl_type].format(user_id) ...
Downloads a playlist
def download_playlist(playlist): """ Downloads a playlist """ global arguments invalid_chars = '\/:*?|<>"' playlist_name = playlist['title'].encode('utf-8', 'ignore') playlist_name = playlist_name.decode('utf8') playlist_name = ''.join(c for c in playlist_name if c not in invalid_chars) ...
Downloads a track
def download_track(track, playlist_name=None, playlist_file=None): """ Downloads a track """ global arguments title = track['title'] title = title.encode('utf-8', 'ignore').decode('utf8') logger.info('Downloading {0}'.format(title)) # Not streamable if not track['streamable']: ...
Returns True if the file has already been downloaded
def already_downloaded(track, title, filename): """ Returns True if the file has already been downloaded """ global arguments already_downloaded = False if os.path.isfile(filename): already_downloaded = True if arguments['--flac'] and can_convert(filename) \ ...
Returns True if a track_id exists in the download archive
def in_download_archive(track): """ Returns True if a track_id exists in the download archive """ global arguments if not arguments['--download-archive']: return archive_filename = arguments.get('--download-archive') try: with open(archive_filename, 'a+', encoding='utf-8') a...
Write the track_id in the download archive
def record_download_archive(track): """ Write the track_id in the download archive """ global arguments if not arguments['--download-archive']: return archive_filename = arguments.get('--download-archive') try: with open(archive_filename, 'a', encoding='utf-8') as file: ...
Sets the mp3 file metadata using the Python module Mutagen
def set_metadata(track, filename, album=None): """ Sets the mp3 file metadata using the Python module Mutagen """ logger.info('Setting tags...') global arguments artwork_url = track['artwork_url'] user = track['user'] if not artwork_url: artwork_url = user['avatar_url'] artwo...
Convert a string to utf8. If the argument is an iterable (list/tuple/set), then each element of it would be converted instead. >>> to_utf8('a') 'a' >>> to_utf8(u'a') 'a' >>> to_utf8([u'a', u'b', u'\u4f60']) ['a', 'b', '\\xe4\\xbd\\xa0']
def to_utf8(s): """Convert a string to utf8. If the argument is an iterable (list/tuple/set), then each element of it would be converted instead. >>> to_utf8('a') 'a' >>> to_utf8(u'a') 'a' >>> to_utf8([u'a', u'b', u'\u4f60']) ['a', 'b', '\\xe4\\xbd\\xa0'] """ if six.PY2: ...
Make sure the first parameter of the decorated method to be a unicode object.
def unicode_compact(func): """ Make sure the first parameter of the decorated method to be a unicode object. """ @wraps(func) def wrapped(self, text, *a, **kw): if not isinstance(text, six.text_type): text = text.decode('utf-8') return func(self, text, *a, **kw) ...
Send a reply to the sender using Web API (This function supports formatted message when using a bot integration) If the message was send in a thread, answer in a thread per default.
def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None): """ Send a reply to the sender using Web API (This function supports formatted message when using a bot integration) If the message was send in a thread, answer in a thread per default...
Send a reply using Web API (This function supports formatted message when using a bot integration)
def send_webapi(self, text, attachments=None, as_user=True, thread_ts=None): """ Send a reply using Web API (This function supports formatted message when using a bot integration) """ self._client.send_message( self._body['channel'], t...
Send a reply to the sender using RTM API (This function doesn't supports formatted message when using a bot integration) If the message was send in a thread, answer in a thread per default.
def reply(self, text, in_thread=None): """ Send a reply to the sender using RTM API (This function doesn't supports formatted message when using a bot integration) If the message was send in a thread, answer in a thread per default. """ if in_thr...
Send a reply via direct message using RTM API
def direct_reply(self, text): """ Send a reply via direct message using RTM API """ channel_id = self._client.open_dm_channel(self._get_user_id()) self._client.rtm_send_message(channel_id, text)
Send a reply using RTM API (This function doesn't supports formatted message when using a bot integration)
def send(self, text, thread_ts=None): """ Send a reply using RTM API (This function doesn't supports formatted message when using a bot integration) """ self._client.rtm_send_message(self._body['channel'], text, thread_ts=thread_ts)
React to a message using the web api
def react(self, emojiname): """ React to a message using the web api """ self._client.react_to_message( emojiname=emojiname, channel=self._body['channel'], timestamp=self._body['ts'])
Decorator declaring the wrapped function to the default reply hanlder. May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``).
def default_reply(*args, **kwargs): """ Decorator declaring the wrapped function to the default reply hanlder. May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``). """ invoked = bo...
Send (data) directly to the websocket.
def send_to_websocket(self, data): """Send (data) directly to the websocket.""" data = json.dumps(data) self.websocket.send(data)
Returns data if available, otherwise ''. Newlines indicate multiple messages
def websocket_safe_read(self): """Returns data if available, otherwise ''. Newlines indicate multiple messages """ data = '' while True: try: data += '{0}\n'.format(self.websocket.recv()) except WebSocketException as e: if isinstance(e, Web...
Get List of prices between two dates
def get_previous_price_list(self, currency, start_date, end_date): """ Get List of prices between two dates """ start = start_date.strftime('%Y-%m-%d') end = end_date.strftime('%Y-%m-%d') url = ( 'https://api.coindesk.com/v1/bpi/historical/close.json' ...
Get Price for one bit coin on given date
def get_previous_price(self, currency, date_obj): """ Get Price for one bit coin on given date """ start = date_obj.strftime('%Y-%m-%d') end = date_obj.strftime('%Y-%m-%d') url = ( 'https://api.coindesk.com/v1/bpi/historical/close.json' '?start={}&...
Convert X bit coins to valid currency amount
def convert_btc_to_cur(self, coins, currency): """ Convert X bit coins to valid currency amount """ if isinstance(coins, Decimal): use_decimal = True else: use_decimal = self._force_decimal url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.js...
Convert X amount to Bit Coins
def convert_to_btc(self, amount, currency): """ Convert X amount to Bit Coins """ if isinstance(amount, Decimal): use_decimal = True else: use_decimal = self._force_decimal url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(curren...
A decorator to handle rate limiting from the Twitter API. If a rate limit error is encountered we will sleep until we can issue the API call again.
def rate_limit(f): """ A decorator to handle rate limiting from the Twitter API. If a rate limit error is encountered we will sleep until we can issue the API call again. """ def new_f(*args, **kwargs): errors = 0 while True: resp = f(*args, **kwargs) if r...
Convert X amount to BTC based on given date rate
def convert_to_btc_on(self, amount, currency, date_obj): """ Convert X amount to BTC based on given date rate """ if isinstance(amount, Decimal): use_decimal = True else: use_decimal = self._force_decimal start = date_obj.strftime('%Y-%m-%d') ...
A decorator to handle connection reset errors even ones from pyOpenSSL until https://github.com/edsu/twarc/issues/72 is resolved
def catch_conn_reset(f): """ A decorator to handle connection reset errors even ones from pyOpenSSL until https://github.com/edsu/twarc/issues/72 is resolved """ try: import OpenSSL ConnectionError = OpenSSL.SSL.SysCallError except: ConnectionError = None def new_f(s...
A decorator to handle read timeouts from Twitter.
def catch_timeout(f): """ A decorator to handle read timeouts from Twitter. """ def new_f(self, *args, **kwargs): try: return f(self, *args, **kwargs) except (requests.exceptions.ReadTimeout, requests.packages.urllib3.exceptions.ReadTimeoutError) as e: ...
A decorator to handle gzip encoding errors which have been known to happen during hydration.
def catch_gzip_errors(f): """ A decorator to handle gzip encoding errors which have been known to happen during hydration. """ def new_f(self, *args, **kwargs): try: return f(self, *args, **kwargs) except requests.exceptions.ContentDecodingError as e: log.warn...
Sleeps for a specified duration, optionally stopping early for event. Returns True if interrupted
def interruptible_sleep(t, event=None): """ Sleeps for a specified duration, optionally stopping early for event. Returns True if interrupted """ log.info("sleeping %s", t) if event is None: time.sleep(t) return False else: return not event.wait(t)
filter_protected will filter out protected tweets and users unless explicitly requested not to.
def filter_protected(f): """ filter_protected will filter out protected tweets and users unless explicitly requested not to. """ def new_f(self, *args, **kwargs): for obj in f(self, *args, **kwargs): if self.protected == False: if 'user' in obj and obj['user']['pr...
Parse media file URL:s form tweet data :extended_entities_dict: :returns: list of media file urls
def parse_extended_entities(extended_entities_dict): """Parse media file URL:s form tweet data :extended_entities_dict: :returns: list of media file urls """ urls = [] if "media" in extended_entities_dict.keys(): for item in extended_entities_dict["media"]: # add static i...
Parse binary file url:s from a single tweet. :tweetdict: json data dict for tweet :returns: list of urls for media files
def parse_binlinks_from_tweet(tweetdict): """Parse binary file url:s from a single tweet. :tweetdict: json data dict for tweet :returns: list of urls for media files """ urls = [] if "user" in tweetdict.keys(): urls.append(tweetdict["user"]["profile_image_url_https"]) urls.ap...
Iterates over json files in path.
def tweets_files(string, path): """Iterates over json files in path.""" for filename in os.listdir(path): if re.match(string, filename) and ".jsonl" in filename: f = gzip.open if ".gz" in filename else open yield path + filename, f Ellipsis
Extract and write found attributes.
def extract(json_object, args, csv_writer): """Extract and write found attributes.""" found = [[]] for attribute in args.attributes: item = attribute.getElement(json_object) if len(item) == 0: for row in found: row.append("NA") else: found1 = [...
adds a relation to the graph
def add(from_user, from_id, to_user, to_id, type): "adds a relation to the graph" if options.users and to_user: G.add_node(from_user, screen_name=from_user) G.add_node(to_user, screen_name=to_user) if G.has_edge(from_user, to_user): weight = G[from_user][to_user]['we...
Pass in a user_id and you will be returned a generator of friendship tuples (user_id, friend_id). By default it will return the friend of a friend network (level=2), but you can expand this by settings the level parameter to either another number. But beware, it could run for a while!
def friendships(user_id, level=2): """ Pass in a user_id and you will be returned a generator of friendship tuples (user_id, friend_id). By default it will return the friend of a friend network (level=2), but you can expand this by settings the level parameter to either another number. But beware,...
Pass in a query with optional max_id, min_id, lang or geocode and get back an iterator for decoded tweets. Defaults to recent (i.e. not mixed, the API default, or popular) tweets.
def search(self, q, max_id=None, since_id=None, lang=None, result_type='recent', geocode=None, max_pages=None): """ Pass in a query with optional max_id, min_id, lang or geocode and get back an iterator for decoded tweets. Defaults to recent (i.e. not mixed, the API defaul...
Returns a collection of the most recent tweets posted by the user indicated by the user_id or screen_name parameter. Provide a user_id or screen_name.
def timeline(self, user_id=None, screen_name=None, max_id=None, since_id=None, max_pages=None): """ Returns a collection of the most recent tweets posted by the user indicated by the user_id or screen_name parameter. Provide a user_id or screen_name. """ ...
A generator that returns users for supplied user ids, screen_names, or an iterator of user_ids of either. Use the id_type to indicate which you are supplying (user_id or screen_name)
def user_lookup(self, ids, id_type="user_id"): """ A generator that returns users for supplied user ids, screen_names, or an iterator of user_ids of either. Use the id_type to indicate which you are supplying (user_id or screen_name) """ if id_type not in ['user_id', 'sc...
Returns Twitter user id lists for the specified user's followers. A user can be a specific using their screen_name or user_id
def follower_ids(self, user): """ Returns Twitter user id lists for the specified user's followers. A user can be a specific using their screen_name or user_id """ user = str(user) user = user.lstrip('@') url = 'https://api.twitter.com/1.1/followers/ids.json' ...
Returns an iterator for tweets that match a given filter track from the livestream of tweets happening right now. If a threading.Event is provided for event and the event is set, the filter will be interrupted.
def filter(self, track=None, follow=None, locations=None, event=None, record_keepalive=False): """ Returns an iterator for tweets that match a given filter track from the livestream of tweets happening right now. If a threading.Event is provided for event and the event is...
Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets. If a threading.Event is provided for event and the event is set, the sample will be in...
def sample(self, event=None, record_keepalive=False): """ Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets. If a threading.Event...
Pass in an iterator of tweets' JSON and get back an iterator of the IDs of each tweet.
def dehydrate(self, iterator): """ Pass in an iterator of tweets' JSON and get back an iterator of the IDs of each tweet. """ for line in iterator: try: yield json.loads(line)['id_str'] except Exception as e: log.error("uhoh...
Pass in an iterator of tweet ids and get back an iterator for the decoded JSON for each corresponding tweet.
def hydrate(self, iterator): """ Pass in an iterator of tweet ids and get back an iterator for the decoded JSON for each corresponding tweet. """ ids = [] url = "https://api.twitter.com/1.1/statuses/lookup.json" # lookup 100 tweets at a time for tweet_id ...
Retrieves up to the last 100 retweets for the provided tweet.
def retweets(self, tweet_id): """ Retrieves up to the last 100 retweets for the provided tweet. """ log.info("retrieving retweets of %s", tweet_id) url = "https://api.twitter.com/1.1/statuses/retweets/""{}.json".format( tweet_id) resp = self.get(u...
Returns a list of regions for which Twitter tracks trends.
def trends_available(self): """ Returns a list of regions for which Twitter tracks trends. """ url = 'https://api.twitter.com/1.1/trends/available.json' try: resp = self.get(url) except requests.exceptions.HTTPError as e: raise e return res...
Returns recent Twitter trends for the specified WOEID. If exclude == 'hashtags', Twitter will remove hashtag trends from the response.
def trends_place(self, woeid, exclude=None): """ Returns recent Twitter trends for the specified WOEID. If exclude == 'hashtags', Twitter will remove hashtag trends from the response. """ url = 'https://api.twitter.com/1.1/trends/place.json' params = {'id': woeid}...
Returns the closest regions for the supplied lat/lon.
def trends_closest(self, lat, lon): """ Returns the closest regions for the supplied lat/lon. """ url = 'https://api.twitter.com/1.1/trends/closest.json' params = {'lat': lat, 'long': lon} try: resp = self.get(url, params=params) except requests.except...
replies returns a generator of tweets that are replies for a given tweet. It includes the original tweet. If you would like to fetch the replies to the replies use recursive=True which will do a depth-first recursive walk of the replies. It also walk up the reply chain if you supply a tw...
def replies(self, tweet, recursive=False, prune=()): """ replies returns a generator of tweets that are replies for a given tweet. It includes the original tweet. If you would like to fetch the replies to the replies use recursive=True which will do a depth-first recursive walk o...
Sets up the HTTP session to talk to Twitter. If one is active it is closed and another one is opened.
def connect(self): """ Sets up the HTTP session to talk to Twitter. If one is active it is closed and another one is opened. """ if not (self.consumer_key and self.consumer_secret and self.access_token and self.access_token_secret): raise RuntimeError(...
Returns the members of a list. List id or (slug and (owner_screen_name or owner_id)) are required
def list_members(self, list_id=None, slug=None, owner_screen_name=None, owner_id=None): """ Returns the members of a list. List id or (slug and (owner_screen_name or owner_id)) are required """ assert list_id or (slug and (owner_screen_name or owner_id)) url = 'https://a...
Get the Twitter API keys. Order of precedence is command line, environment, config file. Return True if all the keys were found and False if not.
def get_keys(self): """ Get the Twitter API keys. Order of precedence is command line, environment, config file. Return True if all the keys were found and False if not. """ env = os.environ.get if not self.consumer_key: self.consumer_key = env('CONSUM...