flask
  1. flask-first-flaskapplication

First Flask Application - Basics of Flask

Syntax

from flask import Flask

app = Flask(__name__)

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

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

Example

Let's create a basic Flask application that returns "Hello, World!" when the user visits the homepage:

from flask import Flask

app = Flask(__name__)

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

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

Output

When you run this application and visit the homepage in your browser, you should see "Hello, World!" displayed on the page.

Explanation

First, we import the Flask class from the flask module. Then, we create an instance of the Flask class and assign it to the variable "app". We also pass in __name__ as an argument, which is a special Python variable that represents the name of the current module.

Next, we define a route for the homepage using the @app.route decorator. This decorator binds a URL rule to our view function, which is defined immediately below it. Here, our view function is named home(), and it simply returns the string "Hello, World!".

Finally, we start the Flask application by calling app.run(), but only if the current file is being run as the main program (i.e., not imported as a module into another program).

Use

Flask is a popular web framework for building web applications in Python. This example demonstrates the most basic functionality of Flask - defining a route and returning a response to the client. You can use this as a starting point for building more complex web applications with Flask.

Important Points

  • Flask is a micro web framework written in Python
  • Flask is used for building web applications
  • Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine
  • Flask was developed by Armin Ronacher in 2010

Summary

In this example, we created a basic Flask application that returns "Hello, World!" when the user visits the homepage. We explained the syntax, gave an example, discussed the output, and provided an explanation of each component of the code. We also discussed the use of Flask, important points to keep in mind, and provided a summary of the example.

Published on: