zoukankan      html  css  js  c++  java
  • Flask 入门(八)

    flask操作数据库:操作数据:

    承接上文:

    修改main.py中的代码如下:

    #encoding:utf-8
    from flask_sqlalchemy import SQLAlchemy
    from flask import Flask
     
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:005@127.0.0.1:3306/data'
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
    app.config['JSON_AS_ASCII']=False

    db = SQLAlchemy(app)
    db = SQLAlchemy(use_native_unicode='utf8')


    class test(db.Model):
        __tablename__='test'
        id = db.Column(db.Integer,primary_key=True,autoincrement=True)
        name = db.Column(db.String(20),nullable=False)


    @app.route('/')
    def index():
        db.create_all()
        return '连接成功'

    @app.route('/add/')
    def add():
        test_add=test(name='test_add')
        db.session.add(test_add)
        db.session.commit()
        return '增加成功!'

    @app.route('/del/')
    def del_():
        test_del=test.query.filter(test.name=='test_update').first()
        db.session.delete(test_del)
        db.session.commit()
        return '删除成功!'

    @app.route('/update/')
    def update():
        test_update=test.query.filter(test.name=='test_add').first()
        test_update.name='test_update'
        db.session.commit()
        return '更新成功!'

    @app.route('/show1/')
    def show1():
        test_show1=test.query.filter(test.name=='test_add').first()
        return test_show1.name

    @app.route('/show2/')
    def show2():
        test_show2=test.query.filter(test.name=='test_add')
        return test_show2[0].name
    @app.route('/show3/')
    def show3():
        test_show3=test.query.filter(test.name=='test_add').all()
        return test_show3[0].name
            

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

    按图执行相应操作,并且结果若与图中相符,则测试成功:

  • 相关阅读:
    自我介绍
    java web 学习计划
    团队-团队编程项目中国象棋-代码设计规范
    团队-中国象棋游戏-设计文档
    团队-象棋游戏-开发环境搭建过程
    结对-贪吃蛇游戏-开发环境搭建过程
    结对-结对编项目贪吃蛇-设计文档
    20170912-构建之法:现代软件工程-阅读笔记
    课后作业-阅读任务-阅读提问-1
    团队-团队编程项目中国象棋-成员简介及分工
  • 原文地址:https://www.cnblogs.com/viplanyue/p/12700687.html
Copyright © 2011-2022 走看看