def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) # 注册蓝图 from app.home import home as home_blueprint from app.admin import admin as admin_blueprint app.register_blueprint(home_blueprint) app.register_blueprint(admin_blueprint, url_prefix="/admin") return app
时间: 2023-06-13 15:08:02 浏览: 68
这是一个 Flask 应用工厂函数,用于创建 Flask 应用实例。它根据传入的配置名参数,加载对应的配置文件,并对应用实例进行配置。接着,初始化数据库实例,注册蓝图并返回应用实例。
具体来说,`app = Flask(__name__)` 创建了一个 Flask 应用实例,`app.config.from_object(config[config_name])` 加载对应的配置文件,`config[config_name].init_app(app)` 对应用实例进行配置。`db.init_app(app)` 初始化数据库实例。接下来,注册蓝图,其中 `home` 和 `admin` 分别是两个蓝图的名称,`url_prefix` 参数指定了 `admin` 蓝图的 URL 前缀。最后,返回应用实例。
相关问题
db = SQLAlchemy() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) # 注册蓝图 from app.home import home as home_blueprint app.register_blueprint(home_blueprint) return app
这是一个用Python语言编写的程序,其中包含了Flask和SQLAlchemy库。这段代码定义了一个create_app函数,该函数初始化了一个Flask应用程序,并加载了一个配置。然后通过db.init_app函数初始化了SQLAlchemy,将其连接到应用程序中。
flask mysql config
To configure Flask to work with MySQL, you first need to install the necessary packages. You can do this using pip by running the following command:
```
pip install flask-mysql
```
Once you have installed the package, you can then create a connection to your MySQL database using the following code:
```python
from flask import Flask
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'your_username'
app.config['MYSQL_DATABASE_PASSWORD'] = 'your_password'
app.config['MYSQL_DATABASE_DB'] = 'your_database'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
```
In this code, you should replace `your_username`, `your_password`, and `your_database` with your own MySQL database credentials. You can then use the `mysql` object to execute SQL queries on your database.
For example:
```python
@app.route('/')
def index():
cursor = mysql.get_db().cursor()
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
return str(users)
```
This will execute a simple SQL query to select all the rows from the `users` table and return the result as a string.