Skip to content

Commit

Permalink
Updated examples with marshmallow serializers
Browse files Browse the repository at this point in the history
  • Loading branch information
avara1986 committed Jan 20, 2020
1 parent f173dbb commit 0ed75f5
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 9 deletions.
2 changes: 1 addition & 1 deletion project/models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def dump_datetime(value: datetime) -> list:
return [value.strftime("%Y-%m-%d"), value.strftime("%H:%M:%S")]


class Colors(db.Model):
class Color(db.Model):
"""Example model"""
__tablename__ = 'colors'

Expand Down
9 changes: 9 additions & 0 deletions project/serializers/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from marshmallow_sqlalchemy import ModelSchema

from project.models.models import Color


class ColorSchema(ModelSchema):
class Meta:
model = Color
fields = ('id', 'name', 'timestamp')
18 changes: 11 additions & 7 deletions project/views/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,32 @@
from flask import jsonify, current_app

from project.models.init_db import db
from project.models.models import Colors
from project.models.models import Color
from project.serializers.serializers import ColorSchema


def list_view():
"""Example endpoint return a list of colors by palette
"""
current_app.logger.info("Return all color list")
query = Colors.query.all()

return jsonify([i.serialize for i in query])
query = Color.query.paginate(
connexion.request.args.get("paginationKey", 1),
connexion.request.args.get("pageSize", 5)
)
schema = ColorSchema()
result = schema.dump(query.items, many=True)
return jsonify(result), 200


def create_view():
"""Example endpoint return create a color
"""
# import ipdb; ipdb.set_trace()
current_app.logger.info("Create color")
if connexion.request.is_json:
data = connexion.request.get_json()
color = Colors(name=data["name"])
color = Color(name=data["name"])
db.session.add(color)
db.session.commit()

return jsonify(color.serialize)
return jsonify(ColorSchema().dump(color))
return jsonify({})
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
Flask-SQLAlchemy==2.4.1
SQLAlchemy==1.3.12
Flask-Script==2.0.6
py-ms==2.0.0
py-ms==2.0.0
marshmallow==3.3.0
marshmallow-sqlalchemy==0.21.0

0 comments on commit 0ed75f5

Please sign in to comment.