Flask – Variable Rules

Flask – Variable Rules ”; Previous Next It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as <variable-name>. 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 <name> 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/<name>”) def hello_name(name): return ”Hello %s!” % name if __name__ == ”__main__”: app.run(debug = True) Save the above script as hello.py and run it from Python shell. Next, open the browser and enter URL http://localhost:5000/hello/TutorialsPoint. The following output will be displayed in the browser. Hello TutorialsPoint! In addition to the default string variable part, rules can be constructed using the following converters − Sr.No. Converters & Description 1 int accepts integer 2 float For floating point value 3 path accepts slashes used as directory separator character In the following code, all these constructors are used. 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 above code from Python Shell. Visit the URL http://localhost:5000/blog/11 in the browser. The given number is used as argument to the show_blog() function. The browser displays the following output − Blog Number 11 Enter this URL in the browser − http://localhost:5000/rev/1.1 The revision() function takes up the floating point number as argument. The following result appears in the browser window − Revision Number 1.100000 The URL rules of Flask are based on Werkzeug’s routing module. This ensures that the URLs formed are unique and based on precedents laid down by Apache. Consider the rules defined in the following script − 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() Both the rules appear similar but in the second rule, trailing slash (/) is used. As a result, it becomes a canonical URL. Hence, using /python or /python/ returns the same output. However, in case of the first rule, /flask/ URL results in 404 Not Found page. Print Page Previous Next Advertisements ”;

Flask – FastCGI

Flask – FastCGI ”; Previous Next FastCGI is another deployment option for Flask application on web servers like nginix, lighttpd, and Cherokee. Configuring FastCGI First, you need to create the FastCGI server file. Let us call it yourapplication.fcgi. from flup.server.fcgi import WSGIServer from yourapplication import app if __name__ == ”__main__”: WSGIServer(app).run() nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work, you need to pass the path to the socket to the WSGIServer. WSGIServer(application, bindAddress = ”/path/to/fcgi.sock”).run() Configuring Apache For a basic Apache deployment, your .fcgi file will appear in your application URL e.g. example.com/yourapplication.fcgi/hello/. There are few ways to configure your application so that yourapplication.fcgi does not appear in the URL. <VirtualHost *> ServerName example.com ScriptAlias / /path/to/yourapplication.fcgi/ </VirtualHost> Configuring lighttpd Basic configuration of lighttpd looks like this − fastcgi.server = (“/yourapplication.fcgi” => (( “socket” => “/tmp/yourapplication-fcgi.sock”, “bin-path” => “/var/www/yourapplication/yourapplication.fcgi”, “check-local” => “disable”, “max-procs” => 1 ))) alias.url = ( “/static/” => “/path/to/your/static” ) url.rewrite-once = ( “^(/static($|/.*))$” => “$1”, “^(/.*)$” => “/yourapplication.fcgi$1″ ) Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication. Print Page Previous Next Advertisements ”;

Flask – Quick Guide

Flask – Quick Guide ”; Previous Next Flask – Overview What is Web Framework? Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc. What is Flask? Flask is a web application framework written in Python. It is developed by Armin Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications. Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases. Jinja2 Jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages. Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form a validation support. Instead, Flask supports the extensions to add such functionality to the application. Some of the popular Flask extensions are discussed later in the tutorial. Flask – Environment Prerequisite Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7. Install virtualenv for development environment virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries. The following command installs virtualenv pip install virtualenv This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager. Sudo apt-get install virtualenv Once installed, new virtual environment is created in a folder. mkdir newproj cd newproj virtualenv venv To activate corresponding environment, on Linux/OS X, use the following − venv/bin/activate On Windows, following can be used venvscriptsactivate We are now ready to install Flask in this environment. pip install Flask The above command can be run directly, without virtual environment for system-wide installation. Flask – Application In order to test Flask installation, type the following code in the editor as Hello.py from flask import Flask app = Flask(__name__) @app.route(”/”) def hello_world(): return ”Hello World” if __name__ == ”__main__”: app.run() Importing flask module in the project is mandatory. An object of Flask class is our WSGI application. Flask constructor takes the name of current module (__name__) as argument. The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function. app.route(rule, options) The rule parameter represents URL binding with the function. The options is a list of parameters to be forwarded to the underlying Rule object. In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered. Finally the run() method of Flask class runs the application on the local development server. app.run(host, port, debug, options) All parameters are optional Sr.No. Parameters & 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 4 options To be forwarded to underlying Werkzeug server. The above given Python script is executed from Python shell. Python Hello.py A message in Python shell informs you that * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it. Debug mode A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application. The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method. app.debug = True app.run() app.run(debug = True) Flask – Routing Modern web frameworks use the routing technique to help a user remember application URLs. It is useful to access the desired page directly without having to navigate from the home page. The route() decorator in Flask is used to bind URL to a function. For example − @app.route(‘/hello’) def hello_world(): return ‘hello world’ Here, URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser. The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used. A decorator’s purpose is also served by the following representation − def hello_world(): return ‘hello world’ app.add_url_rule(‘/’, ‘hello’, hello_world) Flask – Variable Rules It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as <variable-name>. 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 <name> variable part attached to URL ‘/hello’. Hence, if the http://localhost:5000/hello/TutorialsPoint is entered as a URL in the

Flask – Extensions

Flask – Extensions ”; Previous Next Flask is often referred to as a micro framework, because a core functionality includes WSGI and routing based on Werkzeug and template engine based on Jinja2. In addition, Flask framework has support for cookie and sessions as well as web helpers like JSON, static files etc. Obviously, this is not enough for the development of a full-fledged web application. This is where the Flask extensions come in picture. Flask extensions give extensibility to Flask framework. There are a large number of Flask extensions available. A Flask extension is a Python module, which adds specific type of support to the Flask application. Flask Extension Registry is a directory of extensions available. The required extension can be downloaded by pip utility. In this tutorial, we will discuss the following important Flask extensions − Flask Mail − provides SMTP interface to Flask application Flask WTF − adds rendering and validation of WTForms Flask SQLAlchemy − adds SQLAlchemy support to Flask application Flask Sijax − Interface for Sijax – Python/jQuery library that makes AJAX easy to use in web applications Each type of extension usually provides extensive documentation about its usage. Since an extension is a Python module, it needs to be imported for it to be used. Flask extensions are generally named as flask-foo. To import, from flask_foo import [class, function] For versions of Flask later than 0.7, you can also use the syntax − from flask.ext import foo For this usage, a compatibility module needs to be activated. It can be installed by running flaskext_compat.py import flaskext_compat flaskext_compat.activate() from flask.ext import foo Print Page Previous Next Advertisements ”;

Flask – Useful Resources

Flask – Useful Resources ”; Previous Next The following resources contain additional information on Flask. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Flask Framework Online Training 23 Lectures 6 hours Tutorialspoint More Detail Python Flask and SQLAlchemy ORM 22 Lectures 1.5 hours Jack Chan More Detail Build and Deploy Computer Vision & Image Processing Web App using Python, Flask, ML Most Popular 55 Lectures 6 hours Srikanth Guskra More Detail From Zero to Flask: The Professional Way 88 Lectures 3.5 hours Jorge Escobar More Detail Essential Docker for Python Flask Development 21 Lectures 2 hours Stone River ELearning More Detail From Zero to Flask: The Professional Way|Stone River ELearning 90 Lectures 4 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;

Flask – Sessions

Flask – Sessions ”; Previous Next Like Cookie, Session data is stored on client. Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in the client browser. A session with each client is assigned a Session ID. The Session data is stored on top of cookies and the server signs them cryptographically. For this encryption, a Flask application needs a defined SECRET_KEY. Session object is also a dictionary object containing key-value pairs of session variables and associated values. For example, to set a ‘username’ session variable use the statement − Session[‘username’] = ’admin’ To release a session variable use pop() method. session.pop(”username”, None) The following code is a simple demonstration of session works in Flask. URL ‘/’ simply prompts user to log in, as session variable ‘username’ is not set. @app.route(”/”) def index(): if ”username” in session: username = session[”username”] return ”Logged in as ” &plus; username &plus; ”<br>” &plus; “<b><a href = ”/logout”>click here to log out</a></b>” return “You are not logged in <br><a href = ”/login”></b>” &plus; “click here to log in</b></a>” As user browses to ‘/login’ the login() view function, because it is called through GET method, opens up a login form. A Form is posted back to ‘/login’ and now session variable is set. Application is redirected to ‘/’. This time session variable ‘username’ is found. @app.route(”/login”, methods = [”GET”, ”POST”]) def login(): if request.method == ”POST”: session[”username”] = request.form[”username”] return redirect(url_for(”index”)) return ””” <form action = “” method = “post”> <p><input type = text name = username/></p> <p<<input type = submit value = Login/></p> </form> ””” The application also contains a logout() view function, which pops out ‘username’ session variable. Hence, ‘/’ URL again shows the opening page. @app.route(”/logout”) def logout(): # remove the username from the session if it is there session.pop(”username”, None) return redirect(url_for(”index”)) Run the application and visit the homepage. (Ensure to set secret_key of the application) from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = ”any random string’ The output will be displayed as shown below. Click the link “click here to log in”. The link will be directed to another screen. Type ‘admin’. The screen will show you the message, ‘Logged in as admin’. Print Page Previous Next Advertisements ”;

Flask – URL Building

Flask – URL Building ”; Previous Next 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/<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) The above script has a function user(name) which accepts a value to its argument from the URL. The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it. Save the above code and run from Python shell. Open the browser and enter URL as − http://localhost:5000/user/admin The application response in browser is − Hello Admin Enter the following URL in the browser − http://localhost:5000/user/mvl The application response now changes to − Hello mvl as Guest Print Page Previous Next Advertisements ”;

Flask – Sijax

Flask – Sijax ”; Previous Next Sijax stands for ‘Simple Ajax’ and it is a Python/jQuery library designed to help you easily bring Ajax to your application. It uses jQuery.ajax to make AJAX requests. Installation Installation of Flask-Sijax is easy. pip install flask-sijax Configuration SIJAX_STATIC_PATH − the static path where you want the Sijax javascript files to be mirrored. The default location is static/js/sijax. In this folder, sijax.js and json2.js files are kept. SIJAX_JSON_URI − the URI to load the json2.js static file from Sijax uses JSON to pass the data between the browser and the server. This means that the browsers need either to support JSON natively or get JSON support from the json2.js file. Functions registered that way cannot provide Sijax functionality, because they cannot be accessed using a POST method by default (and Sijax uses POST requests). To make a View function capable of handling Sijax requests, make it accessible via POST using @app.route(”/url”, methods = [”GET”, ”POST”]) or use the @flask_sijax.route helper decorator like this − @flask_sijax.route(app, ”/hello”) Every Sijax handler function (like this one) receives at least one parameter automatically, much like Python passes ‘self’ to the object methods. The ‘obj_response’ parameter is the function”s way of talking back to the browser. def say_hi(obj_response): obj_response.alert(”Hi there!”) When Sijax request is detected, Sijax handles it like this − g.sijax.register_callback(”say_hi”, say_hi) return g.sijax.process_request() Sijax Application A minimal Sijax application code looks as follows − import os from flask import Flask, g from flask_sijax import sijax path = os.path.join(”.”, os.path.dirname(__file__), ”static/js/sijax/”) app = Flask(__name__) app.config[”SIJAX_STATIC_PATH”] = path app.config[”SIJAX_JSON_URI”] = ”/static/js/sijax/json2.js” flask_sijax.Sijax(app) @app.route(”/”) def index(): return ”Index” @flask_sijax.route(app, ”/hello”) def hello(): def say_hi(obj_response): obj_response.alert(”Hi there!”) if g.sijax.is_sijax_request: # Sijax request detected – let Sijax handle it g.sijax.register_callback(”say_hi”, say_hi) return g.sijax.process_request() return _render_template(”sijaxexample.html”) if __name__ == ”__main__”: app.run(debug = True) When a Sijax requests (a special jQuery.ajax() request) to the server, this request is detected on the server by g.sijax.is_sijax_request(), in which case you let Sijax handle the request. All the functions registered using g.sijax.register_callback() are exposed for calling from the browser. Calling g.sijax.process_request() tells Sijax to execute the appropriate (previously registered) function and return the response to the browser. Print Page Previous Next Advertisements ”;

Flask – Routing

Flask – Routing ”; Previous Next Modern web frameworks use the routing technique to help a user remember application URLs. It is useful to access the desired page directly without having to navigate from the home page. The route() decorator in Flask is used to bind URL to a function. For example − @app.route(‘/hello’) def hello_world(): return ‘hello world’ Here, URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser. The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used. A decorator’s purpose is also served by the following representation − def hello_world(): return ‘hello world’ app.add_url_rule(‘/’, ‘hello’, hello_world) Print Page Previous Next Advertisements ”;

Flask – Cookies

Flask – Cookies ”; Previous Next A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics. A Request object contains a cookie’s attribute. It is a dictionary object of all the cookie variables and their corresponding values, a client has transmitted. In addition to it, a cookie also stores its expiry time, path and domain name of the site. In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie. Reading back a cookie is easy. The get() method of request.cookies attribute is used to read a cookie. In the following Flask application, a simple form opens up as you visit ‘/’ URL. @app.route(”/”) def index(): return render_template(”index.html”) This HTML page contains one text input. <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> The Form is posted to ‘/setcookie’ URL. The associated view function sets a Cookie name userID and renders another page. @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 ‘readcookie.html’ contains a hyperlink to another view function getcookie(), which reads back and displays the cookie value in browser. @app.route(”/getcookie”) def getcookie(): name = request.cookies.get(”userID”) return ”<h1>welcome ”&plus;name&plus;”</h1>” Run the application and visit http://localhost:5000/ The result of setting a cookie is displayed like this − The output of read back cookie is shown below. Print Page Previous Next Advertisements ”;