First Flask Application
\nIn the previous chapter, we successfully installed Flask. Next, we can create a simple Flask application.
\nFirst, create a file named app.py and add the following content:
Example (app.py)
\nfrom 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\nRun the Flask application in the command line:
\npython app.py\nYou 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...\nOpen 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\n\n\nNever name your file
flask.py, as this will conflict with the Flask library itself and cause import errors.
Code Explanation:
\n- \n
from flask import Flask: This line imports theFlaskclass from theflaskmodule. TheFlaskclass 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 theFlaskconstructor 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 namedhello_world, which will be called when a user visits the root URL. \n return 'Hello, World!': This line is the return value of thehello_worldfunction. 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 therunmethod of the Flask application instance to start Flask's built-in development server. Thedebug=Trueparameter enables debug mode, meaning the application will automatically reload when code changes and provide a debugger when errors occur. \n
If you have installed python-dotenv, you can create a .flaskenv file in the project directory to simplify commands:
# File path:.flaskenv FLASK_APP=app FLASK_DEBUG=True\nAfter configuration, you can simply run flask run without specifying the --app parameter each time:
(.venv) $ flask run * Serving Flask app 'app' * Debug mode: on * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)\n\n\nIf you name your file
app.pyorwsgi.py, Flask can automatically detect it, allowing you to omit even the--appflag. However, explicitly specifying it is considered a good practice.
\n\n
Debug Mode
\nIt 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
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\n\nSecurity 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
Comparison of Execution Methods
\nBesides the flask run command, you may also see another way to run the application:
Example
\n# Not recommended: calling app in the code.run()\n\nif __name__ =="__main__":\n\n app.run(debug=True)\nThen run it using python app.py.
| Execution Method | \nAdvantages | \nDisadvantages | \n
|---|---|---|
| flask run | \nSupports command-line arguments (--host, --port, --debug); flexible configuration; automatically loads .flaskenv | \nRequires remembering command arguments | \n
| python app.py | \nSimple and intuitive | \nInflexible; requires changing code to enable debug mode; not recommended by Flask officially | \n
\n\nThe Flask official documentation recommends using the
flask runcommand. If you writeapp.run()in your code and also useflask run, Flask will intelligently ignore theapp.run()call and display a yellow warning message.
\n\n
Adding More Content to Responses
\nView functions can not only return simple strings but also HTML content:
\n\nExample
\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\nWelcome to Flask tutorial
\n\nThis 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 """\nVisit http://127.0.0.1:5000/, and the output will be as follows:
\n\nOf 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.
YouTip