SQLAlchemy是Python中比较优秀的orm框架,在SQLAlchemy中定义了多种数据库表的对应关系,

其中一对多是一种比较常见的关系。利用flask sqlalchemy实现一对多的关系如下:

1. 建立数据库的模型

在本次试验中建立三个表: user, phone ,atttr。user 和phone, phone 和atttr均为一对多的关系。实现如下:

#!/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";

第二个参数backref为类Phone申明新属性的方法;第三个参数lazy决定了什么时候SQLALchemy从

数据库中加载数据。

2. 构造api获取数据资源

  注意:在获取资源之前,先向数据库中写入测试数据

#!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