flask: Don't create View instances for each request

View.as_view creates a function that instantiates the class every request. This seems inefficient for no real gain.

class DeleteView(View):
    methods = ['DELETE']

    # this only needs to happen once
    def __init__(self, model):
        self.model = model
        # imagine if we did something expensive here
        # like generating a form based on the model

The only argument I could think of for instantiating every request is if the constructor does something different based on the request. That seems like bad design, but any use that I can think of for that could be accomplished with properties instead.

Yes, there are ways to make it less expensive, like generating more ahead of time and passing more arguments, but that is not intuitive, and makes the class just a more complicated view factory.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 5
  • Comments: 19 (17 by maintainers)

Most upvoted comments

I don’t see how this can safely be changed without risking to break people’s code if they store stuff on self e.g. because they call other methods in the same class and pass some thing via attributes instead of arguments.

Besides that, instantiating a class is quite cheap…

@davidism i could imagine a lifetime attribute on the view that the generic as_view function internally references. It could be 'request' which means it lives for the single request only, 'application' which binds it to the application instance or 'global' which makes it an actual singleton that then cannot have state.

Generally the only values I think make sense are 'request' and 'application' though.

I’ll have to think on how we could do SingletonView without copying the View.as_view code, which would be harder to maintain. But I’m ok with it in principal, assuming we change the docs to push it as the normal choice and View as a more advanced choice.

We could probably do something with __setattr__, similar to how the Flask object prevents setup methods after handling requests. From my experience on Stack Overflow, the users who would use globals will find a way and insist it’s ok anyway.