Nam's

Flask Study 03 - Marshmallow 본문

개발/Back-end

Flask Study 03 - Marshmallow

namespace 2021. 1. 26. 00:26

marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes. - marshmallow.readthedocs.io/en/latest/

[공식 예제]

1
2
3
4
5
6
7
from your_orm import Model, Column, Integer, String, DateTime
 
 
class User(Model):
    email = Column(String)
    password = Column(String)
    date_created = Column(DateTime, auto_now_add=True)
cs

 

[내 예제]

1
2
3
4
5
6
7
8
9
10
11
12
from marshimallow import fields
from marshmallow_sqlalchemy import ModelSchema
from models import Machine
 
class UserSchema(ModelSchema):
    class Meta:
        # Fields to expose
        fields = ("email""date_created")
 
 
user_schema = UserSchema()
users_schema = UserSchema(many=True)
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def users():
    all_users = User.all()
    return users_schema.dump(all_users)
 
 
@app.route("/api/users/<id>")
def user_detail(id):
    user = User.get(id)
    return user_schema.dump(user)
 
 
# {
#     "email": "fred@queen.com",
#     "date_created": "Fri, 25 Apr 2014 06:02:56 -0000",
# }
cs
Comments