Skip to content

Conversation

@nggit
Copy link
Owner

@nggit nggit commented Dec 17, 2025

Currently, HelloView.__init__() is called per-request. This makes each class instances belong to each requests, and therefore is safe by default.

class HelloView:
    async def get(self, request, **server):
        return 'Hello, World!'


app.add_route(HelloView, '/hello')
app.add_route(HelloView(), '/world')  # doesn't work

But some people may have a certain requirement or want to only call HelloView.__init__() once on main.

This little change will make this possible. No configuration, no extra flags... like init_every_request = False. Just pass a class instance!

Example

class HelloView:
    def __init__(self, event, *args, **kwargs):
        print('--> calling __init__ on:', event)

    async def get(self, request, **server):
        return 'Hello, World!'


app.add_route(HelloView, '/hello', event='request')
app.add_route(HelloView('main'), '/world')

Note

  • A class with def __call__ is intentionally not supported to avoid complexity
  • **server is required

Bonus

module-based is likely to work. But this should be treated as a side effect, not feature.

# mymodules/mymodule.py
async def get(request, **server):  # no 'self' here. if you insist, 'self' points to this module
    return 'Hello, World!'
from mymodules import mymodule

app.add_route(mymodule, '/foo')

@sonarqubecloud
Copy link

@nggit nggit merged commit 2fc1c8c into main Dec 20, 2025
23 checks passed
@nggit nggit deleted the cbv_instance branch December 20, 2025 04:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants