python - flask-sqlalchemy 怎么设置json格式的字段
習慣沉默
習慣沉默 2017-05-18 10:47:02
0
1
840

flask-sqlalchemy 怎么设置json格式的字段

習慣沉默
習慣沉默

全部回复(1)
Ty80

有两种方法:
1.sqlalchemy中PickleType可以对应任何python对象.
2.可以通过编写方法的方式生成json.

具体代码如下:

#!usr/bin/env python
# coding:utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:psw@localhost/test_json'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)

class Users(db.Model):
    __tablename__ = 'users'
    user_id = db.Column(db.Integer, primary_key=True)
    user_info = db.Column(db.PickleType)

    def __repr__(self):
        return self.user_info


class Students(db.Model):
    __tablename__ = 'students'
    student_id = db.Column(db.Integer, primary_key=True)
    student_name = db.Column(db.String(80), unique=True)
    student_age = db.Column(db.Integer)
    student_sex = db.Column(db.String(20))

    def to_json(self):
        json_student = {
            'student_id': self.student_id,
            'student_name': self.student_name,
            'student_sex': self.student_sex,
            'student_age': self.student_age
        }

        return json_student

    def __repr__(self):
        return '%r' % self.student_id


if __name__ == "__main__":
    #-----------------------生成-----------------------
    USER_INFO = {"name":"nisiwa", "mail":"2222233333@qq.com"}
    db.create_all()
    USER = Users(user_info=USER_INFO)
    STUDENT = Students(student_name="nisiwa", student_age="28", student_sex="male")
    db.session.add(USER)
    db.session.add(STUDENT)
    db.session.commit()
    #-----------------------调用------------------------
    user = Users.query.filter_by(user_id=1).first()
    student = Students.query.filter_by(student_id=1).first()
    print 'student:', student.to_json()
    print 'user:', user.user_info

结果如下:

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板