python实现web

本文介绍了使用Python实现一个基本的HTTP服务器,包括静态文件处理和扩展到处理动态内容(通过WSGI)。从接收客户端请求、解析到文件查找,再到响应构建,最后展示了如何集成WSGI来运行Python脚本作为动态内容源。
摘要由CSDN通过智能技术生成

import socket

from multiprocessing import Process

def handle_client(client_socket):
“”"
处理客户端请求
“”"
request_data = client_socket.recv(1024)
print(“request data:”, request_data)
# 构造响应数据
response_start_line = “HTTP/1.1 200 OK\r\n”
response_headers = “Server: My server\r\n”
response_body = “

Python HTTP Test


response = response_start_line + response_headers + “\r\n” + response_body

# 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8"))

# 关闭客户端连接
client_socket.close()

if name == “main”:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 8000))
server_socket.listen(128)

while True:
    client_socket, client_address = server_socket.accept()
    print("[%s, %s]用户连接上了" % client_address)
    handle_client_process = Process(target=handle_client, args=(client_socket,))
    handle_client_process.start()
    client_socket.close()

运行程序,打开浏览器输入:http://127.0.0.1:8000/,显示如下:

在这里插入图片描述

coding:utf-8

import socket
import re

from multiprocessing import Process

设置静态文件根目录

HTML_ROOT_DIR = “./html”

def handle_client(client_socket):
“”"
处理客户端请求
“”"
# 获取客户端请求数据
request_data = client_socket.recv(1024)
print(“request data:”, request_data)
request_lines = request_data.splitlines()
# 解析请求报文
request_start_line = request_lines[0]
# 提取用户请求的文件名
file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode(“utf-8”)).group(1)

if "/" == file_name:
    file_name = "/index.html"

# 打开文件,读取内容
try:
    file = open(HTML_ROOT_DIR + file_name, "rb")
except IOError:
    response_start_line = "HTTP/1.1 404 Not Found\r\n"
    response_headers = "Server: My server\r\n"
    response_body = "The file is not found!"
else:
    file_data = file.read()
    file.close()

    # 构造响应数据
    response_start_line = "HTTP/1.1 200 OK\r\n"
    response_headers = "Server: My server\r\n"
    response_body = file_data.decode("utf-8")

response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response)

# 向客户端返回响应数据
client_socket.send(bytes(response, "utf-8"))

# 关闭客户端连接
client_socket.close()

if name == “main”:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("", 8000))
server_socket.listen(128)

while True:
    client_socket, client_address = server_socket.accept()
    print("[%s, %s]用户连接上了" % client_address)
    handle_client_process = Process(target=handle_client, args=(client_socket,))
    handle_client_process.start()
    client_socket.close()

在程序所在目录下新建文件夹(html),里面放入HTML文件,运行程序,打开浏览器输入:http://127.0.0.1:8000/,显示如下:

在这里插入图片描述
改为面向对象的程序:

复制代码

coding:utf-8

import socket
import re

from multiprocessing import Process

设置静态文件根目录

HTML_ROOT_DIR = “./html”

class HTTPServer(object):
def init(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def start(self):
    self.server_socket.listen(128)
    while True:
        client_socket, client_address = self.server_socket.accept()
        print("[%s, %s]用户连接上了" % client_address)
        handle_client_process = Process(target=self.handle_client, args=(client_socket,))
        handle_client_process.start()
        client_socket.close()

def handle_client(self, client_socket):
    """
    处理客户端请求
    """
    # 获取客户端请求数据
    request_data = client_socket.recv(1024)
    print("request data:", request_data)
    request_lines = request_data.splitlines()
    # 解析请求报文
    request_start_line = request_lines[0]
    # 提取用户请求的文件名
    file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)

    if "/" == file_name:
        file_name = "/index.html"

    # 打开文件,读取内容
    try:
        file = open(HTML_ROOT_DIR + file_name, "rb")
    except IOError:
        response_start_line = "HTTP/1.1 404 Not Found\r\n"
        response_headers = "Server: My server\r\n"
        response_body = "The file is not found!"
    else:
        file_data = file.read()
        file.close()

        # 构造响应数据
        response_start_line = "HTTP/1.1 200 OK\r\n"
        response_headers = "Server: My server\r\n"
        response_body = file_data.decode("utf-8")

    response = response_start_line + response_headers + "\r\n" + response_body
    print("response data:", response)

    # 向客户端返回响应数据
    client_socket.send(bytes(response, "utf-8"))

    # 关闭客户端连接
    client_socket.close()

def bind(self, port):
    self.server_socket.bind(("", port))

def main():
http_server = HTTPServer()
http_server.bind(8000)
http_server.start()

if name == “main”:
main()
复制代码
三.返回动态内容(运用wsgi)

复制代码

coding:utf-8

import socket
import re
import sys

from multiprocessing import Process

设置静态文件根目录

HTML_ROOT_DIR = “./html”

设置动态文件根目录

WSGI_PYTHON_DIR = “./wsgitest”

class HTTPServer(object):
def init(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def start(self):
    self.server_socket.listen(128)
    while True:
        client_socket, client_address = self.server_socket.accept()
        print("[%s, %s]用户连接上了" % client_address)
        handle_client_process = Process(target=self.handle_client, args=(client_socket,))
        handle_client_process.start()
        client_socket.close()

def start_response(self, status, headers):
    response_headers = "HTTP/1.1 " + status + "\r\n"
    for header in headers:
        response_headers += "%s: %s\r\n" % header

    self.response_headers = response_headers

def handle_client(self, client_socket):
    """
    处理客户端请求
    """
    # 获取客户端请求数据
    request_data = client_socket.recv(1024)
    print("request data:", request_data)
    request_lines = request_data.splitlines()
    for line in request_lines:
        print(line)

    # 解析请求报文
    request_start_line = request_lines[0]
    # 提取用户请求的文件名及请求方法
    file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
    method = re.match(r"(\w+) +/[^ ]* ", request_start_line.decode("utf-8")).group(1)

    # 处理动态文件
    if file_name.endswith(".py"):
        try:
            m = __import__(file_name[1:-3])
        except Exception:
            self.response_headers = "HTTP/1.1 404 Not Found\r\n"
            response_body = "not found"
        else:
            env = {
                "PATH_INFO": file_name,
                "METHOD": method
            }
            response_body = m.application(env, self.start_response)

        response = self.response_headers + "\r\n" + response_body
    # 处理静态文件
    else:
        if "/" == file_name:
            file_name = "/index.html"

        # 打开文件,读取内容
        try:
            file = open(HTML_ROOT_DIR + file_name, "rb")
        except IOError:
            response_start_line = "HTTP/1.1 404 Not Found\r\n"
            response_headers = "Server: My server\r\n"
            response_body = "The file is not found!"
        else:
            file_data = file.read()
            file.close()

            # 构造响应数据
            response_start_line = "HTTP/1.1 200 OK\r\n"
            response_headers = "Server: My server\r\n"
            response_body = file_data.decode("utf-8")

        response = response_start_line + response_headers + "\r\n" + response_body
        print("response data:", response)

    # 向客户端返回响应数据
    client_socket.send(bytes(response, "utf-8"))

    # 关闭客户端连接
    client_socket.close()

def bind(self, port):
    self.server_socket.bind(("", port))

def main():
sys.path.insert(1, WSGI_PYTHON_DIR)
http_server = HTTPServer()
http_server.bind(8000)
http_server.start()

if name == “main”:
main()
复制代码
在程序所在目录下新建文件夹(wsgitest),里面放入python文件(ctime.py)

复制代码

coding:utf-8

import time

def application(env, start_response):

status = "200 OK"
headers = [("Content-Type", "text/plain")]

start_response(status, headers)

return time.ctime()

运行程序,打开浏览器输入:http://127.0.0.1:8000/ctime.py,显示如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曾忆少年时~峥嵘岁月稠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值