seed.utils package¶
Submodules¶
seed.utils.api module¶
:copyright (c) 2014 - 2016, 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. # 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.
-
-
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.
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).
TODO: this isn’t particularly expensive now, but if the number of urls grows a lot, it may be worth caching this somewhere.
-
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_client module¶
:copyright (c) 2014 - 2016, 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. # NOQA :author
Demo and testing features for interacting with a SEED API.
-
class
seed.utils.api_client.
APIClient
(base_url, api_key='', email_address='')¶ Bases:
object
Implementation of a demonstration client for using SEED’s API.
Example Usage:
client = APIClient('http://seeddomain.com', api_key='your_key_here', email_address='youremail@address.com') # get all orgs user belongs to client.get_organizations() # organization id 17 will now be used for most requests client.set_organization(17) # create a dataset client.create_dataset('dataset name here') >>> {u'id': 34, u'name': u'test_data_set2', u'status': u'success'} # upload a file client.upload_file('/path/to/file', 34, 'Assessed Raw') >>> {'import_file_id': 54, 'success': true, 'filename': 'DataforSEED_dos15.csv'} # save the file's to the DB as raw buildings client.save_raw_data(payload={'file_id': 54}) >>> {u'progress_key': u':1:SEED:save_raw_data:PROG:54', u'status': u'success'} # check the progress of the saving client.progress( payload={'progress_key':':1:SEED:save_raw_data:PROG:54'} ) >>> {u'progress': 78, u'progress_key': u':1:SEED:save_raw_data:PROG:54'}
For nearly all endpoints, functions named for the endpoint are created from the get_api_schema endpoint. If an endpoint requires a payload it can be provided as a dictionary to the keyword ‘payload’:
client.update_project( payload={'project': {'project_slug': 'myproject', 'name': 'My Project', 'description': 'My description here', 'end_date': 1407231741, 'deadline_date': 1407200000 } } >>> {'status': 'success'}
If an endpoint requires a GET query string, provide those parameters as a dict to the keyword ‘params’:
client.get_import_file(params={'import_file_id': 54}) >>> {'status': 'success', 'import_file': {<snip>} }
-
create_dataset
(name)¶ Example method including a payload.
- Args:
- name: The name of the new dataset.
- Returns:
- {‘id’: 34, ‘name’: name, ‘status’: ‘success’}
-
describe
(what)¶ Provides a human-readable description of an endpoint, specified either by name or URI. E.g.:
client.describe('save_match') >>> save_match >>> /app/save_match/ >>> Adds or removes a match between two BuildingSnapshots[...]
-
get_organizations
()¶ Example method for overriding the autogenerated methods.
- Returns:
- All organizations the user belongs to. See ``seed.views.accounts.get_organizations()’‘
-
get_schema
()¶ Retrieves all of the API endpoints for this SEED instance.
-
set_organization_id
(org_id)¶ Sets the client’s organization_id. As this is needed for most requests, you can set it once and include it in all requests.
- Args:
- org_id: An ID of an org the user belongs to. Will validate against
- the API.
-
upload_file
(filepath, import_record_id, source_type)¶ Determines the correct method to upload a file (S3 or direct) and does so. Makes use of several endpoints in the process, depending on where the SEED instance stores files.
- Args:
- filepath: Full path to file on local filesystem. import_record_id: ID of the dataset to associate file with. source_type: Usually one of ‘Assessed Raw’ or ‘Portfolio Raw’
- Returns:
- {“import_file_id”: 54,
- “success”: true, “filename”: “DataforSEED_dos15.csv”}
-
seed.utils.buildings module¶
:copyright (c) 2014 - 2016, 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. # NOQA :author
-
seed.utils.buildings.
get_buildings_for_user_count
(user)¶ returns the number of buildings in a user’s orgs
-
seed.utils.buildings.
get_columns
(is_project, org_id, all_fields=False)¶ gets default columns, to be overridden in future
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
seed.utils.constants module¶
:copyright (c) 2014 - 2016, 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. # NOQA :author
seed.utils.mapping module¶
:copyright (c) 2014 - 2016, 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. # NOQA :author
-
seed.utils.mapping.
get_mappable_columns
(exclude_fields=None)¶ Get a list of all the columns we’re able to map to.
-
seed.utils.mapping.
get_mappable_types
(exclude_fields=None)¶ Like get_mappable_columns, but with type information.
seed.utils.organizations module¶
:copyright (c) 2014 - 2016, 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. # NOQA :author
-
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.
seed.utils.projects module¶
:copyright (c) 2014 - 2016, 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. # NOQA :author
-
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. :param 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. :param 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. :param 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. :param 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. :param 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
seed.utils.time module¶
:copyright (c) 2014 - 2016, 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. # NOQA :author
-
seed.utils.time.
convert_datestr
(datestr)¶ Converts dates like 12/31/2010 into datetime objects.
-
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, stftime.
Module contents¶
:copyright (c) 2014 - 2016, 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. # NOQA :author