Flask Web Framework – Your First Hello World App

Published by BrighterBees on

Flask-hello-world-app

In the previous blog, we have discussed Flask introduction, virtual environment and Flask installation. In this blog, we will create our First Hello World App in Flask.

In order to test Flask installation, type following code in the editor as app.py

from flask import Flask
app = Flask(__name__)

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

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

Importing flask module in the project is mandatory. An object of Flask class is our WSGI application.

Flask constructor takes the name of current module (__name__) as an argument.

The route() function of the function class is a decorator, which tells the application which URL should call the associated function.

app.route(rule, options)
  • The rule parameter represents URL binding with the function
  • The options is a list of parameters to be forwarded to the underlaying Rule object.

In the above ‘/’ URL is bound with the home() function. Hence, when the home page of web server opened in the browser, the output of this function will be rendered.

Finally the run() method of Flask class runs the application on the local development server.

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

All parameters are optional.

  • Host : Hostname is listened on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have a server available externally.
  • Port : Defaults to 5000
  • Debug : Defaults to false. It set to true, proc=vides a debug information.
  • Options : To be forwarded to underlaying Werkzeug server.

The above given Python script executed from Python shell or CMD.

Python app.py

A message in Python shell or CMD informs you that

* Running on http://127.0.0.1:5000/

Open the above URL in the browser. ‘Hello World’ message will be displayed on it.

Debug Mode

A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid the inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.

The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.

# Method 1
app.debug = True
app.run()

#Method 2
app.run(debug = True)

Now we have successfully created our First application in Flask. In the next blog we will discuss more Flask routing. If you have any doubt then you can comment below.

Connect with the author on LinkedIn.

If want to know about Web Scraping click here.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY CONNECT WITH US