text
stringlengths
81
112k
Partial update of a document in named index. Partial updates are invoked via a call to save the document with 'update_fields'. These fields are passed to the as_search_document method so that it can build a partial document. NB we don't just call as_search_document and then stri...
Delete document from named index. def delete_search_document(self, *, index): """Delete document from named index.""" cache.delete(self.search_document_cache_key) get_client().delete(index=index, doc_type=self.search_doc_type, id=self.pk)
Create a new SearchQuery instance and execute a search against ES. def execute(cls, search, search_terms="", user=None, reference=None, save=True): """Create a new SearchQuery instance and execute a search against ES.""" warnings.warn( "Pending deprecation - please use `execute_search` func...
Save and return the object (for chaining). def save(self, **kwargs): """Save and return the object (for chaining).""" if self.search_terms is None: self.search_terms = "" super().save(**kwargs) return self
Return the query from:size tuple (0-based). def page_slice(self): """Return the query from:size tuple (0-based).""" return ( None if self.query is None else (self.query.get("from", 0), self.query.get("size", 10)) )
Sets the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param value: the value to set for the plugin setting :param namespace: The namespace. If not passed or None, the namespace will be inferred from the caller method. Normally, ...
Returns the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param namespace: The namespace. If not passed or None, the namespace will be inferred from the caller method. Normally, this should not be passed, since it suffices to let thi...
Reads the settings corresponding to the plugin from where the method is called. This function has to be called in the __init__ method of the plugin class. Settings are stored in a settings.json file in the plugin folder. Here is an eample of such a file: [ {"name":"mysetting", "label": "My set...
Delete search index. def do_index_command(self, index, **options): """Delete search index.""" if options["interactive"]: logger.warning("This will permanently delete the index '%s'.", index) if not self._confirm_action(): logger.warning( "Abor...
Create an index and apply mapping if appropriate. def create_index(index): """Create an index and apply mapping if appropriate.""" logger.info("Creating search index: '%s'", index) client = get_client() return client.indices.create(index=index, body=get_index_mapping(index))
Re-index every document in a named index. def update_index(index): """Re-index every document in a named index.""" logger.info("Updating search index: '%s'", index) client = get_client() responses = [] for model in get_index_models(index): logger.info("Updating search index model: '%s'", mo...
Delete index entirely (removes all documents and mapping). def delete_index(index): """Delete index entirely (removes all documents and mapping).""" logger.info("Deleting search index: '%s'", index) client = get_client() return client.indices.delete(index=index)
Remove all orphaned documents from an index. This function works by scanning the remote index, and in each returned batch of documents looking up whether they appear in the default index queryset. If they don't (they've been deleted, or no longer fit the qs filters) then they are deleted from the index...
Check whether a document should be pruned. This method uses the SearchDocumentManagerMixin.in_search_queryset method to determine whether a 'hit' (search document) should be pruned from an index, and if so it returns the hit as a Django object(id=hit_id). Args: hit: dict object the represents ...
Yield all documents of model type in an index. This function calls the elasticsearch.helpers.scan function, and yields all the documents in the index that match the doc_type produced by a specific Django model. Args: index: string, the name of the index to scan, must be a configured ...
Yield bulk api 'actions' from a collection of objects. The output from this method can be fed in to the bulk api helpers - each document returned by get_documents is decorated with the appropriate bulk api op_type. Args: objects: iterable (queryset, list, ...) of SearchDocumentMixin ...
Validate settings.SEARCH_SETTINGS. def _validate_config(strict=False): """Validate settings.SEARCH_SETTINGS.""" for index in settings.get_index_names(): _validate_mapping(index, strict=strict) for model in settings.get_index_models(index): _validate_model(model) if settings.get_...
Check that an index mapping JSON file exists. def _validate_mapping(index, strict=False): """Check that an index mapping JSON file exists.""" try: settings.get_index_mapping(index) except IOError: if strict: raise ImproperlyConfigured("Index '%s' has no mapping file." % index) ...
Check that a model configured for an index subclasses the required classes. def _validate_model(model): """Check that a model configured for an index subclasses the required classes.""" if not hasattr(model, "as_search_document"): raise ImproperlyConfigured("'%s' must implement `as_search_document`." %...
Connect up post_save, post_delete signals for models. def _connect_signals(): """Connect up post_save, post_delete signals for models.""" for index in settings.get_index_names(): for model in settings.get_index_models(index): _connect_model_signals(model)
Connect signals for a single model. def _connect_model_signals(model): """Connect signals for a single model.""" dispatch_uid = "%s.post_save" % model._meta.model_name logger.debug("Connecting search index model post_save signal: %s", dispatch_uid) signals.post_save.connect(_on_model_save, sender=model...
Update document in search index post_save. def _on_model_save(sender, **kwargs): """Update document in search index post_save.""" instance = kwargs.pop("instance") update_fields = kwargs.pop("update_fields") for index in instance.search_indexes: try: _update_search_index( ...
Remove documents from search indexes post_delete. def _on_model_delete(sender, **kwargs): """Remove documents from search indexes post_delete.""" instance = kwargs.pop("instance") for index in instance.search_indexes: try: _delete_from_search_index(instance=instance, index=index) ...
Wrapper around the instance manager method. def _in_search_queryset(*, instance, index) -> bool: """Wrapper around the instance manager method.""" try: return instance.__class__.objects.in_search_queryset(instance.id, index=index) except Exception: logger.exception("Error checking object in...
Process index / update search index update actions. def _update_search_index(*, instance, index, update_fields): """Process index / update search index update actions.""" if not _in_search_queryset(instance=instance, index=index): logger.debug( "Object (%r) is not in search queryset, ignori...
Remove a document from a search index. def _delete_from_search_index(*, instance, index): """Remove a document from a search index.""" pre_delete.send(sender=instance.__class__, instance=instance, index=index) if settings.auto_sync(instance): instance.delete_search_document(index=index)
Validate config and connect signals. def ready(self): """Validate config and connect signals.""" super(ElasticAppConfig, self).ready() _validate_config(settings.get_setting("strict_validation")) _connect_signals()
Return specific search setting from Django conf. def get_setting(key, *default): """Return specific search setting from Django conf.""" if default: return get_settings().get(key, default[0]) else: return get_settings()[key]
Return the JSON mapping file for an index. Mappings are stored as JSON files in the mappings subdirectory of this app. They must be saved as {{index}}.json. Args: index: string, the name of the index to look for. def get_index_mapping(index): """Return the JSON mapping file for an index. ...
Return the list of properties specified for a model in an index. def get_model_index_properties(instance, index): """Return the list of properties specified for a model in an index.""" mapping = get_index_mapping(index) doc_type = instance._meta.model_name.lower() return list(mapping["mappings"][doc_ty...
Return list of models configured for a named index. Args: index: string, the name of the index to look up. def get_index_models(index): """Return list of models configured for a named index. Args: index: string, the name of the index to look up. """ models = [] for app_model ...
Return list of all indexes in which a model is configured. A model may be configured to appear in multiple indexes. This function will return the names of the indexes as a list of strings. This is useful if you want to know which indexes need updating when a model is saved. Args: model: a ...
Return dict of index.doc_type: model. def get_document_models(): """Return dict of index.doc_type: model.""" mappings = {} for i in get_index_names(): for m in get_index_models(i): key = "%s.%s" % (i, m._meta.model_name) mappings[key] = m return mappings
Returns bool if auto_sync is on for the model (instance) def auto_sync(instance): """Returns bool if auto_sync is on for the model (instance)""" # this allows us to turn off sync temporarily - e.g. when doing bulk updates if not get_setting("auto_sync"): return False model_name = "{}.{}".format...
Returns an indented HTML pretty-print version of JSON. Take the event_payload JSON, indent it, order the keys and then present it as a <code> block. That's about as good as we can get until someone builds a custom syntax function. def pprint(data): """ Returns an indented HTML pretty-print version...
Adds a help menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the about menu is to be added. def addHelpMenu(menuName, parentMenuFunction=None): ''' Adds a help menu to the plugin menu. This method sh...
Adds an 'about...' menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the about menu is to be added def addAboutMenu(menuName, parentMenuFunction=None): ''' Adds an 'about...' menu to the plugin menu. ...
Show a dialog containing a given text, with a given title. The text accepts HTML syntax def showMessageDialog(title, text): ''' Show a dialog containing a given text, with a given title. The text accepts HTML syntax ''' dlg = QgsMessageOutput.createMessageOutput() dlg.setTitle(title) ...
Asks for a file or files, opening the corresponding dialog with the last path that was selected when this same function was invoked from the calling method. :param parent: The parent window :param msg: The message to use for the dialog title :param isSave: true if we are asking for file to save :pa...
Asks for a folder, opening the corresponding dialog with the last path that was selected when this same function was invoked from the calling method :param parent: The parent window :param msg: The message to use for the dialog title def askForFolder(parent, msg = None): ''' Asks for a folder, ope...
Executes a lengthy tasks in a separate thread and displays a waiting dialog if needed. Sets the cursor to wait cursor while the task is running. This function does not provide any support for progress indication :param func: The function to execute. :param message: The message to display in the wait ...
Context manager used to temporarily disable auto_sync. This is useful when performing bulk updates on objects - when you may not want to flood the indexing process. >>> with disable_search_updates(): ... for obj in model.objects.all(): ... obj.save() The function works by temporarily ...
Make a network request by calling QgsNetworkAccessManager. redirections argument is ignored and is here only for httplib2 compatibility. def request(self, url, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, blocking=True): """ Make a network req...
Trap the timeout. In Async mode requestTimedOut is called after replyFinished def requestTimedOut(self, reply): """Trap the timeout. In Async mode requestTimedOut is called after replyFinished""" # adapt http_call_result basing on receiving qgs timer timout signal self.exception_class = Request...
Handle SSL errors, logging them if debug is on and ignoring them if disable_ssl_certificate_validation is set. def sslErrors(self, ssl_errors): """ Handle SSL errors, logging them if debug is on and ignoring them if disable_ssl_certificate_validation is set. """ if ssl_e...
Handle request to cancel HTTP call def abort(self): """ Handle request to cancel HTTP call """ if (self.reply and self.reply.isRunning()): self.on_abort = True self.reply.abort()
Return all the loaded layers. Filters by name (optional) first and then type (optional) :param name: (optional) name of layer to return.. :param type: (optional) The QgsMapLayer type of layer to return. Accepts a single value or a list of them :return: List of loaded layers. If name given will return all l...
Add one or several layers to the QGIS session and layer registry. :param layer: The layer object or list with layers to add the QGIS layer registry and session. :param loadInLegend: True if this layer should be added to the legend. :return: The added layer def addLayer(layer, loadInLegend=True): """ ...
Tries to add a layer from layer object Same as the addLayer method, but it does not ask for CRS, regardless of current configuration in QGIS settings def addLayerNoCrsDialog(layer, loadInLegend=True): ''' Tries to add a layer from layer object Same as the addLayer method, but it does not ask for CR...
Creates a new vector layer :param filename: The filename to store the file. The extensions determines the type of file. If extension is not among the supported ones, a shapefile will be created and the file will get an added '.shp' to its path. If the filename is None, a memory layer will be created ...
Returns the layer from the current project with the passed name Raises WrongLayerNameException if no layer with that name is found If several layers with that name exist, only the first one is returned def layerFromName(name): ''' Returns the layer from the current project with the passed name Rais...
Returns the layer from the current project with the passed source Raises WrongLayerSourceException if no layer with that source is found def layerFromSource(source): ''' Returns the layer from the current project with the passed source Raises WrongLayerSourceException if no layer with that source is fo...
Tries to load a layer from the given file :param filename: the path to the file to load. :param name: the name to use for adding the layer to the current project. If not passed or None, it will use the filename basename def loadLayer(filename, name = None, provider=None): ''' Tries to load a laye...
Tries to load a layer from the given file Same as the loadLayer method, but it does not ask for CRS, regardless of current configuration in QGIS settings def loadLayerNoCrsDialog(filename, name=None, provider=None): ''' Tries to load a layer from the given file Same as the loadLayer method, but it ...
Adds a 'open settings...' menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the settings menu is to be added :param parentMenuFunction: a function from QgisInterface to indicate where to put the container plug...
Opens a dialog to enter parameters. Parameters are passed as a list of Parameter objects Returns a dict with param names as keys and param values as values Returns None if the dialog was cancelled def openParametersDialog(params, title=None): ''' Opens a dialog to enter parameters. Parameters a...
Rebuild search index. def do_index_command(self, index, **options): """Rebuild search index.""" if options["interactive"]: logger.warning("This will permanently delete the index '%s'.", index) if not self._confirm_action(): logger.warning( "Ab...
Run do_index_command on each specified index and log the output. def handle(self, *args, **options): """Run do_index_command on each specified index and log the output.""" for index in options.pop("indexes"): data = {} try: data = self.do_index_command(index, **o...
Creates a template. :param Name: Name of template :param Subject: The content to use for the Subject when this template is used to send email. :param HtmlBody: The content to use for the HtmlBody when this template is used to send email. :param TextBody: The content to use for the HtmlB...
Returns simple console logger. def get_logger(name, verbosity, stream): """ Returns simple console logger. """ logger = logging.getLogger(name) logger.setLevel( {0: DEFAULT_LOGGING_LEVEL, 1: logging.INFO, 2: logging.DEBUG}.get(min(2, verbosity), DEFAULT_LOGGING_LEVEL) ) logger.handl...
Helper method for instantiating PostmarkClient from dict-like objects. def from_config(cls, config, prefix="postmark_", is_uppercase=False): """ Helper method for instantiating PostmarkClient from dict-like objects. """ kwargs = {} for arg in get_args(cls): key = pre...
Split a container into n-sized chunks. def chunks(container, n): """ Split a container into n-sized chunks. """ for i in range(0, len(container), n): yield container[i : i + n]
Helper to iterate over remote data via count & offset pagination. def sizes(count, offset=0, max_chunk=500): """ Helper to iterate over remote data via count & offset pagination. """ if count is None: chunk = max_chunk while True: yield chunk, offset offset += ch...
Constructs appropriate exception from list of responses and raises it. def raise_for_response(self, responses): """ Constructs appropriate exception from list of responses and raises it. """ exception_messages = [self.client.format_exception_message(response) for response in responses] ...
Converts list to string with comma separated values. For string is no-op. def list_to_csv(value): """ Converts list to string with comma separated values. For string is no-op. """ if isinstance(value, (list, tuple, set)): value = ",".join(value) return value
Converts incoming attachment into dictionary. def prepare_attachments(attachment): """ Converts incoming attachment into dictionary. """ if isinstance(attachment, tuple): result = {"Name": attachment[0], "Content": attachment[1], "ContentType": attachment[2]} if len(attachment) == 4: ...
Additionally encodes headers. :return: def as_dict(self): """ Additionally encodes headers. :return: """ data = super(BaseEmail, self).as_dict() data["Headers"] = [{"Name": name, "Value": value} for name, value in data["Headers"].items()] for field in (...
Attaches given binary data. :param bytes content: Binary data to be attached. :param str filename: :return: None. def attach_binary(self, content, filename): """ Attaches given binary data. :param bytes content: Binary data to be attached. :param str filename: ...
Instantiates ``Email`` instance from ``MIMEText`` instance. :param message: ``email.mime.text.MIMEText`` instance. :param manager: :py:class:`EmailManager` instance. :return: :py:class:`Email` def from_mime(cls, message, manager): """ Instantiates ``Email`` instance from ``MIME...
Converts all available emails to dictionaries. :return: List of dictionaries. def as_dict(self, **extra): """ Converts all available emails to dictionaries. :return: List of dictionaries. """ return [self._construct_email(email, **extra) for email in self.emails]
Converts incoming data to properly structured dictionary. def _construct_email(self, email, **extra): """ Converts incoming data to properly structured dictionary. """ if isinstance(email, dict): email = Email(manager=self._manager, **email) elif isinstance(email, (M...
Sends email batch. :return: Information about sent emails. :rtype: `list` def send(self, **extra): """ Sends email batch. :return: Information about sent emails. :rtype: `list` """ emails = self.as_dict(**extra) responses = [self._manager._send_...
Sends a single email. :param message: :py:class:`Email` or ``email.mime.text.MIMEText`` instance. :param str From: The sender email address. :param To: Recipient's email address. Multiple recipients could be specified as a list or string with comma separated values. :...
Constructs :py:class:`Email` instance. :return: :py:class:`Email` def Email( self, From, To, Cc=None, Bcc=None, Subject=None, Tag=None, HtmlBody=None, TextBody=None, Metadata=None, ReplyTo=None, Headers=None, ...
Constructs :py:class:`EmailTemplate` instance. :return: :py:class:`EmailTemplate` def EmailTemplate( self, TemplateId, TemplateModel, From, To, TemplateAlias=None, Cc=None, Bcc=None, Subject=None, Tag=None, ReplyTo=None, ...
Activates the bounce instance and updates it with the latest data. :return: Activation status. :rtype: `str` def activate(self): """ Activates the bounce instance and updates it with the latest data. :return: Activation status. :rtype: `str` """ respons...
Returns many bounces. :param int count: Number of bounces to return per request. :param int offset: Number of bounces to skip. :param str type: Filter by type of bounce. :param bool inactive: Filter by emails that were deactivated by Postmark due to the bounce. :param str emailF...
Helper to support handy dictionaries merging on all Python versions. def update_kwargs(self, kwargs, count, offset): """ Helper to support handy dictionaries merging on all Python versions. """ kwargs.update({self.count_key: count, self.offset_key: offset}) return kwargs
Gets a brief overview of statistics for all of your outbound email. def overview(self, tag=None, fromdate=None, todate=None): """ Gets a brief overview of statistics for all of your outbound email. """ return self.call("GET", "/stats/outbound", tag=tag, fromdate=fromdate, todate=todate)
Gets a total count of emails you’ve sent out. def sends(self, tag=None, fromdate=None, todate=None): """ Gets a total count of emails you’ve sent out. """ return self.call("GET", "/stats/outbound/sends", tag=tag, fromdate=fromdate, todate=todate)
Gets total counts of emails you’ve sent out that have been returned as bounced. def bounces(self, tag=None, fromdate=None, todate=None): """ Gets total counts of emails you’ve sent out that have been returned as bounced. """ return self.call("GET", "/stats/outbound/bounces", tag=tag, fr...
Gets a total count of recipients who have marked your email as spam. def spam(self, tag=None, fromdate=None, todate=None): """ Gets a total count of recipients who have marked your email as spam. """ return self.call("GET", "/stats/outbound/spam", tag=tag, fromdate=fromdate, todate=toda...
Gets a total count of emails you’ve sent with open tracking or link tracking enabled. def tracked(self, tag=None, fromdate=None, todate=None): """ Gets a total count of emails you’ve sent with open tracking or link tracking enabled. """ return self.call("GET", "/stats/outbound/tracked",...
Gets total counts of recipients who opened your emails. This is only recorded when open tracking is enabled for that email. def opens(self, tag=None, fromdate=None, todate=None): """ Gets total counts of recipients who opened your emails. This is only recorded when open tracking is enab...
Gets an overview of the platforms used to open your emails. This is only recorded when open tracking is enabled for that email. def opens_platforms(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the platforms used to open your emails. This is only recorded when ope...
Gets an overview of the email clients used to open your emails. This is only recorded when open tracking is enabled for that email. def emailclients(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the email clients used to open your emails. This is only recorded whe...
Gets the length of time that recipients read emails along with counts for each time. This is only recorded when open tracking is enabled for that email. Read time tracking stops at 20 seconds, so any read times above that will appear in the 20s+ field. def readtimes(self, tag=None, fromdate=None, todat...
Gets total counts of unique links that were clicked. def clicks(self, tag=None, fromdate=None, todate=None): """ Gets total counts of unique links that were clicked. """ return self.call("GET", "/stats/outbound/clicks", tag=tag, fromdate=fromdate, todate=todate)
Gets an overview of the browsers used to open links in your emails. This is only recorded when Link Tracking is enabled for that email. def browserfamilies(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the browsers used to open links in your emails. This is only r...
Gets an overview of the browser platforms used to open your emails. This is only recorded when Link Tracking is enabled for that email. def clicks_platforms(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the browser platforms used to open your emails. This is only ...
Gets an overview of which part of the email links were clicked from (HTML or Text). This is only recorded when Link Tracking is enabled for that email. def location(self, tag=None, fromdate=None, todate=None): """ Gets an overview of which part of the email links were clicked from (HTML or Text...
Return the global line rate of the coverage report. If the `filename` file is given, return the line rate of the file. def line_rate(self, filename=None): """ Return the global line rate of the coverage report. If the `filename` file is given, return the line rate of the file. "...
Return the global branch rate of the coverage report. If the `filename` file is given, return the branch rate of the file. def branch_rate(self, filename=None): """ Return the global branch rate of the coverage report. If the `filename` file is given, return the branch rate of the file....
Return a list of uncovered line numbers for each of the missed statements found for the file `filename`. def missed_statements(self, filename): """ Return a list of uncovered line numbers for each of the missed statements found for the file `filename`. """ el = self._get...
Return a list of tuples `(lineno, status)` of all the lines found in the Cobertura report for the given file `filename` where `lineno` is the line number and `status` is coverage status of the line which can be either `True` (line hit) or `False` (line miss). def line_statuses(self, filename): ...
Return a list of extrapolated uncovered line numbers for the file `filename` according to `Cobertura.line_statuses`. def missed_lines(self, filename): """ Return a list of extrapolated uncovered line numbers for the file `filename` according to `Cobertura.line_statuses`. """ ...
Return a list of namedtuple `Line` for each line of code found in the source file with the given `filename`. def file_source(self, filename): """ Return a list of namedtuple `Line` for each line of code found in the source file with the given `filename`. """ lines = [] ...
Return the total number of uncovered statements for the file `filename`. If `filename` is not given, return the total number of uncovered statements for all files. def total_misses(self, filename=None): """ Return the total number of uncovered statements for the file `filename`....
Return the total number of covered statements for the file `filename`. If `filename` is not given, return the total number of covered statements for all files. def total_hits(self, filename=None): """ Return the total number of covered statements for the file `filename`. If `fil...
Return the total number of statements for the file `filename`. If `filename` is not given, return the total number of statements for all files. def total_statements(self, filename=None): """ Return the total number of statements for the file `filename`. If `filename` is not give...