• 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

  • 相关阅读:
    将new Date()的时间转换为常用时间格式
    封装通用的jsonp方式
    javascript实现手机震动API代码
    webstorm 2016.3.2 破解代码(免费)
    淘宝镜像在npm中执行的代码
    jQuery lazyload 懒加载
    uniapp小程序获取时间戳转换时间例子
    微信小程序解析HTML标签
    微信小程序之tab切换效果
    巧用weui.gallery(),点击图片后预览图片
  • 原文地址:https://www.cnblogs.com/holaworld/p/12670509.html
Copyright © 2020-2023  润新知