You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.6 KiB

import flask
import flask_cors
from quote import engine, Base, Session, Quote, QuoteSchema
app = flask.Flask(__name__)
flask_cors.CORS(app)
Base.metadata.create_all(engine)
@app.route('/quotes')
def get_quotes():
args = flask.request.args
filter = args.get('filter', type=str)
sort_by = args.get('sort_by', type=str)
sort_order = args.get('sort_order', type=str)
page_number = args.get('page_number', type=int)
page_size = args.get('page_size', type=int)
session = Session()
try:
q = session.query(Quote)
if filter:
q = q.filter(Quote.text.ilike('%{}%'.format(filter)))
count = q.count()
if sort_by:
col = getattr(Quote, sort_by, None)
if col:
if sort_order:
order_by = getattr(col, sort_order, None)
if order_by:
q = q.order_by(order_by())
else:
q = q.order_by(col)
if page_size:
q = q.limit(page_size)
if page_number and page_size:
q = q.offset(page_number * page_size)
data = QuoteSchema(many=True).dump(q).data
finally:
session.close()
return flask.jsonify(data), 200, {'X-Total-Count': count}
@app.route('/quotes', methods=['POST'])
def add_quote():
q = QuoteSchema().load(flask.request.get_json())
quote = Quote(**q.data)
session = Session()
try:
session.add(quote)
session.commit()
data = QuoteSchema().dump(quote).data
except:
session.rollback()
raise
finally:
session.close()
return flask.jsonify(data), 201