cuizin/cuizin/web.py

104 lines
2.3 KiB
Python
Raw Normal View History

2018-02-27 17:47:32 +01:00
import json
import bottle
2018-02-27 17:47:32 +01:00
from cuizin import add_recipe
from cuizin import db
2018-02-27 17:47:32 +01:00
app = bottle.Bottle()
@app.hook('after_request')
def enable_cors():
"""
Add CORS headers at each request.
"""
# The str() call is required as we import unicode_literal and WSGI
# headers list should have plain str type.
bottle.response.headers[str('Access-Control-Allow-Origin')] = str('*')
bottle.response.headers[str('Access-Control-Allow-Methods')] = str(
'PUT, GET, POST, DELETE, OPTIONS, PATCH'
)
bottle.response.headers[str('Access-Control-Allow-Headers')] = str(
'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
)
2018-02-27 17:47:32 +01:00
@app.route('/api/v1', ['GET', 'OPTIONS'])
def api_v1_index():
return {
'recipes': '/api/v1/recipes'
}
2018-02-27 17:47:32 +01:00
@app.route('/api/v1/recipes', ['GET', 'OPTIONS'])
def api_v1_recipes():
2018-02-27 17:47:32 +01:00
# CORS
if bottle.request.method == 'OPTIONS':
return ''
return {
'recipes': [
recipe.to_dict() for recipe in db.Recipe.select()
]
}
2018-02-27 17:47:32 +01:00
@app.post('/api/v1/recipes')
def api_v1_recipes_post():
data = json.load(bottle.request.body)
if 'url' not in data:
return {
'error': 'No URL provided'
}
recipes = []
try:
2018-02-28 22:06:21 +01:00
recipe = db.Recipe.select().where(
2018-02-27 17:47:32 +01:00
db.Recipe.url == data['url']
2018-02-28 22:06:21 +01:00
).first()
assert recipe
recipes = [recipe.to_dict()]
except AssertionError:
recipes = [add_recipe(data['url']).to_dict()]
2018-02-27 17:47:32 +01:00
return {
'recipes': recipes
}
@app.route('/api/v1/recipe/:id', ['GET', 'OPTIONS'])
def api_v1_recipe(id):
2018-02-27 17:47:32 +01:00
# CORS
if bottle.request.method == 'OPTIONS':
return ''
return {
'recipes': [
recipe.to_dict() for recipe in db.Recipe.select().where(
db.Recipe.id == id
)
]
}
2018-02-28 22:06:21 +01:00
@app.delete('/api/v1/recipe/:id', ['DELETE', 'OPTIONS'])
def api_v1_recipe_delete(id):
# CORS
if bottle.request.method == 'OPTIONS':
return ''
db.Recipe.delete().where(
db.Recipe.id == id
).execute()
return {
'status': 'OK'
}
@app.get('/static/<filename:path>')
def get_static_files(filename):
"""Get Static files"""
2018-02-27 17:47:32 +01:00
return bottle.static_file(filename) # TODO: root=