0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

falconでイメージのアップロードとダウンロード

Last updated at Posted at 2020-11-05

falconでイメージのアップロードとダウンロード

falconでイメージファイルをダウロードする必要があったのですが、Qiitaに記事がなかったのでアップします。

APIのソースコード

server.py
import os
import json
import uuid
import falcon
from falcon_multipart.middleware import MultipartMiddleware

IMAGE_DIR = './images'
if not os.path.exists(IMAGE_DIR):
    os.mkdir(IMAGE_DIR)

class PostResource:
    def on_post(self, req, resp):
        image = req.get_param('file')
        raw = image.file.read()
        image_id = str(uuid.uuid4())
        filepath = os.path.join(IMAGE_DIR, f'{image_id}.png')
        with open(filepath, 'wb') as fp:
            fp.write(raw)
        resp.status = falcon.HTTP_200
        resp.content_type = 'application/json'
        resp.body = json.dumps({'image_id': image_id})


class GetResource:
    def on_get(self, req, resp, image_id):
        filepath = os.path.join(IMAGE_DIR, f'{image_id}.png')
        if not os.path.exists(filepath):
            resp.status = falcon.HTTP_404
            return

        resp.downloadable_as = filepath
        resp.content_type = 'image/png'

        resp.stream = open(filepath, 'rb')
        resp.status = falcon.HTTP_200


app = falcon.API(middleware=[MultipartMiddleware()])
app.add_route('/images', PostResource())
app.add_route('/images/{image_id}', GetResource())

if __name__ == "__main__":
    from wsgiref import simple_server
    httpd = simple_server.make_server("0.0.0.0", 8000, app)
    httpd.serve_forever()

起動方法

python3 server.py

呼び出し方

イメージの登録

イメージをPOSTするとイメージID(以下の例では""44fea721-ef84-41c1-8845-3f2d5ad8b990")がJSONで返却されます。

curl -X POST -F file=@image.png http://localhost:8000/images
{"image_id": "44fea721-ef84-41c1-8845-3f2d5ad8b990"}

イメージの参照

さきほどのイメージ登録時に返却されたイメージIDを利用してGETします。

curl -X GET -o out.png http://localhost:8000/images/44fea721-ef84-41c1-8845-3f2d5ad8b990

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?