SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Python Certification Training https://www.edureka.co/python
Agenda
Python Certification Training https://www.edureka.co/python
Agenda
Python Certification Training https://www.edureka.co/python
Agenda
Introduction 01
Introduction
to Flask
Getting Started 02
Concepts 03
Practical Approach 04
Installing and working
with Flask
Looking at code to
understand theory
Overview of all the
concepts in Flask
Python Certification Training https://www.edureka.co/python
Introduction to Flask
Python Certification Training https://www.edureka.co/python
Introduction to Flask
Open Source
Flask is a web application framework written in Python.What is Flask?
Large community for
Learners and Collaborators
Let’s get started then!
Python Certification Training https://www.edureka.co/python
Introduction to Flask
What is a Web Framework?
Life without Flask! Using Flask!
ModulesLibraries
Web Developer
Python Certification Training https://www.edureka.co/python
Introduction to Flask
Flask!!
Enthusiasts named Pocco!
Werkzeug WSGI Toolkit Jinga2 Template Engine
I’m learning Flask!
Python Certification Training https://www.edureka.co/python
Installing Flask
Python Certification Training https://www.edureka.co/python
Installation - Prerequisite
Prerequisite
I’m learning Flask!
virtualenv Virtual Python Environment builder
pip install virtualenv
Sudo apt-get install virtualenv
Python Certification Training https://www.edureka.co/python
Installation - Flask
Installation
I’m learning Flask!
Once installed, new virtual environment is created in a folder
mkdir newproj
cd newproj
virtualenv venv
To activate corresponding environment, use the following:
venvscriptsactivate
pip install Flask
Python Certification Training https://www.edureka.co/python
Flask - Application
Python Certification Training https://www.edureka.co/python
Flask - Application
Test Installation
I’m learning Flask!
Use this simple code, save it as Hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World’
if __name__ == '__main__':
app.run()
Python Certification Training https://www.edureka.co/python
Flask - Application
Importing flask module in the project is mandatory!
I’m learning Flask!
Flask constructor takes name of current module (__name__) as argument
App.route(rule, options)
route() function
URL binding with the function
List of parameters to be forwarded to the underlying Rule object
Python Certification Training https://www.edureka.co/python
Flask - Application
App.run(host, port, options
Sl.no Parameter Description
1 host
Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to
‘0.0.0.0’ to have server available externally
2 port Defaults to 5000
3 debug Defaults to false. If set to true, provides a debug information
3 options To be forwarded to underlying Werkzeug server.
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
All these parameters are optional
Python hello.py
Python Certification Training https://www.edureka.co/python
Flask – Application
Python Certification Training https://www.edureka.co/python
Flask - Application
Debug mode
Flask application is
started by calling
run() method
How to enable Debug mode?
app.debug = True
app.run()
app.run(debug = True)
Python Certification Training https://www.edureka.co/python
Flask – Routing
Python Certification Training https://www.edureka.co/python
Flask - Routing
Route() decorator in Flask is used to bind URL to a function
@app.route(‘/hello’)
def hello_world():
return ‘hello world’
add_url_rule() function is also used to bind URL with function
Check out the following representation
def hello_world():
return ‘hello world’
app.add_url_rule(‘/’, ‘hello’, hello_world)
Python Certification Training https://www.edureka.co/python
Flask –Variable Rules
Python Certification Training https://www.edureka.co/python
Flask – Variable Rules
It is possible to build a URL dynamically!
How? By adding variable parts to the rule parameter
Consider the example
from flask import Flask
app = Flask(__name__)
@app.route('/hello/<name>')
def hello_name(name):
return 'Hello %s!' % name
if __name__ == '__main__':
app.run(debug = True)
http://localhost:5000/hello/Edureka
Python Certification Training https://www.edureka.co/python
Flask – Variable Rules
More rules can be constructed using these converters
Sl.no Parameter Description
1 int Accepts Integer
2 Float For Floating point value
3 Path
Accepts slashes used as
directory separator character
from flask import Flask
app = Flask(__name__)
@app.route('/blog/<int:postID>')
def show_blog(postID):
return 'Blog Number %d' % postID
@app.route('/rev/<float:revNo>')
def revision(revNo):
return 'Revision Number %f' % revNo
if __name__ == '__main__':
app.run()
Run the code
Visit the URL: http://localhost:5000/blog/11
Blog number 11Browser Output
http://localhost:5000/rev/1.1 Revision Number 1.100000
Python Certification Training https://www.edureka.co/python
Flask – Variable Rules
Consider the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/flask')
def hello_flask():
return 'Hello Flask'
@app.route('/python/')
def hello_python():
return 'Hello Python'
if __name__ == '__main__':
app.run()
Run the code
/flask /flask/
/python /python/
Python Certification Training https://www.edureka.co/python
Flask – URL Binding
Python Certification Training https://www.edureka.co/python
Flask – URL Building
url_for() function is used for dynamically building a URL for a specific function
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/admin')
def hello_admin():
return 'Hello Admin'
@app.route('/guest/<guest>')
def hello_guest(guest):
return 'Hello %s as Guest' % guest
@app.route('/user/<name>')
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://localhost:5000/user/admin
Python Certification Training https://www.edureka.co/python
Flask – HTTP Methods
Python Certification Training https://www.edureka.co/python
Flask – HTTP Methods
HTTP Protocols are the foundation for data communication in WWW
Sl.no Method Description
1 GET Sends data in unencrypted form to server
2 HEAD Same as GET, but without response body
3 POST Used to send HTML form data to server.
4 PUT
Replaces all current representations of target resource with
uploaded content
5 DELETE
Removes all current representations of target resource given by
URL
Let’s look at an example
Python Certification Training https://www.edureka.co/python
Flask – HTTP Methods
First we look at the HTML file
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
Save this as login.html
Python Certification Training https://www.edureka.co/python
Flask – HTTP Methods
Next is Python Script
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
@app.route('/success/<name>')
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)
Let’s check out the output!
Python Certification Training https://www.edureka.co/python
Flask – Templates
Python Certification Training https://www.edureka.co/python
Flask – Templates
Can we return the output of a function bound to a UR: in form of HTML?
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<html><body><h1>'Hello
World'</h1></body></html>'
if __name__ == '__main__':
app.run(debug = True)
But this is cumbersome
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<html><body><h1>'Hello
World'</h1></body></html>'
if __name__ == '__main__':
app.run(debug = True)
Flask will try to find the HTML
file in the templates folder, in
the same folder in which this
script is present.
Python Certification Training https://www.edureka.co/python
Flask – Templates
Flask uses jinga2 template engine
<!doctype html>
<html>
<body>
<h1>Hello {{ name }}!</h1>
</body>
</html>
Flask will try to find the HTML
file in the templates folder, in
the same folder in which this
script is present.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<user>')
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
• # ... ## for Line Statements
Python Certification Training https://www.edureka.co/python
Flask – Templates
Conditional statements in templates
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<int:score>')
def hello_name(score):
return render_template('hello.html', marks = score)
if __name__ == '__main__':
app.run(debug = True)
<!doctype html>
<html>
<body>
{% if marks>50 %}
<h1> Your result is pass!</h1>
{% else %}
<h1>Your result is fail</h1>
{% endif %}
</body>
</html>
HTML Template script
Python Certification Training https://www.edureka.co/python
Flask – Templates
Another example
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/result')
def result():
dict = {'phy':50,'che':60,'maths':70}
return render_template('result.html', result = dict)
if __name__ == '__main__':
app.run(debug = True)
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.iteritems() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
Python Certification Training https://www.edureka.co/python
Flask – Static Files
Python Certification Training https://www.edureka.co/python
Flask – Static Files
Web application will require a static file such as JS or CSS file
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/result')
def result():
dict = {'phy':50,'che':60,'maths':70}
return render_template('result.html', result = dict)
if __name__ == '__main__':
app.run(debug = True)
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.iteritems() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
Python
function sayHello() {
alert("Hello World")
}
JS File
HTML
Python Certification Training https://www.edureka.co/python
Flask – Request Object
Python Certification Training https://www.edureka.co/python
Flask – Request Object
Data from client’s webpage is sent to server as a global request object
Form Dictionary object containing key-value pairs of form parameters and values
args Parsed contents of query string which is part of URL after question mark (?)
Cookies Dictionary object holding Cookie names and values
files Data pertaining to uploaded file
Method Current request method
Python Certification Training https://www.edureka.co/python
Flask – Cookies
Python Certification Training https://www.edureka.co/python
Flask – Cookies
Cookie is stored on client’s machine. And helps with data tracking
@app.route('/')
def index():
return render_template('index.html')
<html>
<body>
<form action = "/setcookie" method = "POST">
<p><h3>Enter userID</h3></p>
<p><input type = 'text' name = 'nm'/></p>
<p><input type = 'submit' value = 'Login'/></p>
</form>
</body>
</html>
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']
resp = make_response(render_template('readcookie.html'))
resp.set_cookie('userID', user)
return resp
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome '+name+'</h1>'
Python Certification Training https://www.edureka.co/python
Flask – Redirect & Errors
Python Certification Training https://www.edureka.co/python
Flask – Redirect & Errors
Flask Class has a redirect() function which returns a response object
Prototype Flask.redirect(location, statuscode, response)
URL where response should be redirected
Statuscode sent to browser’s header
Response parameter used to instantiate response
Python Certification Training https://www.edureka.co/python
Flask – Redirect & Errors
Standardized status codes
Sl.no Status Code
1 HTTP_300_MULTIPLE_CHOICES
2 HTTP_301_MOVED_PERMANENTLY
3 HTTP_302_FOUND
4 HTTP_303_SEE_OTHER
5 HTTP_304_NOT_MODIFIED
6 HTTP_305_USE_PROXY
7 HTTP_306_RESERVED
Sl.no Code Description
1 400 Bad Request
2 401 Unauthenticated
3 403 Forbidden
4 404 Not Found
5 406 Not Acceptable
6 415 Unsupported Media Type
7 429 Too Many Requests
Prototype Flask.abort(code)
Python Certification Training https://www.edureka.co/python
Flask – Extensions
Python Certification Training https://www.edureka.co/python
Flask – Extensions
Flask is a micro framework
Large number of extensions
Flask Mail Flask WTF Flask SQLAlchemy Flask Sijax
Provides SMTP
interface to
Flask
application
Adds rendering
& validation of
WTForms
Adds
SQLAlchemy
support to Flask
Application
Interface for
Sijax –
Python/jQuery
library that
makes AJAX
easy to use
Extensive Documentation
Python Certification Training https://www.edureka.co/python
Conclusion
Python Certification Training https://www.edureka.co/python
Conclusion
Python Flask Training: Introduction to Flask Framework

Weitere ähnliche Inhalte

Was ist angesagt?

A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC FrameworkBala Kumar
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django frameworkKnoldus Inc.
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To DjangoJay Graves
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Edureka!
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 

Was ist angesagt? (20)

A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...
 
PHP
PHPPHP
PHP
 
Jquery
JqueryJquery
Jquery
 
CSS notes
CSS notesCSS notes
CSS notes
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Css3
Css3Css3
Css3
 
Django
DjangoDjango
Django
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
PHP Presentation
PHP PresentationPHP Presentation
PHP Presentation
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
HTML5 & CSS3
HTML5 & CSS3 HTML5 & CSS3
HTML5 & CSS3
 
Html JavaScript and CSS
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSS
 

Ähnlich wie Python Flask Training: Introduction to Flask Framework

Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Lar21
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90minsLarry Cai
 
Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Binh Nguyen
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restxammaraslam18
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 Joe Ferguson
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestJoshua Warren
 
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...Akira Tsuruda
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsPyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsDylan Jay
 
Zen and the Art of Claroline Module Development
Zen and the Art of Claroline Module DevelopmentZen and the Art of Claroline Module Development
Zen and the Art of Claroline Module DevelopmentClaroline
 
What The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsWhat The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsBruno Rocha
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfonyFrancois Zaninotto
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Ondřej Machulda
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanizecoreygoldberg
 

Ähnlich wie Python Flask Training: Introduction to Flask Framework (20)

Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restx
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5
 
Pyramid deployment
Pyramid deploymentPyramid deployment
Pyramid deployment
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
 
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Phalcon 2 - PHP Brazil Conference
Phalcon 2 - PHP Brazil ConferencePhalcon 2 - PHP Brazil Conference
Phalcon 2 - PHP Brazil Conference
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsPyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web apps
 
Zen and the Art of Claroline Module Development
Zen and the Art of Claroline Module DevelopmentZen and the Art of Claroline Module Development
Zen and the Art of Claroline Module Development
 
Phalcon - Giant Killer
Phalcon - Giant KillerPhalcon - Giant Killer
Phalcon - Giant Killer
 
What The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsWhat The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIs
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
 

Mehr von Edureka!

What to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaWhat to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaEdureka!
 
Top 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaTop 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaEdureka!
 
Top 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaTop 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaEdureka!
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaEdureka!
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaEdureka!
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaEdureka!
 
Top Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaTop Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaEdureka!
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaEdureka!
 
How to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaHow to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaEdureka!
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaEdureka!
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | EdurekaEdureka!
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEdureka!
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEdureka!
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaEdureka!
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaEdureka!
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaEdureka!
 
Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Edureka!
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaA star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaEdureka!
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaEdureka!
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | EdurekaEdureka!
 

Mehr von Edureka! (20)

What to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | EdurekaWhat to learn during the 21 days Lockdown | Edureka
What to learn during the 21 days Lockdown | Edureka
 
Top 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaTop 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | Edureka
 
Top 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | EdurekaTop 5 Trending Business Intelligence Tools | Edureka
Top 5 Trending Business Intelligence Tools | Edureka
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
 
Top 5 PMP Certifications | Edureka
Top 5 PMP Certifications | EdurekaTop 5 PMP Certifications | Edureka
Top 5 PMP Certifications | Edureka
 
Top Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | EdurekaTop Maven Interview Questions in 2020 | Edureka
Top Maven Interview Questions in 2020 | Edureka
 
Linux Mint Tutorial | Edureka
Linux Mint Tutorial | EdurekaLinux Mint Tutorial | Edureka
Linux Mint Tutorial | Edureka
 
How to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| EdurekaHow to Deploy Java Web App in AWS| Edureka
How to Deploy Java Web App in AWS| Edureka
 
Importance of Digital Marketing | Edureka
Importance of Digital Marketing | EdurekaImportance of Digital Marketing | Edureka
Importance of Digital Marketing | Edureka
 
RPA in 2020 | Edureka
RPA in 2020 | EdurekaRPA in 2020 | Edureka
RPA in 2020 | Edureka
 
Email Notifications in Jenkins | Edureka
Email Notifications in Jenkins | EdurekaEmail Notifications in Jenkins | Edureka
Email Notifications in Jenkins | Edureka
 
EA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | EdurekaEA Algorithm in Machine Learning | Edureka
EA Algorithm in Machine Learning | Edureka
 
Cognitive AI Tutorial | Edureka
Cognitive AI Tutorial | EdurekaCognitive AI Tutorial | Edureka
Cognitive AI Tutorial | Edureka
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
 
Blue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | EdurekaBlue Prism Top Interview Questions | Edureka
Blue Prism Top Interview Questions | Edureka
 
Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka Big Data on AWS Tutorial | Edureka
Big Data on AWS Tutorial | Edureka
 
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | EdurekaA star algorithm | A* Algorithm in Artificial Intelligence | Edureka
A star algorithm | A* Algorithm in Artificial Intelligence | Edureka
 
Kubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | EdurekaKubernetes Installation on Ubuntu | Edureka
Kubernetes Installation on Ubuntu | Edureka
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
 

Kürzlich hochgeladen

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 

Kürzlich hochgeladen (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 

Python Flask Training: Introduction to Flask Framework

  • 1. Python Certification Training https://www.edureka.co/python Agenda
  • 2. Python Certification Training https://www.edureka.co/python Agenda
  • 3. Python Certification Training https://www.edureka.co/python Agenda Introduction 01 Introduction to Flask Getting Started 02 Concepts 03 Practical Approach 04 Installing and working with Flask Looking at code to understand theory Overview of all the concepts in Flask
  • 4. Python Certification Training https://www.edureka.co/python Introduction to Flask
  • 5. Python Certification Training https://www.edureka.co/python Introduction to Flask Open Source Flask is a web application framework written in Python.What is Flask? Large community for Learners and Collaborators Let’s get started then!
  • 6. Python Certification Training https://www.edureka.co/python Introduction to Flask What is a Web Framework? Life without Flask! Using Flask! ModulesLibraries Web Developer
  • 7. Python Certification Training https://www.edureka.co/python Introduction to Flask Flask!! Enthusiasts named Pocco! Werkzeug WSGI Toolkit Jinga2 Template Engine I’m learning Flask!
  • 8. Python Certification Training https://www.edureka.co/python Installing Flask
  • 9. Python Certification Training https://www.edureka.co/python Installation - Prerequisite Prerequisite I’m learning Flask! virtualenv Virtual Python Environment builder pip install virtualenv Sudo apt-get install virtualenv
  • 10. Python Certification Training https://www.edureka.co/python Installation - Flask Installation I’m learning Flask! Once installed, new virtual environment is created in a folder mkdir newproj cd newproj virtualenv venv To activate corresponding environment, use the following: venvscriptsactivate pip install Flask
  • 11. Python Certification Training https://www.edureka.co/python Flask - Application
  • 12. Python Certification Training https://www.edureka.co/python Flask - Application Test Installation I’m learning Flask! Use this simple code, save it as Hello.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World’ if __name__ == '__main__': app.run()
  • 13. Python Certification Training https://www.edureka.co/python Flask - Application Importing flask module in the project is mandatory! I’m learning Flask! Flask constructor takes name of current module (__name__) as argument App.route(rule, options) route() function URL binding with the function List of parameters to be forwarded to the underlying Rule object
  • 14. Python Certification Training https://www.edureka.co/python Flask - Application App.run(host, port, options Sl.no Parameter Description 1 host Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally 2 port Defaults to 5000 3 debug Defaults to false. If set to true, provides a debug information 3 options To be forwarded to underlying Werkzeug server. * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) All these parameters are optional Python hello.py
  • 15. Python Certification Training https://www.edureka.co/python Flask – Application
  • 16. Python Certification Training https://www.edureka.co/python Flask - Application Debug mode Flask application is started by calling run() method How to enable Debug mode? app.debug = True app.run() app.run(debug = True)
  • 17. Python Certification Training https://www.edureka.co/python Flask – Routing
  • 18. Python Certification Training https://www.edureka.co/python Flask - Routing Route() decorator in Flask is used to bind URL to a function @app.route(‘/hello’) def hello_world(): return ‘hello world’ add_url_rule() function is also used to bind URL with function Check out the following representation def hello_world(): return ‘hello world’ app.add_url_rule(‘/’, ‘hello’, hello_world)
  • 19. Python Certification Training https://www.edureka.co/python Flask –Variable Rules
  • 20. Python Certification Training https://www.edureka.co/python Flask – Variable Rules It is possible to build a URL dynamically! How? By adding variable parts to the rule parameter Consider the example from flask import Flask app = Flask(__name__) @app.route('/hello/<name>') def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run(debug = True) http://localhost:5000/hello/Edureka
  • 21. Python Certification Training https://www.edureka.co/python Flask – Variable Rules More rules can be constructed using these converters Sl.no Parameter Description 1 int Accepts Integer 2 Float For Floating point value 3 Path Accepts slashes used as directory separator character from flask import Flask app = Flask(__name__) @app.route('/blog/<int:postID>') def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<float:revNo>') def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run() Run the code Visit the URL: http://localhost:5000/blog/11 Blog number 11Browser Output http://localhost:5000/rev/1.1 Revision Number 1.100000
  • 22. Python Certification Training https://www.edureka.co/python Flask – Variable Rules Consider the following code: from flask import Flask app = Flask(__name__) @app.route('/flask') def hello_flask(): return 'Hello Flask' @app.route('/python/') def hello_python(): return 'Hello Python' if __name__ == '__main__': app.run() Run the code /flask /flask/ /python /python/
  • 23. Python Certification Training https://www.edureka.co/python Flask – URL Binding
  • 24. Python Certification Training https://www.edureka.co/python Flask – URL Building url_for() function is used for dynamically building a URL for a specific function from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>') 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://localhost:5000/user/admin
  • 25. Python Certification Training https://www.edureka.co/python Flask – HTTP Methods
  • 26. Python Certification Training https://www.edureka.co/python Flask – HTTP Methods HTTP Protocols are the foundation for data communication in WWW Sl.no Method Description 1 GET Sends data in unencrypted form to server 2 HEAD Same as GET, but without response body 3 POST Used to send HTML form data to server. 4 PUT Replaces all current representations of target resource with uploaded content 5 DELETE Removes all current representations of target resource given by URL Let’s look at an example
  • 27. Python Certification Training https://www.edureka.co/python Flask – HTTP Methods First we look at the HTML file <html> <body> <form action = "http://localhost:5000/login" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html> Save this as login.html
  • 28. Python Certification Training https://www.edureka.co/python Flask – HTTP Methods Next is Python Script from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/success/<name>') 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) Let’s check out the output!
  • 29. Python Certification Training https://www.edureka.co/python Flask – Templates
  • 30. Python Certification Training https://www.edureka.co/python Flask – Templates Can we return the output of a function bound to a UR: in form of HTML? from flask import Flask app = Flask(__name__) @app.route('/') def index(): return '<html><body><h1>'Hello World'</h1></body></html>' if __name__ == '__main__': app.run(debug = True) But this is cumbersome from flask import Flask app = Flask(__name__) @app.route('/') def index(): return '<html><body><h1>'Hello World'</h1></body></html>' if __name__ == '__main__': app.run(debug = True) Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.
  • 31. Python Certification Training https://www.edureka.co/python Flask – Templates Flask uses jinga2 template engine <!doctype html> <html> <body> <h1>Hello {{ name }}!</h1> </body> </html> Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present. from flask import Flask, render_template app = Flask(__name__) @app.route('/hello/<user>') 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 • # ... ## for Line Statements
  • 32. Python Certification Training https://www.edureka.co/python Flask – Templates Conditional statements in templates from flask import Flask, render_template app = Flask(__name__) @app.route('/hello/<int:score>') def hello_name(score): return render_template('hello.html', marks = score) if __name__ == '__main__': app.run(debug = True) <!doctype html> <html> <body> {% if marks>50 %} <h1> Your result is pass!</h1> {% else %} <h1>Your result is fail</h1> {% endif %} </body> </html> HTML Template script
  • 33. Python Certification Training https://www.edureka.co/python Flask – Templates Another example from flask import Flask, render_template app = Flask(__name__) @app.route('/result') def result(): dict = {'phy':50,'che':60,'maths':70} return render_template('result.html', result = dict) if __name__ == '__main__': app.run(debug = True) <!doctype html> <html> <body> <table border = 1> {% for key, value in result.iteritems() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html>
  • 34. Python Certification Training https://www.edureka.co/python Flask – Static Files
  • 35. Python Certification Training https://www.edureka.co/python Flask – Static Files Web application will require a static file such as JS or CSS file from flask import Flask, render_template app = Flask(__name__) @app.route('/result') def result(): dict = {'phy':50,'che':60,'maths':70} return render_template('result.html', result = dict) if __name__ == '__main__': app.run(debug = True) <!doctype html> <html> <body> <table border = 1> {% for key, value in result.iteritems() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html> Python function sayHello() { alert("Hello World") } JS File HTML
  • 36. Python Certification Training https://www.edureka.co/python Flask – Request Object
  • 37. Python Certification Training https://www.edureka.co/python Flask – Request Object Data from client’s webpage is sent to server as a global request object Form Dictionary object containing key-value pairs of form parameters and values args Parsed contents of query string which is part of URL after question mark (?) Cookies Dictionary object holding Cookie names and values files Data pertaining to uploaded file Method Current request method
  • 38. Python Certification Training https://www.edureka.co/python Flask – Cookies
  • 39. Python Certification Training https://www.edureka.co/python Flask – Cookies Cookie is stored on client’s machine. And helps with data tracking @app.route('/') def index(): return render_template('index.html') <html> <body> <form action = "/setcookie" method = "POST"> <p><h3>Enter userID</h3></p> <p><input type = 'text' name = 'nm'/></p> <p><input type = 'submit' value = 'Login'/></p> </form> </body> </html> @app.route('/setcookie', methods = ['POST', 'GET']) def setcookie(): if request.method == 'POST': user = request.form['nm'] resp = make_response(render_template('readcookie.html')) resp.set_cookie('userID', user) return resp @app.route('/getcookie') def getcookie(): name = request.cookies.get('userID') return '<h1>welcome '+name+'</h1>'
  • 40. Python Certification Training https://www.edureka.co/python Flask – Redirect & Errors
  • 41. Python Certification Training https://www.edureka.co/python Flask – Redirect & Errors Flask Class has a redirect() function which returns a response object Prototype Flask.redirect(location, statuscode, response) URL where response should be redirected Statuscode sent to browser’s header Response parameter used to instantiate response
  • 42. Python Certification Training https://www.edureka.co/python Flask – Redirect & Errors Standardized status codes Sl.no Status Code 1 HTTP_300_MULTIPLE_CHOICES 2 HTTP_301_MOVED_PERMANENTLY 3 HTTP_302_FOUND 4 HTTP_303_SEE_OTHER 5 HTTP_304_NOT_MODIFIED 6 HTTP_305_USE_PROXY 7 HTTP_306_RESERVED Sl.no Code Description 1 400 Bad Request 2 401 Unauthenticated 3 403 Forbidden 4 404 Not Found 5 406 Not Acceptable 6 415 Unsupported Media Type 7 429 Too Many Requests Prototype Flask.abort(code)
  • 43. Python Certification Training https://www.edureka.co/python Flask – Extensions
  • 44. Python Certification Training https://www.edureka.co/python Flask – Extensions Flask is a micro framework Large number of extensions Flask Mail Flask WTF Flask SQLAlchemy Flask Sijax Provides SMTP interface to Flask application Adds rendering & validation of WTForms Adds SQLAlchemy support to Flask Application Interface for Sijax – Python/jQuery library that makes AJAX easy to use Extensive Documentation
  • 45. Python Certification Training https://www.edureka.co/python Conclusion
  • 46. Python Certification Training https://www.edureka.co/python Conclusion