yourls-python documentation¶
Contents:
Usage¶
Installation¶
$ pip install yourls
Overview¶
yourls is a Python client for your YOURLS server. The API is fairly simple, and API errors are turned into Python exceptions.
The main functionality is shown here:
>>> from yourls import YOURLSClient
>>> yourls = YOURLSClient('http://example.com/yourls-api.php', signature='6f344c2a8p')
>>> shorturl = yourls.shorten('http://google.com')
>>> shorturl
ShortenedURL(
shorturl='http://example.com/abcde',
url='http://google.com',
title='Google',
date=datetime.datetime(2015, 10, 31, 14, 31, 4),
ip='203.0.113.0',
clicks=0,
keyword='abcde')
>>> yourls.expand('abcde')
'http://google.com'
>>> yourls.expand('http://example.com/abcde')
'http://google.com'
>>> yourls.url_stats('abcde')
ShortenedURL(
shorturl='http://example.com/abcde',
url='http://google.com',
title='Google',
date=datetime.datetime(2015, 10, 31, 14, 31, 4),
ip='203.0.113.0',
clicks=0,
keyword='abcde')
>>> links, stats = yourls.stats(filter='random', limit=2)
>>> links
[ShortenedURL(
shorturl='http://example.com/abcde',
url='http://google.com',
title='Google',
date=datetime.datetime(2015, 10, 31, 14, 31, 4),
ip='203.0.113.0',
clicks=2,
keyword='abcde'),
ShortenedURL(
shorturl='http://example.com/gd65t',
url='http://www.youtube.com',
title='YouTube',
date=datetime.datetime(2015, 10, 31, 11, 34, 5),
ip='203.0.113.0',
clicks=567,
keyword='gd65t')]
>>> stats
DBStats(total_clicks=1234, total_links=5678)
>>> yourls.db_stats()
DBStats(total_clicks=1234, total_links=5678)
Exception Handling¶
The YOURLSClient
methods can raise several exceptions. With the
exception of YOURLSURLExistsError
and
YOURLSKeywordExistsError
, they all inherit from
requests.HTTPError
, so it’s not necessary to catch all the
exceptions individually if you just want to display the error to the user:
try:
shorturl = yourls.shorten(url, keyword=keyword)
except YOURLSURLExistsError as exc:
shorturl = exc.url
except YOURLSKeywordExistsError as exc:
print("Keyword '{}' already exists.".format(exc.keyword))
except requests.HTTPError as exc:
print(exc.args[0])
See also
Requests itself can raise more exceptions, so you might want to catch
requests.exceptions.RequestException
.
- Errors and Exceptions:
In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a
ConnectionError
exception.In the rare event of an invalid HTTP response, Requests will raise an
HTTPError
exception.If a request times out, a
Timeout
exception is raised.If a request exceeds the configured number of maximum redirections, a
TooManyRedirects
exception is raised.All exceptions that Requests explicitly raises inherit from
requests.exceptions.RequestException
.
Logging¶
Logging is disabled by default. Let’s enable the logger and set up a logbook handler.
from logbook import StderrHandler
from yourls import YOURLSClient, logger
logger.disabled = False
yourls = YOURLSClient('http://example.com/yourls-api.php', signature='6f344c2a8p')
with StderrHandler():
yourls.shorten('http://www.google.com')
Here, logger is an instance of logbook.Logger
. By default, the
level is set to logbook.NOTSET
(i.e. everything is logged).
In our example, we would see the following output:
[2015-11-01 17:15:57.899368] DEBUG: yourls: Received <Response [200]> with JSON {'message': 'http://www.google.com added to database', 'url': {'keyword': 'abcde', 'title': 'Google', 'date': '2015-11-01 17:15:57', 'url': 'http://www.google.com', 'ip': '203.0.113.0'}, 'status': 'success', 'shorturl': 'http://example.com/abcde', 'title': 'Google', 'statusCode': 200}
API Plugins¶
If you want to support YOURLS plugins that add API methods (e.g. API Delete), the following is the recommended way to do so.
from yourls import YOURLSClientBase, YOURLSAPIMixin
class YOURLSDeleteMixin(object):
def delete(short):
data = dict(action='delete', shorturl=short)
self._api_request(params=data)
class YOURLSClient(YOURLSDeleteMixin, YOURLSAPIMixin, YOURLSClientBase):
"""YOURLS client with API delete support."""
Command Line Interface¶
You can invoke yourls
or python -m yourls
on the command line.
$ yourls
Usage: yourls [OPTIONS] COMMAND [ARGS]...
Command line interface for YOURLS.
Configuration parameters can be passed as switches or stored in .yourls or
~/.yourls.
Please provide one of the following:
• apiurl and signature
• apiurl, username, and password
Configuration file format:
[yourls]
apiurl = http://example.com/yourls-api.php
signature = abcdefghij
Options:
--apiurl TEXT
--signature TEXT
--username TEXT
--password TEXT
--help Show this message and exit.
Commands:
db-stats
expand
shorten
stats
url-stats
You can see help for individual commands: yourls shorten --help
etc.
Module Reference¶
Core¶
Note
The contents of this module are placed here for organisational reasons.
They should be imported from yourls
.
-
class
yourls.core.
YOURLSAPIMixin
¶ Bases:
object
Mixin to provide default YOURLS API methods.
-
db_stats
()¶ Get database statistics.
Returns: Total clicks and links statistics. Return type: DBStats Raises: requests.exceptions.HTTPError
– Generic HTTP Error
-
expand
(short)¶ Expand short URL or keyword to long URL.
Parameters: short – Short URL (
http://example.com/abc
) or keyword (abc).Returns: Expanded/long URL, e.g.
https://www.youtube.com/watch?v=dQw4w9WgXcQ
Raises: YOURLSHTTPError
– HTTP error with response from YOURLS API.requests.exceptions.HTTPError
– Generic HTTP error.
-
shorten
(url, keyword=None, title=None)¶ Shorten URL with optional keyword and title.
Parameters: - url – URL to shorten.
- keyword – Optionally choose keyword for short URL, otherwise automatic.
- title – Optionally choose title, otherwise taken from web page.
Returns: Shortened URL and associated data.
Return type: Raises: YOURLSKeywordExistsError
– The passed keyword already exists.Note
This exception has a
keyword
attribute.YOURLSURLExistsError
– The URL has already been shortened.Note
This exception has a
url
attribute, which is an instance ofShortenedURL
for the existing short URL.YOURLSNoURLError
– URL missing.YOURLSNoLoopError
– Cannot shorten a shortened URL.YOURLSAPIError
– Unhandled API error.YOURLSHTTPError
– HTTP error with response from YOURLS API.requests.exceptions.HTTPError
– Generic HTTP error.
-
stats
(filter, limit, start=None)¶ Get stats about links.
Parameters: - filter – ‘top’, ‘bottom’, ‘rand’, or ‘last’.
- limit – Number of links to return from filter.
- start – Optional start number.
Returns: Tuple containing list of ShortenedURLs and DBStats.
Example
links, stats = yourls.stats(filter='top', limit=10)
Raises: ValueError
– Incorrect value for filter parameter.requests.exceptions.HTTPError
– Generic HTTP Error
-
url_stats
(short)¶ Get stats for short URL or keyword.
Parameters: short – Short URL (http://example.com/abc) or keyword (abc).
Returns: Shortened URL and associated data.
Return type: Raises: YOURLSHTTPError
– HTTP error with response from YOURLS API.requests.exceptions.HTTPError
– Generic HTTP error.
-
-
class
yourls.core.
YOURLSClient
(apiurl, username=None, password=None, signature=None)¶ Bases:
yourls.core.YOURLSAPIMixin
,yourls.core.YOURLSClientBase
YOURLS client.
-
class
yourls.core.
YOURLSClientBase
(apiurl, username=None, password=None, signature=None)¶ Bases:
object
Base class for YOURLS client that provides initialiser and api request method.
Inheritance diagram¶

Data¶
Note
The contents of this module are placed here for organisational reasons.
They should be imported from yourls
.
-
class
yourls.data.
DBStats
(total_clicks, total_links)¶ Represent database statistics as returned by the YOURLS API.
-
total_clicks
¶ Total number of clicks across all links in the database.
-
total_links
¶ Total number of links in the database.
-
-
class
yourls.data.
ShortenedURL
(shorturl, url, title, date, ip, clicks, keyword=None)¶ Represent shortened URL data as returned by the YOURLS API.
-
keyword
¶ Short URL keyword, e.g.
abcdef
forhttp://example.com/abcdef
.
-
url
¶ Long URL that was shortened.
-
title
¶ URL page title.
-
ip
¶ IP address that originally shortened the URL.
-
clicks
¶ Number of clicks the shortened URL has received.
-
Exceptions¶
Note
The contents of this module are placed here for organisational reasons.
They should be imported from yourls
.
-
exception
yourls.exceptions.
YOURLSHTTPError
(*args, **kwargs)¶ Bases:
yourls.exceptions.YOURLSAPIError
,requests.exceptions.HTTPError
Raised when YOURLS API returns HTTP error with response.
-
exception
yourls.exceptions.
YOURLSKeywordExistsError
(*args, **kwargs)¶ Bases:
yourls.exceptions.YOURLSAPIError
Raised when a chosen keyword already exists.
-
keyword
¶ Existing keyword.
-
-
exception
yourls.exceptions.
YOURLSNoLoopError
(*args, **kwargs)¶ Bases:
yourls.exceptions.YOURLSHTTPError
Raised when trying to shorten a shortened URL.
-
exception
yourls.exceptions.
YOURLSNoURLError
(*args, **kwargs)¶ Bases:
yourls.exceptions.YOURLSHTTPError
Raised when trying to shorten an empty URL.
-
exception
yourls.exceptions.
YOURLSURLExistsError
(*args, **kwargs)¶ Bases:
yourls.exceptions.YOURLSAPIError
Raised when a URL has already been shortened.
-
url
¶ Instance of
ShortenedURL
for existing URL.
-
Inheritance diagram¶

Change Log¶
Unreleased¶
N/A
1.2.3¶
Fixed¶
yourls
can be installed with setuptools v38.0+, which requiresinstall_requires
insetup.py
to be ordered.
1.2.2 - 2016-01-29¶
Fixed¶
- Exceptions used incorrect
super()
calls. - Conditional dependencies now work with wheel format.
1.1.1 - 2015-11-15¶
Fixed¶
- Fixed CLI on Python 2 due to incorrect use of
ConfigParser
. - Incorrect
ConfigParser
import.
1.1.0 - 2015-11-15¶
Added¶
- Command line interface.
- Documentation section on exception handling.
Changed¶
- Rename
yourls.api
sub-module toyourls.data
. - Rename
yourls.exc
sub-module toyourls.exceptions
. Users should be importing directly fromyourls
anyway.