1 / 48

Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python Training | Edureka

** Python Certification Training: https://www.edureka.co/python ** <br>This Edureka Python Flask tutorial will cover all the fundamentals of Flask. It will also explain how you can develop your own website using Flask in Python. <br><br>Introduction to Flask <br>Installing Flask <br>Flask Application <br>Routing in Flask <br>Variable Rules in Flask <br>URL Binding in Flask <br>HTTP Methods using Flask <br>Templates in Flask <br>Static Files in Flask <br>Request Objects in Flask <br>Cookies in Flask <br>Redirects and Errors in Flask <br>Flask Extensions <br>Conclusion <br><br>Follow us to never miss an update in the future. <br><br>Instagram: https://www.instagram.com/edureka_learning/ <br>Facebook: https://www.facebook.com/edurekaIN/ <br>Twitter: https://twitter.com/edurekain <br>LinkedIn: https://www.linkedin.com/company/edureka

EdurekaIN
Download Presentation

Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python Training | Edureka

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Agenda Python Certification Training https://www.edureka.co/python

  2. Agenda Python Certification Training https://www.edureka.co/python

  3. Agenda 01 Introduction Introduction to Flask 02 Getting Started Installing and working with Flask 03 Concepts Overview of all the concepts in Flask 04 Practical Approach Looking at code to understand theory Python Certification Training https://www.edureka.co/python

  4. Introduction to Flask Python Certification Training https://www.edureka.co/python

  5. Introduction to Flask Flask is a web application framework written in Python. What is Flask? Large community for Learners and Collaborators Open Source Let’s get started then! Python Certification Training https://www.edureka.co/python

  6. Introduction to Flask What is a Web Framework? Libraries Modules Web Developer Life without Flask! Using Flask! Python Certification Training https://www.edureka.co/python

  7. 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

  8. Installing Flask Python Certification Training https://www.edureka.co/python

  9. Installation - Prerequisite Prerequisite virtualenv Virtual Python Environment builder pip install virtualenv Sudo apt-get install virtualenv I’m learning Flask! Python Certification Training https://www.edureka.co/python

  10. Installation - Flask Installation Once installed, new virtual environment is created in a folder mkdir newproj cd newproj virtualenv venv To activate corresponding environment, use the following: venv\scripts\activate I’m learning Flask! pip install Flask Python Certification Training https://www.edureka.co/python

  11. Flask - Application Python Certification Training https://www.edureka.co/python

  12. Flask - Application Test Installation 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() I’m learning Flask! Python Certification Training https://www.edureka.co/python

  13. Flask - Application Importing flask module in the project is mandatory! Flask constructor takes name of current module (__name__) as argument route() function App.route(rule, options) URL binding with the function List of parameters to be forwarded to the underlying Rule object I’m learning Flask! Python Certification Training https://www.edureka.co/python

  14. Flask - Application App.run(host, port, options All these parameters are optional Sl.no Parameter Description Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally 1 host Defaults to 5000 2 port Defaults to false. If set to true, provides a debug information 3 debug To be forwarded to underlying Werkzeug server. 3 options Python hello.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Python Certification Training https://www.edureka.co/python

  15. Flask – Application Python Certification Training https://www.edureka.co/python

  16. 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

  17. Flask – Routing Python Certification Training https://www.edureka.co/python

  18. 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

  19. Flask –Variable Rules Python Certification Training https://www.edureka.co/python

  20. Flask – Variable Rules It is possible to build a URL dynamically! By adding variable parts to the rule parameter How? 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

  21. Flask – Variable Rules More rules can be constructed using these converters Sl.no Parameter Description from flask import Flask app = Flask(__name__) 1 int Accepts Integer 2 Float For Floating point value @app.route('/blog/<int:postID>') def show_blog(postID): return 'Blog Number %d' % postID Accepts slashes used as directory separator character 3 Path @app.route('/rev/<float:revNo>') def revision(revNo): return 'Revision Number %f' % revNo http://localhost:5000/blog/11 Visit the URL: if __name__ == '__main__': app.run() Browser Output Blog number 11 http://localhost:5000/rev/1.1 Revision Number 1.100000 Run the code Python Certification Training https://www.edureka.co/python

  22. Flask – Variable Rules Consider the following code: from flask import Flask app = Flask(__name__) /python /python/ @app.route('/flask') def hello_flask(): return 'Hello Flask' /flask/ /flask @app.route('/python/') def hello_python(): return 'Hello Python' if __name__ == '__main__': app.run() Run the code Python Certification Training https://www.edureka.co/python

  23. Flask – URL Binding Python Certification Training https://www.edureka.co/python

  24. 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

  25. Flask – HTTP Methods Python Certification Training https://www.edureka.co/python

  26. Flask – HTTP Methods HTTP Protocols are the foundation for data communication in WWW Sl.no 1 2 3 Method GET HEAD POST Description Sends data in unencrypted form to server Same as GET, but without response body Used to send HTML form data to server. Replaces all current representations of target resource with uploaded content Removes all current representations of target resource given by URL 4 PUT 5 DELETE Let’s look at an example Python Certification Training https://www.edureka.co/python

  27. 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

  28. 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

  29. Flask – Templates Python Certification Training https://www.edureka.co/python

  30. 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__) from flask import Flask app = Flask(__name__) @app.route('/') def index(): return '<html><body><h1>'Hello World'</h1></body></html>' @app.route('/') def index(): return '<html><body><h1>'Hello World'</h1></body></html>' if __name__ == '__main__': app.run(debug = True) 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. But this is cumbersome Python Certification Training https://www.edureka.co/python

  31. Flask – Templates Flask uses jinga2 template engine from flask import Flask, render_template app = Flask(__name__) <!doctype html> <html> <body> @app.route('/hello/<user>') def hello_name(user): return render_template('hello.html', name = user) <h1>Hello {{ name }}!</h1> </body> </html> if __name__ == '__main__': app.run(debug = True) TheJinga2template engine uses the following delimiters for escaping from HTML Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present. • {% ... %} 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

  32. Flask – Templates Conditional statements in templates <!doctype html> <html> <body> from flask import Flask, render_template app = Flask(__name__) {% if marks>50 %} <h1> Your result is pass!</h1> {% else %} <h1>Your result is fail</h1> {% endif %} @app.route('/hello/<int:score>') def hello_name(score): return render_template('hello.html', marks = score) if __name__ == '__main__': app.run(debug = True) </body> </html> HTML Template script Python Certification Training https://www.edureka.co/python

  33. Flask – Templates Another example <!doctype html> <html> <body> from flask import Flask, render_template app = Flask(__name__) <table border = 1> {% for key, value in result.iteritems() %} @app.route('/result') def result(): dict = {'phy':50,'che':60,'maths':70} return render_template('result.html', result = dict) <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> if __name__ == '__main__': app.run(debug = True) {% endfor %} </table> </body> </html> Python Certification Training https://www.edureka.co/python

  34. Flask – Static Files Python Certification Training https://www.edureka.co/python

  35. Flask – Static Files Web application will require a static file such as JS or CSS file <!doctype html> <html> <body> 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) <table border = 1> {% for key, value in result.iteritems() %} <tr> if __name__ == '__main__': app.run(debug = True) <th> {{ key }} </th> <td> {{ value }} </td> </tr> Python {% endfor %} </table> JS File </body> </html> function sayHello() { alert("Hello World") } HTML Python Certification Training https://www.edureka.co/python

  36. Flask – Request Object Python Certification Training https://www.edureka.co/python

  37. 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

  38. Flask – Cookies Python Certification Training https://www.edureka.co/python

  39. Flask – Cookies Cookie is stored on client’s machine. And helps with data tracking <html> @app.route('/') def index(): return render_template('index.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) @app.route('/getcookie') def getcookie(): name = request.cookies.get('userID') return '<h1>welcome '+name+'</h1>' return resp Python Certification Training https://www.edureka.co/python

  40. Flask – Redirect & Errors Python Certification Training https://www.edureka.co/python

  41. 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

  42. Flask – Redirect & Errors Standardized status codes Prototype Flask.abort(code) Sl.no 1 2 3 4 5 6 7 Status Code Sl.no 1 2 3 4 5 6 7 Code 400 401 403 404 406 415 429 Description Bad Request Unauthenticated Forbidden Not Found Not Acceptable Unsupported Media Type Too Many Requests HTTP_300_MULTIPLE_CHOICES HTTP_301_MOVED_PERMANENTLY HTTP_302_FOUND HTTP_303_SEE_OTHER HTTP_304_NOT_MODIFIED HTTP_305_USE_PROXY HTTP_306_RESERVED Python Certification Training https://www.edureka.co/python

  43. Flask – Extensions Python Certification Training https://www.edureka.co/python

  44. 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 Interface for Sijax – Python/jQuery library that makes AJAX easy to use Adds rendering & validation of WTForms SQLAlchemy support to Flask Application Extensive Documentation Python Certification Training https://www.edureka.co/python

  45. Conclusion Python Certification Training https://www.edureka.co/python

  46. Conclusion Python Certification Training https://www.edureka.co/python

More Related