一、Web框架本质

  • 所有的web应用程序本质上都是socket,用户的浏览器其实就是一个socket客户端。
  • python中常用的web框架有:
    • Django
    • Flask
    • web.py
  • WSGI(web server gateway interface)定义了使用python编程的web app和web server之间的接口格式,实现了服务端与客户端的解耦。
  • pytho标准库提供的独立WSGI服务器称为wsgired。

二、利用wsgrired自定义Web框架

#!/usr/local/bin/python3
#-*-coding:utf-8 -*-
#Author:Felix Song ;Environment:pycharm 5.0.3(python3.6)

#用python标准库开发一个自己的web框架
from wsgiref.simple_server import  make_server

#第二步改造,获取conf中的内容
import conf_url

def RunServer(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html')])
    #第一步,获取用户URL,debug模式下,在start_response加断点,然后浏览器访问在Variables下的environ中找
    userUrl = environ['PATH_INFO']
    print(userUrl)
    urlpatterns = conf_url.routes() #第三步改造
    #第二步改造
    func = None
    # for item in conf_url.url: #第三步注释掉
    for item in urlpatterns:#第三步改造
        if item[0] == userUrl:
            func =  item[1]
            break

    if func:
        return  func()
    else:
        return  [bytes('<h1>404</h1>',encoding='utf-8')]

    '''
    #第二步,根据URL输入的不同返回不同的值,但是如果页面很多用if else就比较费劲了...改造下,新建一个conf.py在里边定义所有的URL模型
    if userUrl == '/index/':
        return [bytes('<h1>index</h1>',encoding='utf-8')]
    elif userUrl == '/login/':
        return [bytes('<h1>login</h1>',encoding='utf-8')]
    elif userUrl == '/logout/':
        return [bytes('<h1>logout</h1>',encoding='utf-8')]
    else:
        return [bytes('<h1>404 no found</h1>',encoding='utf-8')]
    '''


if __name__ == '__main__':
    httpd = make_server('',8000,RunServer)
    print('Serving http on port 8000...')
    httpd.serve_forever()
server

相关文章:

  • 2021-10-19
  • 2021-09-29
  • 2021-09-16
  • 2021-08-18
  • 2022-12-23
  • 2021-11-23
  • 2021-12-19
  • 2022-12-23
猜你喜欢
  • 2021-12-05
  • 2022-12-23
  • 2022-01-05
  • 2021-04-07
  • 2021-05-30
  • 2021-08-31
  • 2021-12-01
相关资源
相似解决方案