-1

I'm trying to access a page using Flask but static files are not served.

@app.route('/hello/', 
methods=['GET','POST'])
def hello:
    return render_template('hello.html')

I get the page hello.html on the browser but all static files path have changed to localhost:5000/hello/static... But if I change to:

@app.route('/hello')

The static files are served correctly. So whenever I have any route that has a forward slash, it changes the static files being served i.e

@app.route('/editFile/<int:id>')

Static files would change and be served under new path localhost:5000/editFile/static/... Routes with / after makes all static files be searched with wrong paths

If no / is added after route then static files are loaded correctly

John Simiyu
  • 1
  • 1
  • 1

3 Answers3

0

You need to prepend a slash to those routes:

@app.route('/hello')

and:

@app.route('/editFile/<int:id>')

This should give the expected behaviour.

As a side-note, if you also add a trailing slash, for example:

@app.route('/test/')

Then a request to /test/ will return the response, and a request to /test will return a 308 redirect to /test/:

$ curl http://localhost:5009/test/  
response%

$ curl -i http://localhost:5000/test
HTTP/1.0 308 PERMANENT REDIRECT
Location: http://localhost:5000/test/

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL:
<a href="http://localhost:5009/test/">http://localhost:5000/test/</a>.  If not click the link.%   
v25
  • 7,096
  • 2
  • 20
  • 36
0

If you want to add the slash after the route like this /hello/ then when you are accessing the static file you should use this url_for('static',filename = 'file') The static endpoint is used to retrieve the static files

DevHyperCoder
  • 895
  • 1
  • 9
  • 22
0

To refer to a file in the static folder, include a leading '/' in the href for locating the file, i.e. href="/static/filename". The behavior observed in the parent post occurs when the leading slash is omitted, i.e. href="static/filename"

Adam X
  • 1