I had to download the image file with falcon, but I will upload it because there was no article in 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
When you POST the image, the image ID ("44fea721-ef84-41c1-8845-3f2d5ad8b990" in the example below) will be returned in JSON.
curl -X POST -F [email protected] http://localhost:8000/images
{"image_id": "44fea721-ef84-41c1-8845-3f2d5ad8b990"}
GET using the image ID returned at the time of image registration earlier.
curl -X GET -o out.png http://localhost:8000/images/44fea721-ef84-41c1-8845-3f2d5ad8b990
Recommended Posts