Utilities Package¶
Submodules¶
APIs¶
required approvals from the U.S. Department of Energy) and contributors. All rights reserved. # NOQA :author
-
class
seed.utils.api.
APIBypassCSRFMiddleware
¶ Bases:
object
This middleware turns off CSRF protection for API clients.
It must come before CsrfViewMiddleware in settings.MIDDLEWARE_CLASSES.
-
process_view
(request, *args, **kwargs)¶ If this request is an API request, bypass CSRF protection.
-
-
class
seed.utils.api.
OrgCreateMixin
¶ Bases:
seed.utils.api.OrgMixin
Mixin to add organization when creating model instance
-
perform_create
(serializer)¶ Override to add org
-
-
class
seed.utils.api.
OrgCreateUpdateMixin
¶ Bases:
seed.utils.api.OrgCreateMixin
,seed.utils.api.OrgUpdateMixin
Mixin to add organization when creating/updating model instance
-
class
seed.utils.api.
OrgMixin
¶ Bases:
object
Provides get_organization and get_parent_org method
-
get_organization
(request, return_obj=None)¶ Get org from query param or request.user. :param request: request object. :param return_obj: bool. Set to True if obj vs pk is desired. :return: int representing a valid organization pk or
organization object.
-
get_parent_org
(request)¶ Gets parent organization of org from query param or request. :param request: Request object. :return: organization object.
-
-
class
seed.utils.api.
OrgQuerySetMixin
¶ Bases:
seed.utils.api.OrgMixin
Mixin proving a get_queryset method that filters on organization.
In order to use this mixin you must specify the model attributes on the View[Set] class. By default it assumes there is an organization field on the model. You can override this by setting the orgfilter attribute to the appropriate fieldname. This also allows nested fields e.g. foreign_key.organization By default this retrieves organization from query string param OR the default_organization or first returned organization of the logged in user. You can force it to return the appropriate “parent” organization by setting the force_parent attribute to True.
-
get_queryset
()¶ “get_queryset filtered on organization
-
-
class
seed.utils.api.
OrgUpdateMixin
¶ Bases:
seed.utils.api.OrgMixin
Mixin to add organization when updating model instance
-
perform_update
(serializer)¶ Override to add org
-
-
class
seed.utils.api.
OrgValidateMixin
¶ Bases:
object
Mixin to provide a validate() method organization to ensure users belongs to the same org as the instance referenced by a foreign key..
You must set org_validators on the Serializer that uses this Mixin. This is a list of OrgValidator named tuples (where key is the key on request data representing the foreign key, and field the foreign key that represents the organization on the corresponding model.
my_validator = OrgValidator(key=’foreign_key, field=’organization_id’)
..example:
- class MySerializer(OrgValidateMixin, serializers.ModelSerializer):
- foreign_key= serializers.PrimaryKeyRelatedField(
- query_set=MyModel.objects.all()
) org_validators = [my_validator]
This ensures request.user belongs to the org MyModel.organization
You can traverse foreign key relationships by using a double underscore in validator.field
In the example above setting validator field to be ‘property__org_id’ is equivalent to MyModel.property.org_id
If you use this Mixin and write a validate method, you must call super to ensure validation takes place.
-
validate
(data)¶ Object level validation. Checks for self.org_validators on Serializers and ensures users belongs to org corresponding to the foreign key being set.
-
validate_org
(instance, user, validator)¶ Raise error if orgs do not match. :param instance: value in request.data.get(key) to check against :type instance: model instance :param: org_id of user, from get_org_id(request) :type org_id: int :param validator: validator to user :type: OrgValidator named tuple
-
class
seed.utils.api.
OrgValidator
(key, field)¶ Bases:
tuple
-
field
¶ Alias for field number 1
-
key
¶ Alias for field number 0
-
-
seed.utils.api.
api_endpoint
(fn)¶ Decorator function to mark a view as allowed to authenticate via API key.
Decorator must be used before login_required or has_perm to set request.user for those decorators.
-
seed.utils.api.
api_endpoint_class
(fn)¶ Decorator function to mark a view as allowed to authenticate via API key.
Decorator must be used before login_required or has_perm to set request.user for those decorators.
-
seed.utils.api.
clean_api_regex
(url)¶ Given a django-style url regex pattern, strip it down to a human-readable url.
TODO: If pks ever appear in the url, this will need to account for that.
-
seed.utils.api.
drf_api_endpoint
(fn)¶ Decorator to register a Django Rest Framework view with the list of API endpoints. Marks it with is_api_endpoint = True as well as appending it to the global endpoints list.
-
seed.utils.api.
format_api_docstring
(docstring)¶ Cleans up a python method docstring for human consumption.
-
seed.utils.api.
get_all_urls
(urllist, prefix=”)¶ Recursive generator that traverses entire tree of URLs, starting with urllist, yielding a tuple of (url_pattern, view_function) for each one.
-
seed.utils.api.
get_api_endpoints
()¶ Examines all views and returns those with is_api_endpoint set to true (done by the @api_endpoint decorator).
-
seed.utils.api.
get_api_request_user
(request)¶ Determines if this is an API request and returns the corresponding user if so.
-
seed.utils.api.
get_org_id_from_validator
(instance, field)¶ For querysets Django enables you to do things like:
note double underscore. However you can’t do:
This presents an issue as getattr only works 1 level deep:
getattr(obj, ‘org.id’) does not work either.This can be worked around using rgetattr (above). This functions mimics getattr(obj, ‘org__id’) by splitting field on __ and calling rgetattr on the result.
-
seed.utils.api.
rgetattr
(obj, lst)¶ This enables recursive getattr look ups. given obj, [‘a’, ‘b’, ‘c’] as params it will look up: obj.a, a.b, b.c returning b.c unless one of the previous values was None, in which case it returns None immediately.
Parameters: - obj (object) – initial object to examine
- lst (list) – list of successive attributes to look up
Buildings¶
-
seed.utils.buildings.
get_buildings_for_user_count
(user)¶ returns the number of buildings in a user’s orgs
-
seed.utils.buildings.
get_columns
(org_id, all_fields=False)¶ Get default columns, to be overridden in future
Returns:
title: HTML presented title of column sort_column: semantic name used by js and for searching DB class: HTML CSS class for row td elements title_class: HTML CSS class for column td elements type: 'string', 'number', 'date' min, max: the django filter key e.g. gross_floor_area__gte field_type: assessor, pm, or compliance (currently not used) sortable: determines if the column is sortable checked: initial state of "edit columns" modal static: True if option can be toggle (ID is false because it is always needed to link to the building detail page) link: signifies that the cell's data should link to a building detail page
-
seed.utils.buildings.
get_search_query
(user, params)¶
-
seed.utils.buildings.
get_source_type
(import_file, source_type=”)¶ Used for converting ImportFile source_type into an int.
-
seed.utils.buildings.
serialize_building_snapshot
(b, pm_cb, building)¶ returns a dict that’s safe to JSON serialize
Constants¶
Mappings¶
-
seed.utils.mapping.
get_mappable_columns
(exclude_fields=None)¶ Get a list of all the columns we’re able to map to that are fields in the database already
-
seed.utils.mapping.
get_mappable_types
(exclude_fields=None)¶ Like get_mappable_columns, but with type information.
-
seed.utils.mapping.
get_table_and_column_names
(column_mapping, attr_name=’column_raw’)¶ Turns the Column.column_names into a serializable list of str.
Organizations¶
-
seed.utils.organizations.
create_organization
(user, org_name=”, *args, **kwargs)¶ Helper script to create a user/org relationship from scratch.
Parameters: - user – user inst.
- org_name – str, name of Organization we’d like to create.
- kwargs ((optional)) – ‘role’, int; ‘status’, str.
Projects¶
-
seed.utils.projects.
copy_buildings
(source_project, target_project, buildings, select_all, search_params, user)¶ copies buildings from source project to target project
Parameters: - source_project_slug – str, a slug to get a Project inst.
- target_project_slug – str, a slug to get a Project inst.
- buildings – list, list of source_facility_id as str to get BuildingSnapshot inst.
- select_all – bool, if the select all checkbox was checked. i.e. should we transfer all buildings in a project or just the buildings in the list
Search_params: dict, params needed to generate a queryset of buildings, with keys (q, other_params, project_slug)
User: User inst., django user instance needed for select all queryset
-
seed.utils.projects.
delete_matching_buildings
(project, buildings, select_all, search_params, user)¶ deletes buildings in a project that match search search params
Parameters: - project_slug – str, a slug to get a Project inst.
- buildings – list, list of source_facility_id as str to get BuildingSnapshot inst.
- select_all – bool, if the select all checkbox was checked. i.e. should we transfer all buildings in a project or just the buildings in the list
Search_params: dict, params needed to generate a queryset of buildings, with keys (q, other_params, project_slug)
User: User inst., django user instance needed for select all queryset
-
seed.utils.projects.
get_projects
(building, organization)¶ return an JSON friendly list of the building’s projects
Parameters: - building – the BuildingSnapshot inst.
- organization – the Organization inst.
Returns: list of projects
-
seed.utils.projects.
get_transfer_buildings
(source_project, target_project, buildings, select_all, search_params, user)¶ generates move or copy buildings queryset
Parameters: - source_project_slug – str, a slug to get a Project inst.
- target_project_slug – str, a slug to get a Project inst.
- buildings – list, list of source_facility_id as str to get BuildingSnapshot inst.
- select_all – bool, if the select all checkbox was checked. i.e. should we transfer all buildings in a project or just the buildings in the list
Search_params: dict, params needed to generate a queryset of buildings, with keys (q, other_params, project_slug)
User: User inst., django user instance needed for select all queryset
Rtype Queryset: a django queryset of buildings to move or copy
-
seed.utils.projects.
move_buildings
(source_project, target_project, buildings, select_all, search_params, user)¶ moves buildings from source project to target project
Parameters: - source_project_slug – str, a slug to get a Project inst.
- target_project_slug – str, a slug to get a Project inst.
- buildings – list, list of source_facility_id as str to get BuildingSnapshot inst.
- select_all – bool, if the select all checkbox was checked. i.e. should we transfer all buildings in a project or just the buildings in the list
Search_params: dict, params needed to generate a queryset of buildings, with keys (q, other_params, project_slug)
User: User inst., django user instance needed for select all queryset
-
seed.utils.projects.
transfer_buildings
(source_project_slug, target_project_slug, buildings, select_all, search_params, user, copy_flag=False)¶ copies or moves buildings from one project to another
Parameters: - source_project_slug – str, a slug to get a Project inst.
- target_project_slug – str, a slug to get a Project inst.
- buildings – list, list of source_facility_id as str to get BuildingSnapshot inst.
- select_all – bool, if the select all checkbox was checked. i.e. should we transfer all buildings in a project or just the buildings in the list
Search_params: dict, params needed to generate a queryset of buildings, with keys (q, other_params, project_slug)
User: User inst., django user instance needed for select all queryset and to update the projects’ “last changed” and “last changed by”
Copy_flag: bool, True - copy buildings, False - move buildings
Time¶
-
seed.utils.time.
convert_datestr
(datestr, make_tz_aware=False)¶ Converts dates like 12/31/2010 into datetime objects. Dates are returned in UTC time
TODO: reconcile this with seed/lib/mcm/cleaners.py#L85-L85
Parameters: - datestr – string, value to convert
- make_tz_aware – bool, if set to true, then will convert the timezone into UTC time
Returns: datetime or None
-
seed.utils.time.
convert_to_js_timestamp
(timestamp)¶ converts a django/python datetime object to milliseconds since epoch
-
seed.utils.time.
parse_datetime
(maybe_datetime)¶ Process a datetime value that may be None, timestamp, strftime.