WEB框架本质
一、WEB请求流程
所有的web应用,都是基于socket,所有的http请求都是短链接;
python的web框架分为两部分:1、自己写socket,自己处理请求(Tornado);2、基于wsgi,自己处理请求(其他的比如Django);
1、接受请求
2、预处理请求;将预处理的结果放到RunServer中;
二、自定义web框架之路由系统
请求-->wsgi-->Django
请求-->自己写socket-->Tornado
#!/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')]) #根据UL不同,返回不同的字符串 #1、获取URL #2、根据URL的不同做出不同的想相应 request_url =environ['PATH_INFO'] print request_url if request_url == "/home/index": return "Chales" elif request_url == "/haha": return 'hehe' else: return 404 #return '<h1>Hello, web!</h1>' if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print "Serving HTTP on port 8000..." httpd.serve_forever()
#!/usr/bin/env python # _*_ coding:utf-8 _*_ from wsgiref.simple_server import make_server def index(): #return '<h1>index</h1>' data = open('html/index.html').read() return data def dali(): return 'dali' url_list = [ ('/index/',index), ('/dali/',dali), ] def RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) request_url =environ['PATH_INFO'] for url in url_list: if request_url == url[0]: return url[1]() else: return "404" if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print "Serving HTTP on port 8000..." httpd.serve_forever()