美文网首页
flask mysql

flask mysql

作者: wuyuan0127 | 来源:发表于2024-01-10 08:48 被阅读0次

    1.  configs.py

    HOST ='127.0.0.1'

    PORT ='3306'

    DATABASE ='test_order'

    USERNAME ='root'

    PASSWORD ='root'

    DB_URI ="mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOST,port=PORT,db=DATABASE)

    SQLALCHEMY_DATABASE_URI = DB_URI

    SQLALCHEMY_TRACK_MODIFICATIONS =False

    SQLALCHEMY_ECHO =True

    2. models.py

    from flask_sqlalchemyimport SQLAlchemy

    from sqlalchemyimport Integer, String

    from sqlalchemy.ormimport Mapped, mapped_column

    db = SQLAlchemy()

    class Student(db.Model):

    __tablename__ ="student"

        id: Mapped[int] = mapped_column(Integer,primary_key=True)

    name: Mapped[str] = mapped_column(String(255),nullable=False)

    3. app.py

    from flaskimport Flask

    import configs

    from modelsimport db, Student

    app = Flask(__name__)

    # 读取配置文件

    app.config.from_object(configs)

    db.init_app(app)

    @app.route("/add")

    def add():

    stu = Student(name="lisi")

    db.session.add(stu)

    db.session.commit()

    return "

    add ok!

    "

    @app.route("/")

    def hello_world():

    return "

    Hello, World!

    "

    if __name__ =='__main__':

    app.run()

    相关文章

      网友评论

          本文标题:flask mysql

          本文链接:https://www.haomeiwen.com/subject/kshandtx.html