How to set upload file size limit using Python

Introduction : 

Hey Fellow coders , In this tutorial we are going to learn that how can we set upload file size limit using Python . We will be using flask to do our task . So , before we get started let’s know what is flask.

We will do in many simple steps so that it will be easy for us to understand . SO, Let’s begin

Flask : 

Before we will proceed  on doing the program we should know something about flask so . Flask is a microframework, which means it’s designed to be simple and easy to extend. Unlike some other web frameworks, Flask provides the basics for web development and allows you to add additional functionality as needed.

Now , We will start with the code part .

Step 1 : Install Flask 

Before doing all the steps we need to install the Flask to the system . To install that we need to use Command prompt for windows , Terminal on MacOS and Linux.

To install we just need to write a simple command that is ‘ pip install Flask ‘ in our command line

pip install Flask

And here ‘ pip ‘ is a package manager for Python that allows you to install and manage additional libraries and dependencies.

Step 2 : Create a Basic Flask Application 

After installing the flask , In this step, we’ll create a simple Flask application that will serve a basic web page. Think of it as creating the foundation for your web app.

1.Create a New File : 

Open the text editor and create a new file and name it ‘ app.py ‘  . This file will contain your Flask application code.

2.Write the Basic Flask Code : 

In this step we will write the flask code that will create the application , For that we need to write some line in our program the description of the lines are mentioned below ,

from flask import Flask  # Import the Flask class

app = Flask(__name__)  # Create an instance of the Flask class

@app.route('/')
def index():
    return 'Hello, World!'  # Return a simple "Hello, World!" message

if __name__ == "__main__":
    app.run(debug=True)  # Run the app in debug mode

Here ,

  • ‘ from flask import Flask ‘ imports the Flask class from the Flask library.
  • ‘ app = Flask(__name__) ‘ creates an instance of the Flask class. This instance will be your web application.
  • ‘ @app.route(‘/’) ‘ tells Flask to execute the function index when someone visits the root URL (i.e., http://localhost:5000/).
  • ‘ def index() : ‘ This defines a function named ‘ index ‘ .
  • ‘ return ‘Hello, World!’ ‘ This line sends the text “Hello, World!” to the web browser when the root URL is accessed.
  • ‘ if __name__ == “__main__”: ‘ checks if the script is being run directly (and not imported as a module).
  •  ‘ app.run(debug=True) ‘ this starts the Flask web server. The ‘ debug=True ‘  option makes it easier to see errors and reloads the server automatically when you make changes.

Step 3 : Set the Maximum Content Length 

After creating the flask app now we are going to set the maximum content limit . For that we need to open the app file that we have created in the stap 2 and add a configuration setting to limit the file size . For example we are going to set it as 16 mb so we will write the code according to it you can write it according to the limit that you want to set .

To do this we need to write a very simple line in our program , The code is explained below ,

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

Here ,

  • ‘ app.config ‘ is a dictionary-like object where you can set various configuration options for your Flask app.
  • ‘MAX_CONTENT_LENGTH’ is a specific configuration option that tells Flask to limit the size of incoming request data. If the request data exceeds this size, Flask will automatically raise a ‘ 413 Request Entity Too Large ‘ error.
  • ‘ 16 * 1024 * 1024 ‘ sets the maximum size to 16 megabytes. 1024 bytes make up a kilobyte (KB), and 1024 kilobytes make up a megabyte (MB). So, ‘ 16 * 1024 * 1024 ‘  bytes is equal to 16 MB.

Step 4 : Create an Upload Endpoint  

After setting up the maximum content length now we’ll create a specific URL (endpoint) where we can send files to be uploaded to our server. This is where the file handling logic happens.

To do that at first we will open the ‘ app.py ‘ file in our text editor and insert the following code that will ensure the new route that handles the file upload .

The description of the following code is  mentioned so that it will be easy to understand what is the work of every function that we are using to write the code .

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        abort(400, "No file part")
    file = request.files['file']
    if file.filename == '':
        abort(400, "No selected file")
    # Further file processing (like saving the file)
    return "File uploaded successfully"

Here,

  • ‘ @app.route(‘/upload’, methods=[‘POST’]) ‘ defines a new URL route ‘/upload’ that accepts ‘POST’ requests. ‘POST’ is used for sending data to the server (like uploading a file).
  • ‘ def upload_file() ‘ is the function that gets called when someone sends a ‘POST’ request to ‘/upload’
  • ‘ if ‘file’ not in request.files: ‘ checks if a file was included in the request. ‘ request.files ‘  is a dictionary-like object that contains uploaded files. If  ‘file’ is not in this dictionary, it means no file was uploaded.
  • ‘ abort(400, “No file part”) ‘ this line sends a response with status code ‘ 400 ‘ (Bad Request) and a message “No file part”, If no file was uploaded .
  • ‘ file = request.files[‘file’] ‘ retrieves the uploaded file from the request. ‘ request.files[‘file’] ‘ gets the file object associated with the key ‘file’ .
  • ‘ if file.filename == ”: ‘ checks if the file has a filename. If ‘ file.filename ‘ is an empty string, it means no file was selected.
  • ‘ abort(400, “No selected file”) ‘ this line sends a response with status code ‘ 400 ‘ and a message “No selected file” , If no file was selected.
  • ‘ return “File uploaded successfully” ‘ this line sends a success message back to the user , If everything is okay (i.e., a file was uploaded and selected) .

With these steps, we’ve set up an endpoint where users can upload files, and we’ve included basic error handling to manage common issues.

Step 5: Handle File Size Exceed Errors 

After setting up the end point , In this step, you’ll make sure your Flask app can handle situations where a user tries to upload a file that’s too large. When a file exceeds the size limit you set in Step 3, Flask automatically sends an error. You can customize how this error is shown.

To do that we will open our app.py file in our text editor that we had created , and we will insert the following code to handle the error when a file is too large. the code is explained below so that it will be easy for us to understand it ,

@app.errorhandler(413)
def request_entity_too_large(error):
    return "File is too large. Maximum file size is 16 MB.", 413

Here ,

  • ‘ @app.errorhandler(413) ‘ tells Flask to use a specific function to handle errors with the status code ‘ 413 ‘ . This status code means “Request Entity Too Large,” which happens when the uploaded file exceeds the maximum size limit.
  • def request_entity_too_large(error): ‘ is the function that Flask will call when the ‘ 413 ‘ error occurs.
  • ‘ return “File is too large. Maximum file size is 16 MB.”, 413 ‘ sends a response back to the user with a message saying the file is too large and includes the HTTP status code ‘ 413 ‘ .

This setup ensures that your application properly handles situations where users try to upload files that are too large, providing them with a clear error message.

Step 6: Test the Application 

After completion of the above steps now its the time to run our program for that , Run the Flask application by executing the following command in your terminal/Command prompt :

python app.py
Test File Upload : 

To test uploading a file, use the ‘ curl ‘  command .

curl -F "file=@path/to/your/file" http://127.0.0.1:5000/upload

Replace ‘ path/to/your/file ‘  with the actual path to a file you want to upload. You should see the server’s response in the command line. For successful uploads, you should see: “File uploaded successfully”. For files larger than 16 MB, you should get the error message: “File is too large. Maximum file size is 16 MB.”

Full Source Code : 

from flask import Flask, request, abort

app = Flask(__name__)

# Set the maximum file size to 16 megabytes
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB

@app.route('/')
def index():
    return 'Hello, World!'

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        abort(400, "No file part")
    file = request.files['file']
    if file.filename == '':
        abort(400, "No selected file")
    # Further file processing
    return "File uploaded successfully"

@app.errorhandler(413)
def request_entity_too_large(error):
    return "File is too large. Maximum file size is 16 MB.", 413

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

By following these steps, you’ll ensure that your Flask application is properly set up to handle file uploads and that it correctly enforces the file size limits.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top