Create a new jpg file when user hits the route- Flask-Ajax

Question:

app = Flask(__name__)
@app.route('/' , methods = ['GET', 'POST'])
def index():
    print("hello")
    if request.method == 'GET':
        text = request.args.get("image")
        

        print(text)

        base64_img_bytes = text.encode('utf-8')
        with open('decoded_image.jpeg', 'wb') as file_to_save:
            decoded_image_data = base64.decodebytes(base64_img_bytes)
            file_to_save.write(decoded_image_data)

The above code is my app.py in which an ajax request is sent to the route with an image captured from the camera of the user. I encode the image and write that encoded text into an image, but this is for one user I want to achieve this for multiple users. how can I achieve this for every user?

Every time a user hits route, create a new jpg file and save it local.

Asked By: sam

||

Answers:

Every time a user hits route, create a new jpg file and save it local.

You need to generate new filename each time, this can be done for example using uuid following way, add following import

import uuid

and replace

with open('decoded_image.jpeg', 'wb') as file_to_save:

using

with open('decoded_image_{}.jpeg'.format(uuid.uuid4().hex), 'wb') as file_to_save:
Answered By: Daweo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.