参考:https://ruslanspivak.com/lsbaws-part1/

简单的WSGI server

server程序 webserver.py

# Tested with Python 2.7.9, Linux & Mac OS X
import socket
import StringIO
import sys
class WSGIServer(object):
    address_family = socket.AF_INET
    socket_type = socket.SOCK_STREAM
    request_queue_size = 1
    def __init__(self, server_address):
        # Create a listening socket
        self.listen_socket = listen_socket = socket.socket(
            self.address_family,
            self.socket_type
        )
        # Allow to reuse the same address
        listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # Bind
        listen_socket.bind(server_address)
        # Activate
        listen_socket.listen(self.request_queue_size)
        # Get server host name and port
        host, port = self.listen_socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port
        # Return headers set by Web framework/Web application
        self.headers_set = []
    def set_app(self, application):
        self.application = application
    def serve_forever(self):
        listen_socket = self.listen_socket
        while True:
            # New client connection
            self.client_connection, client_address = listen_socket.accept()
            # Handle one request and close the client connection. Then
            # loop over to wait for another client connection
            self.handle_one_request()
    def handle_one_request(self):
        self.request_data = request_data = self.client_connection.recv(40960)
        #self.request_data = request_data = self.client_connection.recv(1024)

# Print formatted request data a la 'curl -v'
        print(''.join(
            '< {line}\n'.format(line=line)
            for line in request_data.splitlines()
        ))
        self.parse_request(request_data)
        # Construct environment dictionary using request data
        env = self.get_environ()
        # It's time to call our application callable and get
        # back a result that will become HTTP response body
        result = self.application(env, self.start_response)
        # Construct a response and send it back to the client
        self.finish_response(result)
    def parse_request(self, text):
        request_line = text.splitlines()[0]
        request_line = request_line.rstrip('\r\n')
        # Break down the request line into components
        (self.request_method,  # GET
         self.path,            # /hello
         self.request_version  # HTTP/1.1
         ) = request_line.split()
    def get_environ(self):
        env = {}
        # The following code snippet does not follow PEP8 conventions
        # but it's formatted the way it is for demonstration purposes
        # to emphasize the required variables and their values
        #
        # Required WSGI variables
        env['wsgi.version']      = (1, 0)
        env['wsgi.url_scheme']   = 'http'
        env['wsgi.input']        = StringIO.StringIO(self.request_data)
        env['wsgi.errors']       = sys.stderr
        env['wsgi.multithread']  = False
        env['wsgi.multiprocess'] = False
        env['wsgi.run_once']     = False
        # Required CGI variables
        env['REQUEST_METHOD']    = self.request_method    # GET
        env['PATH_INFO']         = self.path              # /hello
        env['SERVER_NAME']       = self.server_name       # localhost
        env['SERVER_PORT']       = str(self.server_port)  # 8888
        return env
    def start_response(self, status, response_headers, exc_info=None):
        # Add necessary server headers
        server_headers = [
            ('Date', 'Tue, 31 Mar 2015 12:54:48 GMT'),
            ('Server', 'WSGIServer 0.2'),
        ]
        self.headers_set = [status, response_headers + server_headers]
        # To adhere to WSGI specification the start_response must return
        # a 'write' callable. We simplicity's sake we'll ignore that detail
        # for now.
        # return self.finish_response
    def finish_response(self, result):
        try:
            status, response_headers = self.headers_set
            response = 'HTTP/1.1 {status}\r\n'.format(status=status)
            for header in response_headers:
                response += '{0}: {1}\r\n'.format(*header)
            response += '\r\n'
            for data in result:
                response += data
            # Print formatted response data a la 'curl -v'
            print(''.join(
                '> {line}\n'.format(line=line)
                for line in response.splitlines()
            ))
            self.client_connection.sendall(response)
        finally:
            self.client_connection.close()
SERVER_ADDRESS = (HOST, PORT) = '', 9091
def make_server(server_address, application):
    server = WSGIServer(server_address)
    server.set_app(application)
    return server
if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.exit('Provide a WSGI application object as module:callable')
    app_path = sys.argv[1]
    module, application = app_path.split(':')
    module = __import__(module)
    application = getattr(module, application)
    httpd = make_server(SERVER_ADDRESS, application)
    print('WSGIServer: Serving HTTP on port {port} ...\n'.format(port=PORT))
    httpd.serve_forever()

应用 test.py

def app(environ, start_response):
    """A barebones WSGI application.
    This is a starting point for your own Web framework :)
    """
    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain')]
    start_response(status, response_headers)
    return ['Hello world from a simple WSGI application!\n']

运行

python webserver.py test:app

测试

在浏览器地址栏输入

http://192.168.3.106:9091/hello

注意:server端口设置9091,在server里可以更改

简单的WSGI server的更多相关文章

  1. django自带wsgi server vs 部署uwsgi+nginx后的性能对比

    一.下面先交代一下测试云主机 cpu: root@alexknight:/tmp/webbench-1.5# cat /proc/cpuinfo |grep model model : model n ...

  2. Fiddler-009-AutoResponder 简单的 MOCK SERVER 应用实例

    在我们日常的测试中经常需要测试特定的响应对应的客户端展示样式是否正确无误,实现测试方法一般有如下三种: 创建新的测试数据(工作量较大) 修改已有测试数据(例如修改对应的状态码,若是最终需要测试的按钮状 ...

  3. 最简单删除SQL Server中所有数据的方法

     最简单删除SQL Server中所有数据的方法 编写人:CC阿爸 2014-3-14 其实删除数据库中数据的方法并不复杂,为什么我还要多此一举呢,一是我这里介绍的是删除数据库的所有数据,因为数据之间 ...

  4. 编写一个简单的Web Server

    编写一个简单的Web Server其实是轻而易举的.如果我们只是想托管一些HTML页面,我们可以这么实现: 在VS2013中创建一个C# 控制台程序 编写一个字符串扩展方法类,主要用于在URL中截取文 ...

  5. 一个简单的mock server

    在前后端分离的项目中, 前端无需等后端接口提供了才调试, 后端无需等第三方接口提供了才调试, 基于“契约”,可以通过mock server实现调试, 下面是一个简单的mock server,通过pyt ...

  6. 用Python编写一个简单的Http Server

    用Python编写一个简单的Http Server Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器.Python支持该功能的实现模块是BaseFTTPServe ...

  7. 写了一个简单的CGI Server

    之前看过一些开源程序的源码,也略微知道些Apache的CGI处理程序架构,于是用了一周时间,用C写了一个简单的CGI Server,代码算上头文件,一共1200行左右,难度中等偏上,小伙伴可以仔细看看 ...

  8. nova-api源码分析(WSGI server的创建及启动)

    源码版本:H版 一.前奏 nova api本身作为一个WSGI服务器,对外提供HTTP请求服务,对内调用nova的其他模块响应相应的HTTP请求.分为两大部分,一是服务器本身的启动与运行,一是加载的a ...

  9. 用unity3d实现简单的主server连接

    用unity3d实现简单的主server连接 參考自鹰大的网络实例 -------------------------------------------------华丽的切割线----------- ...

随机推荐

  1. Linux查看进程的所有子进程和线程

    得到进程的pid: ps -ef | grep process_name | grep -v "grep" | awk '{print $2}' 查看进程的所有线程 # ps mp ...

  2. bzoj 2705: [SDOI2012]Longge的问题——欧拉定理

    Description Longge的数学成绩非常好,并且他非常乐于挑战高难度的数学问题.现在问题来了:给定一个整数N,你需要求出∑gcd(i, N)(1<=i <=N). Input 一 ...

  3. Go从入门到精通(持续更新)

    1.0 搭建环境 由于我们 Go官方网站 在我大天朝被和谐了,所以我们只能去 Go语言中文网 来下载了.Go的安装很简单,不像Java还要配置一大堆的东西,选择自己系统的对应版本,下载安装,像安装QQ ...

  4. SQLserver 字符串分割函数

    CREATE function Get_StrArrayStrOfIndex ( @str varchar(), --要分割的字符串 @split varchar(), --分隔符号 @index i ...

  5. 关于win7局域网共享的相关设置

    模式1> 被访问方相关设置步骤: (1)被共享方的电脑开通来宾用户 (2)被共享方的电脑的本地安全策略需要设置成 "仅来宾" (3)被共享方的电脑高级共享设置中 " ...

  6. canvas_简单练习

    效果图 实现原理: 1.定义canvas标签. 2.获取canvas标签节点,创建canvas2D. 3.在canvas进行画图. 效果代码: <!DOCTYPE html> <ht ...

  7. 编译zpool命令

    环境:192.168.50.239(在 illumos源码中编译zpool命令) PS:由于对zpool命令的工作原理不熟悉,所以编译,可在其中加入调试语句来明白其原理 首先介绍 illumos-so ...

  8. AndroidStudio 添加Selector文件,在res文件夹下添加文件夹

    在res文件夹下添加文件夹: 添加Selector文件:

  9. 9.0docker的数据管理

    dopcker容器的数据卷          为容器添加数据卷 sudo docker run -v  ~/container data:/data  -it ubuntu /bin/bash   查 ...

  10. Java中class的初始化顺序

     由于Java 中的一切东西都是对象,所以许多活动 变得更加简单,这个问题便是其中的一例. 除非真的需要代码,否则那个文件是不会载入的.通常,我们可认为除非那个类的一个对象构造完毕,  否则代码不会真 ...