signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def doctypes(self, *doctypes):
return self._clone(next_step=('<STR_LIT>', doctypes))<EOL>
Return a new S instance that will search specified doctypes. .. Note:: Elasticsearch calls these "mapping types". It's the name associated with a mapping.
f12902:c9:m5
def explain(self, value=True):
return self._clone(next_step=('<STR_LIT>', value))<EOL>
Return a new S instance with explain set.
f12902:c9:m6
def values_list(self, *fields):
return self._clone(next_step=('<STR_LIT>', fields))<EOL>
Return a new S instance that returns ListSearchResults. :arg fields: the list of fields to have in the results. With no arguments, passes ``fields=*`` and returns values for any fields you have marked as "stored = True" for that mapping. With arguments, passes ...
f12902:c9:m7
def values_dict(self, *fields):
return self._clone(next_step=('<STR_LIT>', fields))<EOL>
Return a new S instance that returns DictSearchResults. :arg fields: the list of fields to have in the results. With no arguments, passes ``fields=*`` and returns values for any fields you have marked as "stored = True" for that mapping. With arguments, passes ...
f12902:c9:m8
def order_by(self, *fields):
return self._clone(next_step=('<STR_LIT>', fields))<EOL>
Return a new S instance with results ordered as specified You can change the order search results by specified fields:: q = (S().query(title='trucks') .order_by('title') This orders search results by the `title` field in ascending order. If you want to sort by descending order, prepend a ``-``:: ...
f12902:c9:m9
def query(self, *queries, **kw):
q = Q()<EOL>for query in queries:<EOL><INDENT>q += query<EOL><DEDENT>if '<STR_LIT>' in kw:<EOL><INDENT>or_query = kw.pop('<STR_LIT>')<EOL>or_query['<STR_LIT>'] = True<EOL>q += Q(**or_query)<EOL><DEDENT>q += Q(**kw)<EOL>return self._clone(next_step=('<STR_LIT>', q))<EOL>
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 queries **must match** in order for a docume...
f12902:c9:m10
def query_raw(self, query):
return self._clone(next_step=('<STR_LIT>', query))<EOL>
Return a new S instance with a query_raw. :arg query: Python dict specifying the complete query to send to Elasticsearch Example:: S().query_raw({'match': {'title': 'example'}}) .. Note:: If there's a query_raw in your S, then that's your query. All ``.query()``, ``.demote()``, ``.boost()`` and a...
f12902:c9:m11
def filter(self, *filters, **kw):
items = kw.items()<EOL>if six.PY3:<EOL><INDENT>items = list(items)<EOL><DEDENT>return self._clone(<EOL>next_step=('<STR_LIT>', list(filters) + items))<EOL>
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 = S().filter(foo='bar', bat='baz') >>> s = S().filter(foo...
f12902:c9:m12
def filter_raw(self, filter_):
return self._clone(next_step=('<STR_LIT>', filter_))<EOL>
Return a new S instance with a filter_raw. :arg filter_: Python dict specifying the complete filter to send to Elasticsearch Example:: S().filter_raw({'term': {'title': 'example'}}) .. Note:: If there's a filter_raw in your S, then that's your filter. All ``.filter()`` and anything else that affects...
f12902:c9:m13
def boost(self, **kw):
new = self._clone()<EOL>new.field_boosts.update(kw)<EOL>return new<EOL>
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', description__match='a...
f12902:c9:m14
def demote(self, amount_, *queries, **kw):
q = Q()<EOL>for query in queries:<EOL><INDENT>q += query<EOL><DEDENT>q += Q(**kw)<EOL>return self._clone(next_step=('<STR_LIT>', (amount_, q)))<EOL>
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__match='gross'))) This is implemented usi...
f12902:c9:m15
def facet(self, *args, **kw):
return self._clone(next_step=('<STR_LIT>', (args, kw)))<EOL>
Return a new S instance with facet args combined with existing set. :arg args: The list of facets to return. Additional keyword options: * ``size`` -- Maximum number of terms to return for each facet.
f12902:c9:m16
def facet_raw(self, **kw):
items = kw.items()<EOL>if six.PY3:<EOL><INDENT>items = list(items)<EOL><DEDENT>return self._clone(next_step=('<STR_LIT>', items))<EOL>
Return a new S instance with raw facet args combined with existing set.
f12902:c9:m17
def highlight(self, *fields, **kwargs):
return self._clone(next_step=('<STR_LIT>', (fields, kwargs)))<EOL>
Set highlight/excerpting with specified options. :arg fields: The list of fields to highlight. If the field is None, then the highlight is cleared. Additional keyword options: * ``pre_tags`` -- List of tags before highlighted portion * ``post_tags`` -- List of tags after h...
f12902:c9:m18
def search_type(self, search_type):
return self._clone(next_step=('<STR_LIT>', search_type))<EOL>
Set Elasticsearch search type for distributed search behaviour. :arg search_type: The search type to set. The search type affects how much results are fetched from each shard, and how are they then merged back. This can affect the accuracy of the results and the execution speed. ...
f12902:c9:m19
def suggest(self, name, term, **kwargs):
return self._clone(next_step=('<STR_LIT>', (name, term, kwargs)))<EOL>
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...
f12902:c9:m20
def extra(self, **kw):
new = self._clone()<EOL>actions = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']<EOL>for key, vals in kw.items():<EOL><INDENT>assert key in actions<EOL>if hasattr(vals, '<STR_LIT>'):<EOL><INDENT>new.steps.append((key, vals.items()))<EOL><DEDENT>else:<EOL><INDENT>new.steps.append((key...
Return a new S instance with extra args combined with existing set.
f12902:c9:m21
def __getitem__(self, k):
new = self._clone()<EOL>if isinstance(k, slice):<EOL><INDENT>new.start, new.stop = k.start or <NUM_LIT:0>, k.stop<EOL>return new<EOL><DEDENT>else:<EOL><INDENT>new.start, new.stop = k, k + <NUM_LIT:1><EOL>return list(new)[<NUM_LIT:0>]<EOL><DEDENT>
Handles slice and indexes for Elasticsearch results
f12902:c9:m22
def build_search(self):
filters = []<EOL>filters_raw = None<EOL>queries = []<EOL>query_raw = None<EOL>sort = []<EOL>dict_fields = set()<EOL>list_fields = set()<EOL>facets = {}<EOL>facets_raw = {}<EOL>demote = None<EOL>highlight_fields = set()<EOL>highlight_options = {}<EOL>suggestions = {}<EOL>explain = False<EOL>as_list = as_dict = False<EOL...
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...
f12902:c9:m23
def _build_highlight(self, fields, options):
ret = {'<STR_LIT>': dict((f, {}) for f in fields),<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>ret.update(options)<EOL>return ret<EOL>
Return the portion of the query that controls highlighting.
f12902:c9:m24
def _process_filters(self, filters):
rv = []<EOL>for f in filters:<EOL><INDENT>if isinstance(f, F):<EOL><INDENT>if f.filters:<EOL><INDENT>rv.extend(self._process_filters(f.filters))<EOL>continue<EOL><DEDENT><DEDENT>elif isinstance(f, dict):<EOL><INDENT>if six.PY3:<EOL><INDENT>key = list(f.keys())[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>key = f.keys()[<...
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
f12902:c9:m25
def _process_query(self, query):
key, val = query<EOL>field_name, field_action = split_field_action(key)<EOL>boost = self.field_boosts.get(key)<EOL>if boost is None:<EOL><INDENT>boost = self.field_boosts.get(field_name)<EOL><DEDENT>handler_name = '<STR_LIT>'.format(field_action)<EOL>if field_action and hasattr(self, handler_name):<EOL><INDENT>return g...
Takes a key/val pair and returns the Elasticsearch code for it
f12902:c9:m26
def _process_queries(self, queries):
<EOL>new_q = Q()<EOL>for query in queries:<EOL><INDENT>new_q += query<EOL><DEDENT>should_q = [self._process_query(query) for query in new_q.should_q]<EOL>must_q = [self._process_query(query) for query in new_q.must_q]<EOL>must_not_q = [self._process_query(query) for query in new_q.must_not_q]<EOL>if len(must_q) > <NUM_...
Takes a list of queries and returns query clause value :arg queries: list of Q instances :returns: dict which is the query clause value
f12902:c9:m27
def get_results_class(self):
if self.as_list:<EOL><INDENT>return ListSearchResults<EOL><DEDENT>elif self.as_dict:<EOL><INDENT>return DictSearchResults<EOL><DEDENT>else:<EOL><INDENT>return ObjectSearchResults<EOL><DEDENT>
Returns the results class to use The results class should be a subclass of SearchResults.
f12902:c9:m28
def _do_search(self):
if self._results_cache is None:<EOL><INDENT>response = self.raw()<EOL>ResultsClass = self.get_results_class()<EOL>results = self.to_python(response.get('<STR_LIT>', {}).get('<STR_LIT>', []))<EOL>self._results_cache = ResultsClass(<EOL>self.type, response, results, self.fields)<EOL><DEDENT>return self._results_cache<EOL...
Perform the search, then convert that raw format into a SearchResults instance and return it.
f12902:c9:m29
def get_es(self, default_builder=get_es):
<EOL>args = {}<EOL>for action, value in self.steps:<EOL><INDENT>if action == '<STR_LIT>':<EOL><INDENT>args.update(**value)<EOL><DEDENT><DEDENT>return default_builder(**args)<EOL>
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...
f12902:c9:m30
def get_indexes(self, default_indexes=DEFAULT_INDEXES):
for action, value in reversed(self.steps):<EOL><INDENT>if action == '<STR_LIT>':<EOL><INDENT>return list(value)<EOL><DEDENT><DEDENT>if self.type is not None:<EOL><INDENT>indexes = self.type.get_index()<EOL>if isinstance(indexes, string_types):<EOL><INDENT>indexes = [indexes]<EOL><DEDENT>return indexes<EOL><DEDENT>retur...
Returns the list of indexes to act on.
f12902:c9:m31
def get_doctypes(self, default_doctypes=DEFAULT_DOCTYPES):
for action, value in reversed(self.steps):<EOL><INDENT>if action == '<STR_LIT>':<EOL><INDENT>return list(value)<EOL><DEDENT><DEDENT>if self.type is not None:<EOL><INDENT>return [self.type.get_mapping_type_name()]<EOL><DEDENT>return default_doctypes<EOL>
Returns the list of doctypes to use.
f12902:c9:m32
def raw(self):
qs = self.build_search()<EOL>es = self.get_es()<EOL>index = self.get_indexes()<EOL>doc_type = self.get_doctypes()<EOL>if doc_type and not index:<EOL><INDENT>raise BadSearch(<EOL>'<STR_LIT>')<EOL><DEDENT>extra_search_kwargs = {}<EOL>if self.search_type:<EOL><INDENT>extra_search_kwargs['<STR_LIT>'] = self.search_type<EOL...
Build query and passes to Elasticsearch, then returns the raw format returned.
f12902:c9:m33
def count(self):
if self._results_cache is not None:<EOL><INDENT>return self._results_cache.count<EOL><DEDENT>else:<EOL><INDENT>return self[:<NUM_LIT:0>].raw()['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT>
Returns the total number of results Elasticsearch thinks will match this search. :returns: integer For example: >>> all_jimmies = S().query(name__prefix='Jimmy').count()
f12902:c9:m34
def __len__(self):
return len(self._do_search())<EOL>
Executes search and returns the number of results you'd get. Executes search and returns number of results returned as an integer. :returns: integer For example: >>> some_s = S().query(name__prefix='Jimmy') >>> length = len(some_s) This is very different than...
f12902:c9:m35
def all(self):
return self._clone()<EOL>
No-op that returns a clone of self This is here to make it more Django QuerySet-like and work with better with things that accept QuerySets.
f12902:c9:m36
def everything(self):
count = self.count()<EOL>return self[:count].execute()<EOL>
Executes search and returns ALL search results. :returns: `SearchResults` instance For example: >>> s = S().query(name__prefix='Jimmy') >>> all_results = s.everything() .. Warning:: This returns ALL possible search results. The way it does this is by ca...
f12902:c9:m37
def execute(self):
return self._do_search()<EOL>
Executes search and returns a `SearchResults` object. :returns: `SearchResults` instance For example: >>> s = S().query(name__prefix='Jimmy') >>> results = s.execute()
f12902:c9:m38
def __iter__(self):
return iter(self._do_search())<EOL>
Executes search and returns an iterator of results. :returns: iterator of results For example: >>> s = S().query(name__prefix='Jimmy') >>> for obj in s.execute(): ... print obj['id'] ...
f12902:c9:m39
def facet_counts(self):
return _facet_counts(self._raw_facets().items())<EOL>
Executes search and returns facet counts. Example: >>> s = S().query(name__prefix='Jimmy') >>> facet_counts = s.facet_counts()
f12902:c9:m41
def suggestions(self):
return self._do_search().response.get('<STR_LIT>', {})<EOL>
Executes search and returns suggestions. >>> s = S().query(name='Aice').suggest(name='Aice') >>> suggestions = s.suggestions()['name'] .. Note:: Suggestions are only supported since Elasticsearch 0.90.
f12902:c9:m42
def __init__(self, id_, s=None, mlt_fields=None, index=None,<EOL>doctype=None, es=None, **query_params):
<EOL>if s is None and (index is None or doctype is None):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in query_params:<EOL><INDENT>raise DeprecationWarning(<EOL>'<STR_LIT>')<EOL><DEDENT>self.s = s<EOL>if s is not None:<EOL><INDENT>self.index = index or s.get_indexes()[<NUM_LIT:0>]<EOL>self...
When the MLT is evaluated, it generates a list of dict results. :arg id_: The id of the document we want to find more like. :arg s: An instance of an S. Allows you to pass in a query which will be used as the body of the more-like-this request. :arg mlt_fields: A list of fields to look at for more like this. :arg ...
f12902:c10:m0
def get_es(self):
if self.s:<EOL><INDENT>return self.s.get_es()<EOL><DEDENT>return self.es or get_es()<EOL>
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...
f12902:c10:m3
def raw(self):
es = self.get_es()<EOL>params = dict(self.query_params)<EOL>mlt_fields = self.mlt_fields or params.pop('<STR_LIT>', [])<EOL>body = self.s.build_search() if self.s else '<STR_LIT>'<EOL>hits = es.mlt(<EOL>index=self.index, doc_type=self.doctype, id=self.id,<EOL>mlt_fields=mlt_fields, body=body, **params)<EOL>log.debug(hi...
Build query and passes to `Elasticsearch`, then returns the raw format returned.
f12902:c10:m4
def _do_search(self):
if self._results_cache is None:<EOL><INDENT>response = self.raw()<EOL>results = self.to_python(response.get('<STR_LIT>', {}).get('<STR_LIT>', []))<EOL>self._results_cache = DictSearchResults(<EOL>self.type, response, results, None)<EOL><DEDENT>return self._results_cache<EOL>
Perform the mlt call, then convert that raw format into a SearchResults instance and return it.
f12902:c10:m5
@classmethod<EOL><INDENT>def get_index(cls):<DEDENT>
raise NotImplementedError()<EOL>
Returns the index to use for this mapping type. You can specify the index to use for this mapping type. This affects ``S`` built with this type. By default, raises NotImplementedError. Override this to return the index this mapping type should be indexed and searched in.
f12902:c19:m3
@classmethod<EOL><INDENT>def get_mapping_type_name(cls):<DEDENT>
raise NotImplementedError()<EOL>
Returns the mapping type name. You can specify the mapping type name (also sometimes called the document type) with this method. By default, raises NotImplementedError. Override this to return the mapping type name.
f12902:c19:m4
def get_object(self):
return self.get_model().get(id=self._id)<EOL>
Returns the model instance This gets called when someone uses the ``.object`` attribute which triggers lazy-loading of the object this document is based on. By default, this calls:: self.get_model().get(id=self._id) where ``self._id`` is the Elasticsearch documen...
f12902:c19:m5
@classmethod<EOL><INDENT>def get_model(cls):<DEDENT>
raise NoModelError<EOL>
Return the model class related to this MappingType. This can be any class that has an instance related to this MappingType by id. For example, if you're using Django and your MappingType is related to a Django model--this should return the Django model. By default, rai...
f12902:c19:m6
@classmethod<EOL><INDENT>def get_es(cls):<DEDENT>
return get_es()<EOL>
Returns an Elasticsearch object Override this if you need special functionality. :returns: a elasticsearch `Elasticsearch` instance
f12902:c21:m0
@classmethod<EOL><INDENT>def get_mapping(cls):<DEDENT>
return None<EOL>
Returns the mapping for this mapping type. Example:: @classmethod def get_mapping(cls): return { 'properties': { 'id': {'type': 'integer'}, 'name': {'type': 'string'} } ...
f12902:c21:m1
@classmethod<EOL><INDENT>def extract_document(cls, obj_id, obj=None):<DEDENT>
raise NotImplementedError<EOL>
Extracts the Elasticsearch index document for this instance **This must be implemented.** .. Note:: The resulting dict must be JSON serializable. :arg obj_id: the object id for the object to extract from :arg obj: if this is not None, use this as the object to ...
f12902:c21:m2
@classmethod<EOL><INDENT>def get_indexable(cls):<DEDENT>
raise NotImplemented<EOL>
Returns an iterable of things to index. :returns: iterable of things to index
f12902:c21:m3
@classmethod<EOL><INDENT>def index(cls, document, id_=None, overwrite_existing=True, es=None,<EOL>index=None):<DEDENT>
if es is None:<EOL><INDENT>es = cls.get_es()<EOL><DEDENT>if index is None:<EOL><INDENT>index = cls.get_index()<EOL><DEDENT>kw = {}<EOL>if not overwrite_existing:<EOL><INDENT>kw['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>es.index(index=index, doc_type=cls.get_mapping_type_name(),<EOL>body=document, id=id_, **kw)<EOL>
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_`...
f12902:c21:m4
@classmethod<EOL><INDENT>def bulk_index(cls, documents, id_field='<STR_LIT:id>', es=None, index=None):<DEDENT>
if es is None:<EOL><INDENT>es = cls.get_es()<EOL><DEDENT>if index is None:<EOL><INDENT>index = cls.get_index()<EOL><DEDENT>documents = (dict(d, _id=d[id_field]) for d in documents)<EOL>bulk_index(<EOL>es,<EOL>documents,<EOL>index=index,<EOL>doc_type=cls.get_mapping_type_name(),<EOL>raise_on_error=True<EOL>)<EOL>
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...
f12902:c21:m5
@classmethod<EOL><INDENT>def unindex(cls, id_, es=None, index=None):<DEDENT>
if es is None:<EOL><INDENT>es = cls.get_es()<EOL><DEDENT>if index is None:<EOL><INDENT>index = cls.get_index()<EOL><DEDENT>es.delete(index=index, doc_type=cls.get_mapping_type_name(), id=id_)<EOL>
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. ...
f12902:c21:m6
@classmethod<EOL><INDENT>def refresh_index(cls, es=None, index=None):<DEDENT>
if es is None:<EOL><INDENT>es = cls.get_es()<EOL><DEDENT>if index is None:<EOL><INDENT>index = cls.get_index()<EOL><DEDENT>es.indices.refresh(index=index)<EOL>
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. ...
f12902:c21:m7
def to_json(data):
return JSONSerializer().dumps(data)<EOL>
Convert Python structure to JSON used by Elasticsearch This is a helper method that uses the elasticsearch-py JSONSerializer to serialize the structure. This is the serializer that elasticsearch-py uses to serialize data for Elasticsearch and handles dates. :arg data: Python structure (e.g. dict, ...
f12903:m0
def chunked(iterable, n):
iterable = iter(iterable)<EOL>while <NUM_LIT:1>:<EOL><INDENT>t = tuple(islice(iterable, n))<EOL>if t:<EOL><INDENT>yield t<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>
Returns chunks of n length of iterable If len(iterable) % n != 0, then the last chunk will have length less than n. Example: >>> chunked([1, 2, 3, 4, 5], 2) [(1, 2), (3, 4), (5,)]
f12903:m1
def format_explanation(explanation, indent='<STR_LIT:U+0020>', indent_level=<NUM_LIT:0>):
if not explanation:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>line = ('<STR_LIT>' % ((indent * indent_level),<EOL>explanation['<STR_LIT:description>'],<EOL>explanation['<STR_LIT:value>']))<EOL>if '<STR_LIT>' in explanation:<EOL><INDENT>details = '<STR_LIT:\n>'.join(<EOL>[format_explanation(subtree, indent, indent_leve...
Return explanation in an easier to read format Easier to read for me, at least.
f12903:m2
def monkeypatch_es():
if _monkeypatched_es:<EOL><INDENT>return<EOL><DEDENT>def normalize_bulk_return(fun):<EOL><INDENT>"""<STR_LIT>"""<EOL>@wraps(fun)<EOL>def _fixed_bulk(self, *args, **kwargs):<EOL><INDENT>def fix_item(item):<EOL><INDENT>for key, val in item.items():<EOL><INDENT>if '<STR_LIT>' in val:<EOL><INDENT>val['<STR_LIT:status>'] = ...
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.
f12904:m0
def _set_local_file_path(self):
self.FILE_LOCAL = self._transfer.get_env('<STR_LIT>')<EOL>if not self.FILE_LOCAL:<EOL><INDENT>filename = '<STR_LIT>'.format(str(self._transfer.prefix),<EOL>str(self._transfer.namespace),<EOL>str(self.file_extension))<EOL>self.FILE_LOCAL = os.path.join(os.path.expanduser("<STR_LIT>"), filename)<EOL><DEDENT>dirs = os.pat...
Take from environment variable, create dirs and create file if doesn' exist.
f12916:c0:m1
def connect(self):
file_contents = self.load_file()<EOL>if file_contents:<EOL><INDENT>return self.transform_to_custom_dict(file_contents)<EOL><DEDENT>else:<EOL><INDENT>return {}<EOL><DEDENT>
Get all the contents from yaml file to memory.
f12916:c0:m2
@property<EOL><INDENT>def url(self):<DEDENT>
return self._url<EOL>
Return the URL of currently loaded website.
f12923:c3:m1
@property<EOL><INDENT>def response(self):<DEDENT>
return self._response<EOL>
Return the `Response` object of currently loaded website.
f12923:c3:m2
@property<EOL><INDENT>def cookies(self):<DEDENT>
return self.session.cookies<EOL>
Return the CookieJar instance of the current `Session`.
f12923:c3:m3
def soup(self, *args, **kwargs):
if self._url is None:<EOL><INDENT>raise NoWebsiteLoadedError('<STR_LIT>')<EOL><DEDENT>content_type = self._response.headers.get('<STR_LIT:Content-Type>', '<STR_LIT>')<EOL>if not any(markup in content_type for markup in ('<STR_LIT:html>', '<STR_LIT>')):<EOL><INDENT>raise ParsingError('<STR_LIT>'.format(content_type))<EO...
Parse the currently loaded website. Optionally, SoupStrainer can be used to only parse relevant parts of the page. This can be particularly useful if the website is complex or perfomance is a factor. <https://www.crummy.com/software/BeautifulSoup/bs4/doc/#soupstrainer> Args: ...
f12923:c3:m4
def get(self, url, **kwargs):
response = self.session.get(url, **kwargs)<EOL>self._url = response.url<EOL>self._response = response<EOL>return response<EOL>
Send a GET request to the specified URL. Method directly wraps around `Session.get` and updates browser attributes. <http://docs.python-requests.org/en/master/api/#requests.get> Args: url: URL for the new `Request` object. **kwargs: Optional arguments that `Requ...
f12923:c3:m5
def post(self, **kwargs):
if self._url is None:<EOL><INDENT>raise NoWebsiteLoadedError('<STR_LIT>')<EOL><DEDENT>data = kwargs.get('<STR_LIT:data>', {})<EOL>for i in self.soup('<STR_LIT>').select('<STR_LIT>'):<EOL><INDENT>if i.get('<STR_LIT:name>') not in data:<EOL><INDENT>data[i.get('<STR_LIT:name>')] = i.get('<STR_LIT:value>', '<STR_LIT>')<EOL...
Send a POST request to the currently loaded website's URL. The browser will automatically fill out the form. If `data` dict has been passed into ``kwargs``, the contained input values will override the automatically filled out values. Returns: `Response` object of a success...
f12923:c3:m6
def __init__(self, model, MetaConfig=None):
self.model = model<EOL>self.app_label = model._meta.app_label<EOL>self.model_name = model._meta.model_name<EOL>if MetaConfig:<EOL><INDENT>for key, value in MetaConfig.__dict__.items():<EOL><INDENT>if key.startswith('<STR_LIT:_>'):<EOL><INDENT>continue<EOL><DEDENT>setattr(self, key, value)<EOL><DEDENT><DEDENT>
Init config
f12926:c0:m0
def __getattr__(self, item):
try:<EOL><INDENT>return super().__getattr__(item)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>
Get attribute and returns null if not set
f12926:c0:m1
def get_create_form(self):
return self._get_form('<STR_LIT>')<EOL>
Return create form
f12926:c0:m2
def get_create_minimal_form(self):
return self._get_form('<STR_LIT>', True)<EOL>
Return minimal form
f12926:c0:m3
def get_edit_form(self):
return self._get_form('<STR_LIT>')<EOL>
Return edit form
f12926:c0:m4
def get_list_fields(self):
from trionyx.renderer import renderer<EOL>model_fields = {f.name: f for f in self.model.get_fields(True, True)}<EOL>def create_list_fields(config_fields, list_fields=None):<EOL><INDENT>list_fields = list_fields if list_fields else {}<EOL>for field in config_fields:<EOL><INDENT>config = field<EOL>if isinstance(field, st...
Get all list fields
f12926:c0:m5
def _get_form(self, config_name, only_required=False):
if getattr(self, config_name, None):<EOL><INDENT>return import_object_by_string(getattr(self, config_name))<EOL><DEDENT>def use_field(field):<EOL><INDENT>if not only_required:<EOL><INDENT>return True<EOL><DEDENT>return field.default == NOT_PROVIDED<EOL><DEDENT>return modelform_factory(self.model, fields=[f.name for f i...
Get form for given config else create form
f12926:c0:m6
def __init__(self):
self.configs = {}<EOL>
Init models
f12926:c1:m0
def auto_load_configs(self):
for app in apps.get_app_configs():<EOL><INDENT>for model in app.get_models():<EOL><INDENT>config = ModelConfig(model, getattr(app, model.__name__, None))<EOL>self.configs[self.get_model_name(model)] = config<EOL><DEDENT><DEDENT>
Auto load all configs from app configs
f12926:c1:m1
def get_config(self, model):
if not inspect.isclass(model):<EOL><INDENT>model = model.__class__<EOL><DEDENT>return self.configs.get(self.get_model_name(model))<EOL>
Get config for given model
f12926:c1:m2
def get_all_configs(self, trionyx_models_only=True):
from trionyx.models import BaseModel<EOL>for index, config in self.configs.items():<EOL><INDENT>if not isinstance(config.model(), BaseModel):<EOL><INDENT>continue<EOL><DEDENT>yield config<EOL><DEDENT>
Get all model configs
f12926:c1:m3
def get_model_name(self, model):
return '<STR_LIT>'.format(model.__module__, model.__name__)<EOL>
Get model name for given model
f12926:c1:m4
def __init__(self, root_item=None):
self.root_item = root_item<EOL>
Init Menu
f12927:c0:m0
def auto_load_model_menu(self):
from trionyx.trionyx.apps import BaseConfig<EOL>order = <NUM_LIT:0><EOL>for app in apps.get_app_configs():<EOL><INDENT>if not isinstance(app, BaseConfig) or getattr(app, '<STR_LIT>', False):<EOL><INDENT>continue<EOL><DEDENT>app_path = app.name.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL>model_order = <NUM_LIT:0><EOL>for mod...
Auto load model menu entries, can be configured in `trionyx.config.ModelConfig`: - menu_name - menu_icon - menu_order
f12927:c0:m1
def add_item(self, path, name, icon=None, url=None, order=None, permission=None, active_regex=None):
if self.root_item is None:<EOL><INDENT>self.root_item = MenuItem('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>root_item = self.root_item<EOL>current_path = '<STR_LIT>'<EOL>for node in path.split('<STR_LIT:/>')[:-<NUM_LIT:1>]:<EOL><INDENT>if not node:<EOL><INDENT>continue<EOL><DEDENT>current_path = '<STR_LIT:/>' + '<STR_LIT>'....
Add new menu item to menu :param path: Path of menu :param name: Display name :param icon: CSS icon :param url: link to page :param order: Sort order :param permission: :return:
f12927:c0:m2
def get_menu_items(self):
if not self.root_item:<EOL><INDENT>return []<EOL><DEDENT>return self.root_item.childs<EOL>
Get menu items
f12927:c0:m3
def __init__(self, path, name, icon=None, url=None, order=None, permission=None, active_regex=None):
self.path = path<EOL>self.name = name<EOL>self.icon = icon<EOL>self.url = url<EOL>self.order = order<EOL>self.permission = permission<EOL>self.active_regex = active_regex<EOL>self.depth = <NUM_LIT:0><EOL>self.childs = []<EOL>
Init menu item :param path: Path of menu :param name: Display name :param icon: CSS icon :param url: link to page :param order: Sort order :param permission:
f12927:c1:m0
def merge(self, item):
self.name = item.name<EOL>if item.icon:<EOL><INDENT>self.icon = item.icon<EOL><DEDENT>if item.url:<EOL><INDENT>self.url = item.url<EOL><DEDENT>if item.order:<EOL><INDENT>self.order = item.order<EOL><DEDENT>if item.permission:<EOL><INDENT>self.permission = item.permission<EOL><DEDENT>
Merge Menu item data
f12927:c1:m1
def add_child(self, item):
item.depth = self.depth + <NUM_LIT:1><EOL>self.childs.append(item)<EOL>self.childs = sorted(self.childs, key=lambda item: item.order if item.order else <NUM_LIT>)<EOL>
Add child to menu item
f12927:c1:m2
def child_by_code(self, code):
for child in self.childs:<EOL><INDENT>if child.path.split('<STR_LIT:/>')[-<NUM_LIT:1>] == code:<EOL><INDENT>return child<EOL><DEDENT><DEDENT>return None<EOL>
Get child MenuItem by its last path code :param code: :return: MenuItem or None
f12927:c1:m3
def is_active(self, path):
if self.url == '<STR_LIT:/>' and self.url == path:<EOL><INDENT>return True<EOL><DEDENT>elif self.url == '<STR_LIT:/>':<EOL><INDENT>return False<EOL><DEDENT>if self.url and path.startswith(self.url):<EOL><INDENT>return True<EOL><DEDENT>if self.active_regex and re.compile(self.active_regex).match(path):<EOL><INDENT>retur...
Check if given path is active for current item
f12927:c1:m4
def __init__(self):
self.tabs = defaultdict(list)<EOL>
Init Tabs
f12927:c2:m0
def get_tabs(self, model_alias, object):
model_alias = self.get_model_alias(model_alias)<EOL>for item in self.tabs[model_alias]:<EOL><INDENT>if item.display_filter(object):<EOL><INDENT>yield item<EOL><DEDENT><DEDENT>
Get all active tabs for given model :param model_alias: :param object: Object used to filter tabs :return:
f12927:c2:m1
def get_tab(self, model_alias, object, tab_code):
model_alias = self.get_model_alias(model_alias)<EOL>for item in self.tabs[model_alias]:<EOL><INDENT>if item.code == tab_code and item.display_filter(object):<EOL><INDENT>return item<EOL><DEDENT><DEDENT>raise Exception('<STR_LIT>')<EOL>
Get tab for given object and tab code :param model_alias: :param object: Object used to render tab :param tab_code: Tab code to use :return:
f12927:c2:m2
def register(self, model_alias, code='<STR_LIT>', name=None, order=None, display_filter=None):
model_alias = self.get_model_alias(model_alias)<EOL>def wrapper(create_layout):<EOL><INDENT>item = TabItem(<EOL>code=code,<EOL>create_layout=create_layout,<EOL>name=name,<EOL>order=order,<EOL>display_filter=display_filter<EOL>)<EOL>if item in self.tabs[model_alias]:<EOL><INDENT>raise Exception("<STR_LIT>".format(code, ...
Register new tab :param model_alias: :param code: :param name: :param order: :return:
f12927:c2:m3
def register_update(self, model_alias, code):
model_alias = self.get_model_alias(model_alias)<EOL>def wrapper(update_layout):<EOL><INDENT>for item in self.tabs[model_alias]:<EOL><INDENT>if item.code == code:<EOL><INDENT>item.layout_updates.append(update_layout)<EOL><DEDENT><DEDENT>return update_layout<EOL><DEDENT>return wrapper<EOL>
Register tab update function, function is being called with (layout, object) :param model_alias: :param code: :return:
f12927:c2:m4
def update(self, model_alias, code='<STR_LIT>', name=None, order=None, display_filter=None):
model_alias = self.get_model_alias(model_alias)<EOL>for item in self.tabs[model_alias]:<EOL><INDENT>if item.code != code:<EOL><INDENT>continue<EOL><DEDENT>if name:<EOL><INDENT>item.name = name<EOL><DEDENT>if order:<EOL><INDENT>item.order = order<EOL><DEDENT>if display_filter:<EOL><INDENT>item.display_filter = display_f...
Update given tab :param model_alias: :param code: :param name: :param order: :param display_filter: :return:
f12927:c2:m5
def get_model_alias(self, model_alias):
from trionyx.models import BaseModel<EOL>if inspect.isclass(model_alias) and issubclass(model_alias, BaseModel):<EOL><INDENT>config = models_config.get_config(model_alias)<EOL>return '<STR_LIT>'.format(config.app_label, config.model_name)<EOL><DEDENT>return model_alias<EOL>
Get model alias if class then convert to alias string
f12927:c2:m6
def auto_generate_missing_tabs(self):
for config in models_config.get_all_configs():<EOL><INDENT>model_alias = '<STR_LIT>'.format(config.app_label, config.model_name)<EOL>if model_alias not in self.tabs:<EOL><INDENT>@self.register(model_alias)<EOL>def general_layout(obj):<EOL><INDENT>return Layout(<EOL>Column12(<EOL>Panel(<EOL>'<STR_LIT:info>',<EOL>Descrip...
Auto generate tabs for models with no tabs
f12927:c2:m7
def __init__(self, code, create_layout, name=None, order=None, display_filter=None):
self._name = None<EOL>self.code = code<EOL>self.create_layout = create_layout<EOL>self.name = name<EOL>self.order = order<EOL>self.display_filter = display_filter if display_filter else lambda object: True<EOL>self.layout_updates = []<EOL>
Init TabItem
f12927:c3:m0
@property<EOL><INDENT>def name(self):<DEDENT>
if self._name:<EOL><INDENT>return self._name<EOL><DEDENT>return self.code.replace('<STR_LIT:_>', '<STR_LIT:U+0020>').capitalize()<EOL>
Give back tab name if is set else generate name by code
f12927:c3:m1
@name.setter<EOL><INDENT>def name(self, name):<DEDENT>
self._name = name<EOL>
Set name
f12927:c3:m2
def get_layout(self, object):
layout = self.create_layout(object)<EOL>if isinstance(layout, Component):<EOL><INDENT>layout = Layout(layout)<EOL><DEDENT>if isinstance(layout, list):<EOL><INDENT>layout = Layout(*layout)<EOL><DEDENT>for update_layout in self.layout_updates:<EOL><INDENT>update_layout(layout, object)<EOL><DEDENT>layout.set_object(object...
Get complete layout for given object
f12927:c3:m3
def __str__(self):
if not self.name:<EOL><INDENT>return self.name.capitalize()<EOL><DEDENT>return self.name<EOL>
Tab string representation
f12927:c3:m4
def __eq__(self, other):
return self.code == other.code<EOL>
Compare tab based on code
f12927:c3:m5