1

I am trying to write a simple API using Flask. I am following Miguel Grinberg's blog.

I have a use-case where I am trying to serve a static page. I am unable to serve the static webpage.

Here is my app.py

from flask import Flask, request, abort, render_template

app = Flask(__name__)

@app.route('/sample/application/', methods=['GET'])
def static_website():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

And following is my directory layout:

flask_application/
    - app.py
    - static/
        - index.html
        - cs/
            - app.css
            - bootstrap.css
        - js/
            - jquery.js
        - images/
            - logo.png

Before anyone marks this as a duplicate, I have gone through the following posts and it has not resolved my issue.

There are other questions but no ones gives a concrete solution to resolve css, js files in static pages.

The server created by Flask is unable to pickup the js, css files.

Also, I am avoiding templating because this the only use-case I have and I am pretty sure, I am not going to add any other pages or make it more complex.

Community
  • 1
  • 1
Amriteya
  • 1,118
  • 15
  • 37

2 Answers2

1

The template needs to be in a folder called templates. So the correct solution should be

flask_application/
   - templates/
     - index.html 

You can read the documentation for the render_template method.

Jonathan
  • 8,453
  • 9
  • 51
  • 74
  • The css and js files need to be under static folder only? – Amriteya Mar 07 '17 at 11:54
  • Yeah, it's only the html templates that should be in the templates folder. All other files that you're serving should be in the static directory. There might be settings to customize this too though. But that's the general layout. – Jonathan Mar 07 '17 at 11:56
  • @amriteya, But if you're after a completely static website, why are you not using something like pelican? Is there a reason to use flask? – Jonathan Mar 07 '17 at 11:58
  • My page is still showing vanilla html without any style. The css, js files are not getting picked up. – Amriteya Mar 07 '17 at 11:58
  • You'll have to add the template itself so I can see the code for that. – Jonathan Mar 07 '17 at 12:00
-1

If you don't care about renderung a template, you can just send the static file on your route. This way you can just leave everything in the static directory.

app.send_static_file('index.html')

Just remember the rest of the assets will need to be referenced as /static/<asset>, ie <script src="/static/js/jquery.js></script>

mphuie
  • 970
  • 1
  • 9
  • 17