flask-sqlalchemy 是乙個給你的應用新增 sqlalchemy 支援的 flask 擴充套件。sqlalchemy 是python語言的sql工具包及物件關係對映(orm)工具,使用mit許可證發行,提供能相容眾多資料庫(如 sqlite、mysql、postgres、oracle、ms-sql、sqlserver 和 firebird)的企業級永續性模型。
一、為你的flask應用載入flask-sqlalchemy擴充套件
code example:
from flask import flask
from flask.ext.sqlalchemy import sqlalchemy
sqlalchemy_database_uri格式例項:
postgresql://scott:tiger@localhost/mydatabase
mysql://scott:tiger@localhost/mydatabase
oracle:
sqlite:absolute/path/to/foo.db #注意:有3個斜槓+路徑
二、建立資料庫模型和初始化資料庫
建立資料庫模型:
code example:
import hashlib
class user(db.model):
id = db.column(db.integer, primary_key=true) # id
username = db.column(db.string(80), unique=true)
email = db.column(db.string(320), unique=true)
password = db.column(db.string(32), nullable=false)
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password= hashlib.md5(password) #呵呵,這樣在插入資料自動給密碼雜湊了!
def __repr__(self):
return "".format(self.username)
初始化資料庫也特別簡單,只需要呼叫 db.create_all() 函式就可以了。
code example:
if __name__ == '__main__':
db.create_all()
三、插入資料
code example:
u = user(username='peter', email='[email protected]', password='123456')
db.session.add(u) #插入資料
db.session.commit() #只有提交事務了,才可以獲取(u.id)資料的id值。
四、查詢資料
用主鍵獲取資料:
code example:
user.query.get(1)
通過乙個精確引數進行反查:
peter = user.query.filter_by(username='peter').first() #注意:精確查詢函式query.filter_by(),是通過傳遞引數進行查詢;其他增強型查詢函式是query.filter(),通過傳遞表示式進行查詢。
print(peter.id) #如果資料不存在則返回none
模糊查詢:
user.query.filter(user.email.endswith('@example.com')).all()
[, ]
邏輯非1:
peter = user.query.filter(user.username != 'peter').first()
print(peter.id)
邏輯非2:
from sqlalchemy import not_
peter = user.query.filter(not_(user.username=='peter')).first()
print(peter.id)
邏輯與:
from sqlalchemy import and_
peter = user.query.filter(and_(user.username=='peter', user.email.endswith('@example.com'))).first()
print(peter.id)
邏輯或:
from sqlalchemy import or_
peter = user.query.filter(or_(user.username != 'peter', user.email.endswith('@example.com'))).first()
print(peter.id)
六、查詢資料加工
排序和限制函式可以跟在query或filter後面。
排序:
user.query.order_by(user.username) #嘿嘿,你用哪個字段作為排序參考呢?
[, , ]
限制返回的數目:
user.query.limit(1).all()
六、查詢資料返回
返回查詢到的第乙個物件:
r = user.query.first()
print(r)
返回所有查詢到的物件:
r = user.query.all()
print(r)
七、刪除資料u = user.query.first()
db.session.delete(u) #刪除資料和插入資料一樣簡單,但必須是通過查詢返回的物件。
db.session.commit()
八、更新資料u = user.query.first()
u.username = 'guest' #更新資料和變數賦值那麼簡單,但必須是通過查詢返回的物件。
db.session.commit()
資料探勘 資料
對關注的屬性,樣本與原始資料集有相同的性質,則用抽樣計算的結果與全集是一樣。1.1 抽樣的方法 1 簡單隨機抽樣 random sampling 放回 不放回 2 分層抽樣 stratified sampling 如果資料集不同型別的資料數量差異過大,則隨機抽樣會丟失數量少的樣本。可針對不同資料組,...
大資料資料
作業系統 核心 分配和管理硬體 庫 沒有入口的應用軟體 應用軟體 1 設定網絡卡為nat模式 2 確保windows下的服務是否啟動 dhcp,net服務 3 編輯檔案 vi etc sysconfig network scripts ifcfg eth0 4 onboot yes 5 設定ip s...
大資料 資料分析 資料探勘
在大資料領域裡,經常會看到例如資料探勘 olap 資料分析等等的專業詞彙。如果僅僅從字面上,我們很難說清楚每個詞彙的意義和差別。大講台老師通過一些大資料在高校應用的例子,來為大家說明白 資料探勘 大資料 olap 資料統計的區別。一 資料分析 資料分析是乙個大的概念,理論上任何對資料進行計算 處理從...