简易WSGI实现

1.使用python内置WSGI server

# WSGI server in Python
from wsgiref.simple_server import make_server
def application (environ, start_response):
    status = '200 OK'
    response_headers = [
        ('Content-Type', 'text/plain')]
    start_response(status, response_headers)
    return ["welcome to gevent lesson"]
# Instantiate the WSGI server.
# It will receive the request, pass it to the application
# and send the application's response to the client
httpd = make_server(
    'localhost', # The host name.
    8080, # A port number where to wait for the request.
    application # Our application object name, in this case a function.
    )

2.Flask内置WSGI测试和gevent wsgi结合Flask app

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello World!'
if __name__ == '__main__':
    app.run()
from flask import  Flask
import gevent.pywsgi
import gevent
app = Flask(__name__)
@app.route('/')
def handle():
    return 'welcome to gevent lesson!'
gevent_server = gevent.pywsgi.WSGIServer(('', 5000), app)
gevent_server.serve_forever()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WSGI(Web Server Gateway Interface)是Python Web应用程序和Web服务器之间的标准接口。它定义了Web服务器如何与Python应用程序通信,以及Python应用程序如何处理Web请求和响应。以下是WSGI在Python中的实现: 1. WSGI接口定义格式 WSGI接口定义了两个函数:一个是应用程序函数,另一个是服务器函数。应用程序函数接收两个参数:一个是包含请求信息的字典,另一个一个回调函数,用于发送响应。服务器函数接收两个参数:一个是应用程序函数,另一个是服务器环境信息。 2. WSGI的作用 WSGI的作用是将Web服务器和Python应用程序解耦,使得它们可以独立开发和部署。Web服务器只需要实现WSGI接口,Python应用程序只需要实现WSGI应用程序函数,它们之间的通信就可以通过WSGI接口完成。 3. 使用WSGI实现一个mini_frame(web框架) 下面是一个使用WSGI实现的mini_frame(web框架)的示例代码: ```python # mini_frame.py def index(): return "Hello World!" def login(): return "Login Page" def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) if env['PATH_INFO'] == '/index': return [index().encode()] elif env['PATH_INFO'] == '/login': return [login().encode()] else: return [b'404 Not Found'] ``` 上述代码中,我们定义了两个函数index和login,分别用于处理/index和/login请求。然后我们定义了一个WSGI应用程序函数application,它接收两个参数:一个是包含请求信息的字典env,另一个一个回调函数start_response,用于发送响应。在应用程序函数中,我们根据请求路径调用相应的处理函数,并返回响应内容。 4. WSGI实现方式 WSGI实现方式有很多种,其中比较常用的有以下几种: - 使用Python标准库中的wsgiref模块实现WSGI服务器。 - 使用第三方库,如Gunicorn、uWSGI实现WSGI服务器。 - 使用Web框架自带的WSGI服务器,如Flask、Django等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值