flask连接sqlite或者 mysql

方式一:

#此配置文件和movie.sqlite同级目录下
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///{}".format(os.path.join(os.path.dirname(__file__), ‘movie.sqlite‘)) 
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

print(‘app.config["SQLALCHEMY_DATABASE_URI"]‘,app.config["SQLALCHEMY_DATABASE_URI"]) 
# 注意有时他这个是\有时是/
输出:app.config["SQLALCHEMY_DATABASE_URI"] sqlite:///X:/python3.64/Flask/黑马flask/01___name__\movie.sqlite 

方式二:

#此配置文件和movie.sqlite同级目录下
app.config[‘SQLALCHEMY_DATABASE_URI‘] = os.getenv(‘DATABASE_URL‘,‘sqlite:///‘ + os.path.join(app.root_path, ‘movie.sqlite‘))  
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
print(‘app.root_path‘,app.root_path)   
输出: app.root_path X:\python3.64\Flask\黑马flask\01___name__

print(‘app.config["SQLALCHEMY_DATABASE_URI"]‘,app.config["SQLALCHEMY_DATABASE_URI"]) 
输出:app.config["SQLALCHEMY_DATABASE_URI"] sqlite:///X:\python3.64\Flask\黑马flask\01___name__\movie.sqlite

配置mysql

from  flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import  StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo

app = Flask(__name__)
class  Config(object):
    ‘‘‘配置参数‘‘‘
    # sqlalchemy的配置参数
    SQLALCHEMY_DATABASE_URI = "mysql://root:666@10.0.0.105:3306/s2"

    # 设置sqlalchemy自动跟踪数据库
    SQLALCHEMY_TRACK_MODIFICATIONS = True

    # 查询时会显示原始SQL语句
    app.config[‘SQLCHEMY_ECHO‘] = True

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

class Author(db.Model):
    ‘‘‘作者‘‘‘
    __tablename__=‘tbl_authors‘
    id = db.Column(db.SmallInteger, primary_key=True)
    name = db.Column(db.String(8),unique=True)
    books = db.relationship("Book",backref=‘author‘)


class Book(db.Model):
    ‘‘‘书‘‘‘
    __tablename__ = ‘tbl_books‘ # 指明数据库的表名
    id = db.Column(db.SmallInteger, primary_key=True)  # 整形的主键默认自增主键
    name = db.Column(db.String(32),unique=True)
    author_id = db.Column(db.SmallInteger, db.ForeignKey(‘tbl_authors.id‘))  # 外键的类型必须和他所关联的属性一致


# 创建表单模型类
class AuthorBookForm(FlaskForm):
    ‘‘‘作者数据表单模型类‘‘‘
    author_name = StringField(label=‘作者‘,validators=[DataRequired(‘作者必填‘)])
    book_name = StringField(label=‘书籍‘,validators=[DataRequired(‘书籍必填‘)])
    submit = SubmitField(label=‘保存‘)


@app.route(‘/‘,methods=[‘GET‘,‘POST‘])
def index():
    form = AuthorBookForm()

    if form.validate_on_submit():
        # 验证表单成功,提取表单数据
        author_name = form.author_name.data
        book_name = form.book_name.data
        # 保存数据
        author = Author(name=author_name)
        db.session.add(author)
        db.session.commit()

        book = Book(name=book_name,author_id =author.id)
        print(author_name,book_name,book)
        book = Book(name=book_name,author=author)
        db.session.add(book)
        db.session.commit()

    # 查询数据
    author_li = Author.query.all()
    return render_template(‘author_book.html‘,authors = author_li, form=form)
    # return ‘你好啊‘
#
if __name__ == ‘__main__‘:
    # 清除数据库里的所有数据(第一次使用时用,清除数据库中是脏数据)
    # db.drop_all()
    #
    # # 创建所有的表
    # db.create_all()
    #
    # # 创建对象
    # au_xi = Author(name=‘我吃西红柿‘)
    # au_qian = Author(name=‘萧潜‘)
    # au_san = Author(name=‘唐家三少‘)
    # # session记录对象任务
    # 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_xi.id)
    # bk_qian = Book(name=‘缥缈之旅‘,author_id=au_qian.id)
    # bk_san = Book(name=‘冰火魔厨‘,author_id=au_qian.id)
    # db.session.add_all([bk_xi,bk_xi2,bk_qian,bk_san])
    # # 提交任务到数据库中
    # db.session.commit()

    app.run(debug=True)

flask连接sqlite或者 mysql

上一篇:CentOS 7 安装 Mysql 8.0 教程


下一篇:docker mysql 中文乱码问题