from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate,MigrateCommand
import os
app=Flask(__name__)
manager=Manager(app)
db=SQLAlchemy(app)
migrate=Migrate(app,db)
#将迁移命令添加到终端
manager.add_command('db',MigrateCommand)
base_dir=os.path.dirname(__file__)
database_uri='sqlite:///'+os.path.join(base_dir,'data.sqlite')
app.config['SQLALCHEMY_DATABASE_URI']=database_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']= False
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
class User(db.Model):
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String,unique=True)
age=db.Column(db.Integer)
email=db.Column(db.String,unique=True)
@app.route('/')
def index():
return '数据库增、删、改、查操作'
#增加一条数据
@app.route('/add/')
def add():
lt=User(name='凉凉',age=25,email='liangliang@163.com')
db.session.add(lt)
db.session.commit()
return '数据已添加'
#增加多条数据
@app.route('/insert/')
def insert():
lt1=User(name='飞飞',age=18,email='feifei@163.com')
lt2=User(name='照照',age=24,email='zhaozhao@163.com')
lt3=User(name='京京',age=23,email='jingjing@163.com')
lt4=User(name='忠忠',age=26,email='zhongzhong@163.com')
lt5=User(name='帅帅',age=18,email='shuaishuai@163.com')
db.session.add_all([lt1,lt2,lt3,lt4,lt5])
db.session.commit()
return '一次性保存多条数据'
#查询
@app.route('/select//')
def select(uid):
user=User.query.get(uid)
if user:
return user.name
return '查无此人'
#修改
@app.route('/upload//')
def upload(uid):
#根据主键进行查询,找到返回对象,没找到返回None
user=User.query.get(uid)
if user:
user.email='xxx@qq.com'
# db.session.add(user)
return '数据已修改'
return '查无此人'
#删除
@app.route('/del//')
def delete(uid):
user=User.query.get(uid)
if user:
db.session.delete(user)
return '数据已删除'
return '查无此人'
if __name__=='__main__':
manager.run()