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 those field arguments via ``fields`` and returns a list of tuples with values in the order specified. For example (assume id, name and age are stored fields): >>> list(S().values_list()) [([1], ['fred'], [40]), ([2], ['brian'], [30]), ...] >>> list(S().values_list('id', 'name')) [([1], ['fred']), ([2], ['brian']), ([3], ['james'])] >>> list(S().values_list('name', 'id')) [(['fred'], [1]), (['brian'], [2]), (['james'], [3])] .. Note:: If you do not specify any fields and you have no fields marked as stored, then you will get back the ``_id`` and ``_type`` of each result and that's it.
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 those field arguments via ``fields`` and returns a list of dicts with the specified fields. For example (assuming id, name and age are stored): >>> list(S().values_dict()) [{'id': [1], 'name': ['fred'], 'age': [40]}, ...] >>> list(S().values_dict('id', 'name')) [{'id': [1], 'name': ['fred']}, ...] .. Note:: If you do not specify any fields and you have no fields marked as stored, then you will get back the ``_id`` and ``_type`` of each result and that's it.
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 ``-``:: q = (S().query(title='trucks') .order_by('-title') You can also sort by the computed field ``_score`` or pass a dict as a sort field in order to use more advanced sort options. Read the Elasticsearch documentation for details. .. Note:: Calling this again will overwrite previous ``.order_by()`` calls.
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 document to be in the result. If you don't specify a special flag, this is the default. * ``should=True``: Specifies that the queries and kw queries **should match** in order for a document to be in the result. * ``must_not=True``: Specifies the queries and kw queries **must not match** in order for a document to be in the result. These flags work by putting those queries in the appropriate clause of an Elasticsearch boolean query. Examples: >>> s = S().query(foo='bar') >>> s = S().query(Q(foo='bar')) >>> s = S().query(foo='bar', bat__match='baz') >>> s = S().query(foo='bar', should=True) >>> s = S().query(foo='bar', should=True).query(baz='bat', must=True) Notes: 1. Don't specify multiple special flags, but if you did, `should` takes precedence. 2. If you don't specify any, it defaults to `must`. 3. You can specify special flags in the :py:class:`elasticutils.Q`, too. If you're building your query incrementally, using :py:class:`elasticutils.Q` helps a lot. See the documentation on :py:class:`elasticutils.Q` for more details on composing queries with Q. See the documentation on :py:class:`elasticutils.S` for more details on adding support for more query types.
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 anything else that affects the query clause is ignored.
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='bar').filter(bat='baz') By default, everything is combined using AND. If you provide multiple filters in a single filter call, those are ANDed together. If you provide multiple filters in multiple filter calls, those are ANDed together. If you want something different, use the F class which supports ``&`` (and), ``|`` (or) and ``~`` (not) operators. Then call filter once with the resulting F instance. See the documentation on :py:class:`elasticutils.F` for more details on composing filters with F. See the documentation on :py:class:`elasticutils.S` for more details on adding support for new filter types.
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 the filter clause is ignored.
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='awesome') .boost(title=4.0, description__match=2.0)) If the key is a field name, then the boost will apply to all query bits that have that field name. For example:: q = (S().query(title='trucks', title__prefix='trucks', title__fuzzy='trucks') .boost(title=4.0)) applies a 4.0 boost to all three query bits because all three query bits are for the title field name. If the key is a field name and field action, then the boost will apply only to that field name and field action. For example:: q = (S().query(title='trucks', title__prefix='trucks', title__fuzzy='trucks') .boost(title__prefix=4.0)) will only apply the 4.0 boost to title__prefix. Boosts are relative to one another and all boosts default to 1.0. For example, if you had:: qs = (S().boost(title=4.0, summary=2.0) .query(title__match=value, summary__match=value, content__match=value, should=True)) ``title__match`` would be boosted twice as much as ``summary__match`` and ``summary__match`` twice as much as ``content__match``.
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 using the boosting query in Elasticsearch. Anything you specify with ``.query()`` goes into the positive section. The negative query and negative boost portions are specified as the first and second arguments to ``.demote()``. .. Note:: Calling this again will overwrite previous ``.demote()`` calls.
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 highlighted portion Results will have a ``highlight`` attribute on the ``es_meta`` object which contains the highlighted field excerpts. For example:: q = (S().query(title__match='crash', content__match='crash') .highlight('title', 'content')) for result in q: print result.es_meta.highlight['title'] print result.es_meta.highlight['content'] If you pass in ``None``, it will clear the highlight. For example, this search won't highlight anything:: q = (S().query(title__match='crash') .highlight('title') # highlights 'title' field .highlight(None)) # clears highlight .. Note:: Calling this again will overwrite previous ``.highlight()`` calls. .. Note:: Make sure the fields you're highlighting are indexed correctly. Read the Elasticsearch documentation for details.
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. For the list of possible values and additional documentation, consult the Elasticsearch reference: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html If called multiple times, the last search type will be in effect.
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 containing the suggestions for all terms. .. Note:: Suggestions are only supported since Elasticsearch 0.90. Calling this multiple times will add multiple suggest clauses to the query.
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, vals))<EOL><DEDENT><DEDENT>return new<EOL>
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>search_type = None<EOL>for action, value in self.steps:<EOL><INDENT>if action == '<STR_LIT>':<EOL><INDENT>sort = []<EOL>for key in value:<EOL><INDENT>if isinstance(key, string_types) and key.startswith('<STR_LIT:->'):<EOL><INDENT>sort.append({key[<NUM_LIT:1>:]: '<STR_LIT>'})<EOL><DEDENT>else:<EOL><INDENT>sort.append(key)<EOL><DEDENT><DEDENT><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>if not value:<EOL><INDENT>list_fields = set()<EOL><DEDENT>else:<EOL><INDENT>list_fields |= set(value)<EOL><DEDENT>as_list, as_dict = True, False<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>if not value:<EOL><INDENT>dict_fields = set()<EOL><DEDENT>else:<EOL><INDENT>dict_fields |= set(value)<EOL><DEDENT>as_list, as_dict = False, True<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>explain = value<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>queries.append(value)<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>query_raw = value<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>demote = value<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>filters.extend(self._process_filters(value))<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>filters_raw = value<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>facets.update(_process_facets(*value))<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>facets_raw.update(dict(value))<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>if value[<NUM_LIT:0>] == (None,):<EOL><INDENT>highlight_fields = set()<EOL><DEDENT>else:<EOL><INDENT>highlight_fields |= set(value[<NUM_LIT:0>])<EOL><DEDENT>highlight_options.update(value[<NUM_LIT:1>])<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>search_type = value<EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>suggestions[value[<NUM_LIT:0>]] = (value[<NUM_LIT:1>], value[<NUM_LIT:2>])<EOL><DEDENT>elif action in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError(action)<EOL><DEDENT><DEDENT>qs = {}<EOL>if filters_raw:<EOL><INDENT>qs['<STR_LIT>'] = filters_raw<EOL><DEDENT>else:<EOL><INDENT>if len(filters) > <NUM_LIT:1>:<EOL><INDENT>qs['<STR_LIT>'] = {'<STR_LIT>': filters}<EOL><DEDENT>elif filters:<EOL><INDENT>qs['<STR_LIT>'] = filters[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if query_raw:<EOL><INDENT>qs['<STR_LIT>'] = query_raw<EOL><DEDENT>else:<EOL><INDENT>pq = self._process_queries(queries)<EOL>if demote is not None:<EOL><INDENT>qs['<STR_LIT>'] = {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': self._process_queries([demote[<NUM_LIT:1>]]),<EOL>'<STR_LIT>': demote[<NUM_LIT:0>]<EOL>}<EOL>}<EOL>if pq:<EOL><INDENT>qs['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'] = pq<EOL><DEDENT><DEDENT>elif pq:<EOL><INDENT>qs['<STR_LIT>'] = pq<EOL><DEDENT><DEDENT>if as_list:<EOL><INDENT>fields = qs['<STR_LIT>'] = list(list_fields) if list_fields else ['<STR_LIT:*>']<EOL><DEDENT>elif as_dict:<EOL><INDENT>fields = qs['<STR_LIT>'] = list(dict_fields) if dict_fields else ['<STR_LIT:*>']<EOL><DEDENT>else:<EOL><INDENT>fields = set()<EOL><DEDENT>if facets:<EOL><INDENT>qs['<STR_LIT>'] = facets<EOL>for facet in facets.values():<EOL><INDENT>if facet.get('<STR_LIT>', <NUM_LIT:1>) is None and '<STR_LIT>' in qs:<EOL><INDENT>facet['<STR_LIT>'] = qs['<STR_LIT>']<EOL><DEDENT><DEDENT><DEDENT>if facets_raw:<EOL><INDENT>qs.setdefault('<STR_LIT>', {}).update(facets_raw)<EOL><DEDENT>if sort:<EOL><INDENT>qs['<STR_LIT>'] = sort<EOL><DEDENT>if self.start:<EOL><INDENT>qs['<STR_LIT>'] = self.start<EOL><DEDENT>if self.stop is not None:<EOL><INDENT>qs['<STR_LIT:size>'] = self.stop - self.start<EOL><DEDENT>if highlight_fields:<EOL><INDENT>qs['<STR_LIT>'] = self._build_highlight(<EOL>highlight_fields, highlight_options)<EOL><DEDENT>if explain:<EOL><INDENT>qs['<STR_LIT>'] = True<EOL><DEDENT>for suggestion, (term, kwargs) in six.iteritems(suggestions):<EOL><INDENT>qs.setdefault('<STR_LIT>', {})[suggestion] = {<EOL>'<STR_LIT:text>': term,<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': kwargs.get('<STR_LIT>', '<STR_LIT>'),<EOL>},<EOL>}<EOL><DEDENT>self.fields, self.as_list, self.as_dict = fields, as_list, as_dict<EOL>self.search_type = search_type<EOL>return qs<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_json`. :returns: a Python dict
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()[<NUM_LIT:0>]<EOL><DEDENT>val = f[key]<EOL>key = key.strip('<STR_LIT:_>')<EOL>if key not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise InvalidFieldActionError(<EOL>'<STR_LIT>' % f.keys()[<NUM_LIT:0>])<EOL><DEDENT>if '<STR_LIT>' in val:<EOL><INDENT>filter_filters = self._process_filters(val['<STR_LIT>'])<EOL>if len(filter_filters) == <NUM_LIT:1>:<EOL><INDENT>filter_filters = filter_filters[<NUM_LIT:0>]<EOL><DEDENT>rv.append({key: {'<STR_LIT>': filter_filters}})<EOL><DEDENT>else:<EOL><INDENT>rv.append({key: self._process_filters(val)})<EOL><DEDENT><DEDENT>else:<EOL><INDENT>key, val = f<EOL>key, field_action = split_field_action(key)<EOL>handler_name = '<STR_LIT>'.format(field_action)<EOL>if field_action and hasattr(self, handler_name):<EOL><INDENT>rv.append(getattr(self, handler_name)(<EOL>key, val, field_action))<EOL><DEDENT>elif key.strip('<STR_LIT:_>') in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>connector = key.strip('<STR_LIT:_>')<EOL>rv.append({connector: self._process_filters(val.items())})<EOL><DEDENT>elif field_action is None:<EOL><INDENT>if val is None:<EOL><INDENT>rv.append({'<STR_LIT>': {<EOL>'<STR_LIT>': key, "<STR_LIT>": True}})<EOL><DEDENT>else:<EOL><INDENT>rv.append({'<STR_LIT>': {key: val}})<EOL><DEDENT><DEDENT>elif field_action in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>rv.append({'<STR_LIT>': {key: val}})<EOL><DEDENT>elif field_action == '<STR_LIT>':<EOL><INDENT>rv.append({'<STR_LIT>': {key: val}})<EOL><DEDENT>elif field_action in RANGE_ACTIONS:<EOL><INDENT>rv.append({'<STR_LIT>': {key: {field_action: val}}})<EOL><DEDENT>elif field_action == '<STR_LIT>':<EOL><INDENT>lower, upper = val<EOL>rv.append({'<STR_LIT>': {key: {'<STR_LIT>': lower, '<STR_LIT>': upper}}})<EOL><DEDENT>elif field_action == '<STR_LIT>':<EOL><INDENT>distance, latitude, longitude = val<EOL>rv.append({<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': distance,<EOL>key: [longitude, latitude]<EOL>}<EOL>})<EOL><DEDENT>else:<EOL><INDENT>raise InvalidFieldActionError(<EOL>'<STR_LIT>' % field_action)<EOL><DEDENT><DEDENT><DEDENT>return rv<EOL>
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 getattr(self, handler_name)(field_name, val, field_action)<EOL><DEDENT>elif field_action in QUERY_ACTION_MAP:<EOL><INDENT>return {<EOL>QUERY_ACTION_MAP[field_action]: _boosted_value(<EOL>field_name, field_action, key, val, boost)<EOL>}<EOL><DEDENT>elif field_action == '<STR_LIT>':<EOL><INDENT>return {<EOL>'<STR_LIT>': {'<STR_LIT>': field_name, '<STR_LIT>': val}<EOL>}<EOL><DEDENT>elif field_action in RANGE_ACTIONS:<EOL><INDENT>return {<EOL>'<STR_LIT>': {field_name: _boosted_value(<EOL>field_action, field_action, key, val, boost)}<EOL>}<EOL><DEDENT>elif field_action == '<STR_LIT>':<EOL><INDENT>lower, upper = val<EOL>value = {<EOL>'<STR_LIT>': lower,<EOL>'<STR_LIT>': upper,<EOL>}<EOL>if boost:<EOL><INDENT>value['<STR_LIT>'] = boost<EOL><DEDENT>return {'<STR_LIT>': {field_name: value}}<EOL><DEDENT>raise InvalidFieldActionError(<EOL>'<STR_LIT>' % field_action)<EOL>
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_LIT:1> or (len(should_q) + len(must_not_q) > <NUM_LIT:0>):<EOL><INDENT>bool_query = {}<EOL>if must_q:<EOL><INDENT>bool_query['<STR_LIT>'] = must_q<EOL><DEDENT>if should_q:<EOL><INDENT>bool_query['<STR_LIT>'] = should_q<EOL><DEDENT>if must_not_q:<EOL><INDENT>bool_query['<STR_LIT>'] = must_not_q<EOL><DEDENT>return {'<STR_LIT:bool>': bool_query}<EOL><DEDENT>if must_q:<EOL><INDENT>return must_q[<NUM_LIT:0>]<EOL><DEDENT>return {}<EOL>
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, subclass S and override this method.
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>return default_indexes<EOL>
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><DEDENT>hits = es.search(body=qs,<EOL>index=self.get_indexes(),<EOL>doc_type=self.get_doctypes(),<EOL>**extra_search_kwargs)<EOL>log.debug('<STR_LIT>' % (hits['<STR_LIT>'], qs))<EOL>return hits<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 calling :py:meth:`elasticutils.S.count`. If you call :py:meth:`elasticutils.S.count` you get the total number of results that Elasticsearch thinks matches your search. If you call ``len()``, then you get the number of results you got from the search which factors in slices and default from and size values.
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 calling ``.count()`` first to figure out how many to return, then by slicing by that size and returning ALL possible search results. Don't use this if you've got 1000s of results!
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.doctype = doctype or s.get_doctypes()[<NUM_LIT:0>]<EOL>self.type = s.type<EOL><DEDENT>else:<EOL><INDENT>self.index = index<EOL>self.doctype = doctype<EOL>self.type = None<EOL><DEDENT>self.id = id_<EOL>self.mlt_fields = mlt_fields<EOL>self.es = es<EOL>self.query_params = query_params<EOL>self._results_cache = None<EOL>
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 index: The index to use. Falls back to the first index listed in s.get_indexes(). :arg doctype: The doctype to use. Falls back to the first doctype listed in s.get_doctypes(). :arg es: The `Elasticsearch` object to use. If you don't provide one, then it will create one for you. :arg query_params: Any additional query parameters for the more like this call. .. Note:: You must specify either an `s` or the `index` and `doctype` arguments. Omitting them will result in a `ValueError`.
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't correct for you.
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(hits)<EOL>return hits<EOL>
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 document id. Override it to do something different.
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, raises NoModelError. Override this to return a class that works with ``.get_object()`` to return the instance of the model that is related to this document.
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'} } } See the docs for more details on how to specify a mapping. Override this to return a mapping for this doctype. :returns: dict representing the Elasticsearch mapping or None if you want Elasticsearch to infer it. defaults to None.
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 extract from; this allows you to fetch a bunch of items at once and extract them one at a time :returns: dict of key/value pairs representing the document
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_``, then Elasticsearch will make up an id for your document and it'll look like a character name from a Lovecraft novel. :arg overwrite_existing: if ``True`` overwrites existing documents of the same ID and doctype :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. If you don't specify one it'll use `cls.get_index()`. .. Note:: If you need the documents available for searches immediately, make sure to refresh the index by calling ``refresh_index()``.
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 defaults to 'id'. :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. If you don't specify one it'll use `cls.get_index()`. .. Note:: If you need the documents available for searches immediately, make sure to refresh the index by calling ``refresh_index()``.
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. If you don't specify one it'll use `cls.get_index()`.
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. :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. If you don't specify one it'll use `cls.get_index()`.
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, list, ...) :returns: string Examples: >>> to_json({'query': {'match': {'message': 'test message'}}}) '{"query": {"match": {"message": "test message"}}}' >>> from elasticutils import S >>> some_s = S().query(message__match='test message') >>> to_json(some_s.build_search()) '{"query": {"match": {"message": "test message"}}}'
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_level + <NUM_LIT:1>)<EOL>for subtree in explanation['<STR_LIT>']])<EOL>return line + '<STR_LIT:\n>' + details<EOL><DEDENT>return line<EOL>
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>'] = <NUM_LIT><EOL><DEDENT><DEDENT>return item<EOL><DEDENT>ret = fun(self, *args, **kwargs)<EOL>if '<STR_LIT>' in ret:<EOL><INDENT>ret['<STR_LIT>'] = [fix_item(item) for item in ret['<STR_LIT>']]<EOL><DEDENT>return ret<EOL><DEDENT>return _fixed_bulk<EOL><DEDENT>Elasticsearch.bulk = normalize_bulk_return(Elasticsearch.bulk)<EOL>
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.path.dirname(self.FILE_LOCAL)<EOL>if not os.path.exists(dirs):<EOL><INDENT>os.makedirs(dirs)<EOL><DEDENT>try:<EOL><INDENT>open(self.FILE_LOCAL, "<STR_LIT>").close()<EOL><DEDENT>except:<EOL><INDENT>open(self.FILE_LOCAL, "<STR_LIT:a>").close()<EOL><DEDENT>
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))<EOL><DEDENT>strainer = SoupStrainer(*args, **kwargs)<EOL>return BeautifulSoup(self._response.content, self.parser, parse_only=strainer)<EOL>
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: *args: Optional positional arguments that `SoupStrainer` takes. **kwargs: Optional keyword argument that `SoupStrainer` takes. Returns: A `BeautifulSoup` object. Raises: NoWebsiteLoadedError: If no website is currently loaded. ParsingError: If the current response isn't supported by `bs4`
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 `Request` takes. Returns: `Response` object of a successful request.
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><DEDENT><DEDENT>kwargs['<STR_LIT:data>'] = data<EOL>response = self.session.post(self._url, **kwargs)<EOL>self._url = response.url<EOL>self._response = response<EOL>return response<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 successful request. Raises: NoWebsiteLoadedError: If no website is currently loaded.
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, str):<EOL><INDENT>config = {'<STR_LIT>': field}<EOL><DEDENT>if '<STR_LIT>' not in config:<EOL><INDENT>raise Exception("<STR_LIT>".format(config))<EOL><DEDENT>if '<STR_LIT:label>' not in config:<EOL><INDENT>if config['<STR_LIT>'] in model_fields:<EOL><INDENT>config['<STR_LIT:label>'] = model_fields[config['<STR_LIT>']].verbose_name<EOL><DEDENT>else:<EOL><INDENT>config['<STR_LIT:label>'] = config['<STR_LIT>']<EOL><DEDENT><DEDENT>if '<STR_LIT>' not in config:<EOL><INDENT>config['<STR_LIT>'] = renderer.render_field<EOL><DEDENT>list_fields[config['<STR_LIT>']] = config<EOL><DEDENT>return list_fields<EOL><DEDENT>list_fields = create_list_fields(model_fields.keys())<EOL>if self.list_fields:<EOL><INDENT>list_fields = create_list_fields(self.list_fields, list_fields)<EOL><DEDENT>return list_fields<EOL>
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 in self.model.get_fields() if use_field(f)])<EOL>
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 model in app.get_models():<EOL><INDENT>config = models_config.get_config(model)<EOL>if config.menu_exclude:<EOL><INDENT>continue<EOL><DEDENT>menu_icon = None<EOL>menu_path = '<STR_LIT>'.format(app_path, config.model_name)<EOL>if config.menu_root:<EOL><INDENT>order += <NUM_LIT:10><EOL>menu_order = order<EOL>menu_icon = config.menu_icon<EOL>menu_path = config.model_name<EOL><DEDENT>else:<EOL><INDENT>model_order += <NUM_LIT:10><EOL>menu_order = model_order<EOL><DEDENT>self.add_item(<EOL>path=menu_path,<EOL>name=config.menu_name if config.menu_name else model._meta.verbose_name_plural.capitalize(),<EOL>order=config.menu_order if config.menu_order else menu_order,<EOL>icon=menu_icon,<EOL>url=reverse(<EOL>"<STR_LIT>",<EOL>kwargs={<EOL>'<STR_LIT>': model._meta.app_label,<EOL>'<STR_LIT>': model._meta.model_name,<EOL>}<EOL>)<EOL>)<EOL><DEDENT>if model_order > <NUM_LIT:0>:<EOL><INDENT>order += <NUM_LIT:10><EOL>self.add_item(<EOL>path=app_path,<EOL>name=getattr(app, '<STR_LIT>', app.verbose_name),<EOL>icon=getattr(app, '<STR_LIT>', None),<EOL>order=getattr(app, '<STR_LIT>', order),<EOL>)<EOL><DEDENT><DEDENT>
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>'.format(current_path, node).strip('<STR_LIT:/>')<EOL>new_root = root_item.child_by_code(node)<EOL>if not new_root: <EOL><INDENT>new_root = MenuItem(current_path, name=str(node).capitalize())<EOL>root_item.add_child(new_root)<EOL><DEDENT>root_item = new_root<EOL><DEDENT>new_item = MenuItem(path, name, icon, url, order, permission, active_regex)<EOL>current_item = root_item.child_by_code(path.split('<STR_LIT:/>')[-<NUM_LIT:1>])<EOL>if current_item:<EOL><INDENT>current_item.merge(new_item)<EOL><DEDENT>else:<EOL><INDENT>root_item.add_child(new_item)<EOL><DEDENT>
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>return True<EOL><DEDENT>for child in self.childs:<EOL><INDENT>if child.is_active(path):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
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, model_alias))<EOL><DEDENT>self.tabs[model_alias].append(item)<EOL>self.tabs[model_alias] = sorted(self.tabs[model_alias], key=lambda item: item.order if item.order else <NUM_LIT>)<EOL>return create_layout<EOL><DEDENT>return wrapper<EOL>
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_filter<EOL><DEDENT>break<EOL><DEDENT>self.tabs[model_alias] = sorted(self.tabs[model_alias], key=lambda item: item.code if item.code else <NUM_LIT>)<EOL>
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>DescriptionList(*[f.name for f in obj.get_fields()])<EOL>)<EOL>)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>
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)<EOL>return layout<EOL>
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