• Wsgi的web框架实例


    建立server服务端:

    from wsgiref.simple_server import make_server
    import  time
    def f1(request):
        return [b'<h1>hello,Abook!</h1>']
    def f2(request):
        return [b'<h1>hello,Aweb!</h1>']
    
    def cunrrent_time(request):
        cur_time = time.ctime(time.time())
        f=open('cunrrent_time.html','rb')
        data=f.read()
        data=str(data,'utf8').replace("!cur_time!",str(cur_time))
        return [data.encode('utf8')]
        #return  [data]
    def routers():  #封装一个元组可以根据点击的URL路径比配到相对应的函数
        urlpatterns=(
        ('/book',f1),
        ('/web',f2),
        ('/time', cunrrent_time),
        )
        return  urlpatterns
    
    
    
    def applicattion(environ,start_response):
          #通过environ封装程一个所有请求信息的对象
          #start_response可以很方便的设置响应头
           #print("envire",environ)
           #print("environ",environ['PATH_INFO'])
           start_response('200 OK',[('Content-Types','textl/html'),('contex','text')])
           path=environ['PATH_INFO'];#请求返回的路径
           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')]
    #封装soket对象以及准备过程(socket,bind,listen)
    http=make_server('',8080,applicattion)
    print('Serving HTTP on port 8000....')
    http.serve_forever()

    cunrrent_time文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h11>cunrrent_time:!cur_time!</h11>
    </body>
    </html>

    浏览器请求:

  • 相关阅读:
    hostapd AP模式 2.4G/5G
    hostapd挂载不上驱动bcmdhd.ko以及SDIO读写错误
    C++入门 -- const用法(转载)
    C++ 入门 -- size_t
    C++ 入门 -- 全局变量的使用(转载)
    C++ 入门 -- const用法小结
    大数据揭示的10个常见JAVA编程错误
    jsfiddle
    ionic
    React native android 最常见的10个问题
  • 原文地址:https://www.cnblogs.com/lanyinhao/p/9334557.html
Copyright © 2020-2023  润新知