Silver
Silver

Reputation: 1468

Serving a Single index.html With Flask from a Different Directory

I currently have a folder structure like so:

/
--client
----dist
------index.html
------index.js
--server
----server.py

The index.js in dist/ serves a react application. My server.py looks like this:

import os
from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/')
def hello_world():
    return send_from_directory('../client/dist/', 'index.html')

if __name__ == "__main__":
    app.run()

This doesn't work unfortunately and I get a Failed to load resource. I looked at several posts on SO and beyond regarding this. Most of them are very old (and perhaps outdated), and all of them usually have a different folder structure where the index.html file is served from a static folder within server/ or something similar.

I really just want to do what I imagine should be an easy task: When localhost:5000 is visited, Flask serves ../client/dist/index.html and from there React takes over and does its thing.

I would be very grateful if someone can provide me a minimal/clean way of achieving thing.

Upvotes: 3

Views: 1624

Answers (1)

Silver
Silver

Reputation: 1468

Turns out I was somewhat wrong. I thought the question wasn't a repost but after some more searching I found another StackOverflow question very similar to mine:

Serving static html file from another directory from flask restful endpoint

Putting together a couple of answers from there and elsewhere, I have a minimal working solution:

from flask import Flask, send_from_directory
app = Flask(__name__, static_folder='../client/dist')

@app.route('/')
def hello_world():
    return send_from_directory(app.static_folder, 'index.html')

if __name__ == "__main__":
    app.run()

When I now visit localhost:5000 I get the contents of index.html.

Upvotes: 3

Related Questions