How to bind an object of a request instance to a class attempt

hello everyone
I am a novice in sanic, and I want to bind an object of a request instance to a view class. What should I do?

I am accustomed to writing class based views, similar to the following


from sanic.views import HTTPMethodView



class BaseView(HTTPMethodView):

    @property

    def db(self):

        #TODO returns the ctx.session object of the current request instance here

       pass

    async def do_ something(self):

        await self.db.query..........

The following is the request middleware section


_ base_ model_ session_ ctx = ContextVar("session")

async def inject_ session(request):

    request.ctx.session = ConnectionAsync(**kwargs )

    request.ctx.session_ ctx_ token = _ base_ model_ session_ ctx.set(request.ctx.session)

“I can use the request.ctx.session object operation in class view functions, but I prefer to be able to directly use self.db to point to the current session object in all views that inherit from the baseview class.”.

How can I do this in this situation? Or is there a better way?

Take a look at this: Request | Sanic Framework

I think this might be a better solution for you. There is already a bound ContextVar for getting the current request, and from there anything that is set upon it.

from sanic import Request

request = Request.get_current()
1 Like