将Flask类扩展为主应用程序 [英] Extending Flask class as main App
问题描述
from flask import Flask,...
class App(Flask):
def __init __(self,import_name,* args,** kwargs):
super(App,self).__ init __(import_name,* args,** kwargs)
请注意,这可能是一个完全错误的方法。
因此,当我想启动应用程序,我做:
pre $ app $ app $(__ name__)
if __name__ =='__main__':
app.run()
这个方法可以在类中定义我的方法和路由,但问题是使用self-decorators。 (自我,上下文=无):
context = context或dict()
return render_template('home.html',** context)
引发一个错误为未解析的引用'route'
。我想这不是我应该构建应用程序的方式。我应该怎么做,或者我怎么得到的错误修正?
这样做没有任何意义。你可以继承 Flask
来改变它的内部行为,而不是将你的路由定义为类方法。
正在寻找蓝图和应用程序工厂模式。蓝图不需要应用程序即可将视图分组,而工厂只有在调用时才会创建和设置应用程序。
my_app / users / __ init__ .py
from flask import蓝图
bp =蓝图(' users',__name__,url_prefix ='/ users')
my_app / users /views.py
from flask import render_template $ b $ from my_app.users import bp
@ bp.route('/')
def index():
return render_template('users / index.html')
my_app / __ init __。py
def create_app():
app = Flask(__ name__)
#在这里设置应用程序
#例如注册蓝图
from my_app.users import bp
app.register_blueprint(bp)
return app
run.py
from my_app import create_a pp
$ b $ app = create_app()
运行dev服务器:
FLASK_APP = run.py
允许访问视图中的请求。
FLASK_DEBUG = True
烧瓶运行
$ c $如果您需要在视图中访问应用程序,请使用current_app
,就像
$> code> requestfrom flask import current_app
from危险的进口URLSafeSerializer
@ bp.route('/ token')
def token():
s = URLSafeSerializer(current_app.secret_key)
return s.dumps('secret')
你真的想把路由定义为Flask子类的方法,你需要使用
self.add_url_rule
在__ init __
class MyFlask(Flask):
def __init __(self,* args,** kwargs):
super().__ init __(* args,** kwargs):
self.add_url_rule('/',view_func = self.index)
def index(self):
return render_template('index.html')
原因
route
(和self
)不起作用是因为它是一个实例方法,你在定义类时没有实例。I'm learning Flask and am a bit confused about how to structure my code. So I tried to extend Flask main class as follows:
from flask import Flask, ... class App(Flask): def __init__(self, import_name, *args, **kwargs): super(App, self).__init__(import_name, *args, **kwargs)
Note that I am aware of that this may be a completely wrong approach.
So that when I want to start the app I do:app = App(__name__) if __name__ == '__main__': app.run()
This way I can order my methods and routes in the class, but the problem is when using self-decorators:
@route('/') def home(self, context=None): context = context or dict() return render_template('home.html', **context)
Which raises an error as
unresolved reference 'route'
. I guess this is not the way I should be structuring the app. How should I do it instead or how do I get the error fixed?解决方案Doing this doesn't make sense. You would subclass
Flask
to change its internal behavior, not to define your routes as class methods.Instead, you're looking for blueprints and the app factory pattern. Blueprints divide your views into groups without requiring an app, and the factory creates and sets up the app only when called.
my_app/users/__init__.py
from flask import Blueprint bp = Blueprint('users', __name__, url_prefix='/users')
my_app/users/views.py
from flask import render_template from my_app.users import bp @bp.route('/') def index(): return render_template('users/index.html')
my_app/__init__.py
def create_app(): app = Flask(__name__) # set up the app here # for example, register a blueprint from my_app.users import bp app.register_blueprint(bp) return app
run.py
from my_app import create_app app = create_app()
Run the dev server with:
FLASK_APP=run.py FLASK_DEBUG=True flask run
If you need access to the app in a view, use
current_app
, just likerequest
gives access to the request in the view.from flask import current_app from itsdangerous import URLSafeSerializer @bp.route('/token') def token(): s = URLSafeSerializer(current_app.secret_key) return s.dumps('secret')
If you really want to define routes as methods of a Flask subclass, you'll need to use
self.add_url_rule
in__init__
rather than decorating each route locally.class MyFlask(Flask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs): self.add_url_rule('/', view_func=self.index) def index(self): return render_template('index.html')
The reason
route
(andself
) won't work is because it's an instance method, but you don't have an instance when you're defining the class.这篇关于将Flask类扩展为主应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!