Forums

Flask does not see the picture on the server and problems with variables

Hi, my flask application accepts a picture from the user and then saves it on the server, and the path to it is written to a variable, and when switching to the next page, this picture should be displayed on the canvas, but periodically either the variable remains None (initial value) or the image is not found, although by going at its address it will be displayed. My code:

from flask import Flask, render_template, url_for, request, redirect, make_response
from PIL import Image
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.path.join(app.root_path, 'static/images')
app.template_folder = os.path.join(app.root_path, 'templates')

storage = {
    'image_name': None,
    'image_size': None,
    'path': None,
    'quantity': None,
    'file': None,
    'format': None,
    'screen_size': (),
    'calc': None
}


@app.route('/', methods=['POST', 'GET'])
def index():
    return render_template('page_1.html')   <------ submitting a form with an image to '/upload'


@app.route('/upload', methods=['POST', 'GET'])
def upload():
    global storage
    if request.method == 'POST':
        file = request.files.get('image')
        storage['image_name'] = file.filename
        storage['path'] = os.path.join(app.config['UPLOAD_FOLDER'], storage['image_name'])
        file.save(storage['path'])
        image = Image.open(file)
        storage['image_size'] = image.size

    return redirect(url_for('p2'))


@app.route('/p2', methods=['POST', 'GET'])
def p2():
    global storage
    return render_template('page_2.html', image=storage['image_name'])

storage['image_name'] may sometimes be None but the image will be savedю In othre app do image = Image.open(image_path) (PIL method), but the image was not found, but it is there and the path is correct. What's happening?

There are multiple independent processes handling requests to your website, so each of them will have its own global variables. Each request will be allocated to a process, essentially at random. So that means that for one request you might get one storage variable, and for another you might get a different one.

If you want to keep persistent storage between requests, you should use sessions -- there are multiple tutorials on how to use them with Flask, just search for "Flask sessions" and you should be able to find one that explains things.