Django-wsgi实例

wsgiref实现了wsgi,他会将复杂的http请求经过处理,得到Django需要的格式,可以说他是一个接口,一端传入数据,一端处理数据

传统的socket实现

import socket

def handle_request(client):

    buf = client.recv(1024)
    print(buf)

    client.send("HTTP/1.1 200 OK\r\n\r\n<h1 style='color:red'>Hello, Mr_zhang</h1>".encode("utf8"))

def main():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',8001))
    sock.listen(5)

    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':

    main()

采用wsgiref实现

from wsgiref.simple_server import make_server

def application(environ, start_response):
    # environ : 所有的请求数据
    start_response('200 OK', [('Content-Type', 'text/html')])

    return [b"<h1>HELLO Mr_zhang</h1>",]

s=make_server("127.0.0.1",8080,application)
print("server is working...")
s.serve_forever()

Django内部已经处理了wsgi相关·······

模拟数据交互
from wsgiref.simple_server import make_server


def f1(req):
    print(req)
    print(req["QUERY_STRING"])

    f1=open("index1.html","rb")
    data1=f1.read()
    return [data1]

def f2(req):

    f2=open("index2.html","rb")
    data2=f2.read()
    return [data2]

import time

def f3(req):        #模版以及数据库

    f3=open("index3.html","rb")
    data3=f3.read()
    times=time.strftime("%Y-%m-%d %X", time.localtime())
    data3=str(data3,"utf8").replace("!time!",str(times))


    return [data3.encode("utf8")]


def routers():

    urlpatterns = (
        ('/test1',f1),
        ('/test2',f2),
        ("/time",f3)
    )
    return urlpatterns


def application(environ, start_response):

    print(environ['PATH_INFO'])
    path=environ['PATH_INFO']
    start_response('200 OK', [('Content-Type', 'text/html')])


    urlpatterns = routers()
    func = None
    for item in urlpatterns:
        if item[0] == path:
            func = item[1]
            break
    if func:
        return func(environ)
    else:
        return ["<h1>404</h1>".encode("utf8")]

httpd = make_server('', 8080, application)

print('Serving HTTP on port 8080...')

# 开始监听HTTP请求:

httpd.serve_forever()

 

posted @ 2018-03-28 19:42  一石数字欠我15w!!!  阅读(777)  评论(0编辑  收藏  举报