mysql 使用app.config.from_object配置 flask 应用程序

lx0bsm1f  于 2023-03-11  发布在  Mysql
关注(0)|答案(1)|浏览(296)

我有一个使用MySQL DB的 flask 应用程序我想使用config.formobject(object)配置我的应用程序然后,我编写以下类:

import os

    class Config:
        DEBUG = True
        TESTING = False
        SESSION_COOKIE_SECURE = True
        SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:tool789@localhost/city'"
        SQLALCHEMY_TRACK_MODIFICATIONS = False
        SECRET_KEY = os.urandom(24)
        MAIL_SERVER = "Yourdomain"
        MAIL_USERNAME = "username"
        MAIL_PASSWORD = "password"
        MAIL_PORT = 456
        MAIL_USE_SSL = True
        MAIL_USE_TSL = False

并将其导入到我的_init_.py中:

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail, Message
from app.config import *
app = Flask(__name__)
Bootstrap(app)

db = SQLAlchemy(app)
app.config.from_object(Config)

from app import views
from app import admin_views
from app.dbmodels import *

with app.app_context():
    db.create_all()

当我运行我的服务器时,我得到这个错误:

Traceback (most recent call last):
  File "C:\Users\Pourya\PycharmProjects\websiteproject\run.py", line 1, in <module>
    from app import app
  File "C:\Users\Pourya\PycharmProjects\websiteproject\app\__init__.py", line 10, in <module>
    db = SQLAlchemy(app)
  File "C:\Users\Pourya\PycharmProjects\websiteproject\venv\lib\site- 
    packages\flask_sqlalchemy\extension.py", line 219, in __init__
     self.init_app(app)
   File "C:\Users\Pourya\PycharmProjects\websiteproject\venv\lib\site- 
    packages\flask_sqlalchemy\extension.py", line 307, in init_app
     raise RuntimeError(
 RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.

我的问题是什么,我可以由谁来解决?

sdnqo3pr

sdnqo3pr1#

你正在使用app的配置创建db客户端,但尚未配置app。请先尝试配置应用:

app.config.from_object(Config)
db = SQLAlchemy(app)

相关问题