Managing File Paths and Storage

Tutorial 4 of 5

1. Introduction

Welcome to this tutorial on managing file paths and storage in Flask. Flask is a popular web framework for Python, renowned for its simplicity and flexibility. One important aspect of web development with Flask is managing file paths and storage, which is what this tutorial will cover.

By the end of this tutorial, you will understand:
- How to manage file paths within your Flask application
- How to handle file storage and retrieval

Prerequisites:
- Basic understanding of Python
- Familiarity with Flask is helpful, but not mandatory

2. Step-by-Step Guide

In Flask, you will typically manage file paths when serving static files (like CSS, JavaScript, and images) and when handling file uploads/downloads.

File Paths: Flask considers all paths from the root directory of your application. For instance, if you have a directory named static in your root directory, you can access a file inside it as static/filename.

File Storage: When you handle file uploads, you need to decide where to store them. A common approach is to save them in a subdirectory of your application, like uploads.

Best Practices:

  • Keep your static files in a separate directory named static.
  • Don't store uploaded files in your application directory. Use a separate storage service or a well-protected directory.

3. Code Examples

Here's an example of how to serve a static file and handle a file upload:

from flask import Flask, request, send_from_directory
import os

app = Flask(__name__)
UPLOAD_FOLDER = '/path/to/upload/folder'

# Serving a static file
@app.route('/static/<path:filename>')
def serve_static_file(filename):
    # Use send_from_directory to safely serve the file
    return send_from_directory('static', filename)

# Handling a file upload
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return 'No file part'
        file = request.files['file']
        # if user does not select file, browser also submits an empty part without filename
        if file.filename == '':
            return 'No selected file'
        if file:
            file.save(os.path.join(UPLOAD_FOLDER, file.filename))
            return 'File uploaded successfully'

In the first route, we use send_from_directory to serve a file from the static directory.

In the second route, we handle a file upload. If the uploaded file exists, we save it in our UPLOAD_FOLDER.

4. Summary

In this tutorial, we learned how to manage file paths and storage in Flask. We've seen how to serve static files and handle file uploads.

Next, you could learn more about file handling, like how to validate uploaded files or how to handle large files.

5. Practice Exercises

  1. Create a Flask route that serves a file from a directory other than static.
  2. Modify the file upload example to only allow files with a .txt extension.

Here's a solution for the second exercise:

from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            return 'No file part'
        file = request.files['file']
        if file.filename == '':
            return 'No selected file'
        if file and file.filename.endswith('.txt'):
            filename = secure_filename(file.filename)
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            return 'Text file uploaded successfully'
        else:
            return 'Invalid file type. Only .txt files allowed.'

In this solution, we use secure_filename to make sure the filename is secure. We also check the file extension before saving the file.

Happy coding!