Created
April 30, 2018 08:02
-
-
Save ikapper/e19d5042c1c506d56289648ec17d8b2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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