zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    WPF and SL RadioButtonList Tip
    Prism V2之旅(1)
    wpf开发常见问题(1)
    (转)英语学习者的十句经典名言
    json格式化,统一格式?,前端与后端的矛盾
    路由器默认地址跟帐号密码
    ASP操作XML数据小结
    系统封装工具和常用软件下载(2009年10月更新的)
    全国邮编、区号数据、IP数据库
    Linux 包管理速查表
  • 原文地址:https://www.cnblogs.com/holaworld/p/12670509.html
Copyright © 2011-2022 走看看