Saturday, June 11, 2016

Python Flask Tutotials For Beginners Lesson 2 - Flask Hello World and Route Debug Change Port

Hello My dear friends in previous tutorial we have discuss how to setup all the requirements that we need to create video upload web api.so in this tutorial we are going to learn few things.

if images are not clear please click on image to zoom

  • Run Flask Hello world application
  •  
  • Add Debug mod to Flask application
  •  
  • Change Flask Route
  •  
  • Change Host and Port

 Run Flask Hello world application


first open pycharm and goto File and new project then select flask from the menu and give a name and folder to save file.
 

then it will automatically created the hello world program for you


then right click and select run.or you can use alt+shift+f10

then it will give massage it will run on 127.0.0.1:5000

this is run on local host port 5000


so lets type 127.0.0.1:5000 in web browser.

it give a result like this


so you get hello world in Flask.

ok now take a look at the code

from flask import Flask

app = Flask(__name__)



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


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

from flask import Flask

this means we get only Flask module from flask package.
otherwise we can import Flask it will import the all the modules inside the flask package.

app = Flask(__name__)
this means this python program run as flask app named app you can use app or application or whatever name you like

@app.route('/')
This is route this point the function to return value .this is root value that means

if you type 127.0.0.1:5000 this will return Hello World as return

def hello_world():
    return 'Hello World!' 
this is python function

you have to careful to maintain intendant otherwise it will not execute.maintain the suitable spaces.

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

this means run the main function

Add Debug mod to Flask

when you add debug mod you can run application continuously when the code is changed. 

app.debug=True



Change Host and Port in Python Flask

you can change change host and port in a Flask app using 
host='your IP or host name',port=port number
if __name__ == '__main__':
    app.run(host='127.10.20.30',port=8080) 


Change Route in Flask


route is the pointing point to the python flask function.when you route it will point the relevant function and it will return the output of the function.

@app.route('/')

now we create new function called sayhi().to print hello sameera 

@app.route('/sayhi')
def say_hi():
    return 'welcome sameera ! :) '


 so we are going through the 127.10.20.30:5000/sayhi

this will give the output welcome sameera ! :) in web browser



Hope you enjoy tutorial.see you in next lesson

if you like this tutorial please share in facebook,google+ twitter .If you have any question please leave a comment




No comments:

Post a Comment