I am using flask + marshmallow + sqlalchemy.
I am required to:
To send an http request with this content:
{
"first_name": "John"
"last_name": "Doe"
"gender": "male"
}
And save the value as an integer in the database, either 0
for male or 1
for female.
id | first_name | last_name | gender |
---|---|---|---|
42 | John | Doe | 0 |
The road so far:
requirements.txt
...
Flask==2.0.1
flask-marshmallow==0.14.0
Flask-SQLAlchemy==2.5.1
marshmallow==3.13.0
marshmallow-enum==1.5.1
marshmallow-sqlalchemy==0.26.1
SQLAlchemy==1.4.22
...
schema.py
from .models import Users, Genders
from .extensions import ma
class SignUpSchema(ma.SQLAlchemySchema):
class Meta:
model = Users
first_name = ma.auto_field(data_key='firstName', required=True)
last_name = ma.auto_field(data_key='lastName', required=True)
gender = EnumField(enum=Genders, required=True)
views.py
from flask import request
from flask.views import MethodView
from .schemas import SignUpSchema
from .models import Users, Genders
from .extensions import db
class SignUp(MethodView):
methods = ['POST']
def post(self):
json_data = request.get_json()
schema = SignUpSchema()
data = schema.load(json_data)
user = Users(**data)
db.session.add(user)
db.session.commit()
return {'id': user.id}
models.py
import enum
from sqlalchemy import Column,Integer, String, Enum
from .extensions import db
class Genders(enum.Enum):
MALE = "male"
FEMALE = "female"
class Users(db.Model):
id = Column(Integer, primary_key=True)
first_name = Column(String(100))
last_name = Column(String(100))
gender = Column(Enum(Genders))
Current state:
{
"firstName": "john",
"lastName": "doe",
"gender": "MALE"
}
id | first_name | last_name | gender |
---|---|---|---|
42 | john | doe | MALE |
I just can't figure out how to change the enum value in the request and the db insert.