python之資料庫管理工具sandman2
文件:Welcome to sandman2’s documentation! — sandman2 0.0.1 documentation
【安裝】
pip install sandman2
安裝成功後,就可以得到一個sandman2ctl
命令列工具,用它來啟動一個 RESTful API 伺服器
sandman2ctl sqlite+pysqlite:///data.db
啟動之後,預設埠是 5000,訪問地址是http://localhost:5000/admin
就能看到伺服器控制檯了
【資料庫連線】
sandman2 是基於 SQLAlchemy 的,所以使用連線 Url 來連線資料庫
格式為
dialect+driver://username:password@host:port/database
-
dialect 為資料庫型別,如 mysql、SQLite 等
-
driver 為資料庫驅動模組名,例如 pymysql、psycopg2、mysqldb 等,如果忽略,表示使用預設驅動
例如:MySQL
sandman2ctl mysql+pymysql://bob:bobpasswd@localhost:3306/testdb
注意點:如果環境中沒有安裝pymysql
模組,必須先安裝,才能正常啟動,其他資料庫的連線方式可參考 SQLAlchemy 的引擎配置
章節, 在這裡檢視 https://docs.sqlalchemy.org/en/13/core/engines.html
控制檯
需要快速預覽資料,對資料進行簡單調整的話,控制檯很有用
左側選單除了 Home 外,其他的都是庫表名稱
點選相應庫表名稱,會在右側顯示錶內資料,並且可以做增刪改操作
API
以 RESTful 的角度來看,庫表相當於資源
(resource
),一組資源相當於集合
(collection
)
查詢
通過 Http GET 方法,以 JSON 格式將資料返回,例如返回學生表 student
的所有記錄:
$ curl http://localhost:5000/student/ {"resources":[{"age":18,"class":"1","id":1,"name":"\u5f20\u4e09","profile":"\u64c5\u957f\u5b66\u4e60"},...
注意:資源要以/
結尾
通過引數page
來分頁,例如返回學生表 student
的第一頁資料
$ curl http://localhost:5000/student/?page=1 {"resources":[{"age":18,"class":"1"...
通過引數limit
顯示返回行數
如果要獲取具體記錄,可以用主鍵值作為節段,例如獲取 id 為 3 的學生記錄
$ curl http://localhost:5000/student/3 {"age":18,"class":"2","id":3,"name":"\u738b\u4e94","profile":"\u7231\u7f16\u7a0b"}
以欄位名做引數,相當於查詢條件,例如,查詢name
為 Tom 的學生記錄:
$ curl http://localhost:5000/student/?name=Tom {"resources":[{"age":19,"class":"1","id":7,"name":"Tom","profile":"Handsome"}]}
查詢條件可以被組合,例如,查詢班級為 1 年齡為 18 的學生:
$ curl http://localhost:5000/student/?class=1&age=19 {"resources":[{"age":19,"class":"1","id":2,"name":"\u674e\u56db","profile":"\u559c\u6b22\u7bee\u7403"},{"age":19,"class":"1","id":7,"name":"Tom","profile":"Handsome"}]}
修改
POST
方法用於新增,新增內容,由請求的資料部分提供,例如增加一個學生資訊:
$ curl -X POST -d '{"name": "Lily", "age": 17, "class":1, "profile":"Likely"}' -H "Content-Type: application/json" http://127.0.0.1:5000/student/ {"age":17,"class":"1","id":8,"name":"Lily","profile":"Likely"}
注意:庫表主鍵是自增長的,可以忽略主鍵欄位,否則必須提供
PATCH
方法用於更新,更新內容,由請求的資料部分提供,例如將 id 為 1 的學生班級更改為 3
注意: 更新時主鍵資訊通過 url 的主鍵值節段提供,而不在資料部分中
$ curl -X PATCH -d '{"class":3}' -H "Content-Type: application/json" http://127.0.0.1:5000/student/1 {"age":18,"class":"3","id":1,"name":"\u5f20\u4e09","profile":"\u64c5\u957f\u5b66\u4e60"}
DELETE
方法由於刪除,例如刪除 id 為 8 的學生記錄:$ curl -X DELETE -H "Content-Type: application/json" http://127.0.0.1:5000/student/8其他介面
獲取表的欄位定義資訊,通過
meta
節段獲取,例如獲取學生表 student
的欄位定義:$ curl http://127.0.0.1:5000/student/meta {"age":"INTEGER(11)","class":"VARCHAR(255)","id":"INTEGER(11) (required)","name":"VARCHAR(255)","profile":"VARCHAR(500)"}
匯出資料,通過查詢欄位
export
獲取,資料格式為 csv,例如匯出學生資料,存放到 student.csv 檔案中:$ curl -o student.csv http://127.0.0.1:5000/student/?export % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 202 100 202 0 0 2525 0 --:--:-- --:--:-- --:--:-- 2525