SQLAlchemy是Python中比較優秀的orm框架,在SQLAlchemy中定義了多種數據庫表的對應關係,html
其中一對可能是一種比較常見的關係。利用flask sqlalchemy實現一對多的關係以下:python
1. 創建數據庫的模型mysql
在本次試驗中創建三個表: user, phone ,atttr。user 和phone, phone 和atttr均爲一對多的關係。實現以下:sql
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # 配置數據庫 app.config[ 'SQLALCHEMY_DATABASE_URI'] = \ "mysql://root: root@127.0.0.1/test?charset=utf8" db = SQLAlchemy(app) # 創建user表 class Usr(db.Model): __tablename__ = 'usr' id = db.Column(db.Integer, primary_key=True) usrname = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) phone = db.relationship('Phone', backref='user', lazy='dynamic') def __init__(self, username, email): self.usrname = username self.email = email class Phone(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20)) factory = db.Column(db.String(20)) userId = db.Column(db.Integer, db.ForeignKey('usr.id')) attr = db.relationship( 'Atttr', backref='phone', lazy='dynamic') def __init__(self, name, factory, userId): self.name = name self.factory = factory self.userId = userId class Atttr(db.Model): id = db .Column(db.Integer, primary_key=True) color = db.Column(db.String(20)) price = db.Column(db.String(20)) macId = db.Column(db.Integer, db.ForeignKey('phone.id')) def __init__(self, color, price, macId): self.color = color self.price = price self.macId = macId db.create_all()
user表和phone表的一對多的關係經過下面語句肯定:數據庫
phone = db.relationship('Phone', backref='user', lazy='dynamic')
其中rrealtionship描述了user和phone的關係。在此文中,第一個參數爲對應參照的類"Phone";json
第二個參數backref爲類Phone申明新屬性的方法;第三個參數lazy決定了何時SQLALchemy從flask
數據庫中加載數據。api
2. 構造api獲取數據資源瀏覽器
注意:在獲取資源以前,先向數據庫中寫入測試數據restful
#!usr/bin/env pyhton # -*- coding: utf-8 -*- from flask import Flask from flask.ext.restful import reqparse, Api, Resource from model import * app = Flask(__name__) api = Api(app) def to_json(model): """ Returns a JSON representation of an SQLAlchemy-backed object. """ json = {} # json['fields'] = {} # json['pk'] = getattr(model, 'id') for col in model._sa_class_manager.mapper.mapped_table.columns: # json['fields'][col.name] = getattr(model, col.name) json[col.name] = getattr(model, col.name) # return dumps([json]) return json def to_json_list(model_list): json_list = [] for model in model_list: json_list.append(to_json(model)) return json_list def message(record): if record: return to_json(record), 200 return {"message": "not exit"}, 400 class userResource(Resource): def get(self, id): record = Usr.query.filter_by(id=id).first() return to_json_list(record.phone.first().phone) def put(self, id): parser = reqparse.RequestParser() parser.add_argument('username', type=str) args = parser.parse_args(strict=True) record = Usr.query.filter_by(id=id).first() if record: record.username = args['username'] db.session.commit() return {"status": "updated"}, 201 return {"message": "not exit"}, 400 def delete(self, id): record = Usr.query.filter_by(id=id).first() if record: db.session.delete(record) db.session.commit() return {"status": "deleted"}, 204 return {"message": "not exit"}, 400
class AtrrResource(Resource):
def get(self, id):
record = Atttr.query.filter_by(id=id).first()
return message(record.phone.user)
api.add_resource(userResource, '/v1.0/user/<id>')
api.add_resource(usrList, '/v1.0/user', '/v1.0/user/')
api.add_resource(AtrrResource, '/v1.0/atrr/<id>')
if '__name__' == '__main__' :
app.run(DEBUG=True)
經過在瀏覽器中輸入url: 127.0.0.1:5000/v1.0/user/1能夠得到某用戶的某種類型手機的全部屬性。
主要爲get函數,其經過三層訪問,便可獲得相關的信息。固然還能夠經過查詢某一手機的顏色獲取其
用戶的信息,如Atttr get所示。
參考資料:
[1] http://docs.jinkan.org/docs/flask-sqlalchemy/models.html#id3