Menu Close

First Flask Application

Welcome to the Python flask tutorial. In this guide, you will learn how to create the first flask application. In the previous tutorial, we have seen how to setup a flask environment step by step.

Note:- Before going through this Python flask tutorial, You should have basic knowledge of Python programming. You can follow our Python tutorial.

Create First Flask Application

Here we will create first flask application. You can use any text editor according to your choice and start writing Python flask code.

Create a Python file with any name, In my case file name is main.py. Write the following code inside the python file.

main.py


from flask import Flask

#Create the object of the Flask class.
app= Flask(__name__)

#Define route 
@app.route("/")
def Home():
    return "This is my first flask website"

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

Run above code using command line by following command and see the result.

python main.py 

Code Explanation

Let’s understand above code step by step.

  1. Import Flask class from flask module
  2. Create the object of the Flask class.
  3. Define the route of the web application. Slash ( / ) represent the the base URL. route() function of the Flask class is used to define the URL for the associate function.
  4. __name__ is a built-in Python variable that equal to “__main__” if you execute your Python script file.
  5. run() method of the Flask class is used to execute Python flask application and local development server.
  6. app.run(host, port, debug=True, options)

app.run(host, port, debug=True, options)

  • host:- host represents the hostname, Default is localhost (127.0.0.1).
  • post:- post represent which server is listing too, Default is 5000.
  • debug:- The default is False, It provides debug information when it is true.
  • options:- It contains the information to be forwarded server.

Conclusion

In this article, you have learned how to create the first flask application step by step. To build a flask application, you will need to set up a flask environment. You can check out our previous flask tutorial for setup flask environment.

Please share and keep supporting, If you like this python flask tutorial.

Setup Flask Environment

Related Posts