python-实现动态web服务器

# encoding=utf-8
import socket
from multiprocessing import Process
import re
import sys

# 设置静态文件根目录
HTML_ROOT_DIR = ‘./html‘

WSGI_PYTHON_DIR = ‘./wsgipython‘

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

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

    def start_response(self, status, headers):
        """
        status="200 ok"
        headers = [
            (‘Content-Type‘, ‘text/plain‘)
        ]

        :param status:
        :param headers:
        :return:
        """

        response_headers = "HTTP1.1 " + status + "\r\n"
        for header in headers:
            response_headers += "%s: %s\r\n" % header

        self.response_headers = response_headers

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

        # 解析请求报文
        # ‘GET / HTTP/1.1‘
        request_start_line = request_lines[0]
        print(‘&‘ * 20)
        print(type(request_start_line))
        # 提取用户请求的文件名
        print(‘*‘ * 10)
        print(request_start_line.decode(‘utf-8‘))
        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)

        print(file_name)
     # 将路由的分发交给框架去做   ====================================================
        # # "/ctime.py"
        # # "/sayhello.py"
        # if file_name.endswith(‘.py‘):
        #     a = file_name[1:-3]
        #     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: Myserver\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: Myserver\r\n‘
        #         response_body = file_data.decode(‘utf-8‘)
        #         print(‘??‘ * 20)
        #         print(type(response_body))
        #
        #     response = response_start_line + response_headers + ‘\r\n‘ + response_body
        #     print(‘response data:‘, response)

        env = {
                "PATH_INFO": file_name,
                ‘METHOD‘: method
            }
        response_body = self.app(env, self.start_response)
        response = self.response_headers + ‘\r\n‘ + response_body

        # 向客户端返回响应数据
        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)
    if len(sys.argv) < 2:
        sys.exit("python MyWebServer_v1.py Module:app")
        # python MyWebServer_v1.py  MyWebFrameWork:app
    module_name, app_name = sys.argv[1].split(":")
    # module_name = "MyWebFrameWork"
    # app_name = "app"
    m = __import__(module_name)
    app = getattr(m, app_name)
    http_server = HTTPServer(app)
    # http_server.set_port
    http_server.bind(9000)
    http_server.start()

if __name__ == ‘__main__‘:
   main()

框架的实现

MyWebFrameWork_v2.py

# coding:utf-8

import time

# 设置静态文件根目录
HTML_ROOT_DIR = "./html"

class Application(object):
    """框架的核心部分,也就是框架的主题程序,框架是通用的"""
    def __init__(self, urls):
        # 设置路由信息
        self.urls = urls

    def __call__(self, env, start_response):
        path = env.get("PATH_INFO", "/")
        # /static/index.html
        if path.startswith("/static"):
            # 要访问静态文件
            file_name = path[7:]
            # 打开文件,读取内容
            try:
                file = open(HTML_ROOT_DIR + file_name, "rb")
            except IOError:
                # 代表未找到路由信息,404错误
                status = "404 Not Found"
                headers = []
                start_response(status, headers)
                return "not found"
            else:
                file_data = file.read()
                file.close()

                status = "200 OK"
                headers = []
                start_response(status, headers)
                return file_data.decode("utf-8")

        for url, handler in self.urls:
            #("/ctime", show_ctime)
            if path == url:
                return handler(env, start_response)

        # 代表未找到路由信息,404错误
        status = "404 Not Found"
        headers = []
        start_response(status, headers)
        return "not found"

def show_ctime(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return time.ctime()

def say_hello(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return "hello frawework"

def say_haha(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return "hello haha"

urls = [
            ("/", show_ctime),
            ("/ctime", show_ctime),
            ("/sayhello", say_hello),
            ("/sayhaha", say_haha),
        ]
app = Application(urls)

运行上述代码需要pycharm中配置

服务器程序--Edit Configurations....

时间: 2024-10-10 06:22:59

python-实现动态web服务器的相关文章

python 启动简单web服务器

有时我们在开发web静态页面时,需要一个web服务器来测试. 这时可以利用python提供的web服务器来实现. 1.在命令行下进入某个目录 2.在该目录下运行命令: python -m SimpleHTTPServer 3.在浏览器打开 http://localhost:8000/路径 这里的路径是相对上面当前目录下的路径.

Python 实现简单 Web 服务器

Python 实现简单 Web 服务器 最近有个需求,就是要创建一个简到要多简单就有多简单的web服务器,目的就是需要一个后台进程用来接收请求然后处理并返回结果,因此就想到了使用python来实现. 首先创建一个myapp.py文件,其中定义了一个方法,所有的请求都会经过此方法,可以在此方法里处理传递的url和参数,并返回结果. def myapp(environ, start_response): status = '200 OK' headers = [('Content-type', 't

python批量同步web服务器代码核心程序

#!/usr/bin/env python #coding:utf8 import os,sys import md5,tab from mysql_co.my_db import set_mysql from ssh_co.ssh_connect import sshd from ssh_co.cfg.config import ssh_message,item_path from file import findfile def my_mysql(): db_file={} my_conne

python下的web服务器模块

python下的web服务模块有三种: BaseHTTPServer: 提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler SimpleHTTPServer: 包含执行GET和HEAD请求的SimpleHTTPRequestHandler类 CGIHTTPServer: 包含处理POST请求和执行CGIHTTPRequestHandler类. 下面是CGIHTTPServer类示例: 1 [email protected]:~/cp# tre

Python实现简易Web服务器

 1.请自行了解HTTP协议 http://www.cnblogs.com/reboot51/p/8358129.html(点击跳转) 2.创建Socket服务,监听指定IP和端口 3.以阻塞方式等待客户端连接 4.读取客户端请求数据并进行解析 5.准备服务器运行上下文 6.处理客户端请求数据 7.根据用户请求路径读取文件 8.返回响应结果给客户端 9.程序入口 10.目录结构 11.运行 python wsgiserver.py app:run 12.源码 a.wsgiserver.py文件

PYTHON多进程并发WEB服务器(利用LINUX的FORK)

这个又牛X 一点点.. 这还不涉及IO,如果调用GEVENT之类作异步IO或非阻塞IO,那就大框架都有啦.. ##################################################################### # Iterative server - webserver3a.py # # # # Tested with Python 2.7.9 & Python 3.4 on Ubuntu 14.04 & Mac OS X # ###########

Python简单实现Web服务器

import socket import re import gevent from gevent import monkey monkey.patch_all()# 识别等待时间,让协程切换 def client_handler(client_socket): '''接收客户端链接请求,响应对应的的数据''' # 接收数据 request_data = client_socket.recv(4096) # 判断是否接收到数据 if not request_data: print("客户端已经断

Python实现简单Web服务器

实验楼教程链接: https://www.shiyanlou.com/courses/552/labs/1867/document http原理详解(http下午茶): https://www.kancloud.cn/kancloud/tealeaf-http/43837 原文地址:https://www.cnblogs.com/weswes/p/10304475.html

python搭建简单的web服务器

由于要做自动化和性能测试,工作中需要有一个能够控制返回消息数据的web服务器,所以用python初步实现了一个简单的web服务器,能够处理HTTP的请求(GET,POST,PUT),并完成响应.先简单说明下原理,python中实现web服务器大概分两个步骤: 1.      创建一个套接字,绑定到指定的IP和端口,保持监听 2.      创建一个handle类,当收到请求消息时,作出响应 主要使用的类有两个: HTTPServer:HTTP服务器的基类,提供了HTTP服务器的常用方法,创建服务