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. Nginx基础配置指令

    nginx.conf文件的结构 ... #全局块 events{ #events块 ... } http{ #http块 ... #http全局块 server{ #server块 ... #serv ...

  2. select 的字段为空,给他显示默认值

    select 的字段为空,给他显示默认值: 解决办法一: select id,name,(case when level is null then 0 else level end) as a fro ...

  3. [转载]8 种提升 ASP.NET Web API 性能的方法

    http://www.oschina.net/translate/8-ways-improve-asp-net-web-api-performance 英文原文:8 ways to improve A ...

  4. 网上整理的jQuery插件开发教程

    jQuery插件的开发包括两种:一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法.jQuery的全局函数就是属于jQuery命名空间的函数,另一种是对象级别 ...

  5. C++中getline()和cin()同时使用时的注意事项

    今天做tju的oj,遇到一个问题,想前部分用cin函数一个一个的读入数据,中间部分利用getline()一起读入一行,但是测试发现,cin之后的getline函数并无作用,遂谷歌之.原来cin只是在缓 ...

  6. DNS域传送漏洞

    nslookup -type=ptr 8.8.8.8             #查询一个IP地址对应的域名 nslookup -type=ns baidu.com         #查询baidu.c ...

  7. git 放弃本地修改操作

      如果在修改时发现修改错误,而要放弃本地修改时, 一, 未使用 git add 缓存代码时. 可以使用 git checkout -- filepathname (比如: git checkout ...

  8. Linux SSH Backdoor分析排查

    1.SSH后门分类 SSH后门方式有以下几种 软链接 SSH Server wrapper SSH Keylogger 2.软链接 利用方法 [root@helen]# ln -sf /usr/sbi ...

  9. Shell中三种引号的用法及区别

    Linux Shell中有三种引号,分别为双引号(" ").单引号(' ')以及反引号(` `). 其中双引号对字符串中出现的$.''.`和\进行替换:单引号不进行替换,将字符串中 ...

  10. python使用twisted搭建的一个socket服务

    服务端 # -*- coding: utf-8 -*- # @Time : 2018/9/19 21:41 # @Author : cxa # @File : tsTservTW.py # @Soft ...