Beispiel #1
0
 def _paginated(self, query, page_num, results_per_page, model_dict_kargs=None,
                relload=None):
     """Returns a paginated JSONified response from the specified list of
     model instances.
     `instances` is either a Python list of model instances or a
     :class:`~sqlalchemy.orm.Query`.
     The response data is JSON of the form:
     .. sourcecode:: javascript
        {
          "page": 2,
          "total_pages": 3,
          "num_results": 8,
          "objects": [{"id": 1, "name": "Jeffrey", "age": 24}, ...]
        }
     """
     num_results = query.count()
     if results_per_page > 0:
         # get the page number (first page is page 1)
         start = (page_num - 1) * results_per_page
         end = min(num_results, start + results_per_page)
         total_pages = int(math.ceil(float(num_results) / results_per_page))
     else:
         page_num = 1
         start = 0
         end = num_results
         total_pages = 1
     objects = [to_dict(x, **(model_dict_kargs or {})) for x in query[start:end]]
     return dict(page=page_num, objects=objects, total_pages=total_pages,
                 num_results=num_results)
Beispiel #2
0
    def select(self, modelName, queryDict=None, page=1, maxPerPage=None):
        """
        Issue a SELECT statement on the table corresponding to modelName.
        Results are paginaged and the page to be returned or the maximum
        number of results per table may be specified.

        :param modelName str: the name of the model within the Manager
        :param queryDict dict: if not specified, then the whole table
            will be queried. It is a dictionary of the form::

                {
                  "filters": [{"name": "age", "op": "lt", "val": 20}, ...],
                  "order_by": [{"field": "age", "direction": "desc"}, ...],
                  "limit": 10,
                  "offset": 3,
                  "disjunction": True,
                  "to_dict": {"deep":{"employees":[]}},
                  "joinedload" : ["employees"],
                }
            where:
                * ``filters`` is the list of filter specifications,
                * ``order_by`` is the list of order by specifications,
                * ``limit`` is the maximum number of total matching entries to return,
                * ``offset`` is the number of initial entries to skip in
                  the matching result set,
                * ``disjunction`` is whether the filters should be joined as a disjunction (AND) or conjunction (OR),
                  defaults to True (AND)
                * ``to_dict`` specifies the configuration for the SQLAlchemy objects serializer.
                * ``joinedload`` specifies a list of relations to be loaded using the
                  SQLAlchemy joinedload strategy (by default lazy load is used which
                  is not very efficient when serializing relations)
        :param page int: the page number to be returned
        :param maxPerPage int: the maximum number of results per page, defaults
            to the maxResultsPerPage attribute,
        :return dict: a dictionary of the form::

               {
                 "page": 2,
                 "total_pages": 3,
                 "num_results": 8,
                 "objects": [{"id": 1, "name": "Jeffrey", "age": 24}, ...]
               }
            This may depends on some queryDict parameters,
            to decide for instance whether related models should be returned
            as well. Here num_results is the total number of results matching the queryDict.
            As said, however, only maxPerPage results will be returned by each select.
        """
        if not queryDict: queryDict = {}
        model = self.get_model(modelName)
        modelDictKargs = deepcopy(self.modelDictKargs[modelName])
        with closing(self.dbConnection.get_session()) as session:
            sp = SearchParameters.from_dictionary(queryDict)
            q = create_query(session, model, sp)
            is_single = queryDict.get('single')
            functions = queryDict.get('functions')
            todict = queryDict.get('to_dict', {})
            modelDictKargs.update(todict)
            jload = queryDict.pop('joinedload', None)
            if jload:
                q = q.options(*(joinedload(x) for x in jload))
            if is_single:
                return to_dict(q.one(), **modelDictKargs)
            elif functions:
                return self._evaluate_functions(session, model, functions,
                                                sp)
            else:
                if maxPerPage is None:
                    maxPerPage = self._maxResultsPerPage
                return self._paginated(q, page_num=page,
                                       results_per_page=maxPerPage,
                                       model_dict_kargs=modelDictKargs)
Beispiel #3
0
 def select_by_unique(self, modelName, value, fieldName="id"):
     model = self.get_model(modelName)
     with closing(self.dbConnection.get_session()) as session:
         inst = session.query(model).filter(getattr(model, fieldName) == value).\
                         one()
         return to_dict(inst, **self.modelDictKargs[modelName])
Beispiel #4
0
def paginated(query, page_num, results_per_page, model_dict_kargs=None,
              relload=None, num_results=None):
    start, end, page_num, total_pages, num_results = get_pagination(query, page_num, results_per_page, num_results)
    objects = [to_dict(x, **(model_dict_kargs or {})) for x in query[start:end]]
    return dict(page=page_num, objects=objects, total_pages=total_pages,
                num_results=num_results)