What does this construct in Pyramid mean?

Viewed 88

Construction from pyramid docs

@classmethod
def all(cls, request):
    query = request.dbsession.query(BlogRecord)
    return query.order_by(sa.desc(BlogRecord.created))

I don't understand what's going on in this statement.

query = request.dbsession.query(BlogRecord)

As I understand we create an example of a query class, but what do we get from:

  1. query(BlogRecord) inheritance from BlogRecord?
  2. request.dbsession.query I have no idea.
1 Answers

Assuming you walked through all the previous steps in the tutorial including 1. Create your pyramid_blogr project structure and Adding model definitions, you would know that BlogRecord is an object or an instance of the class BlogRecord which inherits from the SQLAlchemy metadata Base class defined in models.meta which was created using the alchemy cookiecutter. This line:

query = request.dbsession.query(BlogRecord)

creates a variable query and assigns a database query object as its value. It does not execute the query yet. The next line does that, and returns the result.

Going further, taking apart request.dbsession.query, the request portion is a request object that is passed around in Pyramid. Attributes can be attached to the request object, in this case the dbsession object (an SQLAlchemy database session object) is the attribute. This in turn has a method named query which accepts a data model as its argument.

This is mostly Python stuff regarding classes and methods, and not specific to Pyramid. I'd suggest reading more about those in the Python documentation and tutorials.

Note: the answer from @not_a_bot_no_really_82353 is completely wrong. Pyramid does not use the requests (plural) library. Pyramid has a request (singular) object. Also the "docs" are a community-contributed tutorial, not documentation. For official documentation and tutorials, visit https://docs.pylonsproject.org/projects/pyramid/en/latest/index.html

Related