text
stringlengths
81
112k
Boost a value if we should in _process_queries def _boosted_value(name, action, key, value, boost): """Boost a value if we should in _process_queries""" if boost is not None: # Note: Most queries use 'value' for the key name except # Match queries which use 'query'. So we have to do some ...
Return obj decorated with es_meta object def decorate_with_metadata(obj, result): """Return obj decorated with es_meta object""" # Create es_meta object with Elasticsearch metadata about this # search result obj.es_meta = Metadata( # Elasticsearch id id=result.get('_id', 0), # S...
OR and AND will create a new F, with the filters from both F objects combined with the connector `conn`. def _combine(self, other, conn='and'): """ OR and AND will create a new F, with the filters from both F objects combined with the connector `conn`. """ f = F() ...
Converts strings in a data structure to Python types It converts datetime-ish things to Python datetimes. Override if you want something different. :arg obj: Python datastructure :returns: Python datastructure with strings converted to Python types .. Note:: ...
Return a new S instance with query args combined with existing set in a must boolean query. :arg queries: instances of Q :arg kw: queries in the form of ``field__action=value`` There are three special flags you can use: * ``must=True``: Specifies that the queries and kw querie...
Return a new S instance with filter args combined with existing set with AND. :arg filters: this will be instances of F :arg kw: this will be in the form of ``field__action=value`` Examples: >>> s = S().filter(foo='bar') >>> s = S().filter(F(foo='bar')) >>> s =...
Return a new S instance with field boosts. ElasticUtils allows you to specify query-time field boosts with ``.boost()``. It takes a set of arguments where the keys are either field names or field name + ``__`` + field action. Examples:: q = (S().query(title='taco trucks', ...
Returns a new S instance with boosting query and demotion. You can demote documents that match query criteria:: q = (S().query(title='trucks') .demote(0.5, description__match='gross')) q = (S().query(title='trucks') .demote(0.5, Q(description__m...
Return a new S instance with raw facet args combined with existing set. def facet_raw(self, **kw): """ Return a new S instance with raw facet args combined with existing set. """ items = kw.items() if six.PY3: items = list(items) return self._...
Set suggestion options. :arg name: The name to use for the suggestions. :arg term: The term to suggest similar looking terms for. Additional keyword options: * ``field`` -- The field to base suggestions upon, defaults to _all Results will have a ``_suggestions`` property cont...
Return a new S instance with extra args combined with existing set. def extra(self, **kw): """ Return a new S instance with extra args combined with existing set. """ new = self._clone() actions = ['values_list', 'values_dict', 'order_by', 'query', ...
Builds the Elasticsearch search body represented by this S. Loop over self.steps to build the search body that will be sent to Elasticsearch. This returns a Python dict. If you want the JSON that actually gets sent, then pass the return value through :py:func:`elasticutils.utils.to_jso...
Return the portion of the query that controls highlighting. def _build_highlight(self, fields, options): """Return the portion of the query that controls highlighting.""" ret = {'fields': dict((f, {}) for f in fields), 'order': 'score'} ret.update(options) return ret
Takes a list of filters and returns ES JSON API :arg filters: list of F, (key, val) tuples, or dicts :returns: list of ES JSON API filters def _process_filters(self, filters): """Takes a list of filters and returns ES JSON API :arg filters: list of F, (key, val) tuples, or dicts ...
Takes a key/val pair and returns the Elasticsearch code for it def _process_query(self, query): """Takes a key/val pair and returns the Elasticsearch code for it""" key, val = query field_name, field_action = split_field_action(key) # Boost by name__action overrides boost by name. ...
Takes a list of queries and returns query clause value :arg queries: list of Q instances :returns: dict which is the query clause value def _process_queries(self, queries): """Takes a list of queries and returns query clause value :arg queries: list of Q instances :returns: ...
Perform the search, then convert that raw format into a SearchResults instance and return it. def _do_search(self): """ Perform the search, then convert that raw format into a SearchResults instance and return it. """ if self._results_cache is None: response ...
Returns the Elasticsearch object to use. :arg default_builder: The function that takes a bunch of arguments and generates a elasticsearch Elasticsearch object. .. Note:: If you desire special behavior regarding building the Elasticsearch object for this S...
Returns the list of indexes to act on. def get_indexes(self, default_indexes=DEFAULT_INDEXES): """Returns the list of indexes to act on.""" for action, value in reversed(self.steps): if action == 'indexes': return list(value) if self.type is not None: in...
Returns the list of doctypes to use. def get_doctypes(self, default_doctypes=DEFAULT_DOCTYPES): """Returns the list of doctypes to use.""" for action, value in reversed(self.steps): if action == 'doctypes': return list(value) if self.type is not None: re...
Build query and passes to Elasticsearch, then returns the raw format returned. def raw(self): """ Build query and passes to Elasticsearch, then returns the raw format returned. """ qs = self.build_search() es = self.get_es() index = self.get_indexes() ...
Returns an `Elasticsearch`. * If there's an s, then it returns that `Elasticsearch`. * If the es was provided in the constructor, then it returns that `Elasticsearch`. * Otherwise, it creates a new `Elasticsearch` and returns that. Override this if that behavior isn...
Build query and passes to `Elasticsearch`, then returns the raw format returned. def raw(self): """ Build query and passes to `Elasticsearch`, then returns the raw format returned. """ es = self.get_es() params = dict(self.query_params) mlt_fields = self...
Perform the mlt call, then convert that raw format into a SearchResults instance and return it. def _do_search(self): """ Perform the mlt call, then convert that raw format into a SearchResults instance and return it. """ if self._results_cache is None: respo...
Adds or updates a document to the index :arg document: Python dict of key/value pairs representing the document .. Note:: This must be serializable into JSON. :arg id_: the id of the document .. Note:: If you don't provide an ``id_`...
Adds or updates a batch of documents. :arg documents: List of Python dicts representing individual documents to be added to the index .. Note:: This must be serializable into JSON. :arg id_field: The name of the field to use as the document id. This...
Removes a particular item from the search index. :arg id_: The Elasticsearch id for the document to remove from the index. :arg es: The `Elasticsearch` to use. If you don't specify an `Elasticsearch`, it'll use `cls.get_es()`. :arg index: The name of the index to use. ...
Refreshes the index. Elasticsearch will update the index periodically automatically. If you need to see the documents you just indexed in your search results right now, you should call `refresh_index` as soon as you're done indexing. This is particularly helpful for unit tests. ...
Monkey patch for elasticsearch-py 1.0+ to make it work with ES 0.90 1. tweaks elasticsearch.client.bulk to normalize return status codes .. Note:: We can nix this whe we drop support for ES 0.90. def monkeypatch_es(): """Monkey patch for elasticsearch-py 1.0+ to make it work with ES 0.90 1. ...
Returns view context dictionary. :rtype: dict. def get_context_data(self, **kwargs): """ Returns view context dictionary. :rtype: dict. """ kwargs.update({ 'entries': Entry.objects.get_for_tag( self.kwargs.get('slug', 0) ) ...
Read the password from the file. def get_password(self, service, username): """ Read the password from the file. """ assoc = self._generate_assoc(service, username) service = escape_for_ini(service) username = escape_for_ini(username) # load the passwords from t...
Write the password in the file. def set_password(self, service, username, password): """Write the password in the file. """ if not username: # https://github.com/jaraco/keyrings.alt/issues/21 raise ValueError("Username cannot be blank.") if not isinstance(passwor...
Ensure the storage path exists. If it doesn't, create it with "go-rwx" permissions. def _ensure_file_path(self): """ Ensure the storage path exists. If it doesn't, create it with "go-rwx" permissions. """ storage_root = os.path.dirname(self.file_path) needs_stora...
Delete the password for the username of the service. def delete_password(self, service, username): """Delete the password for the username of the service. """ service = escape_for_ini(service) username = escape_for_ini(username) config = configparser.RawConfigParser() if...
Returns a list of model classes that subclass Page and include a "tags" field. :rtype: list. def applicable_models(self): """ Returns a list of model classes that subclass Page and include a "tags" field. :rtype: list. """ Page = apps.g...
Add edit handler that includes "related" panels to applicable model classes that don't explicitly define their own edit handler. def add_relationship_panels(self): """ Add edit handler that includes "related" panels to applicable model classes that don't explicitly define their own ...
Adds relationship methods to applicable model classes. def add_relationship_methods(self): """ Adds relationship methods to applicable model classes. """ Entry = apps.get_model('wagtailrelations', 'Entry') @cached_property def related(instance): retu...
Finalizes application configuration. def ready(self): """ Finalizes application configuration. """ import wagtailplus.wagtailrelations.signals.handlers self.add_relationship_panels() self.add_relationship_methods() super(WagtailRelationsAppConfig, self)....
Returns a list of model classes that subclass Page. :rtype: list. def applicable_models(self): """ Returns a list of model classes that subclass Page. :rtype: list. """ Page = apps.get_model('wagtailcore', 'Page') applicable = [] for...
Adds rollback panel to applicable model class's edit handlers. def add_rollback_panels(self): """ Adds rollback panel to applicable model class's edit handlers. """ from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler from wagtailplus.wagtailrollbacks.edit_...
Adds rollback methods to applicable model classes. def add_rollback_methods(): """ Adds rollback methods to applicable model classes. """ # Modified Page.save_revision method. def page_rollback(instance, revision_id, user=None, submitted_for_moderation=False, approved_go_li...
Finalizes application configuration. def ready(self): """ Finalizes application configuration. """ self.add_rollback_panels() self.add_rollback_methods() super(WagtailRollbacksAppConfig, self).ready()
Returns list of related Entry instances for specified page. :param page: the page instance. :rtype: list. def get_related(page): """ Returns list of related Entry instances for specified page. :param page: the page instance. :rtype: list. """ related = [] entry = Entry.get_for_m...
Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str. def get_related_entry_admin_url(entry): """ Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str. """ namespaces = { Document: 'wagtaildo...
Returns list of related tuples (Entry instance, score) for specified page. :param page: the page instance. :rtype: list. def get_related_with_scores(page): """ Returns list of related tuples (Entry instance, score) for specified page. :param page: the page instance. :rtype: list. ...
Get password of the username for the service def get_password(self, service, username): """Get password of the username for the service """ init_part = self._keyring.get_password(service, username) if init_part: parts = [init_part] i = 1 while True: ...
Set password for the username of the service def set_password(self, service, username, password): """Set password for the username of the service """ segments = range(0, len(password), self._max_password_size) password_parts = [ password[i:i + self._max_password_size] for i ...
Given a dictionary of attributes, find the corresponding link instance and return its HTML representation. :param attrs: dictionary of link attributes. :param for_editor: whether or not HTML is for editor. :rtype: str. def expand_db_attributes(attrs, for_editor): """ Gi...
The actual keyczar crypter def crypter(self): """The actual keyczar crypter""" if not hasattr(self, '_crypter'): # initialise the Keyczar keysets if not self.keyset_location: raise ValueError('No encrypted keyset location!') reader = keyczar.readers.C...
Index documents of a specified mapping type. This allows for asynchronous indexing. If a mapping_type extends Indexable, you can add a ``post_save`` hook for the model that it's based on like this:: @receiver(dbsignals.post_save, sender=MyModel) def update_in_index(sender, instance, **kw)...
Remove documents of a specified mapping_type from the index. This allows for asynchronous deleting. If a mapping_type extends Indexable, you can add a ``pre_delete`` hook for the model that it's based on like this:: @receiver(dbsignals.pre_delete, sender=MyModel) def remove_from_index(sen...
Returns specified link instance as JSON. :param link: the link instance. :rtype: JSON. def get_json(self, link): """ Returns specified link instance as JSON. :param link: the link instance. :rtype: JSON. """ return json.dumps({ 'id': ...
Create the cipher object to encrypt or decrypt a payload. def _create_cipher(self, password, salt, IV): """ Create the cipher object to encrypt or decrypt a payload. """ from Crypto.Protocol.KDF import PBKDF2 from Crypto.Cipher import AES pw = PBKDF2(password, salt, dkLe...
Initialize a new password file and set the reference password. def _init_file(self): """ Initialize a new password file and set the reference password. """ self.keyring_key = self._get_new_password() # set a reference password, used to check that the password provided # ...
Check if the file exists and has the expected password reference. def _check_file(self): """ Check if the file exists and has the expected password reference. """ if not os.path.exists(self.file_path): return False self._migrate() config = configparser.RawCon...
check for a valid version an existing scheme implies an existing version as well return True, if version is valid, and False otherwise def _check_version(self, config): """ check for a valid version an existing scheme implies an existing version as well return True, if...
Unlock this keyring by getting the password for the keyring from the user. def _unlock(self): """ Unlock this keyring by getting the password for the keyring from the user. """ self.keyring_key = getpass.getpass( 'Please enter password for encrypted keyring: ...
Single char escape. Return the char, escaped if not already legal def _escape_char(c): "Single char escape. Return the char, escaped if not already legal" if isinstance(c, int): c = _unichr(c) return c if c in LEGAL_CHARS else ESCAPE_FMT % ord(c)
Inverse of escape. def unescape(value): """ Inverse of escape. """ pattern = ESCAPE_FMT.replace('%02X', '(?P<code>[0-9A-Fa-f]{2})') # the pattern must be bytes to operate on bytes pattern_bytes = pattern.encode('ascii') re_esc = re.compile(pattern_bytes) return re_esc.sub(_unescape_code...
Get password of the username for the service def _find_passwords(self, service, username, deleting=False): """Get password of the username for the service """ passwords = [] service = self._safe_string(service) username = self._safe_string(username) for attrs_tuple in (...
Get password of the username for the service def get_password(self, service, username): """Get password of the username for the service """ items = self._find_passwords(service, username) if not items: return None secret = items[0].secret return ( ...
Set password for the username of the service def set_password(self, service, username, password): """Set password for the username of the service """ service = self._safe_string(service) username = self._safe_string(username) password = self._safe_string(password) attrs ...
Delete the password for the username of the service. def delete_password(self, service, username): """Delete the password for the username of the service. """ items = self._find_passwords(service, username, deleting=True) if not items: raise PasswordDeleteError("Password not...
Convert unicode to string as gnomekeyring barfs on unicode def _safe_string(self, source, encoding='utf-8'): """Convert unicode to string as gnomekeyring barfs on unicode""" if not isinstance(source, str): return source.encode(encoding) return str(source)
Returns context dictionary for view. :rtype: dict. def get_context_data(self, **kwargs): """ Returns context dictionary for view. :rtype: dict. """ kwargs.update({ 'view': self, 'email_form': EmailLinkForm(), 'exter...
Returns POST response. :param request: the request instance. :rtype: django.http.HttpResponse. def post(self, request, *args, **kwargs): """ Returns POST response. :param request: the request instance. :rtype: django.http.HttpResponse. """ form =...
Returns form class to use in the view. :rtype: django.forms.ModelForm. def get_form_class(self): """ Returns form class to use in the view. :rtype: django.forms.ModelForm. """ if self.object.link_type == Link.LINK_TYPE_EMAIL: return EmailLinkForm el...
Get password of the username for the service def get_password(self, service, username): """Get password of the username for the service """ try: # fetch the password key = self._key_for_service(service) hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) ...
Write the password to the registry def set_password(self, service, username, password): """Write the password to the registry """ # encrypt the password password_encrypted = _win_crypto.encrypt(password.encode('utf-8')) # encode with base64 password_base64 = base64.encod...
Delete the password for the username of the service. def delete_password(self, service, username): """Delete the password for the username of the service. """ try: key_name = self._key_for_service(service) hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, ...
Encrypt the password. def encrypt(self, password): """Encrypt the password. """ if not password or not self._crypter: return password or b'' return self._crypter.encrypt(password)
Decrypt the password. def decrypt(self, password_encrypted): """Decrypt the password. """ if not password_encrypted or not self._crypter: return password_encrypted or b'' return self._crypter.decrypt(password_encrypted)
Open the password file in the specified mode def _open(self, mode='r'): """Open the password file in the specified mode """ open_file = None writeable = 'w' in mode or 'a' in mode or '+' in mode try: # NOTE: currently the MemOpener does not split off any filename ...
load the passwords from the config file def config(self): """load the passwords from the config file """ if not hasattr(self, '_config'): raw_config = configparser.RawConfigParser() f = self._open() if f: raw_config.readfp(f) f...
Read the password from the file. def get_password(self, service, username): """Read the password from the file. """ service = escape_for_ini(service) username = escape_for_ini(username) # fetch the password try: password_base64 = self.config.get(service, use...
Write the password in the file. def set_password(self, service, username, password): """Write the password in the file. """ service = escape_for_ini(service) username = escape_for_ini(username) # encrypt the password password = password or '' password_encrypted ...
Returns queryset limited to categories with live Entry instances. :rtype: django.db.models.query.QuerySet. def get_queryset(self): """ Returns queryset limited to categories with live Entry instances. :rtype: django.db.models.query.QuerySet. """ queryset = super(LiveEn...
Returns tuple (Entry instance, created) for specified model instance. :rtype: wagtailplus.wagtailrelations.models.Entry. def get_for_model(self, model): """ Returns tuple (Entry instance, created) for specified model instance. :rtype: wagtailplus.wagtailrelations.model...
Returns queryset of Entry instances assigned to specified tag, which can be a PK value, a slug value, or a Tag instance. :param tag: tag PK, slug, or instance. :rtype: django.db.models.query.QuerySet. def get_for_tag(self, tag): """ Returns queryset of Entry instances assigned ...
Returns queryset of EntryTag instances for specified category. :param category: the Category instance. :param live_only: flag to include only "live" entries. :rtype: django.db.models.query.QuerySet. def for_category(self, category, live_only=False): """ Returns queryset of Entr...
Returns queryset of Entry instances related to specified Entry instance. :param entry: the Entry instance. :param live_only: flag to include only "live" entries. :rtype: django.db.models.query.QuerySet. def related_to(self, entry, live_only=False): """ Returns queryset ...
Returns a ChosenView class that extends specified chooser class. :param chooser_cls: the class to extend. :rtype: class. def chosen_view_factory(chooser_cls): """ Returns a ChosenView class that extends specified chooser class. :param chooser_cls: the class to extend. :rtype: class. """ ...
Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. def form_invalid(self, form): """ Processes an invalid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ context =...
Processes a valid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. def form_valid(self, form): """ Processes a valid form submittal. :param form: the form instance. :rtype: django.http.HttpResponse. """ #noinspection PyA...
Returns GET response. :param request: the request instance. :rtype: django.http.HttpResponse. def get(self, request, *args, **kwargs): """ Returns GET response. :param request: the request instance. :rtype: django.http.HttpResponse. """ #noinspection Py...
Returns the keyword arguments for instantiating the form. :rtype: dict. def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. :rtype: dict. """ kwargs = { 'initial': self.get_initial(), 'prefix': self.get_pr...
Creates EntryTag for Entry corresponding to specified ItemBase instance. :param sender: the sending ItemBase class. :param instance: the ItemBase instance. def create_entry_tag(sender, instance, created, **kwargs): """ Creates EntryTag for Entry corresponding to specified ItemBase instance. ...
Deletes EntryTag for Entry corresponding to specified TaggedItemBase instance. :param sender: the sending TaggedItemBase class. :param instance: the TaggedItemBase instance. def delete_entry_tag(sender, instance, **kwargs): """ Deletes EntryTag for Entry corresponding to specified TaggedItemBa...
Deletes Entry instance corresponding to specified instance. :param sender: the sending class. :param instance: the instance being deleted. def delete_entry(sender, instance, **kwargs): """ Deletes Entry instance corresponding to specified instance. :param sender: the sending class. :param ins...
Updates attributes for Entry instance corresponding to specified instance. :param sender: the sending class. :param instance: the instance being saved. def update_entry_attributes(sender, instance, **kwargs): """ Updates attributes for Entry instance corresponding to specified instance. :...
Returns paginated queryset of PageRevision instances for specified Page instance. :param page: the page instance. :param page_num: the pagination page number. :rtype: django.db.models.query.QuerySet. def get_revisions(page, page_num=1): """ Returns paginated queryset of PageRevision instances ...
Returns GET response for specified page revisions. :param request: the request instance. :param page_id: the page ID. :param template_name: the template name. :rtype: django.http.HttpResponse. def page_revisions(request, page_id, template_name='wagtailrollbacks/edit_handlers/revisions.html'): """ ...
Returns GET response for specified page preview. :param request: the request instance. :param reversion_pk: the page revision ID. :rtype: django.http.HttpResponse. def preview_page_version(request, revision_id): """ Returns GET response for specified page preview. :param request: the request ...
Handles page reversion process (GET and POST). :param request: the request instance. :param revision_id: the page revision ID. :param template_name: the template name. :rtype: django.http.HttpResponse. def confirm_page_reversion(request, revision_id, template_name='wagtailrollbacks/pages/confirm_rever...
Get password of the username for the service def get_password(self, service, username): """Get password of the username for the service """ result = self._get_entry(self._keyring, service, username) if result: result = self._decrypt(result) return result
Set password for the username of the service def set_password(self, service, username, password): """Set password for the username of the service """ password = self._encrypt(password or '') keyring_working_copy = copy.deepcopy(self._keyring) service_entries = keyring_working_co...
Helper to actually write the keyring to Google def _save_keyring(self, keyring_dict): """Helper to actually write the keyring to Google""" import gdata result = self.OK file_contents = base64.urlsafe_b64encode(pickle.dumps(keyring_dict)) try: if self.docs_entry: ...
Calculate the request token (`tk`) of a string :param text: str The text to calculate a token for :param seed: str The seed to use. By default this is the number of hours since epoch def calculate_token(self, text, seed=None): """ Calculate the request token (`tk`) of a string :param te...
Make HTTP request, raising an exception if it fails. def _request(method, url, session=None, **kwargs): """Make HTTP request, raising an exception if it fails. """ url = BASE_URL + url if session: request_func = getattr(session, method) else: request_func = getattr(requests, method...
Send a dweet to dweet.io def _send_dweet(payload, url, params=None, session=None): """Send a dweet to dweet.io """ data = json.dumps(payload) headers = {'Content-type': 'application/json'} return _request('post', url, data=data, headers=headers, params=params, session=session)