Skip to content

Instantly share code, notes, and snippets.

@jacquerie
Created April 10, 2015 08:04
Show Gist options
  • Save jacquerie/ec0ad2ee35e8f361a835 to your computer and use it in GitHub Desktop.
Save jacquerie/ec0ad2ee35e8f361a835 to your computer and use it in GitHub Desktop.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import backref
from flask_potion.routes import Relation
from flask_potion import ModelResource, fields, Api
app = Flask(__name__)
db = SQLAlchemy(app)
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(), nullable=False)
last_name = db.Column(db.String(), nullable=False)
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey(Author.id), nullable=False)
title = db.Column(db.String(), nullable=False)
year_published = db.Column(db.Integer)
author = db.relationship(Author, backref=backref('books', lazy='dynamic'))
db.create_all()
class BookResource(ModelResource):
class Meta:
model = Book
class Schema:
author = fields.ToOne('author')
class AuthorResource(ModelResource):
class Meta:
model = Author
api = Api(app)
api.add_resource(BookResource)
api.add_resource(AuthorResource)
if __name__ == '__main__':
app.run()
$ python potion.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [10/Apr/2015 10:03:36] "POST /author HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2015 10:03:37] "POST /book HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2015 10:03:37] "POST /author HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2015 10:03:37] "POST /book HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2015 10:03:37] "GET /author/1/books HTTP/1.1" 404 -
http :5000/author first_name=Charles last_name=Darwin > /dev/null
http :5000/book title="On the Origin of Species" author:=1 year_published:=1859 > /dev/null
http :5000/author first_name=James last_name=Watson > /dev/null
http :5000/book title="The Double Helix" author:=2 year_published:=1968 > /dev/null
http :5000/author/1/books
$ ./potion.sh
HTTP/1.0 404 NOT FOUND
Content-Length: 233
Content-Type: text/html
Date: Fri, 10 Apr 2015 08:03:37 GMT
Server: Werkzeug/0.10.4 Python/2.7.8
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment