Skip to content

Instantly share code, notes, and snippets.

@jfhbrook
Last active April 26, 2019 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfhbrook/0714b4d319ad0801427c47268d975555 to your computer and use it in GitHub Desktop.
Save jfhbrook/0714b4d319ad0801427c47268d975555 to your computer and use it in GitHub Desktop.
A completely fake example of what a controller might look like using our Flask-based python API framework
import cattrs
from flask import Blueprint, request
from flask_sqlalchemy import SQLAlchemy
from kinja_service import create_app
# Our framework's app factory
app = create_app('my_app')
# This is what setting up sqlalchemy models looks like with Flask
db = SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.String(22), primary_key=True)
first_name = db.Column(db.String(100))
last_name = db.Column(db.String(100))
bio = db.Column(db.String(280))
# This is how we tell cattrs how to unstructure a Person.
# In other words, registering this hook is how we turn
# a Person into a simpler object that the JSON module
# knows how to serialize
def unstructure_person(model):
return dict(
id=model.id,
first_name=model.first_name,
last_name=model.last_name,
bio=model.bio
)
cattr.register_unstructure_hook(Person, unstructure_person)
# Blueprints are how we define collections of routes
bp = Blueprint('my_app', __name__)
@bp.route(SOME_ROUTE, methods=['POST'])
@app.requires_auth
def create():
first_name = request.json['firstName']
last_name = request.json['lastName']
bio = request.json.get('bio', '')
person = Person(
first_name,
last_name,
bio
)
db.session.add(person)
db.session.commit()
return person
app.register_blueprint(bp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment