YouTip LogoYouTip

Flask Step1

First Flask Application

\n

In the previous chapter, we successfully installed Flask. Next, we can create a simple Flask application.

\n

First, create a file named app.py and add the following content:

\n\n

Example (app.py)

\n
from flask import Flask\n\napp = Flask( __name__ )\n\n@app.route('/')\n\ndef hello_world():\n\nreturn'Hello, World!'\n\nif __name__ =='__main__':\n\n app.run(debug=True)
\n\n

Run the Flask application in the command line:

\n
python app.py
\n

You will see the Flask development server start up, displaying something similar to the following:

\n
... * Running on http://127.0.0.1:5000Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 977-918-914...
\n

Open your browser and visit http://127.0.0.1:5000/. You should see the message "Hello, World!", indicating that Flask has been successfully installed and is running.

\n\nImage 1\n\n

Never name your file flask.py, as this will conflict with the Flask library itself and cause import errors.

\n\n

Code Explanation:

\n
    \n
  • from flask import Flask: This line imports the Flask class from the flask module. The Flask class is the core of the Flask framework, used to create Flask application instances.
  • \n
  • app = Flask(__name__): This line creates a Flask application instance. __name__ is a special Python variable that is '__main__' when the module is run directly, and the module's name when imported by another module. Passing __name__ to the Flask constructor allows the Flask application to locate and load configuration files.
  • \n
  • @app.route('/'): This is a decorator used to tell Flask which URL should trigger the function below. In this example, it specifies the root URL (i.e., the homepage of the website).
  • \n
  • def hello_world():: This defines a function named hello_world, which will be called when a user visits the root URL.
  • \n
  • return 'Hello, World!': This line is the return value of the hello_world function. When a user visits the root URL, this string will be sent back to their browser.
  • \n
  • if __name__ == '__main__':: This line is a conditional check to determine whether the module is being run directly rather than imported by another module. If run directly, the code block below will be executed.
  • \n
  • app.run(debug=True): This line calls the run method of the Flask application instance to start Flask's built-in development server. The debug=True parameter enables debug mode, meaning the application will automatically reload when code changes and provide a debugger when errors occur.
  • \n
\n\n

If you have installed python-dotenv, you can create a .flaskenv file in the project directory to simplify commands:

\n
# File path:.flaskenv FLASK_APP=app FLASK_DEBUG=True
\nImage 2\n\n

After configuration, you can simply run flask run without specifying the --app parameter each time:

\n
(.venv) $ flask run * Serving Flask app 'app' * Debug mode: on * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
\n

If you name your file app.py or wsgi.py, Flask can automatically detect it, allowing you to omit even the --app flag. However, explicitly specifying it is considered a good practice.

\n\n
\n\n

Debug Mode

\n

It is recommended to enable Debug mode during development, as it provides two important features:

\n
    \n
  • Automatic reloading: After modifying and saving code, the server automatically restarts without manual intervention.
  • \n
  • Interactive debugger: When code errors occur, detailed error messages and stack traces are displayed in the browser.
  • \n
\n

To enable it:

\n
(.venv) $ flask --app app run --debug * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 123-456-789
\n

Security Warning: The interactive debugger in Debug mode allows executing arbitrary Python code in the browser. Although it is protected by a PIN, never enable Debug mode in a production environment.

\n\n
\n\n

Comparison of Execution Methods

\n

Besides the flask run command, you may also see another way to run the application:

\n\n

Example

\n
# Not recommended: calling app in the code.run()\n\nif __name__ =="__main__":\n\n app.run(debug=True)
\n

Then run it using python app.py.

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Execution MethodAdvantagesDisadvantages
flask runSupports command-line arguments (--host, --port, --debug); flexible configuration; automatically loads .flaskenvRequires remembering command arguments
python app.pySimple and intuitiveInflexible; requires changing code to enable debug mode; not recommended by Flask officially
\n\n

The Flask official documentation recommends using the flask run command. If you write app.run() in your code and also use flask run, Flask will intelligently ignore the app.run() call and display a yellow warning message.

\n\n
\n\n

Adding More Content to Responses

\n

View functions can not only return simple strings but also HTML content:

\n\n

Example

\n
# File path:app.py\n\nfrom flask import Flask\n\napp = Flask( __name__ )\n\n@app.route("/")\n\ndef index():\n\n# Return multiple lines of HTML, Flask will automatically set Content-Type-Type for text/html\nreturn"""\n\n

Welcome to Flask tutorial

\n\n

This is a Web application built with Flask.

\n\n
    \n\n
  • Learn routing system
  • \n\n
  • Learn template rendering
  • \n\n
  • Learn database operations
  • \n\n
\n\n """
\n

Visit http://127.0.0.1:5000/, and the output will be as follows:

\n\nImage 3\n\n

Of course, writing HTML directly in Python code quickly becomes hard to maintain. Subsequent chapters will introduce how to use templates to separate HTML and Python code.

← Flask LayoutFlask Tutorial β†’