0
0
Flaskframework~5 mins

WSGI concept overview in Flask

Choose your learning style9 modes available
Introduction

WSGI is a simple way for web servers and Python apps to talk to each other. It helps your Flask app work on the web.

When you want your Flask app to handle web requests from users.
When you need your Python web app to work with different web servers.
When deploying your Flask app to a hosting service that supports WSGI.
When you want a standard way to connect your app and the web server.
When building any Python web app that needs to serve web pages or APIs.
Syntax
Flask
def application(environ, start_response):
    status = '200 OK'
    headers = [('Content-Type', 'text/plain; charset=utf-8')]
    start_response(status, headers)
    return [b'Hello, WSGI!']

environ is a dictionary with request info.

start_response is a function to start the HTTP response.

Examples
A minimal WSGI app that returns 'Hello World' as plain text.
Flask
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return [b'Hello World']
WSGI app that shows different responses based on the URL path.
Flask
def application(environ, start_response):
    path = environ.get('PATH_INFO', '/')
    if path == '/':
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'<h1>Home Page</h1>']
    else:
        start_response('404 Not Found', [('Content-Type', 'text/plain')])
        return [b'Page not found']
Sample Program

This program creates a simple WSGI server that listens on port 8000. It shows a welcome message on the home page and a 404 message on other paths.

Flask
from wsgiref.simple_server import make_server

# Simple WSGI app

def application(environ, start_response):
    path = environ.get('PATH_INFO', '/')
    if path == '/':
        start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
        return [b'<h1>Welcome to WSGI!</h1>']
    else:
        start_response('404 Not Found', [('Content-Type', 'text/plain; charset=utf-8')])
        return [b'Page not found']

# Run server on localhost:8000
with make_server('', 8000, application) as httpd:
    print('Serving on port 8000...')
    httpd.serve_forever()
OutputSuccess
Important Notes

WSGI apps return a list of byte strings as the response body.

Flask uses WSGI behind the scenes to connect your app to the web server.

You usually don't write WSGI apps directly when using Flask, but it's good to understand how it works.

Summary

WSGI is the bridge between Python web apps and web servers.

It uses a simple function with two arguments: environ and start_response.

Flask apps run on WSGI servers to handle web requests.