Почему не создается таблица в базе данных MySQL?
Вот app.py:
from flask_sqlalchemy import SQLAlchemy
# Creating Flask app
app = Flask(__name__)
# Creating SQLAlchemy instance
db = SQLAlchemy()
user = "cubinez85"
pin = "123"
host = "localhost"
db_name = "testbd"
# Configuring database URI
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{user}:{pin}@{host}/{db_name}"
# Disable modification tracking
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
# Creating Models
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
password = db.Column(db.String(128))
def create_db():
with app.app_context():
db.create_all()
if __name__ == "__main__":
create_db()
app.run(debug=True)```
Таблица users не создается:
```mysql> use testbd;
Database changed
mysql> show tables;
Empty set (0,01 sec)
mysql>```
В error.log все хорошо:
```[2024-04-03 18:31:48 +0300] [35124] [INFO] Using worker: sync
[2024-04-03 18:31:48 +0300] [35126] [INFO] Booting worker with pid: 35126
[2024-04-03 18:31:48 +0300] [35127] [INFO] Booting worker with pid: 35127
[2024-04-03 18:31:48 +0300] [35128] [INFO] Booting worker with pid: 35128
[2024-04-03 18:35:13 +0300] [35124] [INFO] Handling signal: term
[2024-04-03 18:35:13 +0300] [35126] [INFO] Worker exiting (pid: 35126)
[2024-04-03 18:35:13 +0300] [35127] [INFO] Worker exiting (pid: 35127)
[2024-04-03 18:35:13 +0300] [35128] [INFO] Worker exiting (pid: 35128)
[2024-04-03 18:35:14 +0300] [35124] [INFO] Shutting down: Master
[2024-04-03 18:35:15 +0300] [35146] [INFO] Starting gunicorn 21.2.0
[2024-04-03 18:35:15 +0300] [35146] [INFO] Listening at: unix:/var/www/project_flask/ipc.sock (35146)
[2024-04-03 18:35:15 +0300] [35146] [INFO] Using worker: sync
[2024-04-03 18:35:15 +0300] [35147] [INFO] Booting worker with pid: 35147
[2024-04-03 18:35:15 +0300] [35148] [INFO] Booting worker with pid: 35148
[2024-04-03 18:35:15 +0300] [35149] [INFO] Booting worker with pid: 35149```
Ответы (1 шт):
Автор решения: cubinez85
→ Ссылка
Решил через DeclarativeBase:
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import DeclarativeBase
app = Flask(__name__)
mysql_database = 'mysql://cubinez85:123@localhost/testdb'
engine = create_engine(mysql_database)
class Base(DeclarativeBase): pass
class Person(Base):
__tablename__ = "people"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(64), unique=True, index=True)
age = Column(String(128))
Base.metadata.create_all(bind=engine)
if __name__ == "__main__":
create_db()
app.run(debug=True)```