3

Flask の設計図がどのようにインポートされるのかに興味があります。それはまだFlaskによって行われたすべての作業の最後にpythonモジュールをインポートします。私が正しければ、pythonはインポート時に2つのことを行います.モジュール名を名前空間に登録し、必要に応じて初期化します.

そのため、Flask ブループリントが登録時に初期化されると、すべてのモジュールがメモリ内にあり、登録するブループリントが多数ある場合、1 つのリクエストで基本的に 1 つのブループリントを使用するため、メモリが無駄になります。大きな損失ではありませんが、それでも...

ただし、名前空間にのみ登録され、必要なとき (実際の要求が到達したとき) にのみ初期化される場合は、それらをすべて一度に登録するのが理にかなっています (私が理解した推奨される方法です)。これは私がここに当てはまると思います:)しかし、もう少し深く尋ねて理解したかっただけです。

4

1 に答える 1

3

私は決して専門家ではありませんが、最近、設計図で少し遊んでいます。

You can only register a blueprint on your flask app if the blueprint code has been imported into the current Python instance, for example:

from my_blueprint import blueprint_object

app.register_blueprint(blueprint_object, url_prefix='/my_blueprint')

meaning that all of the memory required for blueprint_object has been allocated, the __init__.py file associated with my_blueprint has been evaluated and everything is ready to go.

I experimented briefly with trying to load a blueprint in the app.before_first_request method, but flask doesn't allow this, blueprints all need to be loaded before anything makes a request (and before_first_request effectively runs just after that, but before any other code gets to play).

Blueprints are designed to provide extensible functionality to flask web-apps. I'm not sure why loading them in would be a waste of resources, unless you're only ever going to use a particular piece of functionality once, in which case, you might want to re-factor your application into a number of different apps that you can spin up as required.

于 2012-11-12T10:58:20.337 に答える