python - flask-sqlalchemy Bagaimana untuk menetapkan medan dalam format json
習慣沉默
習慣沉默 2017-05-18 10:47:02
0
1
810

Bagaimana untuk menetapkan medan dalam format json dengan flask-sqlalchemy

習慣沉默
習慣沉默

membalas semua(1)
Ty80

Terdapat dua kaedah:
1. PickleType dalam sqlalchemy boleh sesuai dengan mana-mana objek python
2

Kod khusus adalah seperti berikut:

#!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
Keputusan adalah seperti berikut:

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan