django 代码

Django 代码

day1

不含文件的初级版本

连抄带改

import socket
from threading import Thread
server = socket.socket()
server.bind(('127.0.0.1',8001))
server.listen()
def func(conn):
    # 接受请求数据       # 自从用了这个之后  不接收就不渲染 发过去的网页了
    client_msg = conn.recv(1024).decode('utf-8')
    print(client_msg)
    # 组合响应协议的消息格式,然后发送响应信息
    conn.send('HTTP/1.1 200 ok \r\n\r\n'.encode('utf-8'))

    #   打开index.html文件,返回给前端
    with open('01 web 不含文件.html','rb')as f:
        data = f.read()
    conn.send(data)

    # 放在这  否则影响代码渲染 具体为什么?
    conn.send('who are you '.encode('utf-8'))
    # 防止资源占用 所以要断开 无保存连接
    conn.close()

# for i in range(10):
while 1 :
    # 接收连接    如果不在这里会执行100个  只接收了一个,只执行一个线程
    # 在外面一次接收多次执行
    conn, addr = server.accept()
    # 有一次发送了源码 没渲染 错开了? 上面有conn,这里也正常渲染了
    # conn.send('HTTP/1.1 200 ok \r\n\r\n'.encode('utf-8'))
    #开启线程并发
    t = Thread(target=func , args=(conn,))
    t.start()

# for i in range(22222):
#     conn.send(b'b')
# conn.close()
# server.close()

上传文件的代码

import socket
from threading import Thread
server = socket.socket()
server.bind(('127.0.0.1',8001))
server.listen()

def func(conn):
    client_msg = conn.recv(1024).decode('utf-8')
    will_send = client_msg.split('\r\n')[0].split(' ')[1]
    # print(client_msg)
    print(will_send)
    if will_send == '/':
        conn.send(b'HTTP/1.1 200 ok \r\n\r\n')
        with open('01传文件的.html','rb')as f:
            data = f.read()
        conn.send(data)
        conn.close()
    elif will_send == '/index.css':
        conn.send(b'HTTP/1.1 200 ok \r\n\r\n')
        with open('index.css', 'rb')as f:
            data = f.read()
        conn.send(data)
        conn.close()
    elif will_send == '/index.js':
        conn.send(b'HTTP/1.1 200 ok \r\n\r\n')
        with open('index.js', 'rb')as f:
            data = f.read()
        conn.send(data)
        conn.close()
    elif will_send == '/1.jpg':
        conn.send(b'HTTP/1.1 200 ok \r\n\r\n')
        with open('1.jpg', 'rb')as f:
            data = f.read()
        conn.send(data)
        conn.close()
    elif will_send == '/favicon.ico':
        conn.send(b'HTTP/1.1 200 ok \r\n\r\n')
        with open('favicon.ico', 'rb')as f:
            data = f.read()
        conn.send(data)
        conn.close()


while 1 :
    conn,abb = server.accept()
    T = Thread(target=func, args=(conn,))
    T.start()
    
    
    
    conn 接收在循环里,不在主进程里,实现多少次请求,多少次响应
    依然记不住  server.send(b'HTTP/1.1 200 ok \r\n\r\n')
    
    解释
    
    :client_msg.split('\r\n')[1].split(' ')[0]
    
    client_msg  =  
    	    GET / HTTP/1.1
            Host: 127.0.0.1:8001
            Connection: keep-alive
            Cache-Control: max-age=0
            Upgrade-Insecure-Requests: 1.....
                
                GET /index.css HTTP/1.1
                Host: 127.0.0.1:8001
                Connection: keep-alive
                
  本以为会用正则,结果使用client_msg.split(‘/r/n’)[0]   取第一行  然后 .split(' ')[1] 根据空格把/	     这些切出来   
  
     /           第一个是/ 所以当是 /的时候  ,把html文件读出来给他
     /index.css
	/index.js
	/1.jpg
	/favicon.ico

传文件的网页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="index.css">
    <link rel="icon" href="favicon.ico">
    
</head>
<body>

<h1> 欢迎来到20期 </h1>
<img src="1.jpg" alt="">
 
<script src="index.js"></script>
</body>

</html>


index.js  
    alert('ddd dd');

index.css
     h1{
            background-color: red;
            color: #1f87ff;
        }

day3

index.html 文件
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">

  <title>Title</title>
</head>
<body>
  <h1>
      {{ name }}
      <!--jinja2 格式-->
  </h1>
<ul>
    {% for hobby in hobbylist %}
    <li>{{ hobby }}</li>
    {% endfor %}
</ul>
</body>
</html>

基于jinja2的网页传输
from wsgiref.simple_server import make_server
from jinja2 import Template


def index():
    with open("index.html", "r",encoding='utf-8') as f:
        data = f.read()
    template = Template(data)  # 生成模板文件
    print('template\n',template)

    # >> > template = Template('Hello {{ name }}!')   格式
    # >> > template.render(name='John Doe') == u'Hello John Doe!'  render 格式两种

    ret = template.render({"name": "于谦", "hobbylist": ["烫头", "泡吧"]})  # 把数据填充到模板里面
    print('ret\n',ret,'>>>>>>>>>>>>>>>>>>>>end')

    # print(ret)
    print('我',ret.encode('utf-8').decode('utf-8'),'你')
    print('喔喔',repr(ret),ret.encode('utf-8'))

    print('我',repr(bytes(ret, encoding="utf8")),bytes(ret, encoding="utf8"))
    # return [bytes(ret, encoding="utf8"), ]
    # return [ ret.encode('utf-8')]			字符转换成字节的两种写法
    return [ret.encode('utf-8') ]



# 定义一个url和函数的对应关系
URL_LIST = [
    ("/index/", index),
]

def run_server(environ, start_response):			# 不和socketserver一样,两个参数
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])  # 设置HTTP响应的状态码和头信息
    url = environ['PATH_INFO']  # 取到用户输入的url		
    func = None  # 将要执行的函数		
    for i in URL_LIST:
        if i[0] == url:
            func = i[1]  # 去之前定义好的url列表里找url应该执行的函数
            break
    print('func\n',func)			
    if func:  # 如果能找到要执行的函数
        return func()  # 返回函数的执行结果
    else:				
        return [bytes("404没有该页面", encoding="utf8"), ]


if __name__ == '__main__':
    httpd = make_server('127.0.0.1',8000, run_server)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()
posted @ 2019-05-15 23:01  learnacode  阅读(439)  评论(0编辑  收藏  举报