lnk.bitly package

lnk.bitly.cli module

lnk.bitly.command module

Contains the base-class for all bit.ly commands.

class lnk.bitly.command.Command(which)[source]

Bases: lnk.abstract.AbstractCommand

Base-class for all bit.ly commands.

Configures the AbstractCommand base class for all commands in the entire application, which needs information about the service being used. Moreover sets up the necessary parameters needed for any request to the bit.ly API (the OAuth2 access token).

parameters

dict

The necessary parameters for any request to the bit.ly API.

static verify(response, what, inner=None)[source]

Verifies an HTTP-response from the bit.ly API.

Overrides the ‘pure-virtual’ (i.e. not-implemented) base method from AbstractCommand. If the verification finds no faults in the response, the data is returned.

Parameters:
  • response (requests.Response) – The HTTP response to a request to the bit.ly API.
  • what (str) – A human-readable string representing what the request was for, such that if there is an error in the response, an errors.HTTPError or errors.APIError is raised with the message ‘Could not <what>.’
  • inner (str) – If it is expected that data has an inner layer, the key of that inner layer to retrieve the data directly.
Returns:

The actual data of the response, if no fault was found.

Raises:
  • errors.HTTPError – If it was found that there was an HTTP-related exception, such as a faulty URL or other badness.
  • errors.APIError – If it was found that there was an exception related to the API itself.

lnk.bitly.history module

lnk.bitly.info module

Information-retrieval for bitlink.

class lnk.bitly.info.Info(raw=False)[source]

Bases: lnk.bitly.command.Command

Class to retrieve information about a bitlink.

Information about a link may include when it was created, its expanded url, its tags, any note associated with it, when it was last modified and other things. This information is returned in a pretty list. The list can be put into a box for terminal output, or can be returned raw for internal use (such as by the stats command). Note that the information retrieved combines data from the /info and user/link_history endpoints.

Note

A ‘bitlink’ is a link shortened with bit.ly.

raw

bool

Whether or not to return the output as a raw list, or as a string, in a box.

sets

dict

A complete dictionary of the available sets of information.

reverse

dict

A reverse mapping of the above-mentioned sets.

fetch(only, hide, hide_empty, urls)[source]

Fetches the link information.

Parameters:
  • only (tuple) – A tuple of strings representing the sets to include in the response (‘only’ these will be included).
  • hide (tuple) – A tuple of strings representing the sets to hide from the response (either from all possible sets if only is empty, or else from those selected).
  • hide_empty (bool) – Whether or not to show things that are empty, such as an empty list of tags.
  • urls (tuple) – A tuple of urls to fetch information for.
Returns:

A plain list of the raw lines if the ‘raw’ attribute is True, else a boxified, pretty string.

format(key, value)[source]

Handles formatting of a data-point.

Handles cases in which the representation of a key or value is not directly suitable for output, such as when the value is a UNIX timestamp, which should really be formatted into a proper ctime representation. Also changes booleans into ‘Yes’/’No’.

Parameters:
  • key (str) – The key of the data-point.
  • value (str) – The value of the data-point.
Returns:

<value>’. What ‘<key>’ and ‘<value>’ end up being is highly-dependent on the actual values of the arguments.

Return type:

A formatted string of the schema ‘<key>

lineify(url, data, hide_empty)[source]

Returns a list of lines for given (information) data.

The lines returned include a header with the relevant URL, followed by string-formatted key/value pairs. If the value for a given key is a list, this list is further formatted and prettified.

Parameters:
  • url (str) – The URL of which the data should be formatted.
  • data (dict) – The data (information) for the url.
  • hide_empty (bool) – Whether or not to hide empty things, such as an empty list of tags.
Returns:

A list of lines, ready for output.

request(sets, result, hide_empty)[source]

Requests all information about a url.

The information returned for a URL is a combination of the data retrieved from the /info endpoint, and the data retrieved from the /user/link_history endpoint. Both these sets of information are retrieved here and combined into one set of information for a URL. This method is run in a separate thread for each URL, and as such uses a queue to get a URL and then appends the information to the list supplied in the argument. This is done in a thread-safe, locked way.

Parameters:
  • sets (dict) – The sets of information to include in the data.
  • result (list) – The list of results for each URL, to which to append the data requested.
  • hide_empty (bool) – Whether or not to hide empty things, passed on to lineify.
request_history(url)[source]

Requests more information for a url.

Requests the part of the information that can be fetched from the /user/link_history endpoint. This request requires oauth2 authorization.

Parameters:url (str) – The bitlink to request information for.
Returns:The information for the bitlink supplied.
request_info(url)[source]

Requests information for a url.

Requests the part of the information that can be fetched from the /info endpoint.

Parameters:url (str) – The bitlink to request information for.
Returns:The information for the bitlink supplied.
lnk.bitly.info.echo(*args)[source]

Executes an info command and echoes its output.

Parameters:args (variadic) – The arguments to pass to an Info instance’s fetch() method.

lnk.bitly.key module

Handles the oauth2 authorization procedure for the bit.ly API.

class lnk.bitly.key.Key(raw=False)[source]

Bases: lnk.bitly.command.Command

Handles oauth2 authorization for the bit.ly API.

The bulk of the work is done by the user in the command-line interface. When ‘lnk bitly –key’ is run (or ‘lnk –key’ if bitly is the default), the user is prompted for his or her login and password. This information is passed to this class, which then fetches an oauth2 access-token using the appropriate exchange procedure.

raw

bool

Whether or not to return the raw output for internal use or the prettified output for outside representation.

fetch(_, login, password, show, who)[source]

Fetches an oauth2 access-token for a given login and password.

Parameters:
  • _ – This is the –generate flag, just a dummy parameter because it must be passed from the command-line to initiate the procedure but has no actual use here.
  • login (str) – The user’s login (username).
  • password (str) – The user’s password.
  • show (bool) – Whether or not to return the access-token for output once retrieved.
Returns:

If the show flag is set, the raw key as a string if self.raw is True, else the key in a pretty box. If the show flag is unset, an empty string is returned (such that nothing appears in the command-line output).

request(login, password)[source]

Requests an oauth2 token from the bit.ly API.

Parameters:
  • login (str) – The user’s login (username).
  • password (str) – The user’s password.
Returns:

The oauth2 token/key, if the request was successful.

Raises:

Any errors thrown by the verify() method.

static verify(response, what)[source]

Verifies the HTTP response following the request for an oauth2 token.

Parameters:
  • response (requests.Response) – The HTTP-response from the request for an oauth2 token.
  • what (str) – A string-representation of what the request was for, such that if an error is found and raised, its message is ‘Could not <what>’ (e.g. ‘generate an API key’).
Returns:

The plain, string oauth2 access-token.

Raises:

errors.HTTPError – If an HTTP-related fault was found in the response.

lnk.bitly.key.echo(*args)[source]

Executes a key command and echoes its output.

Parameters:args (variadic) – The arguments to pass to a Key instance’s fetch() method.

lnk.bitly.stats module

Statistics and metrics retrieval for bitlinks.

class lnk.bitly.stats.Stats(raw=False)[source]

Bases: lnk.bitly.command.Command

Class to retrieve statistics and info for one or more bitlinks.

The statistics for a link include its referrers (i.e. from where the link was opened), the countries from where the link was opened and of course the number of clicks. These statistics can be retrieved ‘since-forever’, but also for specific (possibly open-ended) time-ranges, such as for ‘the last 5 months’ or ‘between 4 days and 2 minute ago’. Additionally, these statistics can be paired with information about each link, retrieved from the ‘info’ command, thereby making the stats command the ultimate destination for link statistics and information. Output may, as always, be in raw format for internal use or in a pretty box. Multiple URLs are fully supported.

raw

bool

Whether to return the output in raw format for internal use, or in a pretty string-representation for outside-display.

info

lnk.bitly.info.Info

A lnk.bitly.info.Info instance to retrieve addittional information for a bitlink.

class Timespan(span, unit)

Bases: tuple

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__getstate__()

Exclude the OrderedDict from pickling

__repr__()

Return a nicely formatted representation string

span

Alias for field number 0

unit

Alias for field number 1

Stats.fetch(only, hide, times, forever, limit, add_info, full, urls)[source]

Fetches statistics for one or more URLs.

Parameters:
  • only (tuple) – A tuple of strings representing the sets to include in the response (‘only’ these will be included).
  • hide (tuple) – A tuple of strings representing the sets to hide from the response (either from all possible sets if only is empty, or else from those selected).
  • times (tuple) – A tuple of tuples of the schema (<span>, <unit>), representing the timespans for which to fetch statistics.
  • forever (bool) – Whether to include the statistics ‘since forever’.
  • limit (int) – A limit on the number of items fetched per timespan.
  • add_info (bool) – Whether or not to add additional information for each link.
  • full (bool) – Whether to show full country names, or short ISO abbreviations.
  • urls (tuple) – A tuple of urls to fetch statistics for.
Returns:

A plain list of the raw lines if the ‘raw’ attribute is True, else a boxified, pretty string.

static Stats.format(category, key, value, full)[source]

Formats a key/value pair for output.

Handles special cases such as country-name expansion (the API returns them as ISO abbreviations, e.g. ‘DE’, but often the full name, e.g. ‘Germany’, is really wanted)

Parameters:
  • category (str) – The category of the data.
  • key (str) – The key of the data-point.
  • value (str) – The value of the data-point.
  • full (bool) – Whether to show full country names or short ISO abbreviations (e.g. ‘Germany’ or ‘DE’).
Returns:

A pretty list-item.

Stats.get_header(span, unit)[source]

Handles formatting of a timespan header.

This method handles cases such as the ‘since forever’ timespan, as well as the issue with years (years have to be converted to months for bitly).

Parameters:
  • span (int) – The span of the timespan (e.g. 4 months).
  • unit (str) – The unit of the timespan (e.g.. 4 months).
Returns:

A pretty list-item containing the timespan information.

Stats.get_stats(url, timespans, sets)[source]

Retrieves the statistics for a single url.

The statistics returned are for all timespans supplied, filtered according to the sets of statistics wanted.

Note

This method works with threads. For each category and each timespan, a new request must be made. Each request is made in a separate thread.

Parameters:
  • url (str) – The relevant URL to fetch statistics for.
  • timespans (tuple) – A tuple of tuples of the schema (<span>, <unit>), representing the timespans for which to fetch statistics.
  • sets (tuple) – The sets of statistics wanted in the response (others are discarded).
Returns:

A single ‘result’, which is a dictionary where the keys are the sets (categories) and the values a list of the statistics that were fetched for each timespan. Each item in this list is in turn a dictionary with one key/value pair for the timespan and another for the data retrieved in that category, for that timespan. This data is either an integer for the ‘clicks’ category, or a list representing each individual data-point that could be fetched. Each of those data-points has a ‘clicks’ key whose value is an integer representing the clicks for that data-point. A data-point also has another key, which depends on the category, e.g. ‘country’ for the ‘countries’ category.

Stats.get_timespans(times, forever)[source]

Parses the timespans passed to fetch and returns Timespan objects.

The timespans passed to the command-line interface and ultimately to the fetch() method are of the schema ‘(<span>, <unit>)’. These are parsed into Stats.Timespan objects. Parsing handles cases such as where the unit is ‘year’. Bitly cannot handle ‘year’ as a unit, so the timespan must be converted into weeks. Also the ‘forever’ flag is handled here. Moreover, this method retrieves the default timespan from the configuration file if no timespans were passed to the method (and the command on the CLI).

Parameters:
  • times (tuple) – The timespans of the schema ‘(<span>, <unit>)’.
  • forever (bool) – Whether to include the ‘since forever’ timespan.
Returns:

A list of Stats.Timespan objects.

Stats.lineify(data, full)[source]

Turns the data retrieved for a link into a list of lines.

Each category has a header containing a string-representation of the category. For each timespan of a given category, a list is created if the category holds multiple data-points. Lines containing timespans and data-points are formatted into list-items using ecstasy.

Parameters:
  • data (dictionary) – The data (statistics) to lineify. This data should hold key/value pairs where the keys are the sets/categories of data and the values lists of dictionaries for each timespan.
  • full (bool) – Whether to show full country names or short ISO abbreviations (e.g. ‘Germany’ or ‘DE’).
Returns:

A list of lines, ready for output.

Stats.listify(category, data, full)[source]

Formats data with multiple data-points into a pretty list.

Parameters:
  • category (str) – The category to which the data belongs (e.g. referrers).
  • data (dict) – The actual data, as a dictionary.
  • full (bool) – Whether to show full country names or short ISO abbreviations (e.g. ‘Germany’ or ‘DE’).
Returns:

A list of lines, ready for output.

Stats.request(results)[source]

Requests statistics for a given configuration.

The URL, endpoint (set/category) and timespan are all fetched from a queue, because this method is always run in a separate thread for each configuration of the above parameters. The dictionary to which to insert the data must be passed as an argument. The data is inserted in a thread-safe, locked way.

Parameters:results (dict) – The results dictionary for the URL, to which to insert the retrieved statistics.
lnk.bitly.stats.echo(*args)[source]

Executes a stats command and echoes its output.

Parameters:args (variadic) – The arguments to pass to a Stats instance’s fetch() method.

lnk.bitly.user module