How to use Flask In python

Flask Example #01 Hello World!

Default Settings

Create folders and python file.

Typically, the template folder contains html files. and the static folder contains a css file.

FLASKINTRO     # Create FLASKINTRO Folder
│  app.py      # Create app.py
│
├─static       # Create static Folder
└─templates    # Create templates Folder

Write the following in the app.py.


from flask import Flask     # flask module import

app = Flask(__name__)

@app.route('/')             # 127.0.0.1:5000
def index():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()               # server start

Run

>python app.py

Result

image

Flask Example #02 HTTP methods

Add login.html

Flask provides render_template to render html. It can dynamically generate web pages by inserting code into html documents. Jinja.

FLASKINTRO
│  app.py
│
├─static
└─templates
        login.html  # Add login.html

The contents of the login.html file

<html>
   <body>
      <form action = "http://localhost:5000/auth" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "nm" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/login/')
def login():
    return render_template('login.html')

@app.route('/success/<name>')
def success(name):
    return 'welcome %s' % name

@app.route('/auth', methods=['POST', 'GET'])
def auth():
    if request.method == 'POST':
        user = request.form['nm']
        return redirect(url_for('success', name=user))        
    else:
        user = request.args.get('nm')
        return redirect(url_for('success', name=user+' by Get'))


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

Run and Result

image

image

Use set_cookie('cookie Name',value) method. If you want to get the cookie value, you can use request.cookies.get('value').


from flask import Flask, make_response, render_template
app = Flask(__name__)

@app.route('/cookie')
def cookie():
    res = make_response("<h1>cookie is set</h1>")
    res.set_cookie('foo', 'bar')
    return res


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

Run and Result

image

Session

Set : session[‘name’] = value

Get : session[‘name’]


from flask import *

app = Flask(__name__)

app.secret_key = "abc"

@app.route('/')
def home():
    res = make_response(
        "<h4>session variable is set, <a href='/get'>Get Variable</a></h4>")
    session['response'] = 'session#1'           # set Session
    return res

@app.route('/get')
def getVariable():
    if 'response' in session:
        s = session['response']
        return render_template('getsession.html', name=s)

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

Run and Result

image