Flask - Quick Guide
- https://www.tutorialspoint.com/flask/flask_quick_guide.htm
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
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.
Once installed, new virtual environment is created in a folder.
To activate corresponding environment, on Linux/OS X, use the following â
On Windows, following can be used
We are now ready to install Flask in this environment.
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
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.
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.
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.
A message in Python shell informs you that
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.
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 â
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 â
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 browser, âTutorialPointâ will be supplied to hello() function as argument.
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.
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.
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 â
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 â
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 â
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.
Flask â URL Building
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.
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 â
Enter the following URL in the browser â http://localhost:5000/user/mvl
The application response now changes to â
Flask â HTTP methods
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
Now enter the following script in Python shell.
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 â
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 â
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.
Flask â Templates
It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, hello() function will render âHello Worldâ with <h1> tag attached to it.
However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML.
This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function.
Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.
Application folder
Hello.py
templates
hello.html
The term âweb templating systemâ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor.
Flask uses Jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered.
The following code is saved as hello.html in the templates folder.
Next, run the following script from Python shell.
As the development server starts running, open the browser and enter URL as â http://localhost:5000/hello/mvl
The Jinja2 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
In the following example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered.
The Python Script is as follows â
HTML template script of hello.html is as follows â
Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}.
Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally.
The Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser.
The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table.
Run the following code from Python shell.
Save the following HTML script as result.html in the templates folder.
Here, again the Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}.
Flask â Static Files
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.
The HTML script of index.html is given below.
hello.js contains sayHello() function.
Flask â Request Object
The data from a clientâs web page is sent to the server as a global request object. In order to process the request data, it should be imported from the Flask module.
Important attributes of request object are listed below â
Form â It is a dictionary object containing key and value pairs of form parameters and their 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.
Flask â Sending Form Data to Template
We have already seen that the http method can be specified in URL rule. The Form data received by the triggered function can collect it in the form of a dictionary object and forward it to a template to render it on a corresponding web page.
In the following example, â/â URL renders a web page (student.html) which has a form. The data filled in it is posted to the â/resultâ URL which triggers the result() function.
The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html.
The template dynamically renders an HTML table of form data.
Given below is the Python code of application â
Given below is the HTML script of student.html.
Code of template (result.html) is given below â
Flask â Cookies
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.
This HTML page contains one text input.
The Form is posted to â/setcookieâ URL. The associated view function sets a Cookie name userID and renders another page.
âreadcookie.htmlâ contains a hyperlink to another view function getcookie(), which reads back and displays the cookie value in browser.
Flask â Sessions
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 â
To release a session variable use pop() method.
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.
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.
The application also contains a logout() view function, which pops out âusernameâ session variable. Hence, â/â URL again shows the opening page.
Run the application and visit the homepage. (Ensure to set secret_key of the application)
Flask â Redirect & Errors
Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code.
Prototype of redirect() function is as below â
In the above function â
location parameter is the URL where response should be redirected.
statuscode sent to browserâs header, defaults to 302.
response parameter is used to instantiate response.
The following status codes are standardized â
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
HTTP_307_TEMPORARY_REDIRECT
The default status code is 302, which is for âfoundâ.
In the following example, the redirect() function is used to display the login page again when a login attempt fails.
Flask class has abort() function with an error code.
The Code parameter takes one of following values â
400 â for Bad Request
401 â for Unauthenticated
403 â for Forbidden
404 â for Not Found
406 â for Not Acceptable
415 â for Unsupported Media Type
429 â Too Many Requests
Let us make a slight change in the login() function in the above code. Instead of re-displaying the login page, if âUnauthourizedâ page is to be displayed, replace it with call to abort(401).
Flask â Message Flashing
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.
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().
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.
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.
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.
In case of error, the login template is redisplayed with error message.
Login.html
On the other hand, if login is successful, a success message is flashed on the index template.
Index.html
A complete code for Flask message flashing example is given below â
Flash.py
When you click on the link, you will be directed to the Login page.
Flask â File Uploading
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.
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.
Flask â Extensions
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,
For versions of Flask later than 0.7, you can also use the syntax â
For this usage, a compatibility module needs to be activated. It can be installed by running flaskext_compat.py
Flask â Mail
A web based application is often required to have a feature of sending mail to the users/clients. Flask-Mail extension makes it very easy to set up a simple interface with any email server.
At first, Flask-Mail extension should be installed with the help of pip utility.
Then Flask-Mail needs to be configured by setting values of the following application parameters.
Sr.No
Parameters & Description
1
MAIL_SERVER
Name/IP address of email server
2
MAIL_PORT
Port number of server used
3
MAIL_USE_TLS
Enable/disable Transport Security Layer encryption
4
MAIL_USE_SSL
Enable/disable Secure Sockets Layer encryption
5
MAIL_DEBUG
Debug support. Default is Flask applicationâs debug status
6
MAIL_USERNAME
User name of sender
7
MAIL_PASSWORD
password of sender
8
MAIL_DEFAULT_SENDER
sets default sender
9
MAIL_MAX_EMAILS
Sets maximum mails to be sent
10
MAIL_SUPPRESS_SEND
Sending suppressed if app.testing set to true
11
MAIL_ASCII_ATTACHMENTS
If set to true, attached filenames converted to ASCII
The flask-mail module contains definitions of the following important classes.
Mail class
It manages email-messaging requirements. The class constructor takes the following form â
The Constructor takes the Flask application object as a parameter.
Methods of Mail class
Sr.No
Methods & Description
1
send()
Sends contents of Message class object
2
connect()
Opens connection with mail host
3
send_message()
Sends message object
Message class
It encapsulates an email message. Message class constructor has several parameters â
Message class methods
attach() â adds an attachment to message. This method takes the following parameters â
filename â name of file to attach
content_type â MIME type of file
data â raw file data
disposition â content disposition, if any.
add_recipient() â adds another recipient to message
In the following example, SMTP server of Googleâs gmail service is used as MAIL_SERVER for Flask-Mail configuration.
Step 1 â Import Mail and Message class from flask-mail module in the code.
Step 2 â Then Flask-Mail is configured as per following settings.
Step 3 â Create an instance of Mail class.
Step 4 â Set up a Message object in a Python function mapped by URL rule (â/â).
Step 5 â The entire code is given below. Run the following script in Python Shell and visit http://localhost:5000/.
Flask â WTF
One of the essential aspects of a web application is to present a user interface for the user. HTML provides a <form> tag, which is used to design an interface. A Formâs elements such as text input, radio, select etc. can be used appropriately.
Data entered by a user is submitted in the form of Http request message to the server side script by either GET or POST method.
The Server side script has to recreate the form elements from http request data. So in effect, form elements have to be defined twice â once in HTML and again in the server side script.
Another disadvantage of using HTML form is that it is difficult (if not impossible) to render the form elements dynamically. HTML itself provides no way to validate a userâs input.
This is where WTForms, a flexible form, rendering and validation library comes handy. Flask-WTF extension provides a simple interface with this WTForms library.
Using Flask-WTF, we can define the form fields in our Python script and render them using an HTML template. It is also possible to apply validation to the WTF field.
Let us see how this dynamic generation of HTML works.
First, Flask-WTF extension needs to be installed.
The installed package contains a Form class, which has to be used as a parent for user- defined form.
WTforms package contains definitions of various form fields. Some Standard form fields are listed below.
Sr.No
Standard Form Fields & Description
1
TextField
Represents <input type = 'text'> HTML form element
2
BooleanField
Represents <input type = 'checkbox'> HTML form element
3
DecimalField
Textfield for displaying number with decimals
4
IntegerField
TextField for displaying integer
5
RadioField
Represents <input type = 'radio'> HTML form element
6
SelectField
Represents select form element
7
TextAreaField
Represents <testarea> html form element
8
PasswordField
Represents <input type = 'password'> HTML form element
9
SubmitField
Represents <input type = 'submit'> form element
For example, a form containing a text field can be designed as below â
In addition to the ânameâ field, a hidden field for CSRF token is created automatically. This is to prevent Cross Site Request Forgery attack.
When rendered, this will result into an equivalent HTML script as shown below.
A user-defined form class is used in a Flask application and the form is rendered using a template.
WTForms package also contains validator class. It is useful in applying validation to form fields. Following list shows commonly used validators.
Sr.No
Validators Class & Description
1
DataRequired
Checks whether input field is empty
2
Checks whether text in the field follows email ID conventions
3
IPAddress
Validates IP address in input field
4
Length
Verifies if length of string in input field is in given range
5
NumberRange
Validates a number in input field within given range
6
URL
Validates URL entered in input field
We shall now apply âDataRequiredâ validation rule for the name field in contact form.
The validate() function of form object validates the form data and throws the validation errors if validation fails. The Error messages are sent to the template. In the HTML template, error messages are rendered dynamically.
The following example demonstrates the concepts given above. The design of Contact form is given below (forms.py).
Validators are applied to the Name and Email fields.
Given below is the Flask application script (formexample.py).
The Script of the template (contact.html) is as follows â
Flask â SQLite
Python has an in-built support for SQlite. SQlite3 module is shipped with Python distribution. For a detailed tutorial on using SQLite database in Python, please refer to this link. In this section we shall see how a Flask application interacts with SQLite.
Create an SQLite database âdatabase.dbâ and create a studentsâ table in it.
Our Flask application has three View functions.
First new_student() function is bound to the URL rule (â/addnewâ). It renders an HTML file containing student information form.
The HTML script for âstudent.htmlâ is as follows â
As it can be seen, form data is posted to the â/addrecâ URL which binds the addrec() function.
This addrec() function retrieves the formâs data by POST method and inserts in students table. Message corresponding to success or error in insert operation is rendered to âresult.htmlâ.
The HTML script of result.html contains an escaping statement {{msg}} that displays the result of Insert operation.
The application contains another list() function represented by â/listâ URL. It populates ârowsâ as a MultiDict object containing all records in the students table. This object is passed to the list.html template.
This list.html is a template, which iterates over the row set and renders the data in an HTML table.
Finally, the â/â URL rule renders a âhome.htmlâ which acts as the entry point of the application.
Here is the complete code of Flask-SQLite application.
Flask â SQLAlchemy
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.
Step 2 â You need to import SQLAlchemy class from this module.
Step 3 â Now create a Flask application object and set URI for the database to be used.
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.
Step 5 â To create / use database mentioned in URI, run the create_all() method.
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 â
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.
The HTML script of the template (âshow_all.htmlâ) is like this â
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
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.
Given below is the complete code of application (app.py).
Fill the form and submit. The home page reappears with the submitted data.
Flask â Sijax
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.
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 â
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.
When Sijax request is detected, Sijax handles it like this â
Sijax Application
A minimal Sijax application code looks as follows â
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.
Flask â Deployment
Externally Visible Server
A Flask application on the development server is accessible only on the computer on which the development environment is set up. This is a default behavior, because in debugging mode, a user can execute arbitrary code on the computer.
If debug is disabled, the development server on local computer can be made available to the users on network by setting the host name as â0.0.0.0â.
Thereby, your operating system listens to all public IPs.
Deployment
To switch over from a development environment to a full-fledged production environment, an application needs to be deployed on a real web server. Depending upon what you have, there are different options available to deploy a Flask web application.
For small application, you can consider deploying it on any of the following hosted platforms, all of which offer free plan for small application.
Heroku
dotcloud
webfaction
Flask application can be deployed on these cloud platforms. In addition, it is possible to deploy Flask app on Google cloud platform. Localtunnel service allows you to share your application on localhost without messing with DNS and firewall settings.
If you are inclined to use a dedicated web server in place of above mentioned shared platforms, following options are there to explore.
mod_wsgi
mod_wsgi is an Apache module that provides a WSGI compliant interface for hosting Python based web applications on Apache server.
Installing mod_wsgi
To install an official release direct from PyPi, you can run â
To verify that the installation was successful, run the mod_wsgi-express script with the start-server command â
This will start up Apache/mod_wsgi on port 8000. You can then verify that the installation worked by pointing your browser at â
Creating .wsgi file
There should be a yourapplication.wsgi file. This file contains the code mod_wsgi, which executes on startup to get the application object. For most applications, the following file should be sufficient â
Make sure that yourapplication and all the libraries that are in use are on the python load path.
Configuring Apache
You need to tell mod_wsgi, the location of your application.
Standalone WSGI containers
There are many popular servers written in Python that contains WSGI applications and serve HTTP.
Gunicorn
Tornado
Gevent
Twisted Web
Flask â FastCGI
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.
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.
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.
Configuring lighttpd
Basic configuration of lighttpd looks like this â
Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication.
Last updated