flask-連線資料庫flask_aqlalchemy-建表-增加欄位-刪除-修改
阿新 • • 發佈:2018-12-16
安裝模組
pip install pymysql
pip install flask_aqlalchemy
flaskpei配置檔案setting.py 中配置資料庫
設定資料庫url
#coding=utf-8 class DataBaseSetting: DEBUG=True SQLALCHEMY_DATABASE_URI ='mysql+pymysql://root:[email protected]/flaskdb' SQLALCHEMY_TRACK_MODIFICATIONS = True config={ 'db':DataBaseSetting }
from setting import config app.config.from_object(config['db']) from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class Roles(db.Model): #設定資料表名 __tablename__='Roles' #設定資料表字段 rid=db.Column(db.Integer,primary_key=True) rname=db.Column(db.String(20)) def __init__(self,rname): self.rname=rname def __repr__(self): return 'Roles[id={0},name={1}]'.format(self.rid,self.rname) @app.route('/indexx/') def indexx(): return render_template('indexx.html') @app.route('/createroles/') def createroles(): #刪除資料表 db.drop_all() db.create_all() #資料表建立成功 return render_template('indexx.html',msg='資料表建立成功')
#查詢顯示Roles所有物件 @app.route('/showall/') def queryall(): rolesall=db.session.query(Roles).all() return render_template('show.html',rolesall=rolesall) #刪除指定物件 @app.route('/delroles/<int:id>/', methods=['GET','POST']) def delroles(id): db.session.query(Roles).filter_by(rid=id).delete() db.session.commit() return redirect(url_for('queryall')) #修改指定物件 @app.route('/uproles/<int:id>/', methods=['GET','POST']) def uproles(id): if request.method=='POST': rname=request.values.get('rname') data={} data['rname']=rname db.session.query(Roles).filter_by(rid=id).update(data) db.session.commit() return redirect(url_for('queryall')) else: roles=db.session.query(Roles).filter_by(rid=id).first() return render_template('uproles.html',roles=roles)
顯示
<table>
<tr>
<td>
rid
</td>
<td>
rname
</td>
<td>
操作
</td>
</tr>
{% for role in rolesall %}
<tr>
<td>
{{ role.rid }}
</td>
<td>
{{ role.rname }}
</td>
<td>
<a href="/uproles/{{ role.rid }}/">修改</a> /<a href="/delroles/{{ role.rid }}/">刪除</a>
</td>
</tr>
{% endfor %}
</table>
增加
<form method="post" action="/addroles/">
<input name="rname">
<button type="submit">新增</button>
</form>
修改
<form method="post" action="/uproles/{{ roles.rid }}/">
請輸入資料:<input type="text" name="rname" value="{{ roles.rname }}">
<button type="submit">修改</button>
</form>