web_server:

 import socket
import time
import multiprocessing
import re
import mini_frame class WSGIServer(object):
def __init__(self):
# 1.创建socket对象
self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2.设置重复使用地址
self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 3.绑定端口
self.tcp_server_socket.bind(("", 7890))
# 4.设置监听状态
self.tcp_server_socket.listen(128) def clinet_server(self,new_client_socket):
# 1.接受消息
request = new_client_socket.recv(1024).decode("utf-8")
lines = request.splitlines()
# 2.匹配请求网页
request_name = re.match(r"[^/]+(/[^ ]*)",lines[0])
file_name = request_name.group(1)
if file_name == "/":
file_name = "/index.html" # 返回数据给浏览器
if not file_name.endswith(".py"):
# 3.打开文件
try:
f = open("./html" + file_name,"rb")
except Exception as ret:
pass
else:
html_content = f.read() # 4.创建header和body
response_body = html_content
response_header = "HTTP/1.1 200 ok\r\n"
response_header += "Content-Length:%d\r\n" % len(response_body)
response_header += "\r\n"
response = response_header.encode("utf-8") + response_body
# 5.发送
new_client_socket.send(response)
finally:
f.close()
else:
# 如果是.py结尾,则认为是动态页面请求/
env = dict();
env['PATH_INFO'] = file_name
# application(字典, 方法名) 固定用法
body = mini_frame.application(env, self.start_respones_header)
# 拼装header头
header = "HTTP/1.1 %s\r\n" % self.status
for temp in self.headers:
header += "%s:%s\r\n" % (temp[0], temp[1])
header += "\r\n"
# 拼装返回数据
response = header + body
# 发送数据
new_client_socket.send(response.encode("utf-8")) # 6.关闭socket
# new_client_socket.close() def start_respones_header(self, status, headers):
"""接受并保存application传过来的值"""
self.status = status
self.headers = [("server","mini_web v1.0")]
self.headers += headers def run_forever(self):
"""运行"""
while True:
# 5.接收客户地址,创建新socket
new_client_socket,client_addr = self.tcp_server_socket.accept()
# 6.为新客户端服务
p = multiprocessing.Process(target=self.clinet_server,args=(new_client_socket,))
p.start()
# 7.关闭新客户端
new_client_socket.close()
# 7.关闭socket
self.tcp_server_socket.close() def main():
wsgi_server = WSGIServer()
wsgi_server.run_forever() if __name__ == '__main__':
main()

mini_frame.py:

 def login():
"""模拟登陆页面"""
return "---login---welcome to python--->time:%s" % time.ctime() def index():
"""模拟主页"""
return "----index----" def application(env, start_respones):
# 调用传过来的方法,传值
start_respones('200 ok',[("Content-Type","text/html;charset=utf-8")])
# 接受字典传过来的数据
file_name = env['PATH_INFO']
# 判断客户请求
if file_name == "/index.py":
return index()
elif file_name == "/login.py":
return login()
else:
return "python 中国"

WSGI原理的更多相关文章

  1. 想学Python?这里有一个最全面的职位分析

    Python从2015年开始,一直处于火爆的趋势,目前Python工程师超越Java.Web前端等岗位,起薪在15K左右,目前不管是小公司还是知名大公司都在热招中. 当然,每个城市对岗位的需求也不尽相 ...

  2. Python Web开发中,WSGI协议的作用和实现原理详解

    首先理解下面三个概念: WSGI:全称是Web Server Gateway Interface,WSGI不是服务器,python模块,框架,API或者任何软件,只是一种规范,描述web server ...

  3. 理解 OpenStack Swift (2):架构、原理及功能 [Architecture, Implementation and Features]

    本系列文章着重学习和研究OpenStack Swift,包括环境搭建.原理.架构.监控和性能等. (1)OpenStack + 三节点Swift 集群+ HAProxy + UCARP 安装和配置 ( ...

  4. Nginx+uWSGI+Django原理

    Python的Web开发中,如果使用Django框架,那么较为成熟稳定的服务器架构一般是Nginx+uWSGI+Django.而为什么一定要三个结合在一起呢?直接使用Django的runserver来 ...

  5. WSGI规格说明书

    PEP 333 这应该是WSGI最权威的文档了  http://www.python.org/dev/peps/pep-3333/  值翻译了最重要的前面部分,后面读者可以参考 当然文档有些生硬,欢迎 ...

  6. [Django 1.5] Windows + Apache + wsgi配置

    基本步骤 下载安装Apache http://httpd.apache.org/download.cgi. 下载安装modwsgi 模块http://code.google.com/p/modwsgi ...

  7. 读Flask源代码学习Python--config原理

    读Flask源代码学习Python--config原理 个人学习笔记,水平有限.如果理解错误的地方,请大家指出来,谢谢!第一次写文章,发现好累--!. 起因   莫名其妙在第一份工作中使用了从来没有接 ...

  8. nova的wsgi介绍【WIP】

    有关openstack的所有的帖子. https://www.ustack.com/blog/openstack_hacker/#Nova_Workflow 网上已经很多的分析文章了: http:// ...

  9. tornado+WSGI+Apache

    1.原理 2.安装mod_wsgi http://pan.baidu.com/s/1sjsccWH configure的时候会找对应的python脚本,默认是/usr/bin/python 生成mod ...

随机推荐

  1. Centos7挂载新硬盘

    1.查看系统是否检测到新的硬盘设备 ls /dev/ |grep sd linux 中所有外设都会在这个目录下,对应一个文件,其中第一块硬盘是sda,第二块硬盘是sdb,第三块硬盘是sdc.其中sda ...

  2. 笨方法学Python摘记(1)

    编程新手所需的最重要的三种技能:读和写.注重细节.发现不同 不要复制粘贴! #-*-codinig:utf-8 -*-  (脚本使用unicode UTF-8) 书写习惯:操作符的两边加上空格,提高代 ...

  3. laydate 只设置年月日,时分,不设置秒

    laydate.render({ elem: '#deadline_time' ,type: 'datetime' ,format: 'yyyy-MM-dd HH:mm' }); 设置了format, ...

  4. 【LeetCode】最长公共前缀【二分】

    编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow" ...

  5. pyenv基本使用

    pyenv使用 1.安装: git clone https://github.com/pyenv/pyenv.git 2.配置pyenv环境变量 echo 'export PYENV_ROOT=&qu ...

  6. Numpy学习笔记(上篇)

    目录 Numpy学习笔记(上篇) 一.Jupyter Notebook的基本使用 二.Jpuyter Notebook的魔法命令 1.%run 2.%timeit & %%timeit 3.% ...

  7. 基础数字电路的Verilog写法

    Verilog是硬件描述电路,我对此一直稀里糊涂,于是将锆石科技开发板附带的的一些基础数字电路Verilog程序整理记录下来,并且查看他们的RTL视图,总算有点理解了. 1.基本运算符 module ...

  8. c#Queue队列的使用

    消息队列 队列(System.Collections.Queue)代表了一个先进先出的对象集合.当您需要对各项进行先进先出的访问时,则使用队列.当您在列表中添加一项,称为入队,当您从列表中移除一项时, ...

  9. [C#] 生成中文电子通讯录

    var template = @" BEGIN:VCARD VERSION:2.1 N;CHARSET=gb2312:;{0};;; FN;CHARSET=gb2312:{0} TEL;CE ...

  10. MVC模式和Maven项目构建

    1.    尽管Servlet + JSP可以完成全部的开发工作,但是代码耦合度高.可读性差.重用性不好,维护.优化也不方便.所以才有了MVC. MVC是当前WEB开发的主流模式,核心是使用Strut ...