[英]What is the correct way to solve this circular import error with a Flask blueprint?
[英]What is the intended way to pass a parameter to a flask blueprint?
在問上一個問題后,有人告訴我我的應用程序的組織很奇怪,所以我查看了其他示例,看看我如何處理我想做的事情。
我發現的最明顯的例子是一個燒瓶應用的學校案例。 據我了解:
app
對象在app模塊中聲明
路由在routes模塊中聲明
藍圖根據需要導入路線
但是,在我的應用程序中,為了回答一些路由,我需要訪問在app模塊中定義的參數(它們在創建 app 對象之前使用)。
如何在路由模塊中訪問這些參數?
我不能只是從應用程序導入它們,因為那將是循環導入。
我可以使用這個問題中建議的構造函數,但考慮到我對上一個問題的評論,這似乎不是處理這個問題的常用方法。
聽起來您可能需要使用基於類的視圖。
您面臨的問題是您的視圖函數在運行時需要值,但很難將它們導入到定義函數的路由模塊中。 您最初試圖用函數中的函數來解決這個問題(雖然完全有效,但不是很 Python 化)。
我建議創建一個views.py
文件並定義一個基於類的視圖(或者你可以稱之為routes.py
,這並不重要):
from flask.views import View
class MyView(View):
methods = ['GET']
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
def dispatch_request(self):
return 'param1: {}\nparam2: {}'.format(self.param1, self.param2)
def add_routes(app, param1, param2):
# `param1` and `param2` will get passed to the view class constructor
app.add_url_rule('/', view_func=MyView.as_view('myview', param1, param2))
然后,在您的server.py
文件(或您調用的任何文件)中,您可以將應用程序和參數傳遞給add_routes
函數:
from flask import Flask
from .views import add_routes
param1 = 'foo'
param2 = 'bar'
app = Flask(__name__)
add_routes(app, param1, param2)
add_routes
不必存在於views.py
,它可以存在於任何地方。 或者,如果您沒有很多路線,您可以完全擺脫它:
from flask import Flask
from .views import MyView
param1 = 'foo'
param2 = 'bar'
app = Flask(__name__)
app.add_url_rule('/', view_func=MyView.as_view('myview', param1, param2))
請注意,該類將在每個請求上被實例化,而不僅僅是一次。 所以你不應該在構造函數中做任何特別密集的事情(比如讀取文件)。
遵循史蒂夫的回答精神,我得到了這個可行的解決方案:
在 [routes.py] 中:
class Routes:
# constructor
def __init__(self, config: dict):
self.__config = config
# init_session
def init_session(self, type_response: str):
# using the config
config = self.__config
...
# authenticate_user
def authenticate_user(self):
# using the config
config = self.__config
...
在 [main.py]
config={...}
# Flask app
app = Flask(__name__, template_folder="../templates", static_folder="../static")
# routes # routes
from routes import Routes
# class instance with needed parameters
routes = Routes(config)
# adjusting urls with routes
app.add_url_rule('/init-session/<string:type_response>', methods=['GET'],
view_func=routes.init_session)
app.add_url_rule('/authenticate-user', methods=['POST'],
view_func=routes.authenticate_user)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.