01 Web框架介绍

一、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
#!/usr/local/bin/python3
#-*-coding:utf-8 -*-
#Author:Felix Song ;Environment:pycharm 5.0.3(python3.6)

def index():
    return [bytes('<h1>index</h1>',encoding='utf-8')]
    # return [b'<h1>index</h1>']
def login():
    return [bytes('<h1>login</h1>',encoding='utf-8')]

#第三步改造,路由系统
def routes():
    urlpatterns = (('/index',index),('/index',index),('/index',index))
    return urlpatterns

# #第二步改造,网页对照表
# url = (
#     ('/index',index),
#     ('/index',index),
#     ('/index',index),
# )
conf_url

 三、MVC框架(代码的归类)

  Model包:对数据库操作

  View包:存放html文件

    login.html:

  Controller包:业务逻辑处理

    Account.py:账户相关控制放在这里

    Admin.py:后台管理

四、MTV框架(代码的归类)

  Model包:对数据库的操作

  Template包:存放html文件

  View包:业务逻辑

参考:

http://www.cnblogs.com/wupeiqi/articles/4491246.html

http://www.cnblogs.com/wupeiqi/articles/5237672.html

原文地址:https://www.cnblogs.com/apff/p/7609225.html