Skip to content

Instantly share code, notes, and snippets.

@justanr
Last active February 15, 2018 12:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justanr/60f34a300ff4535c95fc to your computer and use it in GitHub Desktop.
Save justanr/60f34a300ff4535c95fc to your computer and use it in GitHub Desktop.
Quotly
from flask import Flask, request
from flask.ext.restful import Resource, Api
from flask.ext.sqlalchemy import SQLAlchemy
from marshmallow import Schema, post_dump
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///quotes.db'
api = Api(app)
db = SQLAlchemy(app)
class Quote(db.Model):
id = db.Column(db.Integer, primary_key=True)
person = db.Column(db.Unicode(50))
quote = db.Column(db.UnicodeText)
class QuoteSchema(Schema):
class Meta:
additional = ('person', 'quote')
@post_dump(raw=True)
def wrap_if_many(self, data, many=False):
if many:
return {'quotes': data}
return data
def make_object(self, data):
assert 'person' in data and 'quote' in data, "Must specify person and quote in request"
return Quote(person=data['person'], quote=data['quote'])
class SingleQuote(Resource):
def get(self, idx):
if idx:
quote = Quote.query.get(idx)
return QuoteSerializer.dump(quote).data if quote else ({'error': 'quote does not exist'}, 404)
return {'error': 'must specify quote id'}
class ListQuote(Resource):
def get(self):
return QuoteSerializer.dump(quotes, many=True).data
def post(self):
json = request.get_json()
if not json:
return {"success": False, "msg": "malformed request"}, 400
if not 'quote' in json:
return {"success": False, "msg": "must specify quote in request"}, 400
else:
q = QuoteSerializer.load(request['json'])
db.session.add(q.data)
db.session.commit()
return {"success": True, "msg": "Quote added."}
QuoteSerialize = QuoteSchema()
api.register_resource(SingleQuote, '/quote/<int:id>')
api.register_resource(ListQuote, '/quotes')
from app import app, db, Quote
if __name__ == '__main__':
db.create_all()
if Quote.query.count() == 0:
quotes = [Quote(p, q) for p, q in [
('Herbert West', 'I was busy pushing bodies around as you well know '
'and what would a note say, Dan? "Cat dead, details later"?'),
('Jack Burton', "You remember what ol' Jack Burton always says at a "
'time like that: "Have ya paid your dues, Jack?" "Yessir, the check '
'is in the mail."'),
('Igor', 'Well, why isn\'t it "Froaderick Fronkensteen"?')
]]
db.session.add_all(quotes)
db.session.commit()
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment