This is a view as part of a RESTful image handler module, written for Flask, I am sure there is a better/more pythonic way of doing parts of this, maybe using List Comprehensions or Generator Functions. But I am a bit of a Python newbie and cannot spot it. Can any experienced pythonistas take a look?
@__mod__.route('/', methods=['GET'])
@__mod__.route('/<filename>', methods=['GET'])
def get(filename=None):
""" Get a list of all Images or a single Image """
couchdb.init_app(current_app)
image = Image()
if filename is None:
results = image.view('images/all')
filenames = []
for result in results.all():
if result._attachments:
for attachment in result._attachments.keys():
filenames.append(url_for('.get', filename=attachment))
response = make_response(simplejson.dumps(filenames), 200)
response.headers['Content-Type'] = 'application/json'
return response
else:
results = image.view('images/all', key=filename)
if results.first() is not None:
try:
image_file = image.get_db().fetch_attachment(results.first(), filename)
image_doc = results.first()._attachments[filename]
response = make_response(image_file, 200)
response.headers['Content-Type'] = image_doc['content_type']
return response
except ResourceNotFound:
abort(404)
else:
abort(404)
I've managed this on my own, using a list comprehension instead of the ugly for-if structures:
if filename is None:
results = image.view('images/all')
filenames = [url_for('.get', filename=attachment)
for result in results
if result._attachments
for attachment in result._attachments]
response = make_response(simplejson.dumps(filenames), 200)
response.headers['Content-Type'] = 'application/json'
return response
else:
results = image.view('images/all', key=filename)
if results.first():
try:
image_file = image.get_db().fetch_attachment(results.first(), filename)
image_doc = results.first()._attachments[filename]
response = make_response(image_file, 200)
response.headers['Content-Type'] = image_doc['content_type']
return response
except ResourceNotFound:
abort(404)
else:
abort(404)