Skip to content

Instantly share code, notes, and snippets.

@Ceasar Ceasar/app.py
Created Mar 10, 2017

Embed
What would you like to do?
import json
from flask import Flask, request, url_for, jsonify
app = Flask(__name__)
with open('photos.json') as fp:
PHOTOS = json.loads(fp.read())
with open('albums.json') as fp:
ALBUMS = json.loads(fp.read())
@app.route("/")
def index():
return jsonify({
'albums_url': url_for('albums', _external=True),
'photos_url': url_for('photos', _external=True)
})
def find_photo(photo_id):
return next(photo for photo in PHOTOS if photo['id'] == photo_id)
def _get(collection, _id=None):
return jsonify(
next(obj for obj in collection if obj['id'] == int(_id)) if _id else
collection
)
@app.route("/albums", methods=['GET', 'POST'])
@app.route("/albums/<album_id>")
def albums(album_id=None):
if request.method == 'POST':
album_data = request.get_json()
album_data['id'] = max([album['id'] for album in ALBUMS]) + 1
ALBUMS.append(album_data)
return jsonify(album_data)
else:
return _get(ALBUMS, album_id)
@app.route("/photos")
@app.route("/photos/<photo_id>")
def photos(photo_id=None):
return _get(PHOTOS, photo_id)
@app.route("/albums/<album_id>/photos", methods=['GET', 'POST'])
def album_photos(album_id):
if request.method == 'POST':
photo_id = request.get_json()['id']
photo_data = dict(find_photo(photo_id))
photo_data['albumId'] = int(album_id)
PHOTOS.append(photo_data)
return jsonify(photo_data)
photos = [photo for photo in PHOTOS if photo['albumId'] == int(album_id)]
return jsonify(photos)
if __name__ == "__main__":
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.