当前位置 : 主页 > 编程语言 > python >

day55——django引入、小型django(socket包装的服务器)

来源:互联网 收集:自由互联 发布时间:2021-06-25
day55 吴超老师Django总网页:https://www.cnblogs.com/clschao/articles/10526431.html 请求(网址访问,提交数据等等) request 响应(回复页面,回复数据等等) response web框架的本质及自定义web框架 我

day55

吴超老师Django总网页:https://www.cnblogs.com/clschao/articles/10526431.html

请求(网址访问,提交数据等等) request

响应(回复页面,回复数据等等) response

web框架的本质及自定义web框架

我们可以这样理解:所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端,基于请求做出响应,客户都先请求,服务端做出对应的响应,按照http协议的请求协议发送请求,服务端按照http协议的响应协议来响应请求,这样的网络通信,我们就可以自己实现Web框架了。

  通过对socket的学习,我们知道网络通信,我们完全可以自己写了,因为socket就是做网络通信用的,下面我们就基于socket来自己实现一个web框架,写一个web服务端,让浏览器来请求,并通过自己的服务端把页面返回给浏览器,浏览器渲染出我们想要的效果。在后面的学习中,大家提前准备一些文件:

    html文件内容如下,名称为test.html:  

详情看:https://www.cnblogs.com/clschao/articles/10391859.html#part_2

简单版回复html页面的web框架

python代码

server.py

import socket

server = socket.socket()
server.bind(('127.0.0.1', 8001))
server.listen()

while 1:
    conn,addr = server.accept()
    from_brower_msg = conn.recv(1024)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    if path == '/':
        with open('05dong.html', 'rb')as f:
            data = f.read()
    elif path == '/style.css':
        with open('style.css', 'rb') as f:
            data = f.read()

    elif path == '/test.js':
        with open('test.js', 'rb') as f:
            data = f.read()

    elif path == '/1.jpg':
        with open('1.jpg', 'rb') as f:
            data = f.read()

    conn.send(data)
    conn.close()
html代码

04test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
<!--    <link rel="icon" href="favicon.ico">-->

</head>
<body>
<h1>24期官网</h1>
<div>
    <img src="1.jpg" alt="">
</div>
</body>


<script src="test.js"></script>

</html>
样式和js等文件

style.css

body{
    background: red;
}

test.js

alert(123);

图片文件--1.jpg

基础函数版

python代码

server.html

import socket
from threading import Thread

server = socket.socket()
server.bind(('127.0.0.1',8003))
server.listen()


def home(conn):
    with open('04test.html', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def css(conn):
    with open('style.css', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def js(conn):
    with open('test.js', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def pic(conn):
    with open('1.jpg', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def nofount(conn):
    conn.send(b'not found 404!')
    conn.close()


def ico(conn):
    with open('favicon.ico', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


urlpatterns = [
    ('/',home),
    ('/style.css',css),
    ('/test.js',js),
    ('/1.jpg',pic),
    ('/favicon.ico',ico),
]


while 1:
    conn,addr = server.accept()
    from_brower_msg = conn.recv(1024)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    for url in urlpatterns:
        if path == url[0]:
            # ret = url[1]()
            t = Thread(target=url[1],args=(conn,))
            t.start()
            break
    else:
        t = Thread(target=nofount,args=(conn,))
        t.start()
html代码

04test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="favicon.ico">
</head>
<body>
<div>
    <img src="1.jpg" alt="">
</div>
<script src="test.js"></script>
</body>
</html>
样式和js等文件

style.css

body{
    background: red;
}

test.js

alert(123);

图片文件--1.jpg

进阶函数版

python文件

server.py

import socket
from urls import urlpatterns
from threading import Thread
import views

server = socket.socket()
server.bind(('127.0.0.1',8003))
server.listen()


while 1:
    conn,addr = server.accept()
    from_brower_msg = conn.recv(1024)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    for url in urlpatterns:
        if path == url[0]:
            t = Thread(target=url[1], args=(conn,))
            t.start()
            break
    else:
        t = Thread(target=views.nofount, args=(conn,))
        t.start()

列表文件--urls.py

import views
urlpatterns = [
    ('/',views.home),
    ('/style.css',views.css),
    ('/test.js',views.js),
    ('/1.jpg',views.pic),
    ('/favicon.ico',views.ico),
]

函数文件--views.py

def home(conn):
    with open('05dong.html', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def css(conn):
    with open('style.css', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def js(conn):
    with open('test.js', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def pic(conn):
    with open('1.jpg', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def nofount(conn):
    conn.send(b'not found 404!')
    conn.close()


def ico(conn):
    with open('favicon.ico', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()
html文件

05dong.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
<!--    <link rel="icon" href="favicon.ico">-->

</head>
<body>
<h1>24期官网</h1>
<div>
    <img src="1.jpg" alt="">
</div>
</body>


<script src="test.js"></script>

</html>
样式和js等文件

style.css

body{
    background: red;
}

test.js

alert(123);

图片文件--1.jpg

动态页面的web框架

python文件

server.py

import socket

server = socket.socket()
server.bind(('127.0.0.1', 8003))
server.listen()

while 1:
    username = "朱凡宇"
    conn, addr = server.accept()
    from_brower_msg = conn.recv(1024)
    path = from_brower_msg.decode('utf-8').split(" ")[1]
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    with open('dong.html', 'r', encoding='utf-8')as f:
        data = f.read()
    data = data.replace('%xxoo%', username)
    conn.send(data.encode())
    conn.close()
html文件

dong.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>欢迎来到%xxoo%的首页</h1>
</body>
</html>

不同html页面的web框架

python文件

server

import socket
from urls import urlpatterns
from threading import Thread
import views

server = socket.socket()
server.bind(('127.0.0.1',8003))
server.listen()


while 1:
    conn,addr = server.accept()
    from_brower_msg = conn.recv(1024)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    for url in urlpatterns:
        if path == url[0]:
            t = Thread(target=url[1], args=(conn,))
            t.start()
            break

    else:
        t = Thread(target=views.nofount, args=(conn,))
        t.start()

urls

import views


urlpatterns = [
    ('/',views.home),
    ('/center',views.person_center),
]

views

def home(conn):
    with open('05dong.html', 'rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()


def person_center(conn):
    with open('center.html', 'rb') as f:
        data = f.read()

    conn.send(data)

    conn.close()


def nofount(conn):
    conn.send(b'not found 404!')

    conn.close()
html文件

05dong.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>欢迎24期来到xx网站</h1>
<a href="/center">个人中心</a>
</body>
</html>

center.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>欢迎来到xx个人中心</h1>
</body>
</html>

wsgiref模块

python文件

server

from wsgiref.simple_server import make_server
from urls import urlpatterns

def application(environ,start_response):
    # environ  所有请求相关信息
    # start_response --封装响应数据格式
    path = environ['PATH_INFO']
    start_response('200 ok',[])  # conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    for url in urlpatterns:
        if path == url[0]:
            ret = url[1]()
            break
    return [ret]


if __name__ == '__main__':
    h = make_server('127.0.0.1', 8080, application)
    h.serve_forever()

urls

import views
urlpatterns = [
    ('/',views.home),
]

views

def home():
    with open('05dong.html', 'rb') as f:
        data = f.read()
    return data
html文件

05dong.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>欢迎24期来到xx网站</h1>
</body>
</html>

jinja2模块

python文件

server

import socket
from urls import urlpatterns
from threading import Thread
import views

server = socket.socket()
server.bind(('127.0.0.1',8003))
server.listen()


while 1:
    conn,addr = server.accept()
    from_brower_msg = conn.recv(1024)
    path = from_brower_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    for url in urlpatterns:
        if path == url[0]:
            t = Thread(target=url[1], args=(conn,))
            t.start()
            break

urls

import views
urlpatterns = [
    ('/',views.home),
    # ('/center',views.person_center),
    # ('/style.css',views.css),
    # ('/test.js',views.js),
    # ('/1.jpg',views.pic),
    # ('/favicon.ico',views.ico),
]

views

from jinja2 import Template


def home(conn):
    # {% for i in hobby %}
    # <li>{{ i }}</li>
    # {% endfor %}

    with open('08jinja2test.html', 'r',encoding='utf-8') as f:
        data = f.read()
    t = Template(data)
    ret = t.render({'hobby':['金钱','女人','张达'], 'name': '朱凡宇'})
    conn.send(ret.encode('utf-8'))
    conn.close()
html文件

08jinja2test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>{{ name }}个人介绍</h1>
我的爱好
<ul>
    {% for i in hobby %}
    <li>{{ i }}</li>
    {% endfor %}
</ul>
</body>
</html>
网友评论