python之Web Server Gateway Interface

本文介绍了WSGI在Python Web开发中的作用,它作为一种接口规范,使得服务器能够封装HTTP协议并运行Web应用。通过示例代码展示了如何使用WSGI创建简单的Web应用,并启动一个基本的Web服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WSGI是pythonWEB编程的接口 相当于Java的servlet规范
服务器根据规范进行底层网络编程 封装HTTP协议
WEB应用开发更加规范编写应用
由服务器来运行WEB应用

根据WSGI编写一个小程序

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

用python中的wsgiref启动一个服务器

from wsgiref.simple_server import make_server
from mark.zhou.my_app import application
httpd = make_server('0.0.0.0', 8080, application)
print('Server HTTP on port 8000...')
httpd.serve_forever()
----------------------------成功访问--------
C:\Python\Python36\python.exe D:/IdeaProjects/python_basic/mark/zhou/my_simple_server.py
This is mark __init__.py
Server HTTP on port 8000...
127.0.0.1 - - [03/Oct/2017 16:57:03] "GET / HTTP/1.1" 200 19
127.0.0.1 - - [03/Oct/2017 16:57:03] "GET /favicon.ico HTTP/1.1" 200 19
127.0.0.1 - - [03/Oct/2017 16:57:03] "GET /favicon.ico HTTP/1.1" 200 19

def application(environ, start_response):

  • environ 封装了HTTP请求的内容
  • start_response 封装了响应的内容

    用environ从PATH_INFO中读取路径参数

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

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值