web框架本质

版权声明:本文为原创文章,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。 https://blog.csdn.net/fgf00/article/details/53512289

一、Web框架本质

所有的web框架、web请求,本质上都是:socket。

HTTP中,浏览器充当socket客户端,一次请求、一次响应,服务就断开了。

import socket

def handle_request(client):
    buf = client.recv(1024)
    client.send(b"HTTP/1.1 200 OK

")
    client.send(b"Hello, Seven")

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',8000))
    sock.listen(5)

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

if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

上述通过socket来实现了其本质,而对于真实开发中的python web程序来说,一般会分为两部分:服务器程序和应用程序。服务器程序负责对socket服务器进行封装,并在请求到来时,对请求的各种数据进行整理。应用程序则负责具体的逻辑处理。为了方便应用程序的开发,就出现了众多的Web框架,例如:Django、Flask、web.py 等。

对服务器来说,需要支持各种不同框架,对框架来说,只有支持它的服务器才能被开发出的应用使用。这时候,标准化就变得尤为重要。

WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦。

python标准库提供的独立WSGI服务器称为wsgiref。

from wsgiref.simple_server import make_server

def RunServer(environ, start_response):
    # environ 客户端发来的所有数据
    # start_response 封装要返回给用户的数据(相应头、相应状态等)
    start_response('200 OK', [('Content-Type', 'text/html')])
    # 返回的内容
    return ['<h1>Hello, web!</h1>'.encode("utf-8"),]
    # return '<h1>Hello, web!</h1>'  # python2版本中

if __name__ == '__main__':
    httpd = make_server('', 8001, RunServer)
    print ("Serving HTTP on port 8000...")
    httpd.serve_forever()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

可以给上面start_response和return处加上断点,看一下里面的具体内容。

访问 127.0.0.1:8000/date 断点显示可以看到,“PATH_INFO” = (str)’/date’

二、自定义web框架

1、框架

通过python标准库提供的wsgiref模块开发一个自己的Web框架

from wsgiref.simple_server import make_server

def index():
    return [b'index',]

def login():
    return [b'login',]

def routers():
    urlpatterns = (
        ('/index',index),
        ('/login',login),
    )
    return urlpatterns

def RunServer(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    url = environ['PATH_INFO']
    urlpatterns = routers()
    func = None
    for item in urlpatterns:
        if item[0] == url:
            func = item[1]
            break
    if func:
        return func()
    else:
        return [b'404 not found',]

if __name__ == '__main__':
    httpd = make_server('', 8000, RunServer)
    print ("Serving HTTP on port 8000...")
    httpd.serve_forever()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

2、模板引擎

在上一步骤中,对于所有的login、index均返回给用户浏览器一个简单的字符串,在现实的Web请求中一般会返回一个复杂的符合HTML规则的字符串,所以我们一般将要返回给用户的HTML写在指定文件中,然后再返回。如:

index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>Index</h1>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

login.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form>
        <input type="text" />
        <input type="submit" />
    </form>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

修改1、框架代码里index和login函数如下

def index():
    with open("index.html", 'rb') as f:
        data = f.read()
    return [data,]

def login():
    with open("login.html", 'rb') as f:
        data = f.read()
    return [data,]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

对于上述代码,虽然可以返回给用户HTML的内容以现实复杂的页面,但是还是存在问题:如何给用户返回动态内容?

  • 自定义一套特殊的语法,进行替换
data = data.replace(b'@@@@@', "永不眠".encode('utf-8'))
  • 1
import time
t = str(time.time())
data = data.replace(b'@@@@@', t.encode('utf-8'))
  • 1
  • 2
  • 3

也可把t改为从数据库里取得数据

  • 使用开源工具jinja2,遵循其指定语法

3、WEB:MVC、MTV

对上面不同功能的进行归类存放。比如数据库操作的都放在Model文件夹、html文件都放在View文件夹、index和login等函数放在Controller文件夹。

把以上三个文件夹首字母连起来,就是MVC。这就是MVC框架:对文件夹分类、对职责的划分。

还有个MTV(Model、Template、View),名称不一样,职责是一样的

        数据库操作   模板文件    业务处理
MVC     Model       View        Controller
MTV     model       Template    View
  • 1
  • 2
  • 3

这就是web框架的本质,Django 是基于MTV的web框架

原文地址:https://www.cnblogs.com/fengff/p/9531504.html