utils

find(iterable: Iterable[T], predicate: Callable[[T], bool]) Optional[T][source]

Return the first item in the iterable that matches the predicate function.

is_uuid(value: str) bool[source]

Check if the string value is a proper UUID string.

UUID check is performed based on a regex pattern:

r”^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$”

Returns

True if there is a match, otherwise False

Return type

bool

is_url(value: str) bool[source]

Return whether or not given value is a valid URL.

If the value is valid URL this function returns True.

This validator implementation is taken and augmented from https://github.com/kvesteri/validators/ Copyright (c) 2013-2014 Konsta Vesterinen, It is Licenced with the MIT license.

This validator is based on the wonderful URL validator of dperini.

Parameters

value (Text) – an alleged url

Returns

True if it is an URL, otherwise False

Return type

bool

Examples

>>> is_url('http://foobar.dk')
True
>>> is_url('ftp://foobar.dk')
True
>>> is_url('http://10.0.0.1')
True
>>> is_url('http://foobar.d')
False
is_valid_email(value: str) bool[source]

Return whether or not given value is a valid email address.

If the value is valid email this function returns True. The email will only be checked if it contains the right form, not if the email address exist. There are many and better ways to check if the email is valid, but in this case we check if the email has the form of name@domain.tld.

Parameters

value (Text) – an alleged email

Returns

True if it is an email, otherwise False

Return type

bool

Examples

>>> is_valid_email("valid_email-address@example.com")
True
>>> is_valid_email("invalid@email")
False
temp_chdir(cwd: Optional[str] = None)[source]

Create and return a temporary directory which you can use as a context manager.

When you are out of the context the temprorary disk gets erased.

New in version 2.3.

Parameters

cwd (basestring or None) – path to change working directory back to path when out of context

Returns

in context a temporary directory

Example

>>> with temp_chdir() as temp_dir:
>>>     # do things here
>>>     print(temp_dir)  # etc etc
...
>>> # when moving out of the context the temp_dir is destroyed
>>> pass
parse_datetime(value: Optional[str]) Optional[datetime][source]

Convert datetime string to datetime object.

Helper function to convert a datetime string found in json responses to a datetime object with timezone information. The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC.

Inspired on the Django project. From django.utils.dateparse.parse_datetime. The code is copyrighted and licences with an MIT license in the following fashion:

Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.

..versionadded 2.5:

Parameters

value (str or None) – datetime string

Returns

datetime of the value is well formatted. Otherwise (including if value is None) returns None

Return type

datetime or None

Raises

ValueError – if the value is well formatted but not a valid datetime

camelcase(string: str) str[source]

Convert string into camel case.

Inspired by: https://github.com/okunishinishi/python-stringcase License: MIT

Parameters

string – String to convert.

Returns

Camel case string.

Examples

>>> camelcase('foo_bar_baz')
fooBarBaz
>>> camelcase('FooBarBaz')
fooBarBaz
capitalcase(string: str) str[source]

Convert string into capital case.

First letters will be uppercase.

Inspired by: https://github.com/okunishinishi/python-stringcase License: MIT

Parameters

string – String to convert.

Returns

Capital case string.

Examples

>>> capitalcase('foo_bar_baz')
Foo_bar_baz
>>> capitalcase('FooBarBaz')
FooBarBaz
lowercase(string: str) str[source]

Convert string into lower case.

Inspired by: https://github.com/okunishinishi/python-stringcase License: MIT

Parameters

string – String to convert.

Returns

lower case string.

Examples

>>> lowercase('foo_bar_baz')
Foo_bar_baz
>>> lowercase('FooBarBaz')
foobarbaz
snakecase(string: str) str[source]

Convert string into snake case.

Join punctuation with underscore

Inspired by: https://github.com/okunishinishi/python-stringcase License: MIT

Parameters

string – String to convert.

Returns

snake_case_string.

Examples

>>> snakecase('foo_bar_baz')
foo_bar_baz
>>> snakecase('FooBarBaz')
foo_bar_baz
uppercase(string: str) str[source]

Convert string into upper case.

Inspired by: https://github.com/okunishinishi/python-stringcase License: MIT

Parameters

string – String to convert.

Returns

Upper case string.

Examples

>>> uppercase('foo_bar_baz')
FOO_BAR_BAZ
>>> uppercase('FooBarBaz')
FOOBARBAZ
slugify_ref(value: str, allow_unicode: bool = False) str[source]

Convert to ASCII if ‘allow_unicode’ is False. Convert spaces to hyphens.

Remove characters that aren’t alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace.

Parameters
  • value – text to slugify

  • allow_unicode – (optional) boolean to allow unicode processing, defaults to False

Returns

slugified value

get_in_chunks(lst: Union[List, Iterable], chunk_size: int) Iterable[source]

Yield successive chunks from a list based on the chunk_size.

Parameters
  • lst (List or Iterable) – list or Iterable

  • chunk_size (int) – size of the chunks

Returns

Iterator that returns list of length chunk_size until original lst is depleted.

Return type

Iterable

class Empty(*args, **kwargs)[source]

Represents an empty value.

In edit functions we want to be able to edit values of model properties, e.g. the due_date of a process. Consider the following example:

def edit(self, start_date, due_date)

self.start_date = start_date self.due_date = due_date self.save()

This OK, we can edit both the start and due date. But what if we want to be able to edit one of the two dates without providing or touching the other.

We would have to change it as follows:

def edit(self, start_date=None, due_date=None)
if start_date:

self.start_date = start_date

if due_date:

self.due_date = due_date

self.save()

Now, if we provide a start_date but not a due_date, the due_date would automatically get a None value. This way only the non-None values are edited and saved. Looks OK.

But what if we want to empty a date and set it to null(None) in the database? If we we send None as a due_date value it would not get saved due to the None value checker we implemented in order to have optional parameters.

Here comes the Empty class into play!

The Empty class is just a Python class which does absolutely nothing and only serves the purpose of being unique. If we give the parameters in our edit function a default value which is an instance of the Empty class, we can check on that in order to know if we want to save the value. Like this:

def edit(self, start_date=Empty(), due_date=Empty())
if not isinstance(start_date, Empty):

self.start_date = start_date

if not isinstance(due_date, Empty):

self.due_date = due_date

self.save()

Now both start_date and due_date are optional but they can also hold a None value which will lead to an actual edit.

Happy coding!

Only create a single instance of this class, i.e. simple singleton pattern.

clean_empty_values(update_dict: Dict, nones: bool = True) Dict[source]

Clean a dictionary by removing all the keys that have an empty value.

Parameters
  • update_dict (dict) – dictionary with keys=request parameters

  • nones – (optional) allow None’s to be in the dict when True, otherwise remove them

Returns

same dictionary but cleaned up if there are values None

Return type

dict

find_obj_in_list(value: str, iterable: List[Any], attribute: Optional[str] = None) Any[source]

Retrieve a Base object belonging to an iterable list on its name, ref or uuid.

You may provide an attribute name of the Base object (such as ‘id’, ‘derived_from’, …) on where to match the val on. So it will check equivalence on Base.get(attribute) == value.

Parameters
  • value – Base object name, ref or UUID to search for

  • iterable – List of Base objects to search in.

  • attribute – the attribute on where to match the comparison on.

Returns

a single Base

Raises
get_offset_from_user_timezone(user: User) int[source]

Retrieve the offset in minutes from UTC time compared to the user defined timezone.

Parameters

user (User object) – (optional) User used to calculate the offset in minutes.

Returns

number of minutes to the nearest integer