pycharm中flask操作数据库

一.新建flask工程

二.新建数据库

三.Terminal中pip install xxx

pip install flask_script
pip install flast_migrate
pip install pymysql

四.添加 config.py, models.py, manage.py

app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

from models import *

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True)

config.py:

DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = 'root'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'book_store'

SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False

models.py:

from app import db

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

manage.py:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from models import *

manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

五.迁移数据库

Terminal中输入

1.生成文件夹migrations

python manage.py db init

2.把models模型生成迁移文件

python manage.py db migrate

3.从migrations文件夹迁移到数据库

python manage.py db upgrade

4.将数据库降回到上一个状态

python manage.py db downgrade

六.操作数据库

例:app.py改成

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

from models import *

#  新增数据
@app.route('/addData')
def addData():
    article = Article(title='蒙牛与伊利开箱评测', content='这篇文章写的很好!')
    db.session.add(article)
    db.session.commit()
    return 'Hello World!'

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True)

访问http://127.0.0.1:5000/addData后:


参考:
https://www.jianshu.com/p/e4fc86fa21e8
https://blog.csdn.net/milk_and_bread/article/details/89222270

posted on 2020-04-09 23:28  HolaWorld  阅读(1951)  评论(0编辑  收藏  举报

导航