In Flask, static files are typically stored in a dedicated directory. By default, Flask looks for static files in a folder named static
at the same level as your main application file. This separation of static and dynamic content helps in organizing your project and makes it easier to manage.
When a client requests a static file, Flask maps the request to the appropriate file in the static directory and sends it back to the client. The process involves routing the request to the correct file location and setting the appropriate HTTP headers for the file type.
Flask has a built - in mechanism to serve static files from a default static
folder. Here is a simple example:
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/')
def index():
# Return an HTML page that references a static CSS file
return '''
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Welcome to my Flask App</h1>
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True)
In this example, the url_for('static', filename='styles.css')
function generates a URL for the styles.css
file in the static
folder. Flask will automatically serve the file when the client requests it.
If you want to use a custom static folder, you can specify it when creating the Flask application:
from flask import Flask, send_from_directory
app = Flask(__name__, static_folder='my_static_folder')
@app.route('/')
def index():
return '''
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Welcome to my Flask App</h1>
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True)
Here, Flask will look for static files in the my_static_folder
instead of the default static
folder.
You can also serve static files directly from URLs. For example, if you want to serve a specific file at a custom URL:
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/static-files/<path:path>')
def send_static(path):
return send_from_directory('static', path)
if __name__ == '__main__':
app.run(debug=True)
In this code, any request to a URL starting with /static - files/
will be mapped to the corresponding file in the static
folder.
Serving static files in Flask is a fundamental aspect of building web applications. By understanding the core concepts, typical usage scenarios, common pitfalls, and best practices, you can effectively serve static files and create high - performance web applications. Remember to test your application thoroughly and follow security best practices to ensure a smooth user experience.