“Hello World !” using python flask framework

In this article we will create a simplest application using pything flask. This will display nothing but simple ” hello world on the page.

Here is the code

from flask import Flask
app = Flask(__name__)

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

This is cleanest code for any framework that I have seen.

Now go to terminal and type following commands

conquistador@inspiron-3542:~/code/flask/tutorial$ export FLASK_APP=hello_world.py
conquistador@inspiron-3542:~/code/flask/tutorial$ flask run
* Serving Flask app "hello_world.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 189-606-216

Now go to http://127.0.0.1:5000/ and  you will see following page

Flask Hello world
Flask Hello world

Adding few more pages.

Let us add aboutus and contact us pages. To add routing, you simple need to add 3 line to the same file. You need to add @app.route(‘/contactus’)

Here is updated hello world file

from flask import Flask
app = Flask(__name__)

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

@app.route('/aboutus')
def aboutus():
   return 'This is about us page'

@app.route('/contactus')
def contactus():
   return 'This is contact us page'

Now you can access about us page at http://127.0.0.1:5000/aboutus and contact us page at  http://127.0.0.1:5000/contactus

Flask About us page
Flask About us page

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.