Hello World

Python + Flask

Talha Hanif Butt
2 min readSep 24, 2020

I was thinking of doing something with the web so decided to start from scratch and tried a hello world program using Flask.

Basically, a single file is required named as app.py to perform the task which is as follows:

# app.pyfrom flask import Flask           # import flask
app = Flask(__name__) # create an app instance

@app.route("/") # at the end point /
def hello(): # call method hello
return "Hello World!" # which returns "hello world"
if __name__ == "__main__": # on running python app.py
app.run() # run the flask app

To run the application, use the following command on terminal:

python app.py
Output after running the app

On hitting the URL from your browser you will see the following:

Output on the browser

Adding name with Hello World

@app.route("/Talha")              # at the end point /<name>
def hello_name(): # call method hello_name
return "Hello World! I am Talha"

Let’s hit http://localhost:5000/Talha. we will get a 404 error.

This is because we are running the server in a production mode. For development purposes, we use something called as debug mode. When debug=Trueis set the server restarts as we add new code to our Flask Application. In order to set the debug mode do the following

  1. Modify the line app.run() to app.run(debug=True).
  2. Stop the running server and restart it again.

You will see “debugger is active” which means that the debug mode has taken effect. Now you can go on and edit your file as much as you want, and the server will be restarted.

After running in development mode

Let’s hit http://localhost:5000/Talha. we will get the following:

Output on the browser after code modification

Code can be accessed using this repository.

References

--

--

Talha Hanif Butt

PhD Student -- Signal and Systems Engineering, Halmstad University, Volvo Trucks http://pk.linkedin.com/in/talhahanifbutt