🔍 Code Extractor

function allowed_file

Maturity: 36

Validates whether a filename has an allowed file extension by checking if it contains a dot and if the extension (case-insensitive) exists in a predefined ALLOWED_EXTENSIONS collection.

File:
/tf/active/vicechatdev/leexi/app.py
Lines:
46 - 49
Complexity:
simple

Purpose

This function is a security utility commonly used in file upload functionality to restrict which file types can be uploaded to a web application. It prevents users from uploading potentially dangerous file types by validating the file extension against a whitelist defined in ALLOWED_EXTENSIONS. This is a common pattern in Flask web applications for secure file handling.

Source Code

def allowed_file(filename):
    """Check if file extension is allowed"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

Parameters

Name Type Default Kind
filename - - positional_or_keyword

Parameter Details

filename: A string representing the name of the file to validate, including its extension (e.g., 'document.pdf', 'image.jpg'). The function expects a filename that may or may not contain a file extension. Empty strings or filenames without extensions will return False.

Return Value

Returns a boolean value: True if the filename contains a dot AND the extension (after the last dot, converted to lowercase) is present in the ALLOWED_EXTENSIONS collection; False otherwise. Returns False for filenames without extensions, filenames that are just extensions (e.g., '.txt'), or extensions not in the allowed list.

Usage Example

# Define allowed extensions (required)
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'docx'}

# Example usage
filename1 = 'document.pdf'
filename2 = 'script.exe'
filename3 = 'noextension'
filename4 = 'REPORT.DOCX'

if allowed_file(filename1):
    print(f"{filename1} is allowed")  # Output: document.pdf is allowed

if not allowed_file(filename2):
    print(f"{filename2} is not allowed")  # Output: script.exe is not allowed

if not allowed_file(filename3):
    print(f"{filename3} is not allowed")  # Output: noextension is not allowed

if allowed_file(filename4):
    print(f"{filename4} is allowed")  # Output: REPORT.DOCX is allowed (case-insensitive)

# Typical Flask usage
from werkzeug.utils import secure_filename

if 'file' in request.files:
    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))

Best Practices

  • Always define ALLOWED_EXTENSIONS as a set rather than a list for O(1) lookup performance
  • Use this function in conjunction with werkzeug.utils.secure_filename() to sanitize filenames before saving
  • This function only validates extensions, not file content - consider adding MIME type validation or file content inspection for enhanced security
  • Remember that file extensions can be spoofed - this should be one layer of validation, not the only security measure
  • Keep ALLOWED_EXTENSIONS restrictive and only include file types your application actually needs to process
  • Consider the security implications of allowing executable extensions or script files
  • The function uses rsplit('.', 1) which correctly handles filenames with multiple dots (e.g., 'my.file.name.pdf')
  • Empty strings or None values will cause the function to return False safely

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function allowed_file_v1 91.3% similar

    Validates whether a given filename has an allowed file extension by checking if the extension exists in a configured whitelist.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function is_valid_document_file 62.0% similar

    Validates whether a given filename has an extension corresponding to a supported document type by checking against a predefined list of valid document extensions.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function api_upload_document_v1 53.1% similar

    Flask API endpoint that handles document file uploads, validates file type and size, stores the file temporarily, and extracts basic text content for processing.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_upload 52.5% similar

    Flask API endpoint that handles file uploads, validates file types, saves files to a configured directory structure, and automatically indexes the uploaded document for search/retrieval.

    From: /tf/active/vicechatdev/docchat/app.py
  • function test_multiple_file_upload 50.7% similar

    A test function that validates multiple file upload functionality to a Flask application endpoint by sending a transcript file and multiple previous report files.

    From: /tf/active/vicechatdev/leexi/test_flask_upload.py
← Back to Browse