J'ai dû télécharger le fichier image avec Falcon, mais je vais le télécharger car il n'y avait pas d'article dans Qiita.
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
Lorsque vous POSTEZ l'image, l'ID de l'image ("44fea721-ef84-41c1-8845-3f2d5ad8b990" dans l'exemple ci-dessous) sera renvoyé en JSON.
curl -X POST -F [email protected] http://localhost:8000/images
{"image_id": "44fea721-ef84-41c1-8845-3f2d5ad8b990"}
Obtenez-le en utilisant l'ID d'image renvoyé lorsque vous avez enregistré l'image plus tôt.
curl -X GET -o out.png http://localhost:8000/images/44fea721-ef84-41c1-8845-3f2d5ad8b990
Recommended Posts