Skip to content

Instantly share code, notes, and snippets.

@ikapper
Created April 30, 2018 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikapper/e19d5042c1c506d56289648ec17d8b2c to your computer and use it in GitHub Desktop.
Save ikapper/e19d5042c1c506d56289648ec17d8b2c to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
Flaskを使って、mongodbに保存した画像ファイルを表示させる。
"""
# まずはmongoDBのセットアップ
from mongoengine import connect
connect('example_image', host='localhost', port=27017)
# 次に、mongoDBに格納するドキュメントのセットアップ
from mongoengine.document import Document
from mongoengine import fields
class Item(Document):
title = fields.StringField()
text = fields.StringField()
# pillowを導入しないと、以下のエラーが出る
# mongoengine.fields.ImproperlyConfigured: PIL library was not found
image = fields.ImageField()
# Flaskのセットアップ
from flask import Flask
from flask import send_file
from io import BytesIO
app = Flask(__name__)
@app.route('/')
def index():
items = []
for item in Item.objects:
rrr = '<p>{0}, {1}, {2}</p>'.format(item.title, item.text, item.image)
items.append(rrr)
print(item.title)
return """
<html>
<head>
<title>Index Page</title>
</head>
<body>
%s
<img src="thumbnail/123"/>
</body>
</html>
""" % ''.join(items)
@app.route('/thumbnail/<name>')
def thumbnail(name=None):
print('name:', name)
# 実際はnameにしたがって扱うファイルを決定する
item = Item.objects[1]
bi = BytesIO(item.image.read())
return send_file(bi, mimetype='image/jpeg')
if __name__ == "__main__":
app.run(host='localhost')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment