Skip to content

Flask in python

wilsonshamim edited this page Jun 21, 2018 · 10 revisions

First application:

from flask import Flask // this is to import flask
app = Flask(name)

@app.route(‘/’) // this is to route the pages.
def index():
return ’Hello index’

@app.route(‘/hello’)
def hello_world():
return ’Hello World’

if name == ‘main’:
app.run()

when you enter http://localhost:5000/hello it will get the value from hello_world function
if you enter http://localhost:5000/ it will return value from index function.

by default application runs on port 5000 and host as localhost. we can change the host, port using
app.run(host, port, debug, options)

we can also enable the debug mode using
app.debug = True
app.run()
app.run(debug = True)


app Routing:
we can also route the app to a method using add_url_rule.

app.add_url_rule(‘/’, ‘hello’, hello_world)

so when you get hello, it will process hello_world method and return the value.


It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as . It is passed as a keyword argument to the function with which the rule is associated.

In the following example, the rule parameter of route() decorator contains variable part attached to URL ‘/hello’. Hence, if the http://localhost:5000/hello/TutorialsPoint is entered as a URL in the browser, ‘TutorialPoint’ will be supplied to hello() function as argument.

from flask import Flask
app = Flask(name)

@app.route(‘/hello/<>’)
def hello_name(name):
return ‘Hello %s!’ % name

if name == ‘main’:
app.run(debug = True)

http://localhost:5000/test/myname


url_for()
The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL.

The following script demonstrates use of url_for() function.

from flask import Flask, redirect, url_for
app = Flask(name)

@app.route(‘/admin’)
def hello_admin():
return ‘Hello Admin’

@app.route(‘/guest/<<>>’)
def hello_guest(guest):
return ‘Hello %s as Guest’ % guest

@app.route(‘/user/<<>>’)
def hello_user(name):
if name ==‘admin’:
return redirect(url_for(‘hello_admin’))
else:
return redirect(url_for(‘hello_guest’,guest = name))

if name == ‘main’:
app.run(debug = True)


HTTP Method:
By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator.

  • GET
  • Head,
  • POST
  • PUT
  • DELETE

from flask import Flask, redirect, url_for, request
app = Flask(name)

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

@app.route(‘/login’,methods = [‘POST’, ‘GET’])
def login():
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))

if name == ‘main’:
app.run(debug = True)


Template:
we can create a html page and place it under templates. we can call that html page using render_template
The following code is saved as hello.html in the templates folder.

“<!doctype html>

Hello {{ name }}!

“Next, run the following script from Python shell.

from flask import Flask, render_template
app = Flask(name)

@app.route(‘/hello/<>’)
def hello_name(user):
return render_template(‘hello.html’, name = user)

if name == ‘main’:
app.run(debug = True)

The Jinga2 template engine uses the following delimiters for escaping from HTML.

{% … %} for Statements
{{ … }} for Expressions to print to the template output
{# … #} for Comments not included in the template output

  1. … ## for Line Statements

A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application.

A special endpoint ‘static’ is used to generate URL for static files.

In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.

from flask import Flask, render_template
app = Flask(name)

@app.route(“/”)
def index():
return render_template(“index.html”)

if name == ‘main’:
app.run(debug = True)

in the html page :


<script type = “text/javascript”
src = “{{ url_for(‘static’, filename = ‘hello.js’) }}” >

hello.js contains sayHello() function.

function sayHello() {
alert(“Hello World”)
}


to get the form data.
1. to get all the form data :
result = request.form

then we need to iterate
for key in result.items():
print(key)
print(value)

2. to get individual items:

fname = request.form[‘fname’]

Clone this wiki locally