Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are Flask Resources created?

Tags:

python

flask

I'm new to Flask. I have a resource class that handles POST requests. The request processing is quite elaborate, and can't be all in the post function. Do I get a new Resource instance for each request? Or are instances reused? Is it safe for me to do something like:

class MyResource(Resource):
    def post(self):
        self.var = 17
        self.do_some_work()
        return self.var * self.var

Does Flask guarantee that my resource instance will not be used for other transactions?

like image 448
zmbq Avatar asked Oct 15 '22 07:10

zmbq


1 Answers

Resource objects are created at the time the request should be served and they are not persistent. Keep in mind that REST principles say that APIs must be stateless. If you want to store data between requests, you should use some kind of database.

The simplest method to prove what I said is to use a print (id(self)) in your get handler and trigger the request a few times. You will see that the object always changes.

Now, if you are interested about Flask internals, here we go. The class Resource is part of Flask-RESTtful and the documentation states the following:

Resources are built on top of Flask pluggable views, giving you easy access to multiple HTTP methods just by defining methods on your resource.

Resources are added with the method Resource.add_resource() and it is simply registering the underlying View object.

if self.app is not None:
    self._register_view(self.app, resource, *urls, **kwargs)
else:
    self.resources.append((resource, urls, kwargs))

Resource._register_view() method does a lot of crazy stuff, but the most meaningful things are those two lines:

resource_func = self.output(resource.as_view(endpoint, *resource_class_args, **resource_class_kwargs))
...
self.blueprint_setup.add_url_rule(url, view_func=resource_func, **kwargs)

Here you can see that the view object provides a handler that will be associated with the URL path. This handler will be called every time a HTTP request is made to this route.

Finally, we arrived at the core, in the View.as_view() method, it creates a function on-the-fly and this function will represent the route handler.

def view(*args, **kwargs):
    self = view.view_class(*class_args, **class_kwargs)
    return self.dispatch_request(*args, **kwargs)

As you can see, this function will create a new object every time a request must be dispatched and as you already guessed, view_class is containing your custom class for handling the requests.

like image 117
Mihail Feraru Avatar answered Oct 21 '22 20:10

Mihail Feraru