Utilities Package

Submodules

APIs

:copyright (c) 2014 - 2022, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Department of Energy) and contributors. All rights reserved. :author

class seed.utils.api.APIBypassCSRFMiddleware(get_response)

Bases: object

This middleware turns off CSRF protection for API clients.

It must come before CsrfViewMiddleware in settings.MIDDLEWARE.

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=False)

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

class seed.utils.api.ProfileIdMixin

Bases: object

Provides methods to get the columns to show based on a profile ID

get_show_columns(org_id, profile_id)

Get list of columns from the profile_id. The result will be in the form of

show_columns = {

‘fields’: [‘field_1’, ‘field_2’, …] ‘extra_data’: [‘extra_data_field_1’, ‘extra_data_field_2’, …]

}

Parameters
  • org_id – str, id of organization

  • profile_id – str, id of profile to retrieve

Returns

dist of lists

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

:copyright (c) 2014 - 2022, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Department of Energy) and contributors. All rights reserved. :author

seed.utils.buildings.get_source_type(import_file, source_type='')

Used for converting ImportFile source_type into an int.

Constants

Mappings

Organizations

:copyright (c) 2014 - 2022, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Department of Energy) and contributors. All rights reserved. :author

seed.utils.organizations.create_organization(user=None, org_name='', *args, **kwargs)

Helper script to create a user/org relationship from scratch. This is heavily used and creates the default labels, columns, and data quality rules when a new organization is created

Parameters
  • user – user inst.

  • org_name – str, name of Organization we’d like to create.

  • kwargs ((optional)) – ‘role’, int; ‘status’, str.

seed.utils.organizations.create_suborganization(user, current_org, suborg_name='', user_role=10)
seed.utils.organizations.default_pm_mappings()

Projects

Time

:copyright (c) 2014 - 2022, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Department of Energy) and contributors. All rights reserved. :author

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.