[PYTHON] Upload and download images with falcon

Upload and download images with falcon

I had to download the image file with falcon, but I will upload it because there was no article in Qiita.

API source code

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()

starting method

python3 server.py

How to call

Image registration

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"}

Image reference

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

reference

Recommended Posts

Upload and download images with falcon
Automatically download images with scraping
I can't download images with Google_images_download
Capturing images with Pupil, python and OpenCV
Easily download mp3 / mp4 with python and youtube-dl!
Cut out and connect images with ImageMagick
Upload images to Google Drive with Python
Automatically search and download YouTube videos with Python
Cannot upload multiple images from form with FastAPI
Load caffe model with Chainer and classify images
Download and import files with Splunk external python
Bulk download images from specific URLs with python
Wavelet transform of images with PyWavelets and OpenCV
Simple management app for download images and face images
Upload images to S3 with GUI using tkinter
Try using S3 object upload and download with AWS SDK for Go v2
Upload files with Django
Get media timeline images and videos with Python + Tweepy
Bulk download images from specific site URLs with python
Download images using requests
Display embedded images of mp3 and flac with mutagen
Easy partial download of mp4 with python and youtube-dl!
Create a batch of images and inflate with ImageDataGenerator
File upload with django
With and without WSGI
Center images with python-pptx
LGTM --Compose LGTM images with videos and photos and output GIF animation
Separate color images into RGB images and display them with OpenCV
Send experiment results (text and images) to slack with Python
Upload images taken with an action camera with a Mapillay script
Convert garbled scanned images to PDF with Pillow and PyPDF
With me, cp, and Subprocess
Programming with Python and Tkinter
Encryption and decryption with Python
Bordering images with python Part 1
Working with tkinter and mouse
Python and hardware-Using RS232C with Python-
Save images with web scraping
Web API with Python + Falcon
Extract and package initrd images
Send and receive Flask images
Super-resolution with SRGAN and ESRGAN
Combine two images with Django
group_by with sqlalchemy and sum
python with pyenv and venv
File upload with Flask + jQuery
Download csv file with python
With me, NER and Flair
Works with Python and R
Batch download images from a specific URL with python Modified version
[Python] Try to recognize characters from images with OpenCV and pyocr
Download the images and videos included in the tweets you liked on Twitter and upload them to Google Drive