Serving static html file from another directory from flask restful endpoint

11,425

When creating flask app, configure static_folder to your client folder.

from flask import Flask
app = Flask(__name__, static_folder="client")

Then you can access js and css on url http://localhost:5000/static/css/main.css

About your initial question. You can serve static html pages with flask like this:

@app.route('/<path:path>')
def serve_page(path):
    return send_from_directory('client', path)
Share:
11,425

Related videos on Youtube

Salvador Dali
Author by

Salvador Dali

I am a Software Engineer in the Google Search Growth team. I use Tensorflow and TFX to analyze search data and Go to write data pipelines. This is my personal profile which has absolutely nothing to do with my employer.

Updated on September 14, 2022

Comments

  • Salvador Dali
    Salvador Dali over 1 year

    I have a toy REST application which is structured in a following way:

     - client/
       - css/
       - js/
       - index.html
     - server/
       - app.py
       ... some other files  which I use in app.py
    

    app.py is a flask restful endpoint which looks like this:

    app = flask.Flask('some-name')
    
    # a lot of API end points, which look in this way
    @app.route('/api/something', methods=['GET'])
    def func_1():
        ...
    

    and now I want to serve my static index html. So after looking at this, this and this, I thought that I would be able to serve it easily by adding the following lines:

    @app.route('/')
    def home():
        # but neither with this line
        return app.send_static_file('../client/index.html')
        # nor with this
        return flask.render_template(flask.url_for('static', filename='../client/index.html'))
    

    I can not see my html file (logs tell me: 127.0.0.1 - - [some day] "GET / HTTP/1.1" 404 -). I know that I can move index.html in the server folder but is there a way to serve it from where it is right now?

    P.S. when I added app._static_folder = "../client/" and changed my home function to return app.send_static_file('index.html') I finally started to receive my html file, but all the css/js file that are inside html are returned with 404.

    • sjudǝʊ
      sjudǝʊ about 9 years
      And of corse, urls in index.html should be set correctly. That means, you need to used "static" endpoint ( example.com/static/main.css )
  • dirkk0
    dirkk0 about 8 years
    or app = Flask(__name__, static_folder='static', static_url_path='') if you want to avoid the 'static' in the url.