flask-sqlalchemy一对多 知了传课 flask web全栈开发实战 黄勇

务必添加app.app_context().push()
不然报错
Flask 2.2.2
Flask-SQLAlchemy 3.0.0

user 为一
articles 为多

# app.py

from flask import Flask, render_template, flash, request, session, redirect, url_for, abort, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# MySQL所在的主机名
HOSTNAME = "127.0.0.1"
# MySQL监听的端口号,默认3306
PORT = 3306
# 连接MySQL的用户名,读者用自己设置的
USERNAME = "root"
# 连接MySQL的密码,读者用自己的
PASSWORD = "root"
# MySQL上创建的数据库名称
DATABASE = "database_learn"
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"

db = SQLAlchemy(app)
app.app_context().push()
# with db.engine.connect() as conn:
#     rs = conn.execute("select 1")
#     print(rs.fetchone())


class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(100))
    password = db.Column(db.String(100))

    articles = db.relationship("Article",back_populates="author")

class Article(db.Model):
    __tablename__ = "article"
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    title = db.Column(db.String(100))
    content = db.Column(db.Text)

    author_id = db.Column(db.Integer,db.ForeignKey("user.id"))
    author = db.relationship("User", back_populates="articles")

db.create_all()

参考
https://github.com/hynever/flask_fullstack/blob/main/database/app.py

你可能感兴趣的:(python,笔记,flask,python,后端)