python WSGL的使用

来源:互联网 发布:mysql分割字符 编辑:程序博客网 时间:2024/06/05 04:40

官方文档

WSGI is not a server, a python module, a framework, an API or any kind of software. It is just an interface specification by which server and application communicate. Both server and application interface sides are specified in the PEP 3333. If an application (or framework or toolkit) is written to the WSGI spec then it will run on any server written to that spec.

从官方文档的解释看,WSGL就是一个Web应用程序,通过这个Web应用程序实现客户端的请求.

  1. 浏览器发送一个HTTP请求;

  2. 服务器收到请求,生成一个HTML文档;

  3. 服务器把HTML文档作为HTTP响应的Body发送给浏览器;

  4. 浏览器收到HTTP响应,从HTTP Body取出HTML文档并显示。

WSGL的接口定义

WSGI application接口应该实现为一个可调用对象,例如函数、方法、类、含 call 方法的实例。这个可调用对象可以接收2个参数:

一个字典,该字典可以包含了客户端请求的信息以及其他信息,可以认为是请求上下文,一般叫做environment(编码中多简写为environ、env);
一个用于发送HTTP响应状态(HTTP status )、响应头(HTTP headers)的回调函数。
同时,可调用对象的返回值是响应正文(response body),响应正文是可迭代的、并包含了多个字符串。

此处定义一个函数即可,通过这个函数处理Http请求

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

完整代码如下:

# encoding=utf-8from wsgiref.simple_server import make_server# 使用environ获取请求类型和Url参数def my_application(environ, start_response):    start_response('200 OK', [{'Content-Type': 'text/html'}])    return '<h1>Hello World</h1>'# 创建一个服务器,监听端口为80httpd = make_server('', 80, my_application)print 'Service Start....'# 开始监听Http请求httpd.serve_forever()

启动此python脚本后,访问80端口(浏览器),可以看到”Hello World”字样

使用Flask框架处理Http请求

这里只介绍简单的Flask框架的使用,从最基本的路由转发功能开始

Flask使用装饰器的模式设置路由,需要在方法名前面加上@app.route()进行装饰

此处处理的路由
1. GET /:首页,返回Home;
2. GET /signin:登录页,显示登录表单;
3. POST /signin:处理登录表单,显示登录结果。

# coding=utf-8# !/usr/bin/env pythonfrom flask import Flaskfrom flask import requestapp = Flask(__name__)# Flask使用装饰器的模式设置路由@app.route('/', methods=['GET'])def home():    return '<h1>this is home page</h1>'@app.route('/signin', methods=['GET'])def sign_form():    return '''        <form action="/signin" method="post">            <p>用户名:<input name="username" /></p>            <p>密码:<input name="password" /></p>            <p><button type="submit">Sign In</button></p>        </form>    '''@app.route('/signin', methods=['POST'])def sign_in():    if request.form['username'] == 'admin' and request.form['password'] == '123':        return '<h2>Hello admin </h2>'    return '<h2>Invalid username or password</h2>'if __name__ == '__main__':    app.run()# 启动Web 监听,默认是5000端口
0 0