Home » Python

Introduction to Web development using Flask

Python flask: In this tutorial, we are going to learn about the introduction to web development using Flask in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on October 16, 2019

Python Flask

Flask< is a python API or a micro framework that enables the programmer to implement the web application. With less base code, a simple web-application could be implemented.

Flask is based on WSGI (Web Server Gateway Interface) toolkit and Jinja2 template engine.

The flask doesn't have native support for accessing the databases, validating the web forms, authenticating or any other high-level operations. These and other key services are available through the extensions that integrate with the core packages. One has to cherry-pick the extensions that work best for the project.

Flask Dependencies

Flask works on python version 2.6+. To use flask libraries, install the flask plugin ( https://pypi.org/project/Flask/) using PIP. Please note, here the environment chosen is Virtual Environment, and hence we use PIP.

from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET'])
def hello_world():
	return "Hello World\n"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005)

If we execute the above program, we see the below in the terminal,

(venv) -bash-4.2$ python3 hello_world_flask.py
 * Serving Flask app "hello_world_flask" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5005/ (Press CTRL+C to quit)

Here, '/' URL is bound with the "hello_world" function. When the home page of the webserver is opened in the browser, the output of this method is rendered.

web development using flask 1

We could also access the above URL using the 'curl' as below,

    -bash-4.2$ curl http://0.0.0.0:5005/
    Hello World
    -bash-4.2$

The flask application is started by invoking the run(). To enable the debug option, use the command app.run(debug=True), by default the debug option is turned off.

Routing

The routing technique is used to navigate to the right rest API directly from the URL. It is useful to access the web pages directly without navigating from the home page. The route() decorator is used to bind the URL.

@app.route('/include', methods=['GET']) # decorator
def include_help(): # binding to the method
	return "Welcome to Include Help\n"

On the browser, http://localhost:5005/include, will display the output of the include_help().

Reading the variables passed in query parameters

To read the variables sent over as query parameters, use the '<>'

# routing the decorator function include_help_welcome 
@app.route('/hello/<name>')   
def include_help_welcome(name): 
   return 'Hello {}, welcome to Include_help\n'.format(name)

The output for the above shall be

>> Using Curl

    -bash-4.2$ curl http://0.0.0.0:5005/hello/guest
    Hello guest, welcome to Include_help
    -bash-4.2$

>> In web browser

web development using flask 2


Support to HTTP methods

The Flask framework, supports the HTTP methods for a rest API, and they are,

Method Name Description
GET retrieves specific information from the server as identified by the request URI.
POST modifies data on the server from which a request was sent.
PUT requests that the message body sent with the request be stored under the location provided in the HTTP message.
DELETE deletes the specified resources.

Static files and templates

A web application always will have static files, like CSS and JS and templates like html files. The Flask application requires to have the following project structure to read the static files and template.

web development using flask 3

The Flask framework provides method like render_template to render the requested html file. Consider the below example,

from flask import Flask, render_template

app = Flask(__name__)

# routing the decorator function hello_name
@app.route('/hello/<name>')

def include_help_welcome(name):
	return render_template('index.html', user_name=name)
	
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5005)

The output of the above will be,

web development using flask 4


Redirect and errors

The redirect() method, when called returns a response object and redirects to another location with the provided status code.

Syntax:

    Flask.redirect(location, statuscode, response)

Here,

  • location = URL where the response shall be redirected
  • statuscode = default to 302
  • response = to initiate a response

The standard status code defined in the HTTP holds good here, which are,

    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 abort() method is used to terminate or end the session with an error code.

Syntax:

    Flask.abort(code)

The code parameter takes either of the following HTTP error codes,

    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



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.