python之web框架(3):WSGI之web应用完善

1.上篇的web框架太low,只能实现回应固定页面。现在将它进行完善。首先将wsgi和web服务器进行分离,并给予它回复静态页面的能力。

  • web_server.py
#!/usr/bin/env python3
# coding:utf-8 from test_frame import app
from socket import *
from multiprocessing import Process class MyWebServer(object):
def start_response(self, status, head_list):
self.response_head = 'HTTP/1.1 ' + status + ' \r\n'
self.response_head = self.response_head.encode()
# print(self.response_head) def deal(self, conn):
recv_data = conn.recv(1024).decode('utf-8')
recv_data_head = recv_data.splitlines()[0]
# print('------recv_data_head: ', recv_data_head)
request_method, request_path, http_version = recv_data_head.split()
request_path = request_path.split('?')[0] # 去掉url中的?和之后的参数 env = {'request_method': request_method, 'request_path': request_path} # 这里是wsgi接口调用的地方
response_body = app(env, self.start_response) response_data = self.response_head + b'\r\n' + response_body
conn.send(response_data)
# print('response_data = ', response_data) def __init__(self):
self.s = socket(AF_INET, SOCK_STREAM)
self.s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.s.bind(('', 8000))
self.s.listen(1023)
self.response_head = '' def start(self):
while 1:
conn, user_info = self.s.accept()
print(user_info, '接入')
p = Process(target=self.deal, args=(conn,))
p.start()
conn.close() # 进程会复制出一个新的conn,所以这里的conn需要关闭 s = MyWebServer()
s.start()
  • test_frame.py
def app(env, start_response):
file_name = env['request_path']
if file_name == '/':
file_name = '/index.html'
try:
f = open('.' + file_name, 'rb')
except IOError:
status = '404 error'
head_list = [("name", "wanghui")]
start_response(status, head_list)
return b'<h1>File not found</h1>' status = '200 OK'
head_list = [("name", "wanghui")]
start_response(status, head_list)
read_data = f.read()
f.close()
return read_data

2.框架已经提供了静态页面的能力。下面对框架进一步完善。

  • web_server.py
#!/usr/bin/env python3
# coding:utf-8 from testframe import app
from socket import *
from multiprocessing import Process class MyWebServer(object):
def start_response(self, status, head_list):
self.response_head = 'HTTP/1.1 ' + status + ' \r\n'
self.response_head = self.response_head.encode() def deal(self, conn):
recv_data = conn.recv(1024).decode('utf-8')
recv_data_head = recv_data.splitlines()[0]
request_method, request_path, http_version = recv_data_head.split()
request_path = request_path.split('?')[0] # 去掉url中的?和之后的参数 env = {'request_method': request_method, 'request_path': request_path} # 这里是wsgi接口调用的地方
response_body = self.app(env, self.start_response) response_data = self.response_head + b'\r\n' + response_body
conn.send(response_data)
conn.close() def __init__(self, app, port=8000):
self.s = socket(AF_INET, SOCK_STREAM)
self.s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.s.bind(('', port))
self.s.listen(1023)
self.response_head = ''
self.app = app def start(self):
while 1:
conn, user_info = self.s.accept()
print(user_info, '接入')
p = Process(target=self.deal, args=(conn,))
p.start()
conn.close() # 进程会复制出一个新的conn,所以这里的conn需要关闭 s = MyWebServer(app)
s.start()
  • test_frame.py
import time

class Application(object):
def __init__(self, url_list):
self.url_list = url_list def __call__(self, env, start_response):
file_name = env['request_path']
if file_name == '/':
file_name = '/index.html' try:
f = open('.' + file_name, 'rb')
except IOError:
get_name = url_list.get(file_name, 'say_error')
return eval(get_name)(start_response) status = '200 OK'
head_list = [("name", "wanghui")]
start_response(status, head_list)
read_data = f.read()
f.close()
return read_data def say_error(start_response):
status = '404 error'
head_list = [("name", "wanghui")]
start_response(status, head_list)
return b'<h1>File not found</h1>' def say_time(start_response):
status = '200 OK'
head_list = [("name", "wanghui")]
start_response(status, head_list)
return time.ctime().encode() def say_hello(start_response):
status = '200 OK'
head_list = [("name", "wanghui")]
start_response(status, head_list)
return b'<h1>hello world</b>' url_list = {'/time.py': 'say_time',
'/error.py': 'say_error',
'/hello.py': 'say_hello',
}
app = Application(url_list)
  • 此时如果访问http://localhost/time.py,则会动态的将当前时间返回给客户。
  • 不过功能还不够完善,像不支持长连接,还不能支持外部py文件动态解析。

python之web框架(3):WSGI之web应用完善的更多相关文章

  1. python web框架 django wsgi 理论

    django wsgi python有个自带的wsgi模块 可以写自定义web框架 用wsgi在内部创建socket对象就可以了 自己只写处理函数就可以了django只是web框架 他也不负责写soc ...

  2. Python web框架开发 - WSGI协议

    浏览器进行http请求的时候,不单单会请求静态资源,还可能需要请求动态页面. 那么什么是静态资源,什么是动态页面呢? 静态资源 : 例如html文件.图片文件.css.js文件等,都可以算是静态资源 ...

  3. [py]彻底细究web框架的wsgi+逻辑处理模块

    wsgi逻辑结构初探 参考: 这里图很精彩,wsgi写的不错 web框架 = wsgi+逻辑处理app 接收请求,返回对应的内容 python wsgiref实现了wsgi规范. from wsgir ...

  4. Python 之WEB框架

    wsgi模块实现socketPython web框架: - 自己实现socket 代表:Tornado - 基于wsgi(一种规范,统一接口) 代表: Django 自己开发web框架(基于wsgi) ...

  5. Python Web 应用:WSGI基础

    在Django,Flask,Bottle和其他一切Python web 框架底层的是Web Server Gateway Interface,简称WSGI.WSGI对Python来说就像 Servle ...

  6. Python全栈开发-web框架之django

    一:web框架 什么是web框架? Web应用框架(Web application framework)是一种开发框架,用来支持动态网站.网络应用程序及网络服务的开发.这种框架有助于减轻网页开发时共通 ...

  7. Python学习 - 编写一个简单的web框架(一)

    自己动手写一个web框架,因为我是菜鸟,对于python的一些内建函数不是清楚,所以在写这篇文章之前需要一些python和WSGI的预备知识,这是一系列文章.这一篇只实现了如何处理url. 参考这篇文 ...

  8. python运维开发(十七)----jQuery续(示例)web框架django

    内容目录: jQuery示例 前端插件 web框架 Django框架 jQuery示例 dom事件绑定,dom绑定在form表单提交按钮地方都会绑定一个onclick事件,所有查看网站的人都能看到代码 ...

  9. python django基础一web框架的本质

    web框架的本质就是一个socket服务端,而浏览器就是一个socker客户端,基于请求做出相应,客户端先请求,服务器做出对应响应 按照http协议的请求发送,服务器按照http协议来相应,这样的通信 ...

  10. python web框架 django 工程 创建 目录介绍

    # 创建Django工程django-admin startproject [工程名称] 默认创建django 项目都会自带这些东西 django setting 配置文件 django可以配置缓存 ...

随机推荐

  1. JavaScript中数组迭代方法

    文章来源 : https://www.cnblogs.com/shuiyi/p/5058524.html

  2. js加载超时 nginx静态资源

    server { listen ; server_name www.example.com; client_max_body_size 20M; root /xxx/xxx;//项目路径 locati ...

  3. yum安装_yum命令的相关操作

    2017年1月11日, 星期三 yum安装的四种方式 一.默认:从国外下载 二.国内:从阿里获取  http://mirrors.aliyun.com 1. cd /etc/yum.repos.d 2 ...

  4. 【leetcode 简单】 第八十一题 4的幂

    给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方. 示例 1: 输入: 16 输出: true 示例 2: 输入: 5 输出: false 进阶: 你能不使用循环或者递 ...

  5. numpy多项式拟合

    关于解决使用numpy.ployfit进行多项式拟合的时候请注意数据类型,解决问题的思路就是统一把数据变成浮点型,就可以了.这是numpy里面的一个bug,非常low希望后面改善. # coding: ...

  6. python初步学习-python模块之 commands

    commands 通过 os.popen() 执行 shell 命令,返回两个对象,一个是 状态码(Int).另一个为命令输出(str) commands.getoutput(cmd) 返回命令执行输 ...

  7. Python概念-Attr系列(林海峰教的)

    这个Attr系列是egon老师自创的,个人还是可以接受这种文化底蕴的,所以直接拿来用,也是毫无违和感的 所谓Attr系列,其实是__setattr__,__delattr__,__getattr__ ...

  8. mysql 数据范围总结

    MEDIUMINT 带符号的范围是-8388608到8388607,无符号的范围是0到16777215,使用3个字节. 一般情况下推荐使用 unsigned (无符号,即只接受正整数)

  9. Java 8 Lambda表达式,让你的代码更简洁

    Lambda表达式是Java 8一个非常重要的新特性.它像方法一样,利用很简单的语法来定义参数列表和方法体.目前Lambda表达式已经成为高级编程语言的标配,像Python,Swift等都已经支持La ...

  10. ES6简单总结

    1.变量声明let和const 我们都是知道在ES6以前,var关键字声明变量.无论声明在何处,都会被视为声明在函数的最顶部(不在函数内即在全局作用域的最顶部).这就是函数变量提升例如: functi ...