fietsboek.util module

Various utility functions.

fietsboek.util.DISPLAY_NAME_PATH = 'DISPLAY_NAME'

Path of the file in a locale resource folder which contains the display name.

fietsboek.util.check_password_constraints(password, repeat_password=None)

Verifies that the password constraints match for the given password.

This is usually also verified client-side, but for people that bypass the client side verification and the API, this is re-implemented here.

If repeat_password is given, this also verifies that the two passwords match.

Raises:

ValueError – If the verification of the constraints failed. The first arg of the error will be a TranslationString with the message of why the verification failed.

Parameters:
  • password (str) – The password which to verify.

  • repeat_password (Optional[str]) – The password repeat.

fietsboek.util.encode_gpx(gpx)

Encodes a GPX in-memory representation to the XML representation.

This ensures that the resulting XML file is valid.

Returns the contents of the XML as bytes, ready to be written to disk.

Parameters:

gpx (GPX) – The GPX file to encode. Might be modified!

Return type:

bytes

Returns:

The encoded GPX content.

fietsboek.util.fix_iso_timestamp(timestamp)

Fixes an ISO timestamp to make it parseable by datetime.datetime.fromisoformat().

This removes an ‘Z’ if it exists at the end of the timestamp, and replaces it with ‘+00:00’.

Parameters:

timestamp (str) – The timestamp to fix.

Return type:

str

Returns:

The fixed timestamp.

fietsboek.util.guess_gpx_timezone(gpx)

Guess which timezone the GPX file was recorded in.

This looks at a few timestamps to see if they have timezone information attached, including some known GPX extensions.

Parameters:

gpx (GPX) – The parsed GPX file to analyse.

Return type:

tzinfo

Returns:

The timezone information.

fietsboek.util.human_size(num_bytes)

Formats the amount of bytes for human consumption.

Parameters:

num_bytes (int) – The amount of bytes.

Return type:

str

Returns:

The formatted amount.

fietsboek.util.list_locales(request)

Lists all available locales.

Returns a list of locale name and display name tuples.

Parameters:

request (Request) – The Pyramid request for which to list the locales.

Return type:

list[tuple[str, str]]

fietsboek.util.locale_display_name(locale_name, locale_packages=None)

Reads the display name for the given locale.

If the name cannot be found, simply returns locale_name.

Parameters:
  • locale_name (str) – Name of the locale.

  • locale_packages (Optional[list[str]]) – Names of packages in which locale data is searched.

Return type:

str

fietsboek.util.month_name(request, month)

Returns the localized name for the month with the given number.

Parameters:
  • request (Request) – The pyramid request.

  • month (int) – Number of the month, 1 = January.

Return type:

str

Returns:

The localized month name.

fietsboek.util.mps_to_kph(mps)

Converts meters/second to kilometers/hour.

Parameters:

mps (float) – Input meters/second.

Return type:

float

Returns:

The converted km/h value.

Safely generates a secret suitable for the link share.

The returned string consists of characters that are safe to use in a URL.

Parameters:

nbytes (int) – Number of random bytes to use.

Return type:

str

Returns:

A randomly drawn string.

fietsboek.util.read_localized_resource(locale_name, path, locale_packages=None, raise_on_error=False)

Reads a localized resource.

Localized resources are located in the fietsboek/locale/** directory. Note that path may contain slashes.

If the resource could not be found, a placeholder string is returned instead.

Parameters:
  • locale_name (str) – Name of the locale.

  • path (str) – Path of the resource.

  • locale_packages (Optional[List[str]]) – Names of packages in which locale data is searched. By default, only built-in locales are searched.

  • raise_on_error (bool) – Raise an error instead of returning a placeholder.

Raises:

FileNotFoundError – If the path could not be found and raise_on_error is True.

Return type:

str

Returns:

The text content of the resource.

fietsboek.util.retrieve_multiple(dbsession, model, params, name)

Parses a reply to retrieve multiple database objects.

This is usable for arrays sent by HTML forms, for example to retrieve all badges or all tagged friends.

If an object could not be found, this raises a HTTPBadRequest.

Raises:

pyramid.httpexceptions.HTTPBadRequest – If an object could not be found.

Parameters:
  • dbsession (Session) – The database session.

  • model (type[TypeVar(T)]) – The model class to retrieve.

  • params (NestedMultiDict) – The form parameters.

  • name (str) – Name of the parameter to look for.

Return type:

list[TypeVar(T)]

Returns:

A list of elements found.

fietsboek.util.round_timedelta_to_multiple(value, multiples)

Round the timedelta value to be a multiple of multiples.

Parameters:
  • value (timedelta) – The value to be rounded.

  • multiples (timedelta) – The size of each multiple.

Return type:

timedelta

Returns:

The rounded value.

fietsboek.util.safe_markdown(md_source)

Transform a markdown document into a safe HTML document.

This uses markdown to first parse the markdown source into HTML, and then bleach to strip any disallowed HTML tags.

Parameters:

md_source (str) – The markdown source.

Return type:

Markup

Returns:

The safe HTML transformed version.

fietsboek.util.secure_filename(filename)

Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to os.path.join(). The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files.

>>> secure_filename("My cool movie.mov")
'My_cool_movie.mov'
>>> secure_filename("../../../etc/passwd")
'etc_passwd'
>>> secure_filename('i contain cool \xfcml\xe4uts.txt')
'i_contain_cool_umlauts.txt'

The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one.

Parameters:

filename (str) – the filename to secure

Return type:

str

Returns:

The secure filename.

fietsboek.util.tile_url(request, route_name, **kwargs)

Generates a URL for tiles.

This is basically request.route_url(), but it keeps the {x}/{y}/{z} placeholders intact for consumption by Leaflet.

Expects that the URL takes a x, y and z parameter.

Parameters:
  • request (Request) – The Pyramid request.

  • route_name (str) – The name of the route.

  • kwargs (str) – Remaining route parameters. Will be passed to route_url.

Return type:

str

Returns:

The route URL, with intact placeholders.

fietsboek.util.tour_metadata(gpx_data)

Calculate the metadata of the tour.

Returns a dict with length, uphill, downhill, moving_time, stopped_time, max_speed, avg_speed, start_time and end_time.

Parameters:

gpx_data (Union[str, bytes, GPX]) – The GPX data of the tour. Can be pre-parsed to save time.

Return type:

dict

Returns:

A dictionary with the computed values.