Related Tutorial

13: Serving Static Files in a Flask Web Application

Introduction:

 In this blog post, we will discuss how to serve static files in a Flask web application. We will walk through the process of setting up a directory for static files, handling user-uploaded files, and serving them to users based on custom URLs. By following these steps, you can enhance your web application to handle both URLs and static files seamlessly.

Code Example: Below is an example code snippet demonstrating how to implement the functionality described above using Flask.

				
					from flask import Flask, redirect, url_for
import json
import os

app = Flask(__name__)

# Load URLs from urls.json file
def load_urls():
    if os.path.exists('urls.json'):
        with open('urls.json') as urls_file:
            return json.load(urls_file)
    return {}

# Define a route to handle custom URLs and static files
@app.route('/<string:code>')
def redirect_or_serve_file(code):
    urls = load_urls()
    
    if code in urls:
        if 'url' in urls[code]:
            return redirect(urls[code]['url'])
        elif 'file' in urls[code]:
            file_path = os.path.join('static/user_files', urls[code]['file'])
            return redirect(url_for('static', filename=f'user_files/{urls[code]["file"]}'))
    
    return "URL not found"

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

Explanation:

  1. We create a Flask route /code that checks if the provided code exists in the loaded URLs data.
  2. If the code matches a key in the URLs dictionary, we check if it is associated with a URL or a file.
  3. If the code is associated with a file, we construct the file path using the static/user_files directory and the file name from the URLs data.
  4. We then use url_for to generate the URL for serving the static file and redirect the user to that URL.
  5. If the code does not match any URLs in the data, we return a message indicating that the URL was not found.

Conclusion:

 In this blog post, we have explored how to serve static files in a Flask web application. By following the steps outlined above, you can enhance your web application to handle user-uploaded files and provide a seamless experience for users accessing custom URLs and static content. This approach can be further extended to incorporate additional features and optimizations based on your specific requirements and use cases..