Flask File Handling


What is file handling in Flask?

File handling in Flask refers to the ability to upload, save, and serve files from the server. Flask provides methods to handle file uploads from clients, such as images or documents, and allows you to process, validate, and store these files on the server.


How do you handle file uploads in Flask?

Flask provides the request.files attribute to handle file uploads. When a client uploads a file, it is sent in a multipart/form-data request, and Flask allows you to access and save the file using the save() method.

Example of handling file uploads:

from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return 'File uploaded successfully'
    return '''
    
      
      
    
    '''

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

In this example, the file is uploaded via a POST request, and Flask saves the file in the uploads/ directory. The secure_filename() function is used to ensure the file name is safe to use on the server.


How do you restrict the file types that can be uploaded in Flask?

You can restrict the types of files that can be uploaded by checking the file's extension or MIME type before saving it to the server. This ensures that only valid files are uploaded.

Example of restricting file types:

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return 'File uploaded successfully'
    return 'Invalid file type'

In this example, only image files with extensions like png, jpg, jpeg, and gif are allowed. If an invalid file type is uploaded, an error message is returned.


How do you serve static files in Flask?

Flask automatically serves static files from the static folder. You can place your CSS, JavaScript, and image files in the static folder, and they can be accessed via a URL.

Example of serving a static file:

@app.route('/static-file')
def serve_static_file():
    return app.send_static_file('example.png')

In this example, the file example.png located in the static folder can be served using the send_static_file() method.


How do you serve uploaded files in Flask?

To serve uploaded files that are stored in the server, you can use Flask's send_from_directory() method, which serves a file from a specified directory. This is commonly used for serving user-uploaded files.

Example of serving uploaded files:

from flask import send_from_directory

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

In this example, uploaded files are served from the uploads/ directory using the send_from_directory() method.


How do you delete files in Flask?

To delete files in Flask, you can use Python's built-in os.remove() function to delete a file from the server. This is useful when you need to remove files uploaded by users or temporary files.

Example of deleting a file:

import os

@app.route('/delete/<filename>')
def delete_file(filename):
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    try:
        os.remove(file_path)
        return 'File deleted successfully'
    except FileNotFoundError:
        return 'File not found'

In this example, the file is deleted from the uploads/ directory using os.remove(). If the file is not found, an error message is returned.


How do you handle large file uploads in Flask?

To handle large file uploads, Flask allows you to limit the maximum size of uploaded files using the MAX_CONTENT_LENGTH configuration setting. You can set this value in your Flask app to prevent users from uploading excessively large files.

Example of limiting file upload size:

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB limit

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    if file:
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return 'File uploaded successfully'
    return 'File upload failed'

In this example, the maximum file size is limited to 16 MB. If a file larger than 16 MB is uploaded, Flask will automatically return a 413 Request Entity Too Large error.


How do you handle file downloads in Flask?

Flask allows you to send files to the client as downloads using the send_file() method. This method allows you to serve any file stored on the server as a downloadable resource.

Example of handling file downloads:

from flask import send_file

@app.route('/download/<filename>')
def download_file(filename):
    return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), as_attachment=True)

In this example, the file is downloaded from the uploads/ directory. The as_attachment=True argument forces the file to be downloaded rather than displayed in the browser.


How do you handle file validation in Flask?

To validate files before saving them, you can check for properties like file extension, MIME type, and file size. This helps ensure that only valid and safe files are uploaded to the server.

Example of file validation:

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    if file and allowed_file(file.filename):
        if file.mimetype.startswith('image/'):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return 'File uploaded successfully'
    return 'Invalid file'

In this example, the file is validated based on its extension and MIME type (only image files are accepted).


How do you handle temporary file storage in Flask?

If you want to store files temporarily before processing them, you can use Python's tempfile module to create temporary files. These files are automatically deleted when they are no longer needed.

Example of handling temporary files:

import tempfile

@app.route('/upload', methods=['POST'])
def upload_temp_file():
    file = request.files['file']
    if file:
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            file.save(temp_file.name)
            return f"Temporary file saved at {temp_file.name}"

In this example, the uploaded file is saved as a temporary file using tempfile.NamedTemporaryFile(), and it can be processed or deleted later.

Ads