Reputation:
I went through many tutorials and everything worked. But I started my own website and I get only error 404 not found.
I downloaded a HTML template and managed to clone the files from Github to PythonAnywhere. Right now the structure of my files is: Screenshot
Flask_app.py Code:
from flask import Flask
# set the project root directory as the static folder, you can set others.
app = Flask(flask_app, static_url_path='/home/dubspher/mysite')
app = Flask(__name__)
@app.route('/home/dubspher/mysite/')
def static_file(path):
return app.send_static_file(index.html)
if __name__ == "__main__":
app.run()
Should I create another website with templates and use render_template or there's a way I can request a static page with flask?
So far I tried many codes but I don't know what to do with static_url_path
HTML if needed : https://www.pythonanywhere.com/user/dubspher/shares/db715c9b9d7c43b7beb4245af23fb56c/
Let me know if I need to add more informations.
Upvotes: 0
Views: 2541
Reputation: 3363
Here is your code fixed up to serve up index.html at the root of your site (e.g. http://example.com/):
from flask import Flask
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_folder='/home/dubspher/mysite/')
@app.route('/')
def static_file():
return app.send_static_file('index.html')
if __name__ == "__main__":
app.run()
That assumes that you have an index.html file in your /home/dubspher/mysite directory.
To follow up on your css question, you can get flask to serve up static files generically by passing in a static_url_path to the Flask constructor. When you do that, any request that comes in matching that static_url_path flask treats as a static file and serves it up based on the static_folder path. In the sample below, I've set static_url_path to static and the static_folder to /home/dubspher/mysite/. When a request for http://example.com/static/css/site.css comes in flask will serve up the file /home/dubspher/mysite/css/site.css.
from flask import Flask
app = Flask(__name__, static_url_path="/static", static_folder='/home/dubspher/mysite/')
@app.route('/')
def static_file():
return app.send_static_file('index.html')
if __name__ == "__main__":
app.run()
Here's an example of referencing a stylesheet at /home/dubspher/mysite/css/site.css from index.html.
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/css/site.css">
</head>
<body>
Hello There
</body>
</html>
If you do use the static_url_path, you need to be very careful that everything under your static_folder path is something you want to be accessible. Flask is going to serve it up as is.
Upvotes: 1