对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端。

阶段1

socket服务端和客户端都自己编写

实现访问8080端口,返回一个'hello world'

#!/usr/bin/env python
#encoding: utf-8
#@2017-03-30
"""最简单的web框架""" import socket def handle_request(client):
"""应用程序,web开发者自定义部分"""
buf = client.recv(1024)
client.send('HTTP/1.1 200 OK\1\n\r\n')
client.send("Hello, world!") def server():
"""服务端程序,web开发者共用部分
本质:对socket进行封装"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 8080))
sock.listen(5) while True:
connection, address = sock.accept()
handle_request(connection) # 阻塞
connection.close() if __name__ == '__main__':
server()

阶段2

WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦。python标准库提供的独立WSGI服务器称为wsgiref

实现访问8000端口,返回一个'hello world'

#!/usr/bin/env python
#coding:utf-8 # 封装后的服务程序
from wsgiref.simple_server import make_server def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return 'Hello, world!' if __name__ == '__main__':
httpd = make_server('0.0.0.0', 8000, RunServer)
print "Serving HTTP on port 8000..."
httpd.serve_forever()

阶段3

一些功能模块化,逐渐有了django的影子

demo:点击下载

main.py作为程序入口

#!/usr/bin/env python
#coding:utf-8 # 封装后的服务程序
from wsgiref.simple_server import make_server
from urls import url def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
# 获取用户URL
user_url = environ['PATH_INFO'] # 根据URL不同返回不同的结果
for item in url:
if item[0] == user_url:
return item[1]()
else:
return '<h1>404 not found</h1>' if __name__ == '__main__':
httpd = make_server('0.0.0.0', 8000, RunServer)
print "Serving HTTP on port 8000..."
httpd.serve_forever()

views.py方法函数

#!/usr/bin/env python
#coding:utf-8 def index():
return 'index' def login():
return 'login' def logout():
return 'logout' url = (
('/index/', index),
('/login/', login),
('/logout/', logout),
)

url到方法函数的映射urls.py

#encoding: utf-8
from views import * """指定URL到处理函数的映射"""
url = (
('/index/', index),
('/login/', login),
('/logout/', logout),
)

最新文章

  1. bzoj 2141: 排队
  2. 使用nmap工具查询局域网某个网段正在使用的ip地址
  3. codevs 2894 保留小数
  4. silverLight--绑定数据dataGrid
  5. 问题解决——ShowWindow不显示窗口
  6. jqmobi 转换语言
  7. Oracle的rownum原理和使用(整理几个达人的帖子)
  8. Android 获取WIFI MAC地址的方法
  9. 在Eclipse中显示空格(space)和制表符(tab)
  10. Computer Vision Algorithm Implementations
  11. 大数据笔记11:MapReduce的运行流程
  12. iOS开发之OC篇-响应式编程Reactive Cocoa
  13. JavaWeb核心编程之(三.4)Servlet Context 配置
  14. javascript object-oriented something
  15. mysql查看表大小
  16. 使用.net core搭建文件服务器
  17. DLC 基本定律与规则2
  18. PHP-FPM安装报错解决
  19. VirtualBox for mac
  20. centos7.2使用rpm安装jdk8

热门文章

  1. 一文看懂NLP神经网络发展历史中最重要的8个里程碑!
  2. 从使用到原理,探究Java线程池
  3. python之进程,线程
  4. Ubuntu查看文件格式(后缀名)
  5. centos7中提升用户权限
  6. 字典树基础进阶全掌握(Trie树、01字典树、后缀自动机、AC自动机)
  7. 别人家的 InfluxDB 实战 + 源码剖析
  8. 学编程这么久,还傻傻分不清什么是方法(method),什么是函数(function)?
  9. 监听窗口大小变化,改变画面大小-[Three.js]-[onResize]
  10. 1037 Magic Coupon (25分)