Flask – Home

Flask Tutorial PDF Version Quick Guide Resources Job Search Discussion Flask is a web application framework written in Python. Armin Ronacher, who leads an international group of Python enthusiasts named Pocco, develops it. Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. Audience This tutorial has been prepared for anyone who has a basic knowledge of Python and has an urge to develop websites. After completing this tutorial, you will find yourself at a moderate level of expertise in developing websites using Flask. Prerequisites Before you start proceeding with this tutorial, we are assuming that you have hands-on experience on HTML and Python. If you are not well aware of these concepts, then we will suggest you to go through our short tutorials on HTML and Python. Print Page Previous Next Advertisements ”;

Flask – File Uploading

Flask – File Uploading ”; Previous Next Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to ‘multipart/form-data’, posting the file to a URL. The URL handler fetches file from request.files[] object and saves it to the desired location. Each uploaded file is first saved in a temporary location on the server, before it is actually saved to its ultimate location. Name of destination file can be hard-coded or can be obtained from filename property of request.files[file] object. However, it is recommended to obtain a secure version of it using the secure_filename() function. It is possible to define the path of default upload folder and maximum size of uploaded file in configuration settings of Flask object. app.config[‘UPLOAD_FOLDER’] Defines path for upload folder app.config[‘MAX_CONTENT_PATH’] Specifies maximum size of file yo be uploaded – in bytes The following code has ‘/upload’ URL rule that displays ‘upload.html’ from the templates folder, and ‘/upload-file’ URL rule that calls uploader() function handling upload process. ‘upload.html’ has a file chooser button and a submit button. <html> <body> <form action = “http://localhost:5000/uploader” method = “POST” enctype = “multipart/form-data”> <input type = “file” name = “file” /> <input type = “submit”/> </form> </body> </html> You will see the screen as shown below. Click Submit after choosing file. Form’s post method invokes ‘/upload_file’ URL. The underlying function uploader() does the save operation. Following is the Python code of Flask application. from flask import Flask, render_template, request from werkzeug import secure_filename app = Flask(__name__) @app.route(”/upload”) def upload_file(): return render_template(”upload.html”) @app.route(”/uploader”, methods = [”GET”, ”POST”]) def upload_file(): if request.method == ”POST”: f = request.files[”file”] f.save(secure_filename(f.filename)) return ”file uploaded successfully” if __name__ == ”__main__”: app.run(debug = True) Print Page Previous Next Advertisements ”;

Flask – Application

Flask – Application ”; Previous Next 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) Print Page Previous Next Advertisements ”;

Flask – Message Flashing

Flask – Message Flashing ”; Previous Next A good GUI based application provides feedback to a user about the interaction. For example, the desktop applications use dialog or message box and JavaScript uses alerts for similar purpose. Generating such informative messages is easy in Flask web application. Flashing system of Flask framework makes it possible to create a message in one view and render it in a view function called next. A Flask module contains flash() method. It passes a message to the next request, which generally is a template. flash(message, category) Here, message parameter is the actual message to be flashed. category parameter is optional. It can be either ‘error’, ‘info’ or ‘warning’. In order to remove message from session, template calls get_flashed_messages(). get_flashed_messages(with_categories, category_filter) Both parameters are optional. The first parameter is a tuple if received messages are having category. The second parameter is useful to display only specific messages. The following flashes received messages in a template. {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% endwith %} Let us now see a simple example, demonstrating the flashing mechanism in Flask. In the following code, a ‘/’ URL displays link to the login page, with no message to flash. @app.route(”/”) def index(): return render_template(”index.html”) The link leads a user to ‘/login’ URL which displays a login form. When submitted, the login() view function verifies a username and password and accordingly flashes a ‘success’ message or creates ‘error’ variable. @app.route(”/login”, methods = [”GET”, ”POST”]) def login(): error = None if request.method == ”POST”: if request.form[”username”] != ”admin” or request.form[”password”] != ”admin”: error = ”Invalid username or password. Please try again!” else: flash(”You were successfully logged in”) return redirect(url_for(”index”)) return render_template(”login.html”, error = error) In case of error, the login template is redisplayed with error message. Login.html <!doctype html> <html> <body> <h1>Login</h1> {% if error %} <p><strong>Error:</strong> {{ error }} {% endif %} <form action = “” method = post> <dl> <dt>Username:</dt> <dd> <input type = text name = username value = “{{request.form.username }}”> </dd> <dt>Password:</dt> <dd><input type = password name = password></dd> </dl> <p><input type = submit value = Login></p> </form> </body> </html> On the other hand, if login is successful, a success message is flashed on the index template. Index.html <!doctype html> <html> <head> <title>Flask Message flashing</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li<{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <h1>Flask Message Flashing Example</h1> <p>Do you want to <a href = “{{ url_for(”login”) }}”> <b>log in?</b></a></p> </body> </html> A complete code for Flask message flashing example is given below − Flash.py from flask import Flask, flash, redirect, render_template, request, url_for app = Flask(__name__) app.secret_key = ”random string” @app.route(”/”) def index(): return render_template(”index.html”) @app.route(”/login”, methods = [”GET”, ”POST”]) def login(): error = None if request.method == ”POST”: if request.form[”username”] != ”admin” or request.form[”password”] != ”admin”: error = ”Invalid username or password. Please try again!” else: flash(”You were successfully logged in”) return redirect(url_for(”index”)) return render_template(”login.html”, error = error) if __name__ == “__main__”: app.run(debug = True) After executing the above codes, you will see the screen as shown below. When you click on the link, you will be directed to the Login page. Enter the Username and password. Click Login. A message will be displayed “You were successfully logged in” . Print Page Previous Next Advertisements ”;

Flask – SQLAlchemy

Flask – SQLAlchemy ”; Previous Next Using raw SQL in Flask web applications to perform CRUD operations on database can be tedious. Instead, SQLAlchemy, a Python toolkit is a powerful OR Mapper that gives application developers the full power and flexibility of SQL. Flask-SQLAlchemy is the Flask extension that adds support for SQLAlchemy to your Flask application. What is ORM (Object Relation Mapping)? Most programming language platforms are object oriented. Data in RDBMS servers on the other hand is stored as tables. Object relation mapping is a technique of mapping object parameters to the underlying RDBMS table structure. An ORM API provides methods to perform CRUD operations without having to write raw SQL statements. In this section, we are going to study the ORM techniques of Flask-SQLAlchemy and build a small web application. Step 1 − Install Flask-SQLAlchemy extension. pip install flask-sqlalchemy Step 2 − You need to import SQLAlchemy class from this module. from flask_sqlalchemy import SQLAlchemy Step 3 − Now create a Flask application object and set URI for the database to be used. app = Flask(__name__) app.config[”SQLALCHEMY_DATABASE_URI”] = ”sqlite:///students.sqlite3” Step 4 − Then create an object of SQLAlchemy class with application object as the parameter. This object contains helper functions for ORM operations. It also provides a parent Model class using which user defined models are declared. In the snippet below, a students model is created. db = SQLAlchemy(app) class students(db.Model): id = db.Column(”student_id”, db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr,pin): self.name = name self.city = city self.addr = addr self.pin = pin Step 5 − To create / use database mentioned in URI, run the create_all() method. db.create_all() The Session object of SQLAlchemy manages all persistence operations of ORM object. The following session methods perform CRUD operations − db.session.add(model object) − inserts a record into mapped table db.session.delete(model object) − deletes record from table model.query.all() − retrieves all records from table (corresponding to SELECT query). You can apply a filter to the retrieved record set by using the filter attribute. For instance, in order to retrieve records with city = ’Hyderabad’ in students table, use following statement − Students.query.filter_by(city = ’Hyderabad’).all() With this much of background, now we shall provide view functions for our application to add a student data. The entry point of the application is show_all() function bound to ‘/’ URL. The Record set of students table is sent as parameter to the HTML template. The Server side code in the template renders the records in HTML table form. @app.route(”/”) def show_all(): return render_template(”show_all.html”, students = students.query.all() ) The HTML script of the template (‘show_all.html’) is like this − <!DOCTYPE html> <html lang = “en”> <head></head> <body> <h3> <a href = “{{ url_for(”show_all”) }}”>Comments – Flask SQLAlchemy example</a> </h3> <hr/> {%- for message in get_flashed_messages() %} {{ message }} {%- endfor %} <h3>Students (<a href = “{{ url_for(”new”) }}”>Add Student </a>)</h3> <table> <thead> <tr> <th>Name</th> <th>City</th> <th>Address</th> <th>Pin</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.city }}</td> <td>{{ student.addr }}</td> <td>{{ student.pin }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> The above page contains a hyperlink to ‘/new’ URL mapping new() function. When clicked, it opens a Student Information form. The data is posted to the same URL in POST method. new.html <!DOCTYPE html> <html> <body> <h3>Students – Flask SQLAlchemy example</h3> <hr/> {%- for category, message in get_flashed_messages(with_categories = true) %} <div class = “alert alert-danger”> {{ message }} </div> {%- endfor %} <form action = “{{ request.path }}” method = “post”> <label for = “name”>Name</label><br> <input type = “text” name = “name” placeholder = “Name” /><br> <label for = “email”>City</label><br> <input type = “text” name = “city” placeholder = “city” /><br> <label for = “addr”>addr</label><br> <textarea name = “addr” placeholder = “addr”></textarea><br> <label for = “PIN”>City</label><br> <input type = “text” name = “pin” placeholder = “pin” /><br> <input type = “submit” value = “Submit” /> </form> </body> </html> When the http method is detected as POST, the form data is added in the students table and the application returns to homepage showing the added data. @app.route(”/new”, methods = [”GET”, ”POST”]) def new(): if request.method == ”POST”: if not request.form[”name”] or not request.form[”city”] or not request.form[”addr”]: flash(”Please enter all the fields”, ”error”) else: student = students(request.form[”name”], request.form[”city”], request.form[”addr”], request.form[”pin”]) db.session.add(student) db.session.commit() flash(”Record was successfully added”) return redirect(url_for(”show_all”)) return render_template(”new.html”) Given below is the complete code of application (app.py). from flask import Flask, request, flash, url_for, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config[”SQLALCHEMY_DATABASE_URI”] = ”sqlite:///students.sqlite3” app.config[”SECRET_KEY”] = “random string” db = SQLAlchemy(app) class students(db.Model): id = db.Column(”student_id”, db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr,pin): self.name = name self.city = city self.addr = addr self.pin = pin @app.route(”/”) def show_all(): return render_template(”show_all.html”, students = students.query.all() ) @app.route(”/new”, methods = [”GET”, ”POST”]) def new(): if request.method == ”POST”: if not request.form[”name”] or not request.form[”city”] or not request.form[”addr”]: flash(”Please enter all the fields”, ”error”) else: student = students(request.form[”name”], request.form[”city”], request.form[”addr”], request.form[”pin”]) db.session.add(student) db.session.commit() flash(”Record was successfully added”) return redirect(url_for(”show_all”)) return render_template(”new.html”) if __name__ == ”__main__”: db.create_all() app.run(debug = True) Run the script from Python shell and enter http://localhost:5000/ in the browser. Click the ‘Add Student’ link to open Student information form. Fill the form and submit. The home page reappears with the submitted data. We can see the output as shown below. Print Page Previous Next Advertisements ”;

Flask – Environment

Flask – Environment ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Flask – HTTP Methods

Flask – HTTP methods ”; Previous Next Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol. The following table summarizes different http methods − Sr.No. Methods & Description 1 GET Sends data in unencrypted form to the server. Most common method. 2 HEAD Same as GET, but without response body 3 POST Used to send HTML form data to server. Data received by POST method is not cached by server. 4 PUT Replaces all current representations of the target resource with the uploaded content. 5 DELETE Removes all current representations of the target resource given by a URL By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator. In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL. Save the following script as login.html <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> Now enter the following script in Python shell. 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) After the development server starts running, open login.html in the browser, enter name in the text field and click Submit. Form data is POSTed to the URL in action clause of form tag. http://localhost/login is mapped to the login() function. Since the server has received data by POST method, value of ‘nm’ parameter obtained from the form data is obtained by − user = request.form[”nm”] It is passed to ‘/success’ URL as variable part. The browser displays a welcome message in the window. Change the method parameter to ‘GET’ in login.html and open it again in the browser. The data received on server is by the GET method. The value of ‘nm’ parameter is now obtained by − User = request.args.get(‘nm’) Here, args is dictionary object containing a list of pairs of form parameter and its corresponding value. The value corresponding to ‘nm’ parameter is passed on to ‘/success’ URL as before. Print Page Previous Next Advertisements ”;

Flask – Static Files

Flask – Static Files ”; Previous Next A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application. A special endpoint ‘static’ is used to generate URL for static files. In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application. from flask import Flask, render_template app = Flask(__name__) @app.route(“/”) def index(): return render_template(“index.html”) if __name__ == ”__main__”: app.run(debug = True) The HTML script of index.html is given below. <html> <head> <script type = “text/javascript” src = “{{ url_for(”static”, filename = ”hello.js”) }}” ></script> </head> <body> <input type = “button” onclick = “sayHello()” value = “Say Hello” /> </body> </html> hello.js contains sayHello() function. function sayHello() { alert(“Hello World”) } Print Page Previous Next Advertisements ”;