Flask – Overview

0
97

Flask – Oversee

Whead use is Web Framework?

Web Application Framework or simply Web Framework represents a collection of libraries and modules thead use enables a web application generateer to write applications withaway having to bother abaway low-level details such as protocols, thread management etc.

Whead use is Flask?

Flask is a web application framework written in Python. It is generateed simply simply 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 generatement. 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 generateing a web framework on top of it. The Flask framework uses Werkzeug as one of it’s bases.

jinja2

jinja2 is a popular templating engine for Python. A web templating system combines a template with a specific data source to render dynamic web pages.

Flask is regularly refercrimsondish coloucrimson to as a micro framework. It aims to maintain the core of an application basic yet extensible. Flask does not have built-in abstrbehaveion layer for database handling, nor does it have form a validation supslot. Instead, Flask supslots the extensions to add such functionality to the application. Some of the popular Flask extensions are talk abouted later in the tutorial.

Flask – Environment

Prerequisite

Python 2.6 or higher is usually requicrimsondish coloucrimson for installation of Flask. Although Flask and it’s dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not supslot it properly. Hence, it is recommended thead use Flask ought to be installed on Python 2.7.

Install virtualenv for generatement environment

virtualenv is a virtual Python environment generateer. It helps a user to generate multiple Python environments aspect-simply simply by-aspect. There’simply simply by, it can avoid compatibility issues between the various versions of the libraries.

The folloearng 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 it’s package manager.

Sudo apt-get install virtualenv

Once installed, brand new virtual environment is generated in a folder.

mkdir brand newproj
cd brand newproj
virtualenv venv

To behaveivate corresponding environment, on Linux/OS X, use the folloearng −

venv/bin/behaveivate

On Windows, folloearng can be used −

venvscriptsbehaveivate

We are now ready to install Flask in this particular environment.

pip install Flask

The above command can be operate immediately, withaway virtual environment for system-wide installation.

Flask – Application

In order to test Flask installation, kind the folloearng code in the editor as Hello.py

from flask imslot Flask
app = Flask(__name__)

@app.rawaye('/')
def hello_world():
   return 'Hello World’

if __name__ == '__main__':
   app.operate()

Imsloting flask module in the project is mandatory. An object of Flask course is our WSGI application.

Flask constructor considers the name of current module (__name__) as argument.

The rawaye() function of the Flask course is a decorator, which tells the application which URL ought to call the bumociated function.

app.rawaye(rule, options)
  • The rule parameter represents URL binding with the function.

  • The options is a list of parameters to be forwarded to the belowlying Rule object.

In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is open uped in browser, the awayplace of this particular function will be rendecrimsondish coloucrimson.

Finally the operate() method of Flask course operates the application on the local generatement server.

app.operate(host, slot, 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

slot

Defaults to 5000

3

debug

Defaults to false. If set to true, provides a debug information

4

options

To be forwarded to belowlying Werkzeug server.

The above given Python script is executed from Python shell.

Python Hello.py

A message in Python shell informs you thead use

* 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 simply simply by calling the operate() method. However, while the application is below generatement, it ought to be restarted manually for every alter in the code. To avoid this particular inconvenience, enable debug supslot. The server will then reload it’self if the code alters. It will furthermore provide a useful debugger to track the errors if any, in the application.

The Debug mode is enabled simply simply by setting the debug real estate of the application object to True before operatening or pbuming the debug parameter to the operate() method.

app.debug = True
app.operate()
app.operate(debug = True)

Flask – Rawaying

Modern web frameworks use the rawaying technique to help a user remember application URLs. It is useful to access the desicrimsondish coloucrimson page immediately withaway having to navigate from the home page.

The rawaye() decorator in Flask is used to bind URL to a function. For example −

@app.rawaye(‘/hello’)
def hello_world():
   return ‘hello world’

Here, URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visit’s http://localhost:5000/hello URL, the awayplace of the hello_world() function will be rendecrimsondish coloucrimson in the browser.

The add_url_rule() function of an application object is furthermore available to bind a URL with a function as in the above example, rawaye() is used.

A decorator’s purpose is furthermore served simply simply by the folloearng representation −

def hello_world():
   return ‘hello world’
app.add_url_rule(‘/’, ‘hello’, hello)

Flask – Variable Rules

It is probable to generate a URL dynamically, simply simply by adding variable parts to the rule parameter. This variable part is marked as <variable-name>. It is pbumed as a keyword argument to the function with which the rule is bumociated.

In the folloearng example, the rule parameter of rawaye() decorator contains <name> variable part attached to URL ‘/hello’. Hence, if the http://localhost:5000/hello/TutorialsPoint is entecrimsondish coloucrimson as a URL in the browser, ‘TutorialPoint’ will be suppare locatedd to hello() function as argument.

from flask imslot Flask
app = Flask(__name__)

@app.rawaye('/hello/<name>')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.operate(debug = True)

Save the above script as hello.py and operate it from Python shell. Next, open up the browser and enter URL http://localhost:5000/hello/TutorialsPoint.

The folloearng awayplace will be displayed in the browser.

Hello TutorialsPoint!

In addition to the default string variable part, rules can be constructed using the folloearng converters −

Sr.No Converters & Description
1

int

accepts integer

2

float

For floating point value

3

path

accepts slashes used as immediateory separator charbehaveer

In the folloearng code, all these constructors are used.

from flask imslot Flask
app = Flask(__name__)

@app.rawaye('/blog/<int:postID>')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.rawaye('/rev/<float:revNo>')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.operate()

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 folloearng awayplace −

Blog Number 11

Enter this particular URL in the browser − http://localhost:5000/rev/1.1

The revision() function considers up the floating point number as argument. The folloearng result appears in the browser earndow −

Revision Number 1.100000

The URL rules of Flask are based on Werkzeug’s rawaying module. This ensures thead use the URLs formed are unique and based on precedents laid down simply simply by Apache.

Conaspectr the rules degoodd in the folloearng script −

from flask imslot Flask
app = Flask(__name__)

@app.rawaye('/flask')
def hello_flask():
   return 'Hello Flask'

@app.rawaye('/python/')
def hello_python():
   return 'Hello Python'

if __name__ == '__main__':
   app.operate()

Both the rules appear similar but in the 2nd rule, trailing slash (/) is used. As a result, it becomes a canonical URL. Hence, using /python or /python/ returns the exbehave same awayplace. However, in case of the very first rule, /flask/ URL results in 404 Not Found page.

Flask – URL Building

The url_for() function is very useful for dynamically generateing a URL for a specific function. The function accepts the name of a function as very first argument, and one or more keyword arguments, every corresponding to the variable part of URL.

The folloearng script demonstrates use of url_for() function.

from flask imslot Flask, crimsondish coloureimmediate, url_for
app = Flask(__name__)

@app.rawaye('/admin')
def hello_admin():
   return 'Hello Admin'

@app.rawaye('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.rawaye('/user/<name>')
def hello_user(name):
   if name =='admin':
      return crimsondish coloureimmediate(url_for('hello_admin'))
   else:
      return crimsondish coloureimmediate(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.operate(debug = True)

The above script has a function user(name) which accepts a value to it’s argument from the URL.

The User() function checks if an argument received match upes ‘admin’ or not. If it match upes, the application is crimsondish coloureimmediateed to the hello_admin() function using url_for(), otherwise to the hello_guest() function pbuming the received argument as guest parameter to it.

Save the above code and operate from Python shell.

Open the browser and enter URL as − http://localhost:5000/hello/admin

The application response in browser is −

Hello Admin

Enter the folloearng URL in the browser − http://localhost:5000/hello/mvl

The application response now alters to −

Hello mvl as Guest

Flask – HTTP methods

Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are degoodd in this particular protocol.

The folloearng table summarizes various http methods −

Sr.No Methods & Description
1

GET

Sends data in unenweeppted form to the server. Most common method.

2

HEAD

Same as GET, but withaway response body

3

POST

Used to send HTML form data to server. Data received simply simply by POST method is not cached simply simply 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 simply simply by a URL

By default, the Flask rawaye responds to the GET requests. However, this particular preference can be altecrimsondish coloucrimson simply simply by providing methods argument to rawaye() decorator.

In order to demonstrate the use of POST method in URL rawaying, very first allow us generate an HTML form and use the POST method to send form data to a URL.

Save the folloearng script as login.html

<html>
   <body>
      
      <form behaveion = "http://localhost:5000/login" method = "post">
         <p>Enter Name:</p>
         <p><inplace kind = "text" name = "nm" /></p>
         <p><inplace kind = "submit" value = "submit" /></p>
      </form>
      
   </body>
</html>

Now enter the folloearng script in Python shell.

from flask imslot Flask, crimsondish coloureimmediate, url_for, request
app = Flask(__name__)

@app.rawaye('/success/<name>')
def success(name):
   return 'welcome %s' % name

@app.rawaye('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return crimsondish coloureimmediate(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return crimsondish coloureimmediate(url_for('success',name = user))

if __name__ == '__main__':
   app.operate(debug = True)

After the generatement server starts operatening, open up login.html in the browser, enter name in the text field and click Submit.

Post Method Example

Form data is POSTed to the URL in behaveion clause of form tag.

http://localhost/login is mapped to the login() function. Since the server has received data simply simply by POST method, value of ‘nm’ parameter obtained from the form data is obtained simply simply by −

user = request.form['nm']

It is pbumed to ‘/success’ URL as variable part. The browser displays a welcome message in the earndow.

Welcome Message

Change the method parameter to ‘GET’ in login.html and open up it again in the browser. The data received on server is simply simply by the GET method. The value of ‘nm’ parameter is now obtained simply simply by −

User = request.args.get(‘nm’)

Here, args is book object containing a list of pairs of form parameter and it’s corresponding value. The value corresponding to ‘nm’ parameter is pbumed on to ‘/success’ URL as before.

Flask – Templates

It is probable to return the awayplace of a function bound to a specific URL in the form of HTML. For instance, in the folloearng script, hello() function will render ‘Hello World’ with <h1> tag attached to it.

from flask imslot Flask
app = Flask(__name__)

@app.rawaye('/')
def index():
   return '<html><body><h1>Hello World'</h1></body></html>'

if __name__ == '__main__':
   app.operate(debug = True)

However, generating HTML content from Python code is cumbera few, especially when variable data and Python language elements like conditionals or loops need to be place. This would require regular escaping from HTML.

This is where one can consider advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendecrimsondish coloucrimson simply simply by the render_template() function.

from flask imslot Flask
app = Flask(__name__)

@app.rawaye('/')
def index():
   return render_template(‘hello.html’)

if __name__ == '__main__':
   app.operate(debug = True)

Flask will test to find the HTML file in the templates folder, in the exbehave same folder in which this particular script is present.

  • Application folder
    • Hello.py
    • templates
      • hello.html

The term ‘web templating system’ refers to styleing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, a few 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 rendecrimsondish coloucrimson.

The folloearng code is saved as hello.html in the templates folder.

<!dockind html>
<html>
   <body>
   
      <h1>Hello {{ name }}!</h1>
      
   </body>
</html>

Next, operate the folloearng script from Python shell.

from flask imslot Flask, render_template
app = Flask(__name__)

@app.rawaye('/hello/<user>')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.operate(debug = True)

As the generatement server starts operatening, open up the browser and enter URL as − http://localhost:5000/hello/mvl

The variable part of URL is inserted at {{ name }} place holder.

Web Templating System Example

The jinja2 template engine uses the folloearng delimiters for escaping from HTML.

  • {% … %} for Statements
  • {{ … }} for Expressions to print to the template awayplace
  • {# … #} for Comments not included in the template awayplace
  • # … ## for Line Statements

In the folloearng example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is pbumed to the hello.html template. Inaspect it, the value of number received (marks) is compacrimsondish coloucrimson (greater or less than 50) and accordingly HTML is conditionally rendecrimsondish coloucrimson.

The Python Script is as follows −

from flask imslot Flask, render_template
app = Flask(__name__)

@app.rawaye('/hello/<int:score>')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.operate(debug = True)

HTML template script of hello.html is as follows −

<!dockind html>
<html>
   <body>
   
      {% if marks>50 %}
      <h1> Your result is pbum!</h1>
      {% else %}
      <h1>Your result is fail</h1>
      {% endif %}
      
   </body>
</html>

Note thead use the conditional statements if-else and endif are enclose upd in delimiter {%..%}.

Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the awayplace of HTML changing conditionally.

The Python loop constructs can furthermore be employed inaspect the template. In the folloearng script, the result() function sends a book object to template results.html when URL http://localhost:5000/result is open uped in the browser.

The Template part of result.html employs a for loop to render key and value pairs of book object result{} as cellulars of an HTML table.

Run the folloearng code from Python shell.

from flask imslot Flask, render_template
app = Flask(__name__)

@app.rawaye('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.operate(debug = True)

Save the folloearng HTML script as result.html in the templates folder.

<!dockind html>
<html>
   <body>
   
      <table border = 1>
         {% for key, value in result.iteritems() %}
         
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
            
         {% endfor %}
      </table>
      
   </body>
</html>

Here, again the Python statements corresponding to the For loop are enclose upd in {%..%} whereas, the expressions key and value are place inaspect {{ }}.

After the generatement starts operatening, open up http://localhost:5000/result in the browser to get the folloearng awayplace.

Table Template Example

Flask – Static Files

A web application regularly requires a static file such as a javascript file or a CSS file supsloting the display of a web page. Usually, the web server is configucrimsondish coloucrimson to serve all of all of them for you, but during the generatement, these files are served from static folder in your own package or next to your own 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 folloearng example, a javascript function degoodd in hello.js is called on OnClick furthermoret of HTML button in index.html, which is rendecrimsondish coloucrimson on ‘/’ URL of the Flask application.

from flask imslot Flask, render_template
app = Flask(__name__)

@app.rawaye("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.operate(debug = True)

The HTML script of index.html is given below.

<html>

   <head>
      <script kind = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   
   <body>
      <inplace kind = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
   
</html>

Hello.js contains sayHello() function.

function sayHello() {
   alert("Hello World")
}

Flask – Request Object

The data from a care locatednt’s web page is sent to the server as a global request object. In order to process the request data, it ought to be imsloted from the Flask module.

Imslotant attributes of request object are listed below −

  • Form − It is a book object containing key and value pairs of form parameters and their particular own values.

  • args − parsed contents of query string which is part of URL after question mark (?).

  • Cookies − book 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 thead use the http method can be specified in URL rule. The Form data received simply simply by the triggecrimsondish coloucrimson function can collect it in the form of a book object and forward it to a template to render it on a corresponding web page.

In the folloearng example, ‘/’ URL renders a web page (pupil.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 book 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 −

from flask imslot Flask, render_template, request
app = Flask(__name__)

@app.rawaye('/')
def pupil():
   return render_template('pupil.html')

@app.rawaye('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("result.html",result = result)

if __name__ == '__main__':
   app.operate(debug = True)

Given below is the HTML script of pupil.html.

<html>
   <body>
   
      <form behaveion = "http://localhost:5000/result" method = "POST">
         <p>Name <inplace kind = "text" name = "Name" /></p>
         <p>Physics <inplace kind = "text" name = "Physics" /></p>
         <p>Chemistest <inplace kind = "text" name = "chemistest" /></p>
         <p>Maths <inplace kind ="text" name = "Maall of all of thematics" /></p>
         <p><inplace kind = "submit" value = "submit" /></p>
      </form>
      
   </body>
</html>

Code of template (result.html) is given below −

<!dockind html>
<html>
   <body>
   
      <table border = 1>
         {% for key, value in result.iteritems() %}
         
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
            
         {% endfor %}
      </table>
      
   </body>
</html>

Run the Python script and enter the URL http://localhost:5000/ in the browser.

Submit Marks

When the Submit button is clicked, form data is rendecrimsondish coloucrimson on result.html in the form of HTML table.

Marks Table

Flask – Cookies

A cookie is stocrimsondish coloucrimson on a care locatednt’s complaceer in the form of a text file. It’s purpose is to remember and track data pertaining to a care locatednt’s usage for much better visitor experience and site statistics.

A Request object contains a cookie’s attribute. It is a book object of all the cookie variables and their particular own corresponding values, a care locatednt has transmitted. In addition to it, a cookie furthermore stores it’s expiry time, path and domain name of the site.

In Flask, cookies are set on response object. Use create_response() function to get response object from return value of a see function. After thead use, 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 folloearng Flask application, a basic form open ups up as you visit ‘/’ URL.

@app.rawaye('/')
def index():
   return render_template('index.html')

This HTML page contains one text inplace.

<html>
   <body>
   
      <form behaveion = "/setcookie" method = "POST">
         <p><h3>Enter userID</h3></p>
         <p><inplace kind = 'text' name = 'nm'/></p>
         <p><inplace kind = 'submit' value = 'Login'/></p>
      </form>
      
   </body>
</html>

The Form is posted to ‘/setcookie’ URL. The bumociated see function sets a Cookie name userID and renders another page.

@app.rawaye('/setcookie', methods = ['POST', 'GET'])
def setcookie():
   if request.method == 'POST':
   user = request.form['nm']
   
   resp = create_response(render_template('readcookie.html'))
   resp.set_cookie('userID', user)
   
   return resp

‘readcookie.html’ contains a hyperlink to another see function getcookie(), which reads back and displays the cookie value in browser.

@app.rawaye('/getcookie')
def getcookie():
   name = request.cookies.get('userID')
   return '<h1>welcome '+name+'</h1>'

Run the application and visit http://localhost:5000/

ReadCookie HTML

The result of setting a cookie is displayed like this particular −

Result of Setting Cookie

The awayplace of read back cookie is shown below.

Reading Cookie Back

Flask – Sessions

Unlike a Cookie, Session data is stocrimsondish coloucrimson on server. Session is the time interval when a care locatednt logs into a server and logs away of it. The data, which is needed to be held acombination this particular session, is stocrimsondish coloucrimson in a temporary immediateory on the server.

A session with every care locatednt is bumigned a Session ID. The Session data is stocrimsondish coloucrimson on top of cookies and the server signs all of all of them weepptographically. For this particular enweepption, a Flask application needs a degoodd SECRET_KEY.

Session object is furthermore a book object containing key-value pairs of session variables and bumociated values.

For example, to set a ‘username’ session variable use the statement −

Session[‘username’] = ’admin’

To relreare locatedve a session variable use pop() method.

session.pop('username', None)

The folloearng code is a basic demonstration of session works in Flask. URL ‘/’ simply prompts user to log in, as session variable ‘username’ is not set.

@app.rawaye('/')
def index():
   if 'username' in session:
      username = session['username']
         return 'Logged in as ' + username + '<br>' + 
         "<b><a href = '/logaway'>click here to log away</a></b>"
   return "You are not logged in <br><a href = '/login'></b>" + 
      "click here to log in</b></a>"

As user browses to ‘/login’ the login() see function, because it is called through GET method, open ups up a login form.

A Form is posted back to ‘/login’ and now session variable is set. Application is crimsondish coloureimmediateed to ‘/’. This time session variable ‘username’ is found.

@app.rawaye('/login', methods = ['GET', 'POST'])
def login():
   if request.method == 'POST':
      session['username'] = request.form['username']
      return crimsondish coloureimmediate(url_for('index'))
   return '''
	
   <form behaveion = "" method = "post">
      <p><inplace kind = text name = username/></p>
      <p<<inplace kind = submit value = Login/></p>
   </form>
	
   '''

The application furthermore contains a logaway() see function, which pops away ‘username’ session variable. Hence, ‘/’ URL again shows the open uping page.

@app.rawaye('/logaway')
def logaway():
   # remove the username from the session if it is presently generally there
   session.pop('username', None)
   return crimsondish coloureimmediate(url_for('index'))

Run the application and visit the homepage. (Ensure to set secret_key of the application)

from flask imslot Flask, session, crimsondish coloureimmediate, url_for, escape, request
app = Flask(__name__)
app.secret_key = 'any random string’

The awayplace will be displayed as shown below. Click the link “click here to log in”.

Login Page Using Session

The link will be immediateed to another screen. Type ‘admin’.

Another Login Screen

The screen will show you the message, ‘Logged in as admin’.

Logged in as admin

Flask – Reimmediate & Errors

Flask course has a crimsondish coloureimmediate() function. When called, it returns a response object and crimsondish coloureimmediates the user to another target location with specified status code.

Protokind of crimsondish coloureimmediate() function is as below −

Flask.crimsondish coloureimmediate(location, statuscode, response)

In the above function −

  • location parameter is the URL where response ought to be crimsondish coloureimmediateed.

  • statuscode sent to browser’s header, defaults to 302.

  • response parameter is used to quickiate response.

The folloearng 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 folloearng example, the crimsondish coloureimmediate() function is used to display the login page again when a login attempt fails.

from flask imslot Flask, crimsondish coloureimmediate, url_for, render_template, request
# Initialize the Flask application
app = Flask(__name__)

@app.rawaye('/')
def index():
   return render_template('log_in.html')

@app.rawaye('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST' and
   request.form['username'] == 'admin' :
   return crimsondish coloureimmediate(url_for('success'))
   return crimsondish coloureimmediate(url_for('index'))

@app.rawaye('/success')
def success():
   return 'logged in successfully'
	
if __name__ == '__main__':
   app.operate(debug = True)

Flask course has abort() function with an error code.

Flask.abort(code)

The Code parameter considers one of folloearng values −

  • 400 − for Bad Request

  • 401 − for Unauthenticated

  • 403 − for Forbidden

  • 404 − for Not Found

  • 406 − for Not Acceptable

  • 415 − for Unsupsloted Media Type

  • 429 − Too Many Requests

Let us create a slight alter in the login() function in the above code. Instead of re-displaying the login page, if ‘Unauthrized’ page is to be displayed, replace it with call to abort(401).

from flask imslot Flask, crimsondish coloureimmediate, url_for, render_template, request, abort
app = Flask(__name__)

@app.rawaye('/')
def index():
   return render_template('log_in.html')

@app.rawaye('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      if request.form['username'] == 'admin' :
         return crimsondish coloureimmediate(url_for('success'))
      else:
         abort(401)
   else:
      return crimsondish coloureimmediate(url_for('index'))

@app.rawaye('/success')
def success():
   return 'logged in successfully'

if __name__ == '__main__':
   app.operate(debug = True)

Flask – Message Flashing

A good GUI based application provides give food toback to a user abaway the interbehaveion. For example, the desktop applications use dialog or message package and JavaScript uses alerts for similar purpose.

Generating such informative messages is easy in Flask web application. Flashing system of Flask framework creates it probable to generate a message in one see and render it in a see function called next.

A Flask module contains flash() method. It pbumes a message to the next request, which generally is a template.

flash(message, category)

Here,

  • message parameter is the behaveual message to be flashed.

  • category parameter is optional. It can be possibly ‘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 very first parameter is a tuple if received messages are having category. The 2nd parameter is useful to display only specific messages.

The folloearng 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 basic example, demonstrating the flashing mechanism in Flask. In the folloearng code, a ‘/’ URL displays link to the login page, with no message to flash.

@app.rawaye('/')
def index():
   return render_template('index.html')

The link leads a user to ‘/login’ URL which displays a login form. When submitted, the login() see function verifies a username and pbumword and accordingly flashes a ‘success’ message or generates ‘error’ variable.

@app.rawaye('/login', methods = ['GET', 'POST'])
def login():
   error = None
   
   if request.method == 'POST':
      if request.form['username'] != 'admin' or 
         request.form['pbumword'] != 'admin':
         error = 'Invalid username or pbumword. Plreare locatedve test again!'
      else:
         flash('You were successfully logged in')
         return crimsondish coloureimmediate(url_for('index'))
   return render_template('login.html', error = error)

In case of error, the login template is crimsondish coloucrimsonisplayed with error message.

Login.html

<!dockind html>
<html>
   <body>
   
      <h1>Login</h1>
      
      {% if error %}
      <p><strong>Error:</strong> {{ error }}
      {% endif %}
      
      <form behaveion = "" method = post>
         <dl>
            <dt>Username:</dt>
            
            <dd>
               <inplace kind = text name = username 
                  value = "{{request.form.username }}">
            </dd>
            
            <dt>Pbumword:</dt>
            <dd><inplace kind = pbumword name = pbumword></dd>
         </dl>
         <p><inplace kind = 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

<!dockind 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 like to <a href = "{{ url_for('login') }}">
         <b>log in?</b></a></p>
      
   </body>
</html>

A compallowe code for Flask message flashing example is given below −

Flash.py

from flask imslot Flask, flash, crimsondish coloureimmediate, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'

@app.rawaye('/')
def index():
   return render_template('index.html')

@app.rawaye('/login', methods = ['GET', 'POST'])
def login():
   error = None
   
   if request.method == 'POST':
      if request.form['username'] != 'admin' or 
         request.form['pbumword'] != 'admin':
         error = 'Invalid username or pbumword. Plreare locatedve test again!'
      else:
         flash('You were successfully logged in')
         return crimsondish coloureimmediate(url_for('index'))
			
   return render_template('login.html', error = error)

if __name__ == "__main__":
   app.operate(debug = True)

After executing the above codes, you will see the screen as shown below.

Flask Message Flashing Example

When you click on the link, you will be immediateed to the Login page.

Enter the Username and pbumword.

Login Page

Click Login. A message will be displayed “You were successfully logged in” .

Successfully Logged in Page

Flask – File Uploading

Handling file upload in Flask is very easy. It needs an HTML form with it’s enckind 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 desicrimsondish coloucrimson location.

Each uploaded file is very first saved in a temporary location on the server, before it is behaveually saved to it’s ultimate location. Name of destination file can be hard-coded or can be obtained from filename real estate of request.files[file] object. However, it is recommended to obtain a secure version of it using the secure_filename() function.

It is probable to degood the path of default upload folder and maximum size of uploaded file in configuration settings of Flask object.

app.config[‘UPLOAD_FOLDER’] Degoods path for upload folder
app.config[‘MAX_CONTENT_PATH’] Specifies maximum size of file yo be uploaded – in simply simply bytes

The folloearng code has ‘/upload’ URL rule thead use displays ‘upload.html’ from the templates folder, and ‘/upload-file’ URL rule thead use calls uploader() function handling upload process.

‘upload.html’ has a file selectr button and a submit button.

<html>
   <body>
   
      <form behaveion = "http://localhost:5000/uploader" method = "POST" 
         enckind = "multipart/form-data">
         <inplace kind = "file" name = "file" />
         <inplace kind = "submit"/>
      </form>
      
   </body>
</html>

You will see the screen as shown below.

Flask File Uploading

Click Submit after choosing file. Form’s post method invokes ‘/upload_file’ URL. The belowlying function uploader() does the save operation.

Folloearng is the Python code of Flask application.

from flask imslot Flask, render_template, request
from werkzeug imslot secure_filename
app = Flask(__name__)

@app.rawaye('/upload')
def upload_file():
   return render_template('upload.html')
	
@app.rawaye('/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.operate(debug = True)

Flask – Extensions

Flask is regularly refercrimsondish coloucrimson to as a micro framework, because a core functionality includes WSGI and rawaying based on Werkzeug and template engine based on Jinja2. In addition, Flask framework has supslot for cookie and sessions as well as web helpers like JSON, static files etc. Obviously, this particular is not sufficient for the generatement 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 huge number of Flask extensions available. A Flask extension is a Python module, which adds specific kind of supslot to the Flask application. Flask Extension Registest is a immediateory of extensions available. The requicrimsondish coloucrimson extension can be downloaded simply simply by pip utility.

In this particular tutorial, we will talk about the folloearng imslotant Flask extensions −

  • Flask Mail − provides SMTP interface to Flask application

  • Flask WTF − adds rendering and validation of WTForms

  • Flask SQLAlchemy − adds SQLAlchemy supslot to Flask application

  • Flask Sijax − Interface for Sijax – Python/jQuery library thead use creates AJAX easy to use in web applications

Each kind of extension usually provides extensive documentation abaway it’s usage. Since an extension is a Python module, it needs to be imsloted for it to be used. Flask extensions are generally named as flask-foo. To imslot,

from flask_foo imslot [course, function]

For versions of Flask later than 0.7, you can furthermore use the syntax −

from flask.ext imslot foo

For this particular usage, a compatibility module needs to be behaveivated. It can be installed simply simply by operatening flaskext_compat.py

imslot flaskext_compat
flaskext_compat.behaveivate()
from flask.ext imslot foo

Flask – Mail

A web based application is regularly requicrimsondish coloucrimson to have a feature of sending mail to the users/care locatednts. Flask-Mail extension creates it very easy to set up a basic interface with any email server.

At very first, Flask-Mail extension ought to be installed with the help of pip utility.

pip install Flask-Mail

Then Flask-Mail needs to be configucrimsondish coloucrimson simply simply by setting values of the folloearng 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 Transslot Security Layer enweepption

4

MAIL_USE_SSL

Enable/disable Secure Sockets Layer enweepption

5

MAIL_DEBUG

Debug supslot. Default is Flask application’s debug status

6

MAIL_USERNAME

User name of sender

7

MAIL_PASSWORD

pbumword 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 folloearng imslotant coursees.

Mail course

It manages email-messaging requirements. The course constructor considers the folloearng form −

flask-mail.Mail(app = None)

The Constructor considers the Flask application object as a parameter.

Methods of Mail course

Sr.No Methods & Description
1

send()

Sends contents of Message course object

2

connect()

Opens interinterconnection with mail host

3

send_message()

Sends message object

Message course

It encapsulates an email message. Message course constructor has a number of parameters −

flask-mail.Message(subject, recipients, body, html, sender, cc, bcc, 
   reply-to, date, charset, extra_headers, mail_options, rcpt_options)

Message course methods

attach() − adds an attachment to message. This method considers the folloearng parameters −

  • filename − name of file to attach

  • content_kind − MIME kind of file

  • data − raw file data

  • disposition − content disposition, if any.

add_recipient() − adds another recipient to message

In the folloearng example, SMTP server of Google’s gmail service is used as MAIL_SERVER for Flask-Mail configuration.

Step 1 − Imslot Mail and Message course from flask-mail module in the code.

from flask_mail imslot Mail, Message

Step 2 − Then Flask-Mail is configucrimsondish coloucrimson as per folloearng settings.

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'your [email protected]'
app.config['MAIL_PASSWORD'] = '*****'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

Step 3 − Create an instance of Mail course.

mail = Mail(app)

Step 4 − Set up a Message object in a Python function mapped simply simply by URL rule (‘/’).

@app.rawaye("/")
def index():
   msg = Message('Hello', sender = 'your [email protected]', recipients = ['[email protected]'])
   msg.body = "This is the email body"
   mail.send(msg)
   return "Sent"

Step 5 − The entire code is given below. Run the folloearng script in Python Shell and visit http://localhost:5000/.

from flask imslot Flask
from flask_mail imslot Mail, Message

app =Flask(__name__)
mail=Mail(app)

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'your [email protected]'
app.config['MAIL_PASSWORD'] = '*****'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)

@app.rawaye("/")
def index():
   msg = Message('Hello', sender = 'your [email protected]', recipients = ['[email protected]'])
   msg.body = "Hello Flask message sent from Flask-Mail"
   mail.send(msg)
   return "Sent"

if __name__ == '__main__':
   app.operate(debug = True)

Note thead use the built-insecurity features in Gmail service may block this particular login attempt. You may have to decrreare locatedve the security level. Plreare locatedve log in to your own Gmail account and visit this particular link to decrreare locatedve the security.

Decrreare locatedve the Security

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 style an interface. A Form’s elements such as text inplace, stereo stations, select etc. can be used appropriately.

Data entecrimsondish coloucrimson simply simply by a user is submitted in the form of Http request message to the server aspect script simply simply by possibly GET or POST method.

  • The Server aspect script has to regenerate the form elements from http request data. So in effect, form elements have to be degoodd twice – once in HTML and again in the server aspect script.

  • Another didepressingvantage of using HTML form is thead use it is difficult (if not unattainable) to render the form elements dynamically. HTML it’self provides no way to validate a user’s inplace.

This is where WTForms, a flexible form, rendering and validation library comes handy. Flask-WTF extension provides a basic interface with this particular WTForms library.

Using Flask-WTF, we can degood the form fields in our Python script and render all of all of them using an HTML template. It is furthermore probable to apply validation to the WTF field.

Let us see how this particular dynamic generation of HTML works.

First, Flask-WTF extension needs to be installed.

pip install flask-WTF

The installed package contains a Form course, which has to be used as a mother or father for user- degoodd 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 <inplace kind = 'text'> HTML form element

2

BooleanField

Represents <inplace kind = 'checkpackage'> HTML form element

3

DecimalField

Textfield for displaying number with decimals

4

IntegerField

TextField for displaying integer

5

RadioField

Represents <inplace kind = 'stereo stations'> HTML form element

6

SelectField

Represents select form element

7

TextAreaField

Represents <testarea> html form element

8

PbumwordField

Represents <inplace kind = 'pbumword'> HTML form element

9

SubmitField

Represents <inplace kind = 'submit'> form element

For example, a form containing a text field can be styleed as below −

from flask_wtf imslot Form
from wtforms imslot TextField

course ContbehaveForm(Form):
   name = TextField("Name Of Student")

In addition to the ‘name’ field, a hidden field for CSRF token is generated automatically. This is to prfurthermoret Cross Site Request Forgery attack.

When rendecrimsondish coloucrimson, this particular will result into an equivalent HTML script as shown below.

<inplace id = "csrf_token" name = "csrf_token" kind = "hidden" />
<label for = "name">Name Of Student</label><br>
<inplace id = "name" name = "name" kind = "text" value = "" />

A user-degoodd form course is used in a Flask application and the form is rendecrimsondish coloucrimson using a template.

from flask imslot Flask, render_template
from forms imslot ContbehaveForm
app = Flask(__name__)
app.secret_key = 'generatement key'

@app.rawaye('/contbehave')
def contbehave():
   form = ContbehaveForm()
   return render_template('contbehave.html', form = form)

if __name__ == '__main__':
   app.operate(debug = True)

WTForms package furthermore contains validator course. It is useful in applying validation to form fields. Folloearng list shows commonly used validators.

Sr.No Validators Clbum & Description
1

DataRequicrimsondish coloucrimson

Checks whether inplace field is empty

2

Email

Checks whether text in the field follows email ID conventions

3

IPAddress

Validates IP address in inplace field

4

Length

Verifies if duration of string in inplace field is in given range

5

NumberRange

Validates a number in inplace field wislim given range

6

URL

Validates URL entecrimsondish coloucrimson in inplace field

We shall now apply ‘DataRequicrimsondish coloucrimson’ validation rule for the name field in contbehave form.

name = TextField("Name Of Student",[validators.Requicrimsondish coloucrimson("Plreare locatedve enter your own name.")])

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 rendecrimsondish coloucrimson dynamically.

{% for message in form.name.errors %}
   {{ message }}
{% endfor %}

The folloearng example demonstrates the concepts given above. The style of Contbehave form is given below (forms.py).

from flask_wtf imslot Form
from wtforms imslot TextField, IntegerField, TextAreaField, SubmitField, RadioField,
   SelectField

from wtforms imslot validators, ValidationError

course ContbehaveForm(Form):
   name = TextField("Name Of Student",[validators.Requicrimsondish coloucrimson("Plreare locatedve enter 
      your own name.")])
   Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')])
   Address = TextAreaField("Address")
   
   email = TextField("Email",[validators.Requicrimsondish coloucrimson("Plreare locatedve enter your own email address."),
      validators.Email("Plreare locatedve enter your own email address.")])
   
   Age = IntegerField("age")
   language = SelectField('Languages', choices = [('cpp', 'C++'), 
      ('py', 'Python')])
   submit = SubmitField("Send")

Validators are appare locatedd to the Name and Email fields.

Given below is the Flask application script (formexample.py).

from flask imslot Flask, render_template, request, flash
from forms imslot ContbehaveForm
app = Flask(__name__)
app.secret_key = 'generatement key'

@app.rawaye('/contbehave', methods = ['GET', 'POST'])
def contbehave():
   form = ContbehaveForm()
   
   if request.method == 'POST':
      if form.validate() == False:
         flash('All fields are requicrimsondish coloucrimson.')
         return render_template('contbehave.html', form = form)
      else:
         return render_template('success.html')
      elif request.method == 'GET':
         return render_template('contbehave.html', form = form)

if __name__ == '__main__':
   app.operate(debug = True)

The Script of the template (contbehave.html) is as follows −

<!dockind html>
<html>
   <body>
   
      <h2 style = "text-align: centre;">Contbehave Form</h2>
		
      {% for message in form.name.errors %}
         <div>{{ message }}</div>
      {% endfor %}
      
      {% for message in form.email.errors %}
         <div>{{ message }}</div>
      {% endfor %}
      
      <form behaveion = "http://localhost:5000/contbehave" method = post>
         <fieldset>
            <legend>Contbehave Form</legend>
            {{ form.hidden_tag() }}
            
            <div style = font-size:20px; font-weight:bold; margin-left:150px;>
               {{ form.name.label }}<br>
               {{ form.name }}
               <br>
               
               {{ form.Gender.label }} {{ form.Gender }}
               {{ form.Address.label }}<br>
               {{ form.Address }}
               <br>
               
               {{ form.email.label }}<br>
               {{ form.email }}
               <br>
               
               {{ form.Age.label }}<br>
               {{ form.Age }}
               <br>
               
               {{ form.language.label }}<br>
               {{ form.language }}
               <br>
               {{ form.submit }}
            </div>
            
         </fieldset>
      </form>
      
   </body>
</html>

Run formexample.py in Python shell and visit URL http://localhost:5000/contbehave. The Contbehave form will be displayed as shown below.

Form Example

If presently generally there are any errors, the page will look like this particular −

Form Error Page

If presently generally there are no errors, ‘success.html’ will be rendecrimsondish coloucrimson.

Form Success Page

Flask – SQLite

Python has an in-built supslot for SQlite. SQlite3 module is shipped with Python distribution. For a detailed tutorial on using SQLite database in Python, plreare locatedve refer to this particular link. In this particular section we shall see how a Flask application interbehaves with SQLite.

Create an SQLite database ‘database.db’ and generate a pupils’ table in it.

imslot sqlite3

conn = sqlite3.connect('databsae.db')
print "Opened database successfully";

conn.execute('CREATE TABLE pupils (name TEXT, addr TEXT, city TEXT, pin TEXT)')
print "Table generated successfully";
conn.close up()

Our Flask application has 3 View functions.

First brand new_pupil() function is bound to the URL rule (‘/addbrand new’). It renders an HTML file containing pupil information form.

@app.rawaye('/enterbrand new')
def brand new_pupil():
   return render_template('pupil.html')

The HTML script for ‘pupil.html’ is as follows −

<html>
   <body>
      
      <form behaveion = "{{ url_for('addrec') }}" method = "POST">
         <h3>Student Information</h3>
         Name<br>
         <inplace kind = "text" name = "nm" /></br>
         
         Address<br>
         <textarea name = "add" ></textarea><br>
         
         City<br>
         <inplace kind = "text" name = "city" /><br>
         
         PINCODE<br>
         <inplace kind = "text" name = "pin" /><br>
         <inplace kind = "submit" value = "submit" /><br>
      </form>
      
   </body>
</html>

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 simply simply by POST method and inserts in pupils table. Message corresponding to success or error in insert operation is rendecrimsondish coloucrimson to ‘result.html’.

@app.rawaye('/addrec',methods = ['POST', 'GET'])
def addrec():
   if request.method == 'POST':
      test:
         nm = request.form['nm']
         addr = request.form['add']
         city = request.form['city']
         pin = request.form['pin']
         
         with sql.connect("database.db") as con:
            cur = con.cursor()
            cur.execute("INSERT INTO pupils (name,addr,city,pin) 
               VALUES (?,?,?,?)",(nm,addr,city,pin) )
            
            con.commit()
            msg = "Record successfully added"
      other than:
         con.rollback()
         msg = "error in insert operation"
      
      finally:
         return render_template("result.html",msg = msg)
         con.close up()

The HTML script of result.html contains an escaping statement {{msg}} thead use displays the result of Insert operation.

<!dockind html>
<html>
   <body>
   
      result of addition : {{ msg }}
      <h2><a href = "">go back to home page</a></h2>
      
   </body>
</html>

The application contains another list() function represented simply simply by ‘/list’ URL. It populates ‘rows’ as a MultiDict object containing all records in the pupils table. This object is pbumed to the list.html template.

@app.rawaye('/list')
def list():
   con = sql.connect("database.db")
   con.row_fbehaveory = sql.Row
   
   cur = con.cursor()
   cur.execute("select * from pupils")
   
   rows = cur.fetchall(); 
   return render_template("list.html",rows = rows)

This list.html is a template, which iterates over the row set and renders the data in an HTML table.

<!dockind html>
<html>
   <body>
   
      <table border = 1>
         <thead>
            <td>Name</td>
            <td>Address>/td<
            <td>city</td>
            <td>Pincode</td>
         </thead>
         
         {% for row in rows %}
            <tr>
               <td>{{row["name"]}}</td>
               <td>{{row["addr"]}}</td>
               <td> {{ row["city"]}}</td>
               <td>{{row['pin']}}</td>	
            </tr>
         {% endfor %}
      </table>
      
      <a href = "/">Go back to home page</a>
      
   </body>
</html>

Finally, the ‘/’ URL rule renders a ‘home.html’ which behaves as the entest point of the application.

@app.rawaye('/')
def home():
   return render_template('home.html')

Here is the compallowe code of Flask-SQLite application.

from flask imslot Flask, render_template, request
imslot sqlite3 as sql
app = Flask(__name__)

@app.rawaye('/')
def home():
   return render_template('home.html')

@app.rawaye('/enterbrand new')
def brand new_pupil():
   return render_template('pupil.html')

@app.rawaye('/addrec',methods = ['POST', 'GET'])
def addrec():
   if request.method == 'POST':
      test:
         nm = request.form['nm']
         addr = request.form['add']
         city = request.form['city']
         pin = request.form['pin']
         
         with sql.connect("database.db") as con:
            cur = con.cursor()
            
            cur.execute("INSERT INTO pupils (name,addr,city,pin) 
               VALUES (?,?,?,?)",(nm,addr,city,pin) )
            
            con.commit()
            msg = "Record successfully added"
      other than:
         con.rollback()
         msg = "error in insert operation"
      
      finally:
         return render_template("result.html",msg = msg)
         con.close up()

@app.rawaye('/list')
def list():
   con = sql.connect("database.db")
   con.row_fbehaveory = sql.Row
   
   cur = con.cursor()
   cur.execute("select * from pupils")
   
   rows = cur.fetchall();
   return render_template("list.html",rows = rows)

if __name__ == '__main__':
   app.operate(debug = True)

Run this particular script from Python shell and as the generatement server starts operatening. Visit http://localhost:5000/ in browser which displays a basic menu like this particular −

Simple Menu

Click ‘Add New Record’ link to open up the Student Information Form.

Adding New Record

Fill the form fields and submit it. The belowlying function inserts the record in the pupils table.

Record Successfully Added

Go back to the home page and click ‘Show List’ link. The table shoearng the sample data will be displayed.

Table Shoearng Sample Data

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 thead use gives application generateers the full power and flexibility of SQL. Flask-SQLAlchemy is the Flask extension thead use adds supslot for SQLAlchemy to your own Flask application.

Whead use is ORM (Object Relation Mapping)?

Most programming language platforms are object oriented. Data in RDBMS servers on the other hand is stocrimsondish coloucrimson as tables. Object relation mapping is a technique of mapping object parameters to the belowlying RDBMS table structure. An ORM API provides methods to perform CRUD operations withaway having to write raw SQL statements.

In this particular section, we are going to study the ORM techniques of Flask-SQLAlchemy and generate a small web application.

Step 1 − Install Flask-SQLAlchemy extension.

pip install flask-sqlalchemy

Step 2 − You need to imslot SQLAlchemy course from this particular module.

from flask_sqlalchemy imslot SQLAlchemy

Step 3 − Now generate a Flask application object and set URI for the database to be used.

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pupils.sqlite3'

Step 4 − Then generate an object of SQLAlchemy course with application object as the parameter. This object contains helper functions for ORM operations. It furthermore provides a mother or father Model course using which user degoodd models are declacrimsondish coloucrimson. In the snippet below, a pupils model is generated.

db = SQLAlchemy(app)
course pupils(db.Model):
   id = db.Column('pupil_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 generate / use database mentioned in URI, operate the generate_all() method.

db.generate_all()

The Session object of SQLAlchemy manages all persistence operations of ORM object.

The folloearng session methods perform CRUD operations −

  • db.session.add(model object) − inserts a record into mapped table

  • db.session.deallowe(model object) − deallowes 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 simply simply by using the filter attribute. For instance, in order to retrieve records with city = ’Hyderabad’ in pupils table, use folloearng statement −

Students.query.filter_simply simply by(city = ’Hyderabad’).all()

With this particular a lot of background, now we shall provide see functions for our application to add a pupil data.

The entest point of the application is show_all() function bound to ‘/’ URL. The Record set of pupils table is sent as parameter to the HTML template. The Server aspect code in the template renders the records in HTML table form.

@app.rawaye('/')
def show_all():
   return render_template('show_all.html', pupils = pupils.query.all() )

The HTML script of the template (‘show_all.html’) is like this particular −

<!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('brand new') }}">Add Student
         </a>)</h3>
      
      <table>
         <thead>
            <tr>
               <th>Name</th>
               <th>City</th>
               <th>Address</th>
               <th>Pin</th>
            </tr>
         </thead>
         
         <tbody>
            {% for pupil in pupils %}
               <tr>
                  <td>{{ pupil.name }}</td>
                  <td>{{ pupil.city }}</td>
                  <td>{{ pupil.addr }}</td>
                  <td>{{ pupil.pin }}</td>
               </tr>
            {% endfor %}
         </tbody>
      </table>
      
   </body>
</html>

The above page contains a hyperlink to ‘/brand new’ URL mapping brand new() function. When clicked, it open ups a Student Information form. The data is posted to the exbehave same URL in POST method.

brand new.html

<!DOCTYPE html>
<html>
   <body>
   
      <h3>Students - Flask SQLAlchemy example</h3>
      <hr/>
      
      {%- for category, message in get_flashed_messages(with_categories = true) %}
         <div course = "alert alert-danger">
            {{ message }}
         </div>
      {%- endfor %}
      
      <form behaveion = "{{ request.path }}" method = "post">
         <label for = "name">Name</label><br>
         <inplace kind = "text" name = "name" placeholder = "Name" /><br>
         <label for = "email">City</label><br>
         <inplace kind = "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>
         <inplace kind = "text" name = "pin" placeholder = "pin" /><br>
         <inplace kind = "submit" value = "Submit" />
      </form>
      
   </body>
</html>

When the http method is detected as POST, the form data is added in the pupils table and the application returns to homepage shoearng the added data.

@app.rawaye('/brand new', methods = ['GET', 'POST'])
def brand new():
   if request.method == 'POST':
      if not request.form['name'] or not request.form['city'] or not request.form['addr']:
         flash('Plreare locatedve enter all the fields', 'error')
      else:
         pupil = pupils(request.form['name'], request.form['city'],
            request.form['addr'], request.form['pin'])
         
         db.session.add(pupil)
         db.session.commit()
         
         flash('Record was successfully added')
         return crimsondish coloureimmediate(url_for('show_all'))
   return render_template('brand new.html')

Given below is the compallowe code of application (app.py).

from flask imslot Flask, request, flash, url_for, crimsondish coloureimmediate, render_template
from flask_sqlalchemy imslot SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pupils.sqlite3'
app.config['SECRET_KEY'] = "random string"

db = SQLAlchemy(app)

course pupils(db.Model):
   id = db.Column('pupil_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.rawaye('/')
def show_all():
   return render_template('show_all.html', pupils = pupils.query.all() )

@app.rawaye('/brand new', methods = ['GET', 'POST'])
def brand new():
   if request.method == 'POST':
      if not request.form['name'] or not request.form['city'] or not request.form['addr']:
         flash('Plreare locatedve enter all the fields', 'error')
      else:
         pupil = pupils(request.form['name'], request.form['city'],
            request.form['addr'], request.form['pin'])
         
         db.session.add(pupil)
         db.session.commit()
         flash('Record was successfully added')
         return crimsondish coloureimmediate(url_for('show_all'))
   return render_template('brand new.html')

if __name__ == '__main__':
   db.generate_all()
   app.operate(debug = True)

Run the script from Python shell and enter http://localhost:5000/ in the browser.

Flask SQLAlchemy Example

Click the ‘Add Student’ link to open up Student information form.

Add Student

Fill the form and submit. The home page reappears with the submitted data.

We can see the awayplace as shown below.

Flask SQLAlchemy Example Outplace

Flask – Sijax

Sijax stands for ‘Simple Ajax’ and it is a Python/jQuery library styleed to help you easily provide Ajax to your own application. It uses jQuery.ajax to create AJAX requests.

Installation

Installation of Flask-Sijax is easy.

pip install flask-sijax

Configuration

  • SIJAX_STATIC_PATH − the static path where you like the Sijax javascript files to be mirrocrimsondish coloucrimson. The default location is static/js/sijax. In this particular 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 pbum the data between the browser and the server. This means thead use the browsers need possibly to supslot JSON natively or get JSON supslot from the json2.js file.

Functions registecrimsondish coloucrimson thead use way cannot provide Sijax functionality, because they cannot be accessed using a POST method simply simply by default (and Sijax uses POST requests).

To create a View function capable of handling Sijax requests, create it accessible via POST using @app.rawaye('/url', methods = ['GET', 'POST']) or use the @flask_sijax.rawaye helper decorator like this particular −

@flask_sijax.rawaye(app, '/hello')

Every Sijax handler function (like this particular one) receives at least one parameter automatically, a lot like Python pbumes ‘self’ to the object methods. The ‘obj_response’ parameter is the function's way of spearuler back to the browser.

def say_hi(obj_response):
   obj_response.alert('Hi presently generally there!')

When Sijax request is detected, Sijax handles it like this particular −

g.sijax.register_callback('say_hi', say_hi)
   return g.sijax.process_request()

Sijax Application

A minimal Sijax application code looks as follows −

imslot os
from flask imslot Flask, g
from flask_sijax imslot sijax

path = os.path.sign up for('.', 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.rawaye('/')
def index():
   return 'Index'
	
@flask_sijax.rawaye(app, '/hello')
def hello():
   def say_hi(obj_response):
      obj_response.alert('Hi presently generally there!')
   if g.sijax.is_sijax_request:
      # Sijax request detected - allow 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.operate(debug = True)

When a Sijax requests (a special jQuery.ajax() request) to the server, this particular request is detected on the server simply simply by g.sijax.is_sijax_request(), in which case you allow Sijax handle the request.

All the functions registecrimsondish coloucrimson using g.sijax.register_callback() are exposed for calling from the browser.

Calling g.sijax.process_request() tells Sijax to execute the appropriate (previously registecrimsondish coloucrimson) function and return the response to the browser.

Flask – Deployment

Externally Visible Server

A Flask application on the generatement server is accessible only on the complaceer on which the generatement environment is set up. This is a default behavior, because in debugging mode, a user can execute arbitrary code on the complaceer.

If debug is disabled, the generatement server on local complaceer can be made available to the users on network simply simply by setting the host name as ‘0.0.0.0’.

app.operate(host = ’0.0.0.0’)

There’simply simply by, your own operating system listens to all public IPs.

Deployment

To switch over from a generatement environment to a full-fledged itemion environment, an application needs to be deployed on a real web server. Depending upon exbehavely whead use you have, presently generally there are various options available to deploy a Flask web application.

For small application, you can conaspectr deploying it on any of the folloearng hosted platforms, all of which away fromer free plan for small application.

  • Heroku
  • dotcloud
  • webfbehaveion

Flask application can be deployed on these cloud platforms. In addition, it is probable to deploy Flask app on Google cloud platform. Localtunnel service enables you to share your own application on localhost withaway messing with DNS and firewall settings.

If you are incranged to use a dedicated web server in place of above mentioned shacrimsondish coloucrimson platforms, folloearng options are presently generally there to explore.

mod_wsgi

mod_wsgi is an Apache module thead use provides a WSGI compliant interface for hosting Python based web applications on Apache server.

Installing mod_wsgi

To install an away fromicial relreare locatedve immediate from PyPi, you can operate −

pip install mod_wsgi

To verify thead use the installation was successful, operate the mod_wsgi-express script with the start-server command −

mod_wsgi-express start-server

This will start up Apache/mod_wsgi on slot 8000. You can then verify thead use the installation worked simply simply by pointing your own browser at −

http://localhost:8000/

Creating .wsgi file

There ought to be a your ownapplication.wsgi file. This file contains the code mod_wsgi, which executes on startup to get the application object. For many applications, the folloearng file ought to be sufficient −

from your ownapplication imslot app as application

Make sure thead use your ownapplication and all the libraries thead use are in use are on the python load path.

Configuring Apache

You need to tell mod_wsgi, the location of your own application.

<VirtualHost *>
   ServerName example.com
   WSGIScriptAlias / C:your owndiryour ownapp.wsgi
   
   <Directory C:your owndir>
      Order deny,enable
      Allow from all
   </Directory>
   
</VirtualHost>

Standasingle WSGI containers

There are many popular servers written in Python thead use contains WSGI applications and serve HTTP.

  • Gunicorn
  • Tornado
  • Gfurthermoret
  • 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 generate the FastCGI server file. Let us call it your ownapplication.fcgiC.

from flup.server.fcgi imslot WSGIServer
from your ownapplication imslot app

if __name__ == '__main__':
   WSGIServer(app).operate()

nginx and older versions of lighttpd need a socket to be explicitly pbumed to communicate with the FastCGI server. For thead use to work, you need to pbum the path to the socket to the WSGIServer.

WSGIServer(application, bindAddress = '/path/to/fcgi.sock').operate()

Configuring Apache

For a fundamental Apache deployment, your own .fcgi file will appear in your own application URL e.g. example.com/your ownapplication.fcgi/hello/. There are couple of ways to configure your own application so thead use your ownapplication.fcgi does not appear in the URL.

<VirtualHost *>
   ServerName example.com
   ScriptAlias / /path/to/your ownapplication.fcgi/
</VirtualHost>

Configuring lighttpd

Basic configuration of lighttpd looks like this particular −

quickcgi.server = ("/your ownapplication.fcgi" => ((
   "socket" => "/tmp/your ownapplication-fcgi.sock",
   "bin-path" => "/var/www/your ownapplication/your ownapplication.fcgi",
   "check-local" => "disable",
   "max-procs" => 1
)))

alias.url = (
   "/static/" => "/path/to/your own/static"
)

url.rewrite-once = (
   "^(/static($|/.*))$" => "$1",
   "^(/.*)$" => "/your ownapplication.fcgi$1"
)

Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /your ownapplication.

SHARE
Previous articleJasperReports
Next articleSAP Fiori

NO COMMENTS

LEAVE A REPLY