Forums

Save and display static file with flask

I've created a Flask app that receives image byte data, saves the image, and displays it on screen. it works fine in a local environment, but when uploaded to pythonanywhere it doesn't seem to even save the file to display on screen anymore. Here is my Flask apps route that is responsible for saving the image

@app.route('/vid', methods=['POST'])
def receive_frame():
    try:
        frame_data = request.data

        # Save the received frame as an image
        with open('static/images/received_frame.jpg', 'wb') as f:
            f.write(frame_data)
        return "Frame received and saved"
    except Exception as e:
        return f"Error: {e}"

@app.route('/static/images/<filename>')
def serve_image(filename):
    return send_from_directory('static/images', filename)

In my HTML I use some js to update the image every so often

<img id="image_display" src="{{ url_for('serve_image', filename='received_frame.jpg') }}">
<script>
        function updateImage() {
            //reset img src to update it
            $('#image_display').attr('src', '/static/images/received_frame.jpg?' + new Date().getTime());
        }
        setInterval(updateImage, 1000);
</script>

The file layout for my project looks like this

Home
├───mysite 
│   └─── templates
│   │    └─── index.html
│   └─── server.py (flask app)
└─── static
    └───images

I assume its a problem with how I am handling static files. I think its also worth mentioning that I set a path to Static files in my web tab like this

URL       Directory
/static   /home/786bg8isdfuy/mysite/static

Dose anyone know how to handle static files with flask on pythonanywhere? thank you.

What is the working directory that you have set for your website? Looking at that code, it should be /home/786bg8isdfuy/mysite in order for the open command in your Flask code to write to the location that you expect.

My directories are setup like this

Source code: /home/786bg8isdfuy/mysite
Working directory: /home/786bg8isdfuy/
WSGI configuration file:/var/www/786bg8isdfuy_pythonanywhere_com_wsgi.py
Python version: 3.10

I don't see a way to edit them to the path you mentioned though

ANSWER:

Nevermind you can edit the working directory path by just clicking on it lol...

I fixed my problem by changing my working directory from this

Working directory: /home/786bg8isdfuy/

to this

Working directory: /home/786bg8isdfuy/mysite

then I moved the static folder into the mysite folder changing the file layout to look like this

    Home
    ├───mysite 
        └─── templates
        │    └─── index.html
        └─── static
        │        └───images
        └─── server.py (flask app)

Thank you.

Glad you got that working.