📖
zhaoqiang
  • Home
  • Python
    • Python Base
      • Grammar
      • Issue
    • Web DEV
      • Html
      • WebFrame
        • Flask
        • Django
      • WebTemplate
    • Web Crawler
  • Linux
    • Navieboom
    • Telegram Bot
      • RSSBot
      • TwitterBot
    • LetsEncrypt
      • ACME Create
      • ACME Install
    • NextCloud
      • NextCloud创建
      • NextCloud性能优化
    • Google
      • Google Drive
        • 离线下载
      • Chromium
    • Synology
      • Docker
        • 清理Docker占用的磁盘空间
      • Youtube-dl
      • 群晖—-外部访问DDNS教程(第一部分)
      • 群晖—-外部访问DDNS教程(第二部分)
      • SpeedTest - Install
      • BestTrace - Install
      • Rclone - Install
      • IPKG - Install
      • LEDE - Install
    • OpenWrt
      • Compile
        • Lean-4.14
        • Lean-4.9
    • LEDE
    • Linux Base
      • Command
      • Cron
  • DynamicsAX
    • Functions
      • Document Services
        • Auto Generate XML From AX
        • Load XML Files On Server
      • Webservice
      • DB Connect
      • DirectSQL
      • Email Alert
      • Auto Items
      • Auto BOM
      • Auto Order
      • Auto Invoice
      • Auto Packing
    • Data Import
      • Initial Static Data
      • initial Dynamic Data
        • Open SO
        • Open PO
        • Opening Balance
    • Access Right
    • Process
    • Instance
      • DYNAMICS 365 FOR OPERATION INSTANCE
  • Other Skills
    • Markdown
    • GIT
      • Command
    • Office365
Powered by GitBook
On this page

Was this helpful?

  1. Python
  2. Web DEV

WebFrame

Web Server Gateway Interface

WSGI处理函数

我们来看一个最简单的Web版本的“Hello, web!”:

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b'<h1>Hello, web!</h1>']

上面的application()函数就是符合WSGI标准的一个HTTP处理函数,它接收两个参数:

  • environ:一个包含所有HTTP请求信息的dict对象;

  • start_response:一个发送HTTP响应的函数。

有了WSGI,我们关心的就是如何从environ这个dict对象拿到HTTP请求信息,然后构造HTML,通过start_response()发送Header,最后返回Body。

WSGI服务器

Python内置了一个WSGI服务器,这个模块叫wsgiref

# server.py
# 从wsgiref模块导入:
from wsgiref.simple_server import make_server
# 导入我们自己编写的application函数:
from hello import application

# 创建一个服务器,IP地址为空,端口是8000,处理函数是application:
httpd = make_server('', 8000, application)
print('Serving HTTP on port 8000...')
# 开始监听HTTP请求:
httpd.serve_forever()

扩展

稍微改造一下,从environ里读取PATH_INFO,这样可以显示更加动态的内容

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
    return [body.encode('utf-8')]

PreviousHtmlNextFlask

Last updated 6 years ago

Was this helpful?