Routing static files using flask
So I'm going to go and get my head around what I know is probably a terrible way to make static files for my site. I came across a lot of other threads (which didn't quite solve my problem) that referred to the fact that I should be using a web server like apache to serve static files. I've been doing this so far for my static website, but basically I just wanted to chat with it this way for development purposes while I learn Flask and add its functionality to the website.
So basically what was giving me problems, I want to serve all my static files (JS, CSS, etc.) with Flask, and also route all my static web pages using flask (for now, so i can run my application without apache and still download all links). My application setup: I have an "app.py" with all my code and a "static" directory for all my static files and a "templates" folder for all of my web pages.
This is my code:
from flask import Flask, render_template
# Create the application object
app = Flask(__name__, static_url_path='/static')
# Routes to path
@app.route('/')
def home():
return render_template('index.html')
# Routes to specific file, want to route all my pages instead
@app.route('/work.html')
def work():
return render_template('work.html')
#Route methods for other webpages
# Serves static files
@app.route('/<path:path>')
def static_file(path):
return app.send_static_file(path)
# Start the server
if __name__ == '__main__':
app.run(debug=True)
There are now a few noticable problems with this code, but unfortunately this is the best, I can get it to work correctly. First, I read a lot that "send_from_directory" instead of "send_static_file" is the correct way to send static files to Flask, but I couldn't get that to work. But currently my main problem is that I cannot route all of my static web pages this way (and I would have thought that "static_file" would do this, besides serving all my JS, CSS, etc. ); as it stands, I can route my web pages by creating a separate function in "app.py" for each web page that seems horribly inefficient. So yes, if in my code I need multiple lines, I will be very grateful forthat it is pointing in the right direction!
source to share
No one has answered this question yet
See similar questions:
or similar: