Running the Development Server in Flask


Flask provides a built-in development server that is easy to set up and use. This server is ideal for testing and development purposes. In this article, we will guide you through the process of running the development server step by step, along with a real example.

Step 1: Install Flask

If Flask is not installed, install it using pip:

            pip install flask
        

This ensures that Flask and its dependencies are available for use.

Step 2: Create the Application File

Create a new Python file, for example, app.py, and add the following code:

            from flask import Flask

            app = Flask(__name__)

            @app.route("/")
            def home():
                return "Hello, Flask Development Server!"

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

Explanation of the code:

  • from flask import Flask: Imports the Flask framework.
  • app = Flask(__name__): Creates a new Flask application instance.
  • @app.route("/"): Defines a route for the home page.
  • app.run(debug=True): Starts the Flask development server with debugging enabled.

Step 3: Run the Development Server

To start the development server, navigate to the directory containing app.py and run the following command:

            python app.py
        

After running the command, you will see output similar to this:

            * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
            * Restarting with stat
            * Debugger is active!
            * Debugger PIN: 123-456-789
        

The Flask development server is now running, and you can access your application at http://127.0.0.1:5000/.

Step 4: Use Debug Mode

The debug=True parameter enables debug mode, which provides the following features:

  • Automatic reloading: The server reloads whenever you make changes to your code.
  • Interactive debugger: Displays detailed error messages and allows you to debug issues directly in the browser.

To see debug mode in action, intentionally create an error in your code and observe the detailed error page displayed in the browser.

Step 5: Stopping the Development Server

To stop the development server, press CTRL+C in the terminal where the server is running.

Step 6: Running on a Different Port

By default, Flask runs on port 5000. You can specify a different port using the port parameter:

            app.run(debug=True, port=8000)
        

After running this code, the application will be accessible at http://127.0.0.1:8000/.

Conclusion

Running the Flask development server is simple and convenient for testing and development purposes. By following these steps, you can quickly set up and use the development server to test your Flask applications.





Advertisement