寫在前面
這篇文章被擱置真的太久了,不知不覺拖到了周三了,當(dāng)然,也算跟falsk系列說再見的時候,真沒什么好神秘的,就是個數(shù)據(jù)庫操作,就大家都知道的CRUD
吧。
Flask SQLAlchemy的使用
1、Flask SQLAlchemy簡介
Flask SQLAlchemy
是基于 Flask web
框架和 SQLAlchemy ORM
(對象關(guān)系映射)的工具。它旨在為 Flask web
應(yīng)用程序提供更方便的數(shù)據(jù)庫操作。SQLAlchemy
本身是一個全功能的 ORM
,而 Flask-SQLAlchemy
是在此基礎(chǔ)上為 Flask
應(yīng)用程序提供了一些額外的功能。
2、安裝Flask-SQLAlchemy
pip install flask-sqlalchemy
3、舉個栗子
后端業(yè)務(wù)代碼如下:
import pymysql
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_case.config import Config
pymysql.install_as_MySQLdb()
# 實例化一個flask對象
app = Flask(__name__)
# 設(shè)置一個密鑰
app.secret_key = 'a_secret_key'
# 從配置對象中加載配置信息
app.config.from_object(Config)
# 創(chuàng)建SQLAlchemy對象
db = SQLAlchemy(app)
class books(db.Model):
id = db.Column('student_id', db.Integer, primary_key=True)
name = db.Column(db.String(100))
price = db.Column(db.String(50))
def __init__(self, name, price):
self.name = name
self.price = price
@app.route('/')
def show_all():
return render_template('show_all.html', books=books.query.all())
@app.route('/add', methods=['GET', 'POST'])
def add():
if request.method == 'POST':
if not request.form['name'] or not request.form['price']:
flash('輸入項不能為空!', 'error')
else:
book = books(request.form['name'], request.form['price'])
print(book)
db.session.add(book)
db.session.commit()
flash('新書上架成功!')
return redirect(url_for('show_all'))
return render_template('add.html')
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
新增書頁面add.html
,示例代碼如下:
<!DOCTYPE html>
<html>
<body>
<h3>Flask SQLAlchemy Demo</h3>
<hr/>
{%- for category, message in get_flashed_messages(with_categories = true) %}
<div class = "alert alert-danger">
{{ message }}
</div>
{%- endfor %}
<form action = "{{ request.path }}" method = "post">
<label for = "name">name</label><br>
<input type = "text" name = "name" placeholder = "name" /><br>
<label for = "price">price</label><br>
<input type = "text" name = "price" placeholder = "price" /><br>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
書單列表頁show_all.html
,示例代碼如下:
<!DOCTYPE html>
<html lang = "en">
<head></head>
<body>
<h3>
<a href = "{{ url_for('show_all') }}">Flask
SQLAlchemy Demo</a>
</h3>
<hr/>
{%- for message in get_flashed_messages() %}
{{ message }}
{%- endfor %}
<h3>Books (<a href = "{{ url_for('add') }}">Add Book
</a>)</h3>
<table>
<thead>
<tr>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<td>{{ book.name }}</td>
<td>{{ book.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
4、效果
5、知識點
CRUD操作:
- db.session.add (模型對象) - 將記錄插入到映射表中
- db.session.delete (模型對象) - 從表中刪除記錄
-
model.query.all() ?- 從表中檢索所有記錄(對應(yīng)于
SELECT
查詢)。
寫在最后
在寫這部分文章時候,總感覺它跟mybatis
很像,比如可以將數(shù)據(jù)從數(shù)據(jù)庫映射到對象,支持創(chuàng)建數(shù)據(jù)庫表和定義數(shù)據(jù)模型,并提供了相應(yīng)的接口及對應(yīng)事務(wù)的操作,直白點說,不用手撕sql
。文章來源:http://www.zghlxwxcb.cn/news/detail-749019.html
但就性能來看的話,還是MyBatis
好,畢竟是持久層框架,哈哈!文章來源地址http://www.zghlxwxcb.cn/news/detail-749019.html
到了這里,關(guān)于大白話說Python+Flask入門(六)Flask SQLAlchemy操作mysql數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!