Django:Web框架,WSGI,WSGI实现浏览器与服务器通信,路由route,WSGI实现页面访问

在这里插入图片描述
在这里插入图片描述
case1:

import socket


def handle_request(conn):  # 处理数据返回
    buff = conn.recv(1024)
    print(buff)
    conn.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf8"))  # HTTP规范
    html = """
        <html>
            <head></head>
            <body>
                <h1> hello my world </h1>
            </body>
        <html>
    """
    conn.send(html.encode("utf8"))


def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("localhost", 8000))  # 绑定Ip,端口
    sock.listen(5)  # 启动监听
    print("启动服务器,等待客户端连接……")

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


if __name__ == "__main__":
    main()

在这里插入图片描述

case2:

import socket


def handle_request(conn):  # 处理数据返回
    buff = conn.recv(1024)
    print(buff)
    conn.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf8"))  # HTTP规范
    # html = """
    #     <html>
    #         <head></head>
    #         <body>
    #             <h1> hello my world </h1>
    #         </body>
    #     <html>
    # """

    with open("demo.html") as f:
        html = f.read()
    conn.send(html.encode("utf8"))


def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("localhost", 8000))  # 绑定Ip,端口
    sock.listen(5)  # 启动监听
    print("启动服务器,等待客户端连接……")

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


if __name__ == "__main__":
    main()

再新建一个html文件,文件名为“demo.html”,里面代码如下:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1> hello my beautiful world.</h1>
</body>
</html>

运行main(),
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

case1:从Python文档,搜索WEGI,复制Example代码:
在这里插入图片描述
在make_server()函数,补全IP地址,这里用"0.0.0.0"即任何的IP过来都可以访问

with make_server('0.0.0.0', 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")

然后run
在这里插入图片描述

from wsgiref.simple_server import make_server

# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):
    # print("请求:environ", environ)  # 查看环境变量environ的值,environ是一个字典
    for k, v in environ.items():   # 解包环境变量environ,更方便地看值
        print(k, ":", v)
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
    start_response(status, headers)

    # The returned object is going to be printed
    return [b"Hello World"]

with make_server('0.0.0.0', 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")

    # Serve until process is killed
    httpd.serve_forever()

截取environ的部分值,如下:
在这里插入图片描述
case2:在上面case1里加一句代码,

    query_string = environ.get("QUERY_STRING")
    print(query_string)

然后run,启动WSGI,然后到浏览器地址栏端口号后面,加一些内容,然后回车:
在这里插入图片描述
可以看到控制台就取到了浏览器的url值
在这里插入图片描述

from wsgiref.simple_server import make_server

# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):
    # print("请求:environ", environ)  # 查看环境变量environ的值
    # for k, v in environ.items():   # 解包环境变量environ,更方便地看值
    #     print(k, ":", v)

    query_string = environ.get("QUERY_STRING")
    print(query_string)

    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
    start_response(status, headers)

    # The returned object is going to be printed
    return [b"Hello World"]

with make_server('0.0.0.0', 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")

    # Serve until process is killed
    httpd.serve_forever()

case3:在上面case1里加一句代码,

    path_info = environ.get("PATH_INFO", "未找到")
    print(path_info)

然后run,启动WSGI,然后到浏览器地址栏端口号后面,加一些内容,然后回车:
在这里插入图片描述
可以看到控制台就取到了浏览器的url值
在这里插入图片描述

from wsgiref.simple_server import make_server

# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):
    # print("请求:environ", environ)  # 查看环境变量environ的值
    # for k, v in environ.items():   # 解包环境变量environ,更方便地看值
    #     print(k, ":", v)

    # query_string = environ.get("QUERY_STRING")
    # print(query_string)

    path_info = environ.get("PATH_INFO", "未找到")
    print(path_info)

    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
    start_response(status, headers)

    # The returned object is going to be printed
    return [b"Hello World"]

with make_server('0.0.0.0', 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")

    # Serve until process is killed
    httpd.serve_forever()

引申:case1和case2,我们在浏览器的各种行为能被localhost所解析,即当我们在浏览器URL输入不同的内容,WSGI传输URL到localhost寻找相应的内容,如果找到了就给我们返回结果。正如,点击百度首页的新闻,跳转到新闻页面;点击地图,跳转到地图页面。
在这里插入图片描述
在这里插入图片描述

WSGI实现页面访问
在这里插入图片描述
首先,在pycharm里新建三个HTML文件,
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
然后在主程序中添加调用的代码,

from wsgiref.simple_server import make_server

# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).

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

def login():
    with open("login.html", "rb") as f:
        login_info = f.read()
    return [login_info]

def notfund():
    with open("notfund.html", "rb") as f:
        notfund_info = f.read()
    return [notfund_info]

def hello_world_app(environ, start_response):
    # print("请求:environ", environ)  # 查看环境变量environ的值
    # for k, v in environ.items():   # 解包环境变量environ,更方便地看值
    #     print(k, ":", v)

    # query_string = environ.get("QUERY_STRING")
    # print(query_string)

    # path_info = environ.get("PATH_INFO", "未找到")
    # print(path_info)

    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
    start_response(status, headers)

    path = environ.get("PATH_INFO")
    if path == "/index":
        return index()
    elif path == "/login":
        return login()
    else:
        return notfund()


with make_server('0.0.0.0', 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")

    # Serve until process is killed
    httpd.serve_forever()

然后到浏览器,在localhost:8000后面输入
在这里插入图片描述
回车,浏览器即显示我们预先在index.html里的内容
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
遗留问题:

    path = environ.get("PATH_INFO")
    if path == "/index":
        return index()
    elif path == "/login":
        return login()
    else:
        return notfund()

这里根据不同的路由返回对应的页面,是在代码里写死的,即硬编码,如果页面很多的话,就需要写很多映射的规则,有没有什么方式对这个路由进行改进呢?

PS: source, bilibili

猜你喜欢

转载自blog.csdn.net/weixin_47008635/article/details/115263712