Python使用flask框架操作sqlite3的兩種方式
本文實(shí)例講述了Python使用flask框架操作sqlite3的兩種方式。分享給大家供大家參考,具體如下:
方式一:raw_sql
import sqlite3 from flask import Flask, request, jsonify app = Flask(__name__) DATABASE_URI = ":memory:" # 創(chuàng)建表格、插入數(shù)據(jù) @app.before_first_request def create_db(): # 連接 conn = sqlite3.connect(DATABASE_URI) c = conn.cursor() # 創(chuàng)建表 c.execute('''DROP TABLE IF EXISTS user''') c.execute('''CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)''') # 數(shù)據(jù) # 格式:用戶名,郵箱 purchases = [('admin', 'admin@example.com'), ('guest1', 'guest1@example.com'), ('guest2', 'guest2@example.com'), ('guest3', 'guest3@example.com'), ('guest4', 'guest4@example.com')] # 插入數(shù)據(jù) c.executemany('INSERT INTO user(name, email) VALUES (?,?)', purchases) # 提交?。?! conn.commit() # 關(guān)閉 conn.close() def get_db(): db = sqlite3.connect(DATABASE_URI) db.row_factory = sqlite3.Row return db def query_db(query, args=(), one=False): db = get_db() cur = db.execute(query, args) db.commit() rv = cur.fetchall() db.close() return (rv[0] if rv else None) if one else rv @app.route("/user") def users(): res = query_db("SELECT * FROM user WHERE id <= ?", args=(6,)) return "<br>".join(["{0}: {1}".format(user[1], user[2]) for user in res]) @app.route("/user/<int:id>") def user(name): res = query_db("SELECT * FROM user WHERE id=?", args=(id,)) #不妨設(shè)定:第一次只返回6個(gè)數(shù)據(jù) return jsonify(id = res[1], name = res[2], email = res[3]) # 返回json格式 if __name__ == "__main__": app.run(debug=True)
方式二:orm(既flask-SQLAlchemy)
# flask_sqlalchemy.py from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) # 定義ORM class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, name, email): self.name = name self.email = email def __repr__(self): return '<User %r>' % self.name # 創(chuàng)建表格、插入數(shù)據(jù) @app.before_first_request def create_db(): # Recreate database each time for demo #db.drop_all() db.create_all() admin = User('admin', 'admin@example.com') db.session.add(admin) guestes = [User('guest1', 'guest1@example.com'), User('guest2', 'guest2@example.com'), User('guest3', 'guest3@example.com'), User('guest4', 'guest4@example.com')] db.session.add_all(guestes) db.session.commit() # 查詢 @app.route('/user') def users(): users = User.query.all() return "<br>".join(["{0}: {1}".format(user.name, user.email) for user in users]) # 查詢 @app.route('/user/<int:id>') def user(id): user = User.query.filter_by(id=id).one() return "{0}: {1}".format(user.name, user.email) # 運(yùn)行 if __name__ == '__main__': app.run('127.0.0.1', 5000)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作SQLite數(shù)據(jù)庫技巧總結(jié)》、《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
- python編程Flask框架簡單使用教程
- 使用Python的Flask框架表單插件Flask-WTF實(shí)現(xiàn)Web登錄驗(yàn)證
- Python的Flask框架標(biāo)配模板引擎Jinja2的使用教程
- Python的Flask框架使用Redis做數(shù)據(jù)緩存的配置方法
- Python的Flask框架中使用Flask-Migrate擴(kuò)展遷移數(shù)據(jù)庫的教程
- Python的Flask框架中使用Flask-SQLAlchemy管理數(shù)據(jù)庫的教程
- python使用Flask框架創(chuàng)建一個(gè)簡單的動態(tài)日歷效果
相關(guān)文章
Python實(shí)現(xiàn)的登錄驗(yàn)證系統(tǒng)完整案例【基于搭建的MVC框架】
這篇文章主要介紹了Python實(shí)現(xiàn)的登錄驗(yàn)證系統(tǒng),結(jié)合完整實(shí)例形式分析了Python基于搭建的MVC框架進(jìn)行登錄驗(yàn)證操作的相關(guān)實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下2019-04-04python3使用mutagen進(jìn)行音頻元數(shù)據(jù)處理的方法
mutagen是一個(gè)處理音頻元數(shù)據(jù)的python模塊,支持多種音頻格式,是一個(gè)純粹的python庫,僅依賴python標(biāo)準(zhǔn)庫,可在Python?3.7及以上版本運(yùn)行,支持Linux、Windows?和?macOS系統(tǒng),這篇文章主要介紹了python3使用mutagen進(jìn)行音頻元數(shù)據(jù)處理,需要的朋友可以參考下2022-10-10python算法與數(shù)據(jù)結(jié)構(gòu)之單鏈表的實(shí)現(xiàn)代碼
鏈表是一種物理存儲單元上非連續(xù)、非順序的存儲結(jié)構(gòu),數(shù)據(jù)元素的邏輯順序是通過鏈表中的指針鏈接次序?qū)崿F(xiàn)的。這篇文章主要介紹了python算法與數(shù)據(jù)結(jié)構(gòu)之單鏈表的實(shí)現(xiàn)代碼,需要的朋友可以參考下2019-06-06Python實(shí)現(xiàn)K-means聚類算法并可視化生成動圖步驟詳解
這篇文章主要介紹了Python實(shí)現(xiàn)K-means聚類算法并可視化生成動圖,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05