Utilities Package



required approvals from the U.S. Department of Energy) and contributors. All rights reserved. # NOQA :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


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.

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 filtered on organization

class seed.utils.api.OrgUpdateMixin

Bases: seed.utils.api.OrgMixin

Mixin to add organization when updating model instance


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’)


class MySerializer(OrgValidateMixin, serializers.ModelSerializer):
foreign_key= serializers.PrimaryKeyRelatedField(

) 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.


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


Alias for field number 1


Alias for field number 0


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.


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.


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.


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.


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.


Examines all views and returns those with is_api_endpoint set to true (done by the @api_endpoint decorator).


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.

  • obj (object) – initial object to examine
  • lst (list) – list of successive attributes to look up



returns the number of buildings in a user’s orgs

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.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

  • 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.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

  • datestr – string, value to convert
  • make_tz_aware – bool, if set to true, then will convert the timezone into UTC time

datetime or None


converts a django/python datetime object to milliseconds since epoch


Process a datetime value that may be None, timestamp, strftime.