PythonTop40 top40

The top40 module contains the high level classes that are used to package the returned data such as Entry, Chart and Change.

In addition the Top40 class provides the main external interface into the module. Once an instance of the Top40 class has been instantiated it can be used to return data from the remote API to the called program:

from pythontop40 import Top40

top40 = Top40()

album_list = top40.albums
singles_list = top40.singles

albums_chart = top40.albums_chart
singles_chart = top40.singles_chart

From there, the returned objects can be interrogated and interacted with:

first_album = album_list[0]
print( first_album.position )
print( first_album.artist )

print("The date of the singles chart is", singles_chart.date)
print(The album_chart was retrieved from the server on", albums_chart.retrieved

And this, don’t forget this:

class Repo(Model):
     name = fields.String()
     owner = fields.Embedded(User)

booby = Repo(
    name='Booby',
    owner={
        'login': 'jaimegildesagredo',
        'name': 'Jaime Gil de Sagredo'
    })

print booby.to_json()
'{"owner": {"login": "jaimegildesagredo", "name": "Jaime Gil de Sagredo"}, "name": "Booby"}'
class top40.Change(**kwargs)

The Change model that describes the change of this entry since last week’s chart.

This class isn’t made publicly visible, so it should never really need to be initialised manually. That said, it is initialised by passing a series of keyword arguments, like so:

change = Change(
    direction = "down",
    amount = 2,
    actual = -2
)

The model does not feature any validation.

direction

str

The direction of the change “up” or “down”.

amount

int

The amount of change in chart position expressed as a positive integer.

actual

int

The amount of the change in chart position expressed as positive or negative (or 0).

Returns:Change: The Change model instance created from the passed arguments.
class top40.Chart(**kwargs)

The Chart model that contains the embedded list of entries.

Parameters:
  • entries (list of dict) – A list of Python dictionaries. Each dictionary describes each Entry type in the chart, so the keys in the dictionary should match the properties of the Entry class.
  • date (int) – The date of this chart as an integer timestamp containing the total number of seconds.
  • retrieved (int) – The date that this chart was retrieved from the API server as an integer timestamp containing the total number of seconds.
  • current (bool) – Optional. A flag used in V2 of the API to signify if the last scheduled read from the BBC’s server worked on not. A value True means that the returned chart is the latest version that we have tried to read. A value of False means that the chart that is being returned is old. In all liekliehood the chart is probably still in accurate as it is only updated once per week, so this flag only means that the last scheduled read from the BBC’s server did not work.
entries

list of Entry

A list of Entry types for each entry in the specific Chart. The entries are returned in the list with the highest chart position (i.e. the lowest number - #1 in the chart) first.

date

int

The date of this chart as an integer timestamp containing the total number of seconds. This value can then be converted to a Python datetime.datetime type by datetime_type = datetime.datetime.fromtimestamp(chart.date) (assuming that the chart variable was of type Chart).

retrieved

int

The date that this chart was retrieved from the API server as an integer timestamp containing the total number of seconds. This can be converted to a datetime type in the same as described for date above.

current

bool

Optional. A flag used in V2 of the API to signify if the last scheduled read from the BBC’s server worked on not. A value True means that the returned chart is the latest version that we have tried to read. A value of False means that the chart that is being returned is old. In all liekliehood the chart is probably still in accurate as it is only updated once per week, so this flag only means that the last scheduled read from the BBC’s server did not work.

Returns:Chart – The Chart model instance created from the arguments.
Return type:Chart
class top40.Entry(**kwargs)

The Entry model that contains the details about the chart entry, a Change Model is embedded in each Entry model.

Parameters:
  • position (int) – The position of this entry in the chart.
  • previousPosition (int) – The position of this entry in the previous week’s chart.
  • numWeeks (int) – The number of weeks this entry has been in the chart.
  • artist (str) – The name of the artist for this entry.
  • title (str) – The title of this entry.
  • change (Change) – The embedded change model that describes the change in position.
  • status (str) – NEW in dev6 The text status from the BBC chart - takes the format of “new” ¦ “up 3” ¦ “down 4” ¦ “non-mover”. Not used in Ben Major’s V1 API - optional
position

int

The position of this entry in the chart.

previousPosition

int

The position of this entry in the previous week’s chart.

numWeeks

int

The number of weeks this entry has been in the chart.

artist

str

The name of the artist for this entry.

title

str

The title of this entry.

change

Change

The embedded change model that describes the change in position.

status

str

NEW in dev6 The text status from the BBC chart - takes the format of “new” ¦ “up 3” ¦ “down 4” ¦ “non-mover”. Not used in Ben Major’s V1 API - optional

Returns:Entry: The Entry model instance created from the arguments.
class top40.Top40(base_url='http://ben-major.co.uk/labs/top40/api/', cache_duration=3600, cache_config=None)

Provides the programmer with properties that return the Top 40 chart data.

The programmer creates an instance of this object, and then uses the exposed properties to access the data about the singles and albums charts.

Creates and returns the object instance.

All results will be cached for the duration of the existence of this instance in memory. However, if cache_duration is specified (not None), then results will be persisted to a local sqlite DB for the duration, in seconds, or cache_duration. A config for requests cache can also be passed in cache_config too, or if None, the default setting is used.

Parameters:
  • base_url (str) – The base url of the remote API before the specific service details are appended. For example, the base url might be “a.site.com/api/”, and the service “/albums/”, when appended to the base url, creates the total url required to access the album data.
  • cache_duration (int) – If None, then the persistent cache will be disabled. Otherwise the cache duration specified will be used.
  • cache_config (dict) – If None the default config will be used to pass to the install_cache method of requests_cache, otherwise the config in this parameter will be used. Any ‘expire_after’ key in the cache config will be replaced and the duration set to cache_duration.
error_format

str

The format string to be used when creating error messages.

base_url

str

The base url used to access the remote api

cache_duration

int

The duration in seconds that results will be returned from the cache before a fresh read of the external API will replace them.

cache_config

dict

A dictionary that describes the config that will be passed to the request_cache instance - allowing different backends and other options to be set.

Returns:Top40 – The Top40 instance.
Return type:Top40
albums

A property that returns a list of album Entry types.

Returns:

list : A list of Entry instances. Each entry describes an album in the chart.

Raises:
  • Top40HTTPError (Top40HTTPError) – If a status code that is not 200 is returned
  • Top40ConnectionError (Top40ConnectionError) – If a connection could not be established to the remote server
  • Top40ReadTimeoutError (Top40ReadTimeoutError) – If the remote server took too long to respond
albums_chart

A property that returns the Chart object for the current Top40 albums

Returns:

Chart: The albums’ chart object - an instance of the Chart class containing the album information and the and the issue and retrieval dates specific to this chart.

Raises:
  • Top40HTTPError (Top40HTTPError) – If a status code that is not 200 is returned
  • Top40ConnectionError (Top40ConnectionError) – If a connection could not be established to the remote server
  • Top40ReadTimeoutError (Top40ReadTimeoutError) – If the remote server took too long to respond
reset_cache(cache_duration=None)

Remove any cached singles or albums charts

Because the UK Top40 charts only change once per week, Top40 will cache the results of singles and albums. This means that during the execution of a program, repeated calls to retrieve singles and albums chart information will only actually call the remote API once. If, for whatever reason you need to ensure that an attempt to access single or album information actually results in a call to the remote API, then calling the Top40.reset_cache() method will do this, by clearing down any existing cached chart information.

If a cache is in place, then the results will also be cached across python runtime executions.

Params:
cache_duration (int): If None we will uninstall the requests cache and the next
read from the API will cause a remote call to be executed. Otherwise it specifies the number of seconds before the persistent cache will expire.
singles

A property that returns a list of single entries.

Returns:

list: A list of Entry instances. Each entry describes a single in the chart.

Raises:
  • Top40HTTPError (Top40HTTPError) – If a status code that is not 200 is returned
  • Top40ConnectionError (Top40ConnectionError) – If a connection could not be established to the remote server
  • Top40ReadTimeoutError (Top40ReadTimeoutError) – If the remote server took too long to respond
singles_chart

A property that returns the Chart object for the current Top40 singles

Returns:

Chart: The singles’ chart object - an instance of the Chart class containing the singles information and the issue and retrieval dates specific to this chart.

Raises:
  • Top40HTTPError (Top40HTTPError) – If a status code that is not 200 is returned
  • Top40ConnectionError (Top40ConnectionError) – If a connection could not be established to the remote server
  • Top40ReadTimeoutError (Top40ReadTimeoutError) – If the remote server took too long to respond