python - flask-sqlalchemy How to set fields in json format
習慣沉默
習慣沉默 2017-05-18 10:47:02
0
1
839

flask-sqlalchemy How to set fields in json format

習慣沉默
習慣沉默

reply all(1)
Ty80

There are two methods:
1. PickleType in sqlalchemy can correspond to any python object.
2. You can generate json by writing methods.

The specific code is as follows:

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

The results are as follows:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template