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)

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

posted @ 2018-07-19 11:28  IT蓝月  阅读(93)  评论(0编辑  收藏  举报
Live2D