Python Web框架——Django学习的第一天

Python Web框架——Django学习的第一天

一:对Django的介绍和基础

django是一个web框架,并且是python下最强大的web框架
1.Http协议
HTTP协议(超文本传输协议)是用于从WWW服务器传输超文本到本地游览器的楚寒松协议。它可以使游览器更加高效,是网络传输减少。它不仅保证计算机正确快速的传输超文本文档,还确定传输文档中的那一部分,以及那部分内容首先显示(如文本先于图形)等。
在这里插入图片描述
在这里插入图片描述

二:使用socket实现一个WEB服务器

代码:

import socket

def main():
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    # 强制释放端口,不管端口有没有被占用,都可以使用
    # sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    sock.bind(('localhost',8000))
    sock.listen(5)
    while True:
        # 等待游览器访问
        conn,addr = sock.accept();
        # 接收游览器发送来的请求
        data = conn.recv(1024)
        print(data)

        # 给游览器返回内容
        conn.send(b"HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=utf-8\r\n\r\n")
        conn.send("<h1 style='color:red'>电脑前的你长的真好看</h1>".encode("utf-8"))

        # 关闭和游览器船舰的socket连接
        conn.close()

if __name__ == '__main__':
    main()

三:使用wsgiref实现一个WEB服务器

注意代码开头的coding=utf-8一定不能去掉,否则便会,出现编码格式错误等问题

#coding=utf-8

from wsgiref.simple_server import make_server


# 该方法必定会除数两个参数
def run_serve(enversion,start_response):
    print('hahaha',enversion)
    # 给游览器返回的内容
    # start_response确定了传输的文本格式:'text/html',传输的编码格式:'utf-8'
    start_response("200 OK",[('Content-Type','text/html;charset=utf-8')])
    return [bytes('<h2>旁边的小云今天真好看!</h2>')]


s = make_server('localhost',8000,run_serve)
s.serve_forever()

四:使用wsgiref实现支持多URL的WEB服务器

#coding=utf-8
from wsgiref.simple_server import make_server

# 1.路由的并发器, 负责为 把url匹配到对应的函数
# 2.开发好对应的业务函数
# 3.一个请求来了之后,先走路由并发器,如果找到对用的function,就执行,如果没有找到,就返回404

def book(environ,start_response):
    print("book page")
    start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
    return [bytes('<h2>book page!</h2>')]

def cloth(environ,start_response):
    print("cloth page")
    start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
    return [bytes('<h2>cloth page!</h2>')]


def url_dispacher(environ,start_response):
    urls = {
    
    
        '/book':book,
        '/cloth':cloth,
    }
    return urls


def run_serve(environ,start_response):
    print('hahaha',environ)
    url_list = url_dispacher(environ,start_response)    #拿到所有的url
    request_url = environ.get("PATH_INFO")
    print('request url',request_url)


    if request_url in url_list:
        func_data = url_list[request_url](environ,start_response)
        return func_data  #真正返回数据给用户
    else:
        start_response("404 ",[('Content-Type','text/html;charset=utf-8')])
        return [bytes('<h1 style="font-size:50px">404,Page not found</h1>')]

    # start_response("200 OK",[('Content-Type','text/html;charset=utf-8')])
    # return [bytes('<h2>旁边的小云今天真好看!</h2>')]


s = make_server('localhost',8001,run_serve)
s.serve_forever()

五:使用wsgired实现支持图片显示的WEB服务器

#coding=utf-8
from wsgiref.simple_server import make_server
import re
import os
# 1.路由的并发器, 负责为 把url匹配到对应的函数
# 2.开发好对应的业务函数
# 3.一个请求来了之后,先走路由并发器,如果找到对用的function,就执行,如果没有找到,就返回404

# 获取当前路径
# BASE_DIR = os.path.abspath(__file__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def book(environ,start_response):
    print("book page")
    start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
    data = """
    <h1>当悟之时人自悟,人不度人天渡人</h1>
    <img src="../static/images/1.png">
    <h1>身后有余忘缩手,眼前无路想回头</h1>
    """
    return [bytes(data)]

def cloth(environ,start_response):
    print("cloth page")
    start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
    return [bytes('<h2>cloth page!</h2>')]


def url_dispacher(environ,start_response):
    urls = {
    
    
        '/book':book,
        '/cloth':cloth,
    }
    return urls

def img_handler(request_url):
    print(request_url)
    img_path = re.sub('/static','static_data',request_url)
    print("Base",BASE_DIR)
    print(img_path)
    if os.path.isfile(img_path):
        print('---------> img exist......')
        #打开该图片
        f =open(img_path,"rb")
        #读取该图片
        data = f.read()  #图片文件 内容
        return [data,0]   #0代表没错     1代表有错
    return [None,1]

def run_serve(environ,start_response):
    # print('hahaha',environ)
    url_list = url_dispacher(environ,start_response)    #拿到所有的url
    request_url = environ.get("PATH_INFO")
    # print('request url',request_url)

    if request_url in url_list:
        func_data = url_list[request_url](environ,start_response)
        return func_data  #真正返回数据给用户
    elif request_url.startswith("/static"): #代表图片
        img_data,img_status=img_handler(request_url)
        if img_status == 0:
            start_response("200 OK",[('Content-Type','text/html;;charset=utf-8')])
            return img_data

    else:
        start_response("404 ",[('Content-Type','text/html;charset=utf-8')])
        return [bytes('<h1 style="font-size:50px">404,Page not found</h1>')]

s = make_server('localhost',8001,run_serve)
s.serve_forever()

os.path.isfile():判断某一对象(需提供绝对路径)是否为文件
os.path.isdir():判断某一对象(需提供绝对路径)是否为目录

猜你喜欢

转载自blog.csdn.net/qq_51269815/article/details/121735781