初学Python的Flask框架,版本python3.6,使用的是pycharm,代码如下。
# -*- coding:utf-8 -*-
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
class Config():
# sqlalchemy配置参数
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:toor@localhost:3306/author_book_py04'
# 设置sqlalchemy自动跟踪数据库
SQLALCHEMY_TRACK_MODIFICATIONS = True
app.config.from_object(Config)
db = SQLAlchemy(app)
# 定义数据库的模型
class Author(db.Model):
"""作者"""
__tablename__ = 'tbl_authors'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True)
class Book(db.Model):
"""书籍"""
__tablename__ = 'tbl_books'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
author_id = db.Column(db.Integer, db.ForeignKey("tbl_authors.id"))
if __name__ == '__main__':
db.drop_all()
db.create_all()
au_xi = Author(name='我吃西红柿')
au_qian = Author(name='萧潜')
au_san = Author(name='唐家三少')
db.session.add_all([au_xi, au_qian, au_san])
db.session.commit()
bk_xi = Book(name='吞噬星空', author_id=au_xi.id)
bk_xi2 = Book(name='寸芒', author_id=au_qian)
bk_qian = Book(name='飘渺之旅', author_id=au_qian)
bk_san = Book(name='冰火魔厨', author_id=au_san)
db.session.add_all([bk_xi, bk_xi2, bk_qian, bk_san])
db.session.commit()
app.run()
主要是想通过Flask链接MySQL数据库进行数据表的创建和内容的写入。
代码不会报错,但是并不会创建新的数据表,也不会赋值,就是主函数没有被执行的样子。如果我把主函数去掉,如下:
# -*- coding:utf-8 -*-
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
class Config():
# sqlalchemy配置参数
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:toor@localhost:3306/author_book_py04'
# 设置sqlalchemy自动跟踪数据库
SQLALCHEMY_TRACK_MODIFICATIONS = True
app.config.from_object(Config)
db = SQLAlchemy(app)
# 定义数据库的模型
class Author(db.Model):
"""作者"""
__tablename__ = 'tbl_authors'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True)
class Book(db.Model):
"""书籍"""
__tablename__ = 'tbl_books'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
author_id = db.Column(db.Integer, db.ForeignKey("tbl_authors.id"))
db.drop_all()
db.create_all()
au_xi = Author(name='我吃西红柿')
au_qian = Author(name='萧潜')
au_san = Author(name='唐家三少')
db.session.add_all([au_xi, au_qian, au_san])
db.session.commit()
bk_xi = Book(name='吞噬星空', author_id=au_xi.id)
bk_xi2 = Book(name='寸芒', author_id=au_qian)
bk_qian = Book(name='飘渺之旅', author_id=au_qian)
bk_san = Book(name='冰火魔厨', author_id=au_san)
db.session.add_all([bk_xi, bk_xi2, bk_qian, bk_san])
db.session.commit()
app.run()
这样的话就没有任何问题,数据表也可以正常创建,数据内容也可以添加进去。
这会图片无法上传,我试试可以在评论里边上传图片不有知道的大佬说一下。