INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Check the old password is valid and set the new password.
def update(self, instance, validated_data): """Check the old password is valid and set the new password.""" if not instance.check_password(validated_data['old_password']): msg = _('Invalid password.') raise serializers.ValidationError({'old_password': msg}) instance.set_...
Set the new password for the user.
def update(self, instance, validated_data): """Set the new password for the user.""" instance.set_password(validated_data['new_password']) instance.save() return instance
Validate if email exists and requires a verification.
def validate_email(self, email): """ Validate if email exists and requires a verification. `validate_email` will set a `user` attribute on the instance allowing the view to send an email confirmation. """ try: self.user = User.objects.get_by_natural_key(email...
Create auth token. Differs from DRF that it always creates new token but not re - using them.
def post(self, request): """Create auth token. Differs from DRF that it always creates new token but not re-using them.""" serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user = serializer.validated_data['user'] signals.user_logged_...
Delete auth token when delete request was issued.
def delete(self, request, *args, **kwargs): """Delete auth token when `delete` request was issued.""" # Logic repeated from DRF because one cannot easily reuse it auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'token': return response.Res...
Disallow users other than the user whose email is being reset.
def initial(self, request, *args, **kwargs): """Disallow users other than the user whose email is being reset.""" email = request.data.get('email') if request.user.is_authenticated() and email != request.user.email: raise PermissionDenied() return super(ResendConfirmationEma...
Validate email and send a request to confirm it.
def post(self, request, *args, **kwargs): """Validate `email` and send a request to confirm it.""" serializer = self.serializer_class(data=request.data) if not serializer.is_valid(): return response.Response( serializer.errors, status=status.HTTP_400_...
Since User. email is unique this check is redundant but it sets a nicer error message than the ORM. See #13147.
def clean_email(self): """ Since User.email is unique, this check is redundant, but it sets a nicer error message than the ORM. See #13147. """ email = self.cleaned_data['email'] try: User._default_manager.get(email__iexact=email) except User.DoesNotEx...
Update token s expiration datetime on every auth action.
def update_expiry(self, commit=True): """Update token's expiration datetime on every auth action.""" self.expires = update_expiry(self.created) if commit: self.save()
Email context to reset a user password.
def password_reset_email_context(notification): """Email context to reset a user password.""" return { 'protocol': 'https', 'uid': notification.user.generate_uid(), 'token': notification.user.generate_token(), 'site': notification.site, }
Send a notification by email.
def email_handler(notification, email_context): """Send a notification by email.""" incuna_mail.send( to=notification.user.email, subject=notification.email_subject, template_name=notification.text_email_template, html_template_name=notification.html_email_template, conte...
Password reset email handler.
def password_reset_email_handler(notification): """Password reset email handler.""" base_subject = _('{domain} password reset').format(domain=notification.site.domain) subject = getattr(settings, 'DUM_PASSWORD_RESET_SUBJECT', base_subject) notification.email_subject = subject email_handler(notificat...
Validation email handler.
def validation_email_handler(notification): """Validation email handler.""" base_subject = _('{domain} account validate').format(domain=notification.site.domain) subject = getattr(settings, 'DUM_VALIDATE_EMAIL_SUBJECT', base_subject) notification.email_subject = subject email_handler(notification, v...
Authenticate a user from a token form field
def authenticate(self, request): """ Authenticate a user from a token form field Errors thrown here will be swallowed by django-rest-framework, and it expects us to return None if authentication fails. """ try: key = request.data['token'] except KeyEr...
Custom authentication to check if auth token has expired.
def authenticate_credentials(self, key): """Custom authentication to check if auth token has expired.""" user, token = super(TokenAuthentication, self).authenticate_credentials(key) if token.expires < timezone.now(): msg = _('Token has expired.') raise exceptions.Authent...
Displays bokeh output inside a notebook.
def notebook_show(obj, doc, comm): """ Displays bokeh output inside a notebook. """ target = obj.ref['id'] load_mime = 'application/vnd.holoviews_load.v0+json' exec_mime = 'application/vnd.holoviews_exec.v0+json' # Publish plot HTML bokeh_script, bokeh_div, _ = bokeh.embed.notebook.note...
Temporary fix to patch HoloViews plot comms
def process_hv_plots(widgets, plots): """ Temporary fix to patch HoloViews plot comms """ bokeh_plots = [] for plot in plots: if hasattr(plot, '_update_callbacks'): for subplot in plot.traverse(lambda x: x): subplot.comm = widgets.server_comm for c...
Returns a CustomJS callback that can be attached to send the widget state across the notebook comms.
def _get_customjs(self, change, p_name): """ Returns a CustomJS callback that can be attached to send the widget state across the notebook comms. """ data_template = "data = {{p_name: '{p_name}', value: cb_obj['{change}']}};" fetch_data = data_template.format(change=chang...
Get widget for param_name
def widget(self, param_name): """Get widget for param_name""" if param_name not in self._widgets: self._widgets[param_name] = self._make_widget(param_name) return self._widgets[param_name]
Return name widget boxes for all parameters ( i. e. a property sheet )
def widgets(self): """Return name,widget boxes for all parameters (i.e., a property sheet)""" params = self.parameterized.params().items() key_fn = lambda x: x[1].precedence if x[1].precedence is not None else self.p.default_precedence sorted_precedence = sorted(params, key=key_fn) ...
The default Renderer function which handles HoloViews objects.
def render_function(obj, view): """ The default Renderer function which handles HoloViews objects. """ try: import holoviews as hv except: hv = None if hv and isinstance(obj, hv.core.Dimensioned): renderer = hv.renderer('bokeh') if not view._notebook: ...
Forces a parameter value to be text
def TextWidget(*args, **kw): """Forces a parameter value to be text""" kw['value'] = str(kw['value']) kw.pop('options', None) return TextInput(*args,**kw)
Given a list of objects returns a dictionary mapping from string name for the object to the object itself.
def named_objs(objlist): """ Given a list of objects, returns a dictionary mapping from string name for the object to the object itself. """ objs = [] for k, obj in objlist: if hasattr(k, '__name__'): k = k.__name__ else: k = as_unicode(k) objs.app...
Returns the instance owning the supplied instancemethod or the class owning the supplied classmethod.
def get_method_owner(meth): """ Returns the instance owning the supplied instancemethod or the class owning the supplied classmethod. """ if inspect.ismethod(meth): if sys.version_info < (3,0): return meth.im_class if meth.im_self is None else meth.im_self else: ...
Take the http_auth value and split it into the attributes that carry the http auth username and password
def _assign_auth_values(self, http_auth): """Take the http_auth value and split it into the attributes that carry the http auth username and password :param str|tuple http_auth: The http auth value """ if not http_auth: pass elif isinstance(http_auth, (tuple...
Returns True if the cluster is up False otherwise.
def ping(self, params=None): """ Returns True if the cluster is up, False otherwise. """ try: self.transport.perform_request('HEAD', '/', params=params) except TransportError: raise gen.Return(False) raise gen.Return(True)
Get the basic info from the current cluster.
def info(self, params=None): """Get the basic info from the current cluster. :rtype: dict """ _, data = yield self.transport.perform_request('GET', '/', params=params) raise gen.Return(data)
Coroutine. Queries cluster Health API.
def health(self, params=None): """Coroutine. Queries cluster Health API. Returns a 2-tuple, where first element is request status, and second element is a dictionary with response data. :param params: dictionary of query parameters, will be handed over to the underlying :cl...
Adds a typed JSON document in a specific index making it searchable. Behind the scenes this method calls index (... op_type = create ) <http:// elasticsearch. org/ guide/ reference/ api/ index_/ > _
def create(self, index, doc_type, body, id=None, params=None): """ Adds a typed JSON document in a specific index, making it searchable. Behind the scenes this method calls index(..., op_type='create') `<http://elasticsearch.org/guide/reference/api/index_/>`_ :arg index: The nam...
Adds or updates a typed JSON document in a specific index making it searchable. <http:// elasticsearch. org/ guide/ reference/ api/ index_/ > _
def index(self, index, doc_type, body, id=None, params=None): """ Adds or updates a typed JSON document in a specific index, making it searchable. `<http://elasticsearch.org/guide/reference/api/index_/>`_ :arg index: The name of the index :arg doc_type: The type of the document ...
Returns a boolean indicating whether or not given document exists in Elasticsearch. <http:// elasticsearch. org/ guide/ reference/ api/ get/ > _
def exists(self, index, id, doc_type='_all', params=None): """ Returns a boolean indicating whether or not given document exists in Elasticsearch. `<http://elasticsearch.org/guide/reference/api/get/>`_ :arg index: The name of the index :arg id: The document ID :arg doc_t...
Retrieve a specified alias. <http:// www. elastic. co/ guide/ en/ elasticsearch/ reference/ current/ indices - aliases. html > _: arg index: A comma - separated list of index names to filter aliases: arg name: A comma - separated list of alias names to return: arg allow_no_indices: Whether to ignore if a wildcard indic...
def get_alias(self, index=None, name=None, params=None): """ Retrieve a specified alias. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_ :arg index: A comma-separated list of index names to filter aliases :arg name: A comma-separated list ...
Execute a search query and get back search hits that match the query. <http:// www. elasticsearch. org/ guide/ reference/ api/ search/ > _
def search(self, index=None, doc_type=None, body=None, params=None): """ Execute a search query and get back search hits that match the query. `<http://www.elasticsearch.org/guide/reference/api/search/>`_ :arg index: A comma-separated list of index names to search; use `_all` ...
Scroll a search request created by specifying the scroll parameter. <http:// www. elasticsearch. org/ guide/ reference/ api/ search/ scroll/ > _
def scroll(self, scroll_id, scroll, params=None): """ Scroll a search request created by specifying the scroll parameter. `<http://www.elasticsearch.org/guide/reference/api/search/scroll/>`_ :arg scroll_id: The scroll ID :arg scroll: Specify how long a consistent view of the ind...
Clear the scroll request created by specifying the scroll parameter to search. <http:// www. elasticsearch. org/ guide/ reference/ api/ search/ scroll/ > _
def clear_scroll(self, scroll_id, params=None): """ Clear the scroll request created by specifying the scroll parameter to search. `<http://www.elasticsearch.org/guide/reference/api/search/scroll/>`_ :arg scroll_id: The scroll ID or a list of scroll IDs """ if no...
Retrieve mapping definition of index or index/ type. <http:// www. elastic. co/ guide/ en/ elasticsearch/ reference/ current/ indices - get - mapping. html > _: arg index: A comma - separated list of index names: arg doc_type: A comma - separated list of document types: arg allow_no_indices: Whether to ignore if a wild...
def get_mapping(self, index=None, doc_type=None, params=None): """ Retrieve mapping definition of index or index/type. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html>`_ :arg index: A comma-separated list of index names :arg doc_type: A c...
The suggest feature suggests similar looking terms based on a provided text by using a suggester. <http:// elasticsearch. org/ guide/ reference/ api/ search/ suggest/ > _
def suggest(self, index=None, body=None, params=None): """ The suggest feature suggests similar looking terms based on a provided text by using a suggester. `<http://elasticsearch.org/guide/reference/api/search/suggest/>`_ :arg index: A comma-separated list of index names to res...
Converts bytes to a human readable format
def bytes_to_readable(num): """Converts bytes to a human readable format""" if num < 512: return "0 Kb" elif num < 1024: return "1 Kb" for unit in ['', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb']: if abs(num) < 1024.0: return "%...
Total CPU load for Synology DSM
def cpu_total_load(self): """Total CPU load for Synology DSM""" system_load = self.cpu_system_load user_load = self.cpu_user_load other_load = self.cpu_other_load if system_load is not None and \ user_load is not None and \ other_load is not None: ...
Total Memory Size of Synology DSM
def memory_size(self, human_readable=True): """Total Memory Size of Synology DSM""" if self._data is not None: # Memory is actually returned in KB's so multiply before converting return_data = int(self._data["memory"]["memory_size"]) * 1024 if human_readable: ...
Function to get specific network ( eth0 total etc )
def _get_network(self, network_id): """Function to get specific network (eth0, total, etc)""" if self._data is not None: for network in self._data["network"]: if network["device"] == network_id: return network
Total upload speed being used
def network_up(self, human_readable=True): """Total upload speed being used""" network = self._get_network("total") if network is not None: return_data = int(network["tx"]) if human_readable: return SynoFormatHelper.bytes_to_readable( ...
Returns all available volumes
def volumes(self): """Returns all available volumes""" if self._data is not None: volumes = [] for volume in self._data["volumes"]: volumes.append(volume["id"]) return volumes
Returns a specific volume
def _get_volume(self, volume_id): """Returns a specific volume""" if self._data is not None: for volume in self._data["volumes"]: if volume["id"] == volume_id: return volume
Total size of volume
def volume_size_total(self, volume, human_readable=True): """Total size of volume""" volume = self._get_volume(volume) if volume is not None: return_data = int(volume["size"]["total"]) if human_readable: return SynoFormatHelper.bytes_to_readable( ...
Total used size in percentage for volume
def volume_percentage_used(self, volume): """Total used size in percentage for volume""" volume = self._get_volume(volume) if volume is not None: total = int(volume["size"]["total"]) used = int(volume["size"]["used"]) if used is not None and used > 0 a...
Average temperature of all disks making up the volume
def volume_disk_temp_avg(self, volume): """Average temperature of all disks making up the volume""" volume = self._get_volume(volume) if volume is not None: vol_disks = volume["disks"] if vol_disks is not None: total_temp = 0 total_d...
Maximum temperature of all disks making up the volume
def volume_disk_temp_max(self, volume): """Maximum temperature of all disks making up the volume""" volume = self._get_volume(volume) if volume is not None: vol_disks = volume["disks"] if vol_disks is not None: max_temp = 0 for vol...
Returns all available ( internal ) disks
def disks(self): """Returns all available (internal) disks""" if self._data is not None: disks = [] for disk in self._data["disks"]: disks.append(disk["id"]) return disks
Returns a specific disk
def _get_disk(self, disk_id): """Returns a specific disk""" if self._data is not None: for disk in self._data["disks"]: if disk["id"] == disk_id: return disk
Build and execute login request
def _login(self): """Build and execute login request""" api_path = "%s/auth.cgi?api=SYNO.API.Auth&version=2" % ( self.base_url, ) login_path = "method=login&%s" % (self._encode_credentials()) url = "%s&%s&session=Core&format=cookie" % ( api_path...
Function to handle sessions for a GET request
def _get_url(self, url, retry_on_error=True): """Function to handle sessions for a GET request""" # Check if we failed to request the url or need to login if self.access_token is None or \ self._session is None or \ self._session_error: # Clear Access Toke...
Function to execute and handle a GET request
def _execute_get_url(self, request_url, append_sid=True): """Function to execute and handle a GET request""" # Prepare Request self._debuglog("Requesting URL: '" + request_url + "'") if append_sid: self._debuglog("Appending access_token (SID: " + ...
Updates the various instanced modules
def update(self): """Updates the various instanced modules""" if self._utilisation is not None: api = "SYNO.Core.System.Utilization" url = "%s/entry.cgi?api=%s&version=1&method=get&_sid=%s" % ( self.base_url, api, self.access...
Getter for various Utilisation variables
def utilisation(self): """Getter for various Utilisation variables""" if self._utilisation is None: api = "SYNO.Core.System.Utilization" url = "%s/entry.cgi?api=%s&version=1&method=get" % ( self.base_url, api) self._utilisation =...
Getter for various Storage variables
def storage(self): """Getter for various Storage variables""" if self._storage is None: api = "SYNO.Storage.CGI.Storage" url = "%s/entry.cgi?api=%s&version=1&method=load_info" % ( self.base_url, api) self._storage = SynoStorage(s...
Creates the context for a specific request.
def for_request(request, body=None): """Creates the context for a specific request.""" tenant, jwt_data = Tenant.objects.for_request(request, body) webhook_sender_id = jwt_data.get('sub') sender_data = None if body and 'item' in body: if 'sender' in body['item']: ...
The cached token of the current tenant.
def tenant_token(self): """The cached token of the current tenant.""" rv = getattr(self, '_tenant_token', None) if rv is None: rv = self._tenant_token = self.tenant.get_token() return rv
Helper function for building an attribute dictionary.
def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs
Class decorator that makes sure the passed apps are present in INSTALLED_APPS.
def with_apps(*apps): """ Class decorator that makes sure the passed apps are present in INSTALLED_APPS. """ apps_set = set(settings.INSTALLED_APPS) apps_set.update(apps) return override_settings(INSTALLED_APPS=list(apps_set))
Class decorator that makes sure the passed apps are not present in INSTALLED_APPS.
def without_apps(*apps): """ Class decorator that makes sure the passed apps are not present in INSTALLED_APPS. """ apps_list = [a for a in settings.INSTALLED_APPS if a not in apps] return override_settings(INSTALLED_APPS=apps_list)
Return a dictionary of all global_settings values.
def get_global_settings(self): """ Return a dictionary of all global_settings values. """ return dict((key, getattr(global_settings, key)) for key in dir(global_settings) if key.isupper())
Handle the retrieval of the code
def do_GET(self): """ Handle the retrieval of the code """ parsed_url = urlparse(self.path) if parsed_url[2] == "/" + SERVER_REDIRECT_PATH: # 2 = Path parsed_query = parse_qs(parsed_url[4]) # 4 = Query if "code" not in parsed_query: self.send_response(200) self.send_header("Content-Type", "t...
Set the app info ( id & secret ) read from the config file on the Reddit object
def _set_app_info(self): """ Set the app info (id & secret) read from the config file on the Reddit object """ redirect_url = "http://{0}:{1}/{2}".format(SERVER_URL, SERVER_PORT, SERVER_REDIRECT_PATH) self.r.set_oauth_app_info(self._get_value(CONFIGKEY_APP_KEY), self._get_value(CONFIG...
Helper method to get a value from the config
def _get_value(self, key, func=None, split_val=None, as_boolean=False, exception_default=None): """ Helper method to get a value from the config """ try: if as_boolean: return self.config.getboolean(key[0], key[1]) value = self.config.get(key[0], key[1]) if split_val is not None: value = valu...
Change the value of the given key in the given file to the given value
def _change_value(self, key, value): """ Change the value of the given key in the given file to the given value """ if not self.config.has_section(key[0]): self.config.add_section(key[0]) self.config.set(key[0], key[1], str(value)) with open(self.configfile, "w") as f: self.config.write(f)
Migrates the old config file format to the new one
def _migrate_config(self, oldname=DEFAULT_CONFIG, newname=DEFAULT_CONFIG): """ Migrates the old config file format to the new one """ self._log("Your OAuth2Util config file is in an old format and needs " "to be changed. I tried as best as I could to migrate it.", logging.WARNING) with open(oldname, "r")...
Start the webserver that will receive the code
def _start_webserver(self, authorize_url=None): """ Start the webserver that will receive the code """ server_address = (SERVER_URL, SERVER_PORT) self.server = HTTPServer(server_address, OAuth2UtilRequestHandler) self.server.response_code = None self.server.authorize_url = authorize_url t = Thread(targe...
Wait until the user accepted or rejected the request
def _wait_for_response(self): """ Wait until the user accepted or rejected the request """ while not self.server.response_code: time.sleep(2) time.sleep(5) self.server.shutdown()
Request new access information from reddit using the built in webserver
def _get_new_access_information(self): """ Request new access information from reddit using the built in webserver """ if not self.r.has_oauth_app_info: self._log('Cannot obtain authorize url from PRAW. Please check your configuration.', logging.ERROR) raise AttributeError('Reddit Session invalid, please ...
Check whether the tokens are set and request new ones if not
def _check_token_present(self): """ Check whether the tokens are set and request new ones if not """ try: self._get_value(CONFIGKEY_TOKEN) self._get_value(CONFIGKEY_REFRESH_TOKEN) self._get_value(CONFIGKEY_REFRESHABLE) except KeyError: self._log("Request new Token (CTP)") self._get_new_access_i...
Set the token on the Reddit Object again
def set_access_credentials(self, _retry=0): """ Set the token on the Reddit Object again """ if _retry >= 5: raise ConnectionAbortedError('Reddit is not accessible right now, cannot refresh OAuth2 tokens.') self._check_token_present() try: self.r.set_access_credentials(self._get_value(CONFIGKEY_SCOP...
Check if the token is still valid and requests a new if it is not valid anymore
def refresh(self, force=False, _retry=0): """ Check if the token is still valid and requests a new if it is not valid anymore Call this method before a call to praw if there might have passed more than one hour force: if true, a new token will be retrieved no matter what """ if _retry >= 5: raise C...
Create DynamoDB table for run manifests
def create_manifest_table(dynamodb_client, table_name): """Create DynamoDB table for run manifests Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name """ try: dynamodb_client.create_table( AttributeDefinition...
Return list of all run ids inside S3 folder. It does not respect S3 pagination ( MaxKeys ) and returns ** all ** keys from bucket and won t list any prefixes with object archived to AWS Glacier
def list_runids(s3_client, full_path): """Return list of all run ids inside S3 folder. It does not respect S3 pagination (`MaxKeys`) and returns **all** keys from bucket and won't list any prefixes with object archived to AWS Glacier Arguments: s3_client - boto3 S3 client (not service) full_pat...
Return pair of bucket without protocol and path
def split_full_path(path): """Return pair of bucket without protocol and path Arguments: path - valid S3 path, such as s3://somebucket/events >>> split_full_path('s3://mybucket/path-to-events') ('mybucket', 'path-to-events/') >>> split_full_path('s3://mybucket') ('mybucket', None) >>> ...
Check if prefix is archived in Glacier by checking storage class of first object inside that prefix
def is_glacier(s3_client, bucket, prefix): """Check if prefix is archived in Glacier, by checking storage class of first object inside that prefix Arguments: s3_client - boto3 S3 client (not service) bucket - valid extracted bucket (without protocol and prefix) example: sowplow-events-...
Extract date part from run id
def extract_run_id(key): """Extract date part from run id Arguments: key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/ (trailing slash is required) >>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/') 'shredded-archive/run=2012-12-11-01-11-33/' >>> ext...
Remove all keys with Nones as values
def clean_dict(dict): """Remove all keys with Nones as values >>> clean_dict({'key': None}) {} >>> clean_dict({'empty_s': ''}) {'empty_s': ''} """ if sys.version_info[0] < 3: return {k: v for k, v in dict.iteritems() if v is not None} else: return {k: v for k, v in dict....
Add run_id into DynamoDB manifest table
def add_to_manifest(dynamodb_client, table_name, run_id): """Add run_id into DynamoDB manifest table Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name run_id - string representing run_id to store """ dynamodb_client.put_ite...
Check if run_id is stored in DynamoDB table. Return True if run_id is stored or False otherwise.
def is_in_manifest(dynamodb_client, table_name, run_id): """Check if run_id is stored in DynamoDB table. Return True if run_id is stored or False otherwise. Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name run_id - string repr...
Extracts Schema information from Iglu URI
def extract_schema(uri): """ Extracts Schema information from Iglu URI >>> extract_schema("iglu:com.acme-corporation_underscore/event_name-dash/jsonschema/1-10-1")['vendor'] 'com.acme-corporation_underscore' """ match = re.match(SCHEMA_URI_REGEX, uri) if match: return { ...
Create an Elasticsearch field name from a schema string
def fix_schema(prefix, schema): """ Create an Elasticsearch field name from a schema string """ schema_dict = extract_schema(schema) snake_case_organization = schema_dict['vendor'].replace('.', '_').lower() snake_case_name = re.sub('([^A-Z_])([A-Z])', '\g<1>_\g<2>', schema_dict['name']).lower() ...
Convert a contexts JSON to an Elasticsearch - compatible list of key - value pairs For example the JSON
def parse_contexts(contexts): """ Convert a contexts JSON to an Elasticsearch-compatible list of key-value pairs For example, the JSON { "data": [ { "data": { "unique": true }, "schema": "iglu:com.acme/unduplicated/jsonschema/1-0-0" }, ...
Convert an unstructured event JSON to a list containing one Elasticsearch - compatible key - value pair For example the JSON
def parse_unstruct(unstruct): """ Convert an unstructured event JSON to a list containing one Elasticsearch-compatible key-value pair For example, the JSON { "data": { "data": { "key": "value" }, "schema": "iglu:com.snowplowanalytics.snowplow/link_click/jsonschem...
Convert a Snowplow enriched event TSV into a JSON
def transform(line, known_fields=ENRICHED_EVENT_FIELD_TYPES, add_geolocation_data=True): """ Convert a Snowplow enriched event TSV into a JSON """ return jsonify_good_event(line.split('\t'), known_fields, add_geolocation_data)
Convert a Snowplow enriched event in the form of an array of fields into a JSON
def jsonify_good_event(event, known_fields=ENRICHED_EVENT_FIELD_TYPES, add_geolocation_data=True): """ Convert a Snowplow enriched event in the form of an array of fields into a JSON """ if len(event) != len(known_fields): raise SnowplowEventTransformationException( ["Expected {} fie...
Extract the used view from the TemplateResponse context ( ContextMixin )
def _get_view_data(self, context_data): """ Extract the used view from the TemplateResponse context (ContextMixin) """ view = context_data.get('view') if not isinstance(view, View): view = None # Denote interesting objects in the template context temp...
Get the template used in a TemplateResponse. This returns a tuple of active choice all choices
def get_used_template(response): """ Get the template used in a TemplateResponse. This returns a tuple of "active choice, all choices" """ if not hasattr(response, 'template_name'): return None, None template = response.template_name if template is None: return None, None ...
Print the entire template context
def print_context(self, context): """ Print the entire template context """ text = [CONTEXT_TITLE] for i, context_scope in enumerate(context): dump1 = linebreaksbr(pformat_django_context_html(context_scope)) dump2 = pformat_dict_summary_html(context_scope)...
Print a set of variables
def print_variables(self, context): """ Print a set of variables """ text = [] for name, expr in self.variables: # Some extended resolving, to handle unknown variables data = '' try: if isinstance(expr.var, Variable): ...
Highlight common SQL words in a string.
def pformat_sql_html(sql): """ Highlight common SQL words in a string. """ sql = escape(sql) sql = RE_SQL_NL.sub(u'<br>\n\\1', sql) sql = RE_SQL.sub(u'<strong>\\1</strong>', sql) return sql
Dump a variable to a HTML string with sensible output for template context fields. It filters out all fields which are not usable in a template context.
def pformat_django_context_html(object): """ Dump a variable to a HTML string with sensible output for template context fields. It filters out all fields which are not usable in a template context. """ if isinstance(object, QuerySet): text = '' lineno = 0 for item in object.a...
Briefly print the dictionary keys.
def pformat_dict_summary_html(dict): """ Briefly print the dictionary keys. """ if not dict: return ' {}' html = [] for key, value in sorted(six.iteritems(dict)): if not isinstance(value, DICT_EXPANDED_TYPES): value = '...' html.append(_format_dict_item(ke...
Apply some HTML highlighting to the contents. This can t be done in the
def _style_text(text): """ Apply some HTML highlighting to the contents. This can't be done in the """ # Escape text and apply some formatting. # To have really good highlighting, pprint would have to be re-implemented. text = escape(text) text = text.replace(' &lt;iterator object&gt;', ...
# Instead of just printing <SomeType at 0xfoobar > expand the fields.
def _format_object(object): """ # Instead of just printing <SomeType at 0xfoobar>, expand the fields. """ attrs = iter(object.__dict__.items()) if object.__class__: # Add class members too. attrs = chain(attrs, iter(object.__class__.__dict__.items())) # Remove private and prote...
Expand a _ ( TEST ) call to something meaningful.
def _format_lazy(value): """ Expand a _("TEST") call to something meaningful. """ args = value._proxy____args kw = value._proxy____kw if not kw and len(args) == 1 and isinstance(args[0], six.string_types): # Found one of the Xgettext_lazy() calls. return LiteralStr(u'ugettext_laz...
Call a method but: param func:: type func:: param extra_exceptions:: type extra_exceptions:: return:: rtype:
def _try_call(func, extra_exceptions=(), return_exceptions=False): """ Call a method, but :param func: :type func: :param extra_exceptions: :type extra_exceptions: :return: :rtype: """ try: return func() except HANDLED_EXCEPTIONS as e: if return_exceptions: ...
Format an item in the result. Could be a dictionary key value etc..
def format(self, object, context, maxlevels, level): """ Format an item in the result. Could be a dictionary key, value, etc.. """ try: return PrettyPrinter.format(self, object, context, maxlevels, level) except HANDLED_EXCEPTIONS as e: return _for...
Recursive part of the formatting
def _format(self, object, stream, indent, allowance, context, level): """ Recursive part of the formatting """ try: PrettyPrinter._format(self, object, stream, indent, allowance, context, level) except Exception as e: stream.write(_format_exception(e))