一个 Flask 自动导入器,可让您的 Flask 应用程序变大。
项目描述
Flask-BigApp
pip install flask-bigapp
NOTE:
这个版本;作为 1.2.* 及更高版本包括对版本 1.1.* 上的任何内容的一些重大更改
什么是 Flask-BigApp?
Flask-BigApp 的主要目的是帮助简化蓝图、路线和模型的导入。它内置了一些额外的功能来帮助主题化、保护页面和密码验证。
最小的 Flask-BigApp 应用程序
配置文件需要位于您的应用程序文件旁边__init__.py
。这默认为default.config.toml
如果 Flask-BigApp 无法找到该default.config.toml
文件,它将创建一个。
您还可以通过设置BA_CONFIG
环境变量来设置配置文件。例如:(在终端中)export BA_CONFIG=production.config.toml
该default.config.toml
文件包含 Flask 配置设置,该文件的最小版本如下所示:
# Updates the Flask app config with the variables below.
# If any variable below does not exist in the standard Flask env vars it is created and will be accessible using
# current_app.config["YOUR_VAR_NAME"] or of course, app.config["YOUR_VAR_NAME"] if you are not using app factory.
[flask]
app_name = "app"
version = "0.0.0"
secret_key = "sdflskjdflksjdflksjdflkjsdf"
debug = true
testing = true
session_time = 480
static_folder = "static"
template_folder = "templates"
error_404_help = true
您还可以在配置文件中使用环境变量标记,这是一个示例:
# Updates the Flask app config with the variables below.
# If any variable below does not exist in the standard Flask env vars it is created and will be accessible using
# current_app.config["YOUR_VAR_NAME"] or of course, app.config["YOUR_VAR_NAME"] if you are not using app factory.
[flask]
app_name = "app"
version = "0.0.0"
secret_key = "<SECRET_KEY>"
debug = "<DEBUG>"
testing = true
session_time = 480
static_folder = "static"
template_folder = "templates"
error_404_help = true
random_value = "<TAGS_CAN_BE_ANYTHING>"
现在,如果您设置标签中包含的环境变量,Flask-BigApp 将用这些值替换它们。下面是一个在linux中设置环境变量的例子:
export SECRET_KEY="asdlasijd90339480239oiqjdpiasdj"
和export DEBUG=True
要传入的环境变量在配置文件中定义,看看random_value
. 要设置它,我们需要这样做:export TAGS_CAN_BE_ANYTHING="what we put here will be the new value"
注意:如果你使用 config 文件中的一些环境变量标签可能不起作用flask run
,你可以通过使用来运行应用程序venv/bin/python run_example.py
。
您的应用程序__init__.py
文件应如下所示:
from flask import Flask
from flask_bigapp import BigApp
bigapp = BigApp()
def create_app():
main = Flask(__name__)
bigapp.import_builtins("routes")
return main
注意:您也可以通过执行手动设置配置文件bigapp.init_app(main, app_config_file="dev.config.toml")
该bigapp.import_builtins("routes")
方法在routes
文件夹中查找.py
要从中导入应用程序路由的文件。
假设我们有这个文件夹结构:
Flask-BigApp
|
- app/
-- static/
-- templates/
--- routes/
------ index.py
-- __init__.py
-- app_config.toml
- venv
- run.py
该index.py
文件应如下所示:
from flask import current_app
@current_app.route("/", methods=['GET'])
def index_page():
"""
Example index route
"""
return "You will see this text in the browser"
import_builtins()
该文件将使用该方法导入主应用程序。
如果我们将另一个文件添加到routes
文件夹中,情况也是如此。假设我们添加my_page.py
到路由文件夹中,它看起来像这样:
from flask import current_app
@current_app.route("/my-page", methods=['GET'])
def my_page():
"""
My Page Route
"""
return "This is my page route"
所以现在我们的文件夹结构如下所示:
Flask-BigApp
|
- app/
-- static/
-- templates/
--- routes/
------ index.py
------ my_page.py
-- __init__.py
-- app_config.toml
- venv
- run.py
路线也将my_page.py
被导入主应用程序。
使用这种方法,您可以将路线保存在不同的文件中,而不必担心将导入添加到__init__.py
文件中。
更多 Flask-BigApp 功能
导入模型
您可以使用以下方法导入模型类:
bigapp.import_models(file="models.py", folder="models")
示例模型文件如下所示:
from app import bigapp
from sqlalchemy import ForeignKey
db = bigapp.db
class ExampleTable(db.Model):
__tablename__ = "fl_example_table"
example_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, ForeignKey('fl_example_user.user_id'))
thing = db.Column(db.String(256), nullable=False)
使用模型
您可以照常使用模型,但不再需要一一导入。
这是一个如何设置 Flask-BigApp 以导入模型文件的示例:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bigapp import BigApp
bigapp = BigApp()
db = SQLAlchemy
def create_app():
main = Flask(__name__)
bigapp.import_builtins("routes")
bigapp.import_models(file="models.py")
# or
bigapp.import_models(folder="models")
return main
这是一个如何使用该bigapp.model_class
方法进行查询的示例:(假设您bigapp = BigApp()
在您的应用程序__init__.py
文件中有)
from flask import render_template
from app import bigapp
from .. import bp
@bp.route("/database-example", methods=["GET"])
def database_example():
# Load the ExampleUser class found in the import_models folder, this way saves having to import files
example_user = bigapp.model_class("ExampleUser")
user_id = 1
result = "NULL"
find_username = True
# Normal query
nq_example_user = example_user.query
# Query class using sql_do session
sq_example_user = bigapp.sql_do.query(example_user)
if find_username:
sq_example_user = sq_example_user.filter(example_user.user_id == user_id).first()
if sq_example_user is not None:
username = sq_example_user.username
result = f"Session Query: Username is {username}"
nq_example_user = nq_example_user.filter(example_user.user_id == user_id).first()
if nq_example_user is not None:
username = nq_example_user.username
example_table_join = nq_example_user.rel_example_table[0].thing
result = f"{result}, Normal Query: Username is {username} -> ExampleTable Join: {example_table_join}"
render = "blueprint1/database-example.html"
return render_template(render, result=result)
该bigapp.sql_do
方法只是一个代理db.session
导入内置(路由、模板过滤器、上下文处理器)
您可以使用以下方法从文件夹中自动导入路由、模板过滤器、上下文处理器等:
bigapp.import_builtins("builtins")
这是内置文件夹结构的示例:
builtins/
|
-- routes.py
-- template_filters.py
导入内置使用 Flaskcurrent_app
来注册路由,这是内置文件夹中的文件示例:
from flask import current_app
from flask import Response
from flask import render_template
from markupsafe import Markup
@current_app.template_filter('example')
def decorate_code(value: str) -> str:
return Markup(f"The string value passed in is: {value} -> here is something after that value.")
@current_app.before_request
def before_request():
pass
@current_app.errorhandler(404)
def request_404(error):
return Response(error, 404)
@current_app.route("/builtin/route")
def builtin_route():
render = "theme1/renders/builtin-route.html"
return render_template(render)
导入蓝图
您可以使用以下方式自动导入蓝图:
bigapp.import_blueprints("blueprints")
要从中导入蓝图的文件夹的形状应如下所示:
blueprints/
|
- blueprint1/
-- routes/
---- index.py
-- templates/
---- blueprint1/
------ index.html
-- static/
-- __init__.py
-- config.toml
|
- another_blueprint/
-- routes/
---- index.py
-- templates/
---- another_blueprint/
------ index.html
-- static/
-- __init__.py
-- config.toml
在上面,我们将所有模板嵌套在与蓝图同名的文件夹下。这是一种解决方法,可让您在不同的蓝图文件夹中拥有同名的模板文件。
蓝图需要一个配置文件来配置它们的设置。配置文件应如下所示:
enabled = "yes"
[settings]
url_prefix = "/"
template_folder = "templates"
static_folder = "static"
static_url_path = "/blueprint1/static"
[session]
var_in_session = "this can be loaded using bp.init_session()"
permissions = ["this", "that"]
logged_in = true
not_logged_in = false
会话部分可以使用该bp.init_session()
方法初始化。这会将值放入 Flask 会话 ->from flask import session
__init__.py
这是您的蓝图文件应该是什么样子的示例:
from flask_bigapp import Blueprint
bp = Blueprint(__name__, "config.toml")
bp.import_routes("routes")
@bp.before_app_request
def before_app_request():
bp.init_session()
@bp.after_app_request
def after_app_request(response):
return response
Flask-BigApp 继承自 Flask 的 Blueprint 类,以便从配置文件中加载。在上面的示例中,它说明了配置文件名,但是您可以省略它,因为它默认为config.toml
. 当然,您可以指定自己的配置文件名。
bp.import_routes("routes")
bigapp.import_builtins
方法的工作原理与蓝图对象的工作范围大致相同。
这是一个例子routes/index.py
from flask import render_template
from .. import bp
@bp.route("/", methods=["GET"])
def index():
render = bp.tmpl("index.html")
return render_template(render)
该bp.tmpl
方法只是用蓝图的名称装饰字符串,更改"index.html"
为"blueprint1/index.html"
.
当然,这仅在您的模板嵌套在与您的蓝图同名的文件夹下时才有效,但是它确实可以稍后更改蓝图名称,而不必担心搜索和替换。
导入结构(主题)
您可以使用以下方法注册结构(主题)文件夹:
bigapp.import_structures("structures")
结构与蓝图的工作方式相同,但用于主题化并且没有配置文件,这是结构文件夹的文件夹布局示例:
structures/
|
- theme1/
-- templates/
--- theme1/
---- extend/
------ main.html
---- includes/
------ footer.html
---- macros/
------ theme1_menu.html
-- static/
---- logo.png
---- style.css
-- __init__.py
-- config.toml
GitHub 项目
这个 github 项目是一个工作示例,它可以做的比上面的最小应用程序要多得多。
该项目涵盖如何使用模型、蓝图和主题(结构)
Linux 设置
(假设位置是主目录)
Git克隆:
git clone https://github.com/CheeseCake87/Flask-BigApp.git
或者
- 下载压缩包并解压
- cd 进入解压后的文件夹
进入 Flask-BigApp 目录:
cd Flask-BigApp
创建虚拟环境:
python3 -m venv venv
进入虚拟环境:
source venv/bin/activate
从 src 安装 Flask-BigApp:
pip install -e .
运行烧瓶:
flask run
或从文件运行:
python3 run_example.py
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。
源分布
内置分布
flask- bigapp -1.2.3.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | eba635ebd0d38a3d0898d7b3603ed8a7839a2e299987fa5b3ef57f7caf2c5e99 |
|
MD5 | cf10c48db56f7a57b4577e61c96de30e |
|
布莱克2-256 | 943dc0b877cf6064ec92a92e62b0aede4376c6a545614fce3cab346d9a1341cc |