Python Create a Flask or Django Application

Document 对象参考手册Python3 Example

We will create a simple Flask application. This application will have a homepage, and when users visit the homepage, it will display "Hello, World!".

Example

from flask import Flask

app = Flask(__name__)

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

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

Code analysis:

  1. from flask import Flask: Import the Flask class, which is the core class of the Flask framework.
  2. app = Flask(__name__): Create a Flask application instance.__name__The parameter is used to determine the root directory of the application.
  3. @app.route('/'): Define a route. When users access the root URL (i.e., the homepage), the following will be calledhomefunction.
  4. def home():: Define a view function. When the route is accessed, this function will be executed.
  5. return "Hello, World!": The view function returns a string "Hello, World!", which will be displayed in the user's browser.
  6. if __name__ == '__main__':: Ensure that the Flask development server is started only when this script is run directly.
  7. app.run(debug=True): Start the Flask development server,debug=Trueindicates enabling debug mode, so the server will automatically restart when code changes.

When you run this script and visithttp://127.0.0.1:5000/, you will see "Hello, World!" in your browser.

Document 对象参考手册Python3 Example

Other extensions