API¶
admin¶
Utilities for the admin site.
allianceauth¶
Utilities related to Alliance Auth.
- get_redis_client() Redis[source]¶
Return configured redis client used for Django caching in Alliance Auth.
- is_night_mode(request) bool[source]¶
Returns True if the current user session is in night mode, else False
- notify_admins(message: str, title: str, level: str = 'info') None[source]¶
Send notification to all admins.
- Parameters:
message – Message text
title – Message title
level – Notification level of the message.
- notify_admins_throttled(message_id: str, message: str, title: str, level: str = 'info', timeout: int | None = None)[source]¶
Send notification to all admins, but limits the frequency for sending messages with the same message ID, e.g. to once per day.
If this function is called during a timeout the notification will simply be ignored.
- Parameters:
message_id – ID representing this message
message – Message text
title – Message title
level – Notification level of the message.
timeout – Time between each notification, e.g. 86400 = once per day. When not provided uses system default, which is 86400 and can also be set via this Django setting: APP_UTILS_NOTIFY_THROTTLED_TIMEOUT
- notify_throttled(message_id: str, user: User, title: str, message: str, level: str = 'info', timeout: int | None = None)[source]¶
Send notification to user, but limits the frequency for sending messages with the same message ID, e.g. to once per day.
If this function is called during a timeout the notification will simply be ignored.
- Parameters:
message_id – ID representing this message
title – Message title
message – Message text
level – Notification level of the message.
timeout – Time between each notification, e.g. 86400 = once per day. When not provided uses system default, which is 86400 and can also be set via this Django setting: APP_UTILS_NOTIFY_THROTTLED_TIMEOUT
app_settings¶
Django settings related utilities.
- clean_setting(name: str, default_value: Any, min_value: int | None = None, max_value: int | None = None, required_type: type | None = None, choices: list | None = None) Any[source]¶
Clean a setting from Django settings.
Will use default_value if setting is not defined. Will use minimum or maximum value if respective boundary is exceeded.
- Parameters:
default_value (otherwise derived from) – value to use if setting is not defined
min_value – minimum allowed value (0 assumed for int)
max_value – maximum value value
required_type – Mandatory if default_value is None,
default_value
- Returns:
cleaned value for setting
This function is designed to be used in a dedicated module like
app_settings.pyas layer between the actual settings and all other modules.app_settings.pywill import and clean all settings and all other modules are supposed to import the settings it.Example for app_settings:
from app_utils.app_settings import clean_setting EXAMPLE_SETTING = clean_setting("EXAMPLE_SETTING", 10)
caching¶
Utilities for caching objects and querysets.
- class ObjectCacheMixin[source]¶
A mixin which adds a simple object cache to a Django manager.
- clear_cache(pk: int)[source]¶
Clear cache for a potentially cached object.
This will also clear cached variants with select_related (if any).
- Parameters:
pk – Primary key for object to fetch
- get_cached(pk, timeout: int | None = None, select_related: str | None = None) Any[source]¶
Return the requested object either from DB or from cache.
Can be disabled globally through the setting
APP_UTILS_OBJECT_CACHE_DISABLED.- Parameters:
pk – Primary key for object to fetch
timeout – Timeout in seconds for cache
select_related – select_related query to be applied (if any)
- Returns:
model instance if found
- Exceptions:
Model.DoesNotExistif object can not be found
Example:
# adding the Mixin to the model manager class MyModelManager(ObjectCacheMixin, models.Manager): pass # using the cache method obj = MyModel.objects.get_cached(pk=42, timeout=3600)
- cached_queryset(queryset: QuerySet, key: str, timeout: int) Any[source]¶
caches the given queryset
- Parameters:
queryset – the query set to cache
key – key to be used to reference this cache
timeout – Timeout in seconds for cache
- Returns:
query set
Example
queryset = cached_queryset( MyModel.objects.filter(name__contains="dummy"), key="my_cache_key", timeout=3600 )
database¶
Database related functionality.
datetime¶
Utilities related to date and time.
- dt_eveformat(my_dt: datetime) str[source]¶
converts a datetime to a string in eve format e.g.
2019-06-25T19:04:44
django¶
Extending the Django utilities.
- admin_boolean_icon_html(value) str | None[source]¶
Variation of the admin boolean type, which returns the HTML for creating the usual True and False icons. But returns None for None, instead of the question mark.
- permission_by_name(perm: str) Permission[source]¶
Return permission specified by qualified name, e.g. ‘app_label.codename’.
Note that an app can have multiple permissions with the same codename. This function will return the first such permission. This emulates Django’s behavior in permission checks, where permission with the same codename are threated as the same permission.
- users_with_permission(permission: Permission, include_superusers=True) QuerySet[source]¶
returns queryset of users that have the given Django permission
- Parameters:
permission – required permission
include_superusers – whether superusers are included in the returned list
esi¶
esi_testing¶
Tools for building unit tests with django-esi.
- class BravadoOperationStub(data, headers: dict | None = None, also_return_response: bool = False, status_code=200, reason='OK')[source]¶
Stub to simulate the operation object return from bravado via django-esi.
- class BravadoResponseStub(status_code, reason='', text='', headers=None, raw_bytes=None)[source]¶
Stub for IncomingResponse in bravado, e.g. for HTTPError exceptions.
- class EsiClientStub(testdata: dict | None, endpoints: List[EsiEndpoint], http_error: Any = False)[source]¶
Stub for replacing a django-esi client in tests.
- Parameters:
testdata – data to be returned from Endpoint
endpoints – List of defined endpoints
http_error – Set True to generate a http 500 error exception or set to a http error code to generate a specific http exception
- __init__(testdata: dict | None, endpoints: List[EsiEndpoint], http_error: Any = False) None[source]¶
- classmethod create_from_endpoints(endpoints: List[EsiEndpoint], **kwargs)[source]¶
Create stub from endpoints.
- replace_endpoints(new_endpoints: List[EsiEndpoint]) EsiClientStub[source]¶
Replace given endpoint.
- Parameters:
new_endpoint – List of new endpoints
- Raises:
ValueError – When trying to replace an non existing endpoint
- Returns:
New stub instance with replaced endpoints
- class EsiEndpoint(category: str, method: str, primary_key: str | Tuple[str, str] | None = None, needs_token: bool = False, data: dict | list | str | None = None, http_error_code: int | None = None, side_effect: Callable | Exception | None = None)[source]¶
Class for defining ESI endpoints used in tests with the ESI client stub.
- Parameters:
category – name of ESI category
method – name of ESI method
primary_key – name of primary key (e.g. corporation_id) or tuple of 2 keys
needs_token – Wether the method requires a token
data – Data to be returned from this endpoint
http_error_code – When provided will raise an HTTP exception with this code
side_effect – A side effect to be triggered. Can be an exception of a function.
raised. (Exceptions will be)
endpoint (Functions will be called with the args of the)
"data". (and it's result returned instead of)
function (Return the object SIDE_EFFECT_DEFAULT in the)
data. (to return the endpoints normal)
- SIDE_EFFECT_DEFAULT = <object object>¶
Special object that can be returned from side_effect functions to indicate that the normal data should be returned (instead of the result of the side_effect function)
helpers¶
General purpose helpers.
- class AttrDict(*args, **kwargs)[source]¶
Enhanced dict that allows property access to its keys.
Example:
>> my_dict = AttrDict({"color": "red", "size": "medium"}) >> my_dict["color"] "red" >> my_dict.color "red"
- humanize_number(value, magnitude: str | None = None, precision: int = 1) str[source]¶
Return the value in humanized format, e.g. 1234 becomes 1.2k
- Parameters:
magnitude – fix the magnitude to format the number, e.g. “b”
precision – number of digits to round for
- throttle(func: Callable, context_id: str, timeout: int | None) Any[source]¶
Call a function, but limit repeated calls with a timeout, e.g. once per day.
When a repeated call falls within the timeout the call will simply be ignored.
- Parameters:
func – the function to be called
context_id – a string representing the context for applying the throttle, e.g. a combination of feature name and user ID
timeout – timeout in seconds between each repeated call of the function
- Returns:
Return cached value of called function func
json¶
JSON related utilities.
- class JSONDateTimeDecoder(*args, **kwargs)[source]¶
Decoder for the standard json library to decode JSON into datetime. To be used together with
JSONDateTimeEncoder.Example
message = json.loads(message_json, cls=JSONDateTimeDecoder)
- class JSONDateTimeEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]¶
Encoder for the standard json library to encode datetime into JSON. To be used together with
JSONDateTimeDecoder.Works with naive and aware datetimes, but only with UTC timezone.
Example
message_json = json.dumps(message, cls=JSONDateTimeEncoder)
logging¶
Utilities for enhancing logging.
Utilities for logging.
messages¶
Improvement of the Django message class.
- class messages_plus[source]¶
Improvement of default Django messages with implicit HTML support.
- classmethod debug(request: HttpRequest, message: str, *args, **kwargs) None[source]¶
Send a debug message with HTML support. Use with safe strings only!
- classmethod error(request: HttpRequest, message: str, *args, **kwargs) None[source]¶
Send an error message with HTML support. Use with safe strings only!
- classmethod info(request: HttpRequest, message: str, *args, **kwargs) None[source]¶
Send an info message with HTML support. Use with safe strings only!
scripts¶
Utilities and helpers for Python scripts.
- start_django(max_hops=10, django_project_name='myauth', settings_module='myauth.settings.local', silent=False) None[source]¶
Start the current Django project.
This function encapsulates the boilerplate code needed to start the current Django project in a normal Python script.
It will also try to detect the path to the current Django project. If it can not be found, the function will exit with code 1.
- Parameters:
max_hops (-) – Max number of hops up on the main path to check
django_project_name (-) – Name of the Django project
settings_module (-) – Qualified name of the settings module in the Django project
silent (-) – When True will not produce any output
Here is an example how to use this function in a script:
from app_utils.scripts import start_django start_django() def main(): # put Django imports here ... if __name__ == "__main__": main()
‘’’
testing¶
Utilities for making it easier to write tests.
- class CacheFake[source]¶
A fake for replacing Django’s cache in tests.
Example:
from app_utils.testing import CacheFake @patch("my_module.cache", new_callable=CacheFake) def test_my_function(self): ...
- class NoSocketsTestCase(methodName='runTest')[source]¶
Variation of Django’s TestCase class that prevents any network use.
Example
class TestMyStuff(NoSocketsTestCase): def test_should_do_what_i_need(self): ...
- add_character_to_user(user: User, character: allianceauth.eveonline.models.EveCharacter, is_main: bool = False, scopes: List[str] | None = None, disconnect_signals: bool = False) allianceauth.authentication.models.CharacterOwnership[source]¶
Generates a token for the given Eve character and makes the given user it’s owner
- Parameters:
user – New character owner
character – Character to add
is_main – Will set character as the users’s main when True
scopes – List of scopes for the token
disconnect_signals – Will disconnect signals temporarily when True
- add_character_to_user_2(user: User, character_id, character_name, corporation_id, corporation_name, alliance_id=None, alliance_name=None, disconnect_signals=False) allianceauth.eveonline.models.EveCharacter[source]¶
Creates a new EVE character and makes the given user the owner
- add_new_token(user: User, character: allianceauth.eveonline.models.EveCharacter, scopes: List[str] | None = None, owner_hash: str | None = None) Token[source]¶
Generate a new token for a user based on a character.
- create_authgroup(states: Iterable[allianceauth.authentication.models.State] | None = None, **kwargs) Group[source]¶
Create Group object with additional Auth related properties for tests.
- create_eve_character(character_id: int, character_name: str, **kwargs) allianceauth.eveonline.models.EveCharacter[source]¶
Create an EveCharacter object for tests.
- create_fake_user(character_id: int, character_name: str, corporation_id: int | None = None, corporation_name: str | None = '', corporation_ticker: str | None = None, alliance_id: int | None = None, alliance_name: str | None = '', permissions: List[str] | None = None) User[source]¶
Create a fake user incl. main character and (optional) permissions.
Will use default corporation and alliance if not set.
- create_state(priority: int, permissions: Iterable[str] | None = None, member_characters: Iterable[allianceauth.eveonline.models.EveCharacter] | None = None, member_corporations: Iterable[allianceauth.eveonline.models.EveCorporationInfo] | None = None, member_alliances: Iterable[allianceauth.eveonline.models.EveAllianceInfo] | None = None, member_factions: Iterable[allianceauth.eveonline.models.EveFactionInfo] | None = None, **kwargs) allianceauth.authentication.models.State[source]¶
Create a State object for tests.
- create_user_from_evecharacter(character_id: int, permissions: List[str] | None = None, scopes: List[str] | None = None) Tuple[User, allianceauth.authentication.models.CharacterOwnership][source]¶
Create new allianceauth user from EveCharacter object.
- Parameters:
character_id – ID of eve character
permissions – list of permission names, e.g. “my_app.my_permission”
scopes – list of scope names
- json_response_to_dict(response: JsonResponse, key='id') dict[source]¶
Convert JSON response into dict by given key.
- json_response_to_python(response: JsonResponse) Any[source]¶
Convert JSON response into Python object.
- multi_assert_in(items: Iterable, container: Iterable) bool[source]¶
Return True if all items are in container.
- multi_assert_not_in(items: Iterable, container: Iterable) bool[source]¶
Return True if none of the item is in container.
- next_number(key=None) int[source]¶
Generate consecutive numbers. Optionally numbers are generates for given key.
- queryset_pks(queryset) set[source]¶
shortcut that returns the pks of the given queryset as set. Useful for comparing test results.
testdata_factories¶
This module provides factories for generating test objects from Django and AA Models.
Important: You need to add the dependency factory_boy to your test environment.
testrunners¶
Custom test runners for Django.
- class TimedTestRunner(pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, parallel=0, tags=None, exclude_tags=None, test_name_patterns=None, pdb=False, buffer=False, enable_faulthandler=True, timing=False, shuffle=False, logger=None, durations=None, **kwargs)[source]¶
Test runner which adds duration measurements to each tests (when verbose) and shows list of slowest tests at the end.
To use in tests define via the
TEST_RUNNERsetting or as--testrunnerparameter fortest, e.g.:TEST_RUNNER = "app_utils.testrunners.TimedTestRunner"
python manage.py test -v 2 --testrunner app_utils.testrunners.TimedTestRunner
- test_runner¶
alias of
_TimedTextTestRunner
urls¶
Utilities related to URLs.
views¶
Utilities for supporting Django views.
- class BootstrapStyle(value)[source]¶
A Bootstrap context style names, e.g. for labels.
DEPRECATED: This class works for Bootstrap 3 only, which is no longer supported by AA.
- DANGER = 'danger'¶
- DEFAULT = 'default'¶
- INFO = 'info'¶
- PRIMARY = 'primary'¶
- SUCCESS = 'success'¶
- WARNING = 'warning'¶
- class BootstrapStyleBS5(value)[source]¶
A Bootstrap context style name, e.g. for labels
- DANGER = 'danger'¶
- DEFAULT = 'secondary'¶
- INFO = 'info'¶
- PRIMARY = 'primary'¶
- SUCCESS = 'success'¶
- WARNING = 'warning'¶
- class HttpResponseNoContent(*args, **kwargs)[source]¶
Special HTTP response with no content, just headers.
The content operations are ignored.
- class JSONResponseMixin[source]¶
A mixin that can be used to render a JSON response for a class based view.
- bootstrap_glyph_2_html(glyph_name, tooltip_text=None, color='initial') str[source]¶
Return HTML for a Bootstrap 3 glyph HTML. Can also have a tool tip and color.
- bootstrap_icon_plus_name_html(icon_url, name, size: int = 32, avatar: bool = False, url: str | None = None, text: str | None = None) str[source]¶
Returns HTML to display an icon next to a name. Can also be a link.
DEPRECATED. To be replaced by bootstrap_icon_plus_text_html.
- bootstrap_icon_plus_text_html(icon_url: str, text: str, size: int = 32, avatar: bool = False, url: str | None = None, suffix: str | None = None) str[source]¶
Return HTML for a widget consisting of an icon with a text or link:
<Icon> <Text/Link> [<Suffix>]
Adds the class
icon-plus-textto all images to enable styling.- Parameters:
icon_url (-) – URL to an icon file, supported by <img>, e.g. GIF, PNG
text (-) – Text to be shown next to icon. Often a name.
size (-) – Size of the icon in pixel
avatar (-) – When enabled the icon will get Bootstrap 3 classes for avatars
url (-) – A provided URL will transform the text into a link
suffix (-) – Additional text to be shown after the main text. Will not be part of a link.
- bootstrap_label_html(text: str, label: str = 'default') str[source]¶
Return HTML for a Bootstrap label.
- bootstrap_link_button_html(url: str, glyph_name: str, button_type: str, disabled: bool = False) str[source]¶
Return HTML for a button with Bootstrap 3 glyphs.
- fontawesome_link_button_html(url: str, fa_code: str, button_type: str, tooltip: str | None = None, disabled: bool = False) str[source]¶
Return HTML for a button with fontawesome symbols.
- fontawesome_modal_button_html(modal_id: str, fa_code: str, ajax_url: str = '', tooltip: str = '', style=BootstrapStyle.DEFAULT) str[source]¶
Return HTML for a modal button with fontawesome symbols.
DEPRECATED: Only works with Bootstrap3, which is no longer supported by AA
- Parameters:
modal_id – DOM ID of modal to invoke
fa_code – fontawesome code, e.g. “fas fa-moon”
ajax_url – URL to invoke via AJAX for loading modal content
tooltip – text to appear as tooltip
style – Bootstrap context style for the button
- humanize_value(value: float, precision: int = 2) str[source]¶
Return a value in a human readable and abbreviated form e.g.
1234678->1.23m.
- image_html(src: str, classes: List[str] | None = None, size: int | None = None) str[source]¶
Return HTML for an image with optional classes and size.