参考: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. [解决] User [dr.who] is not authorized to view the logs for application

    在hadoop集群启用权限控制后,发现job运行日志的ui访问不了, User [dr.who] is not authorized to view the logs for application ...

  2. 2017.6.11 NOIP模拟赛

    题目链接: http://files.cnblogs.com/files/TheRoadToTheGold/2017-6.11NOIP%E6%A8%A1%E6%8B%9F%E8%B5%9B.zip 期 ...

  3. log4net 按照日期备份日志

    配置: <logger name="Log.All">   <level value="INFO" />   <appender- ...

  4. Spring Boot 启动报错:LoggingFailureAnalysisReporter

    17:57:19: Executing task 'bootRun'... Parallel execution with configuration on demand is an incubati ...

  5. Problem L. Visual Cube(杭电多校2018年第三场+模拟)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6330 题目: 题意:给你长宽高,让你画出一个正方体. 思路:模拟即可,湘潭邀请赛热身赛原题,不过比那个 ...

  6. MSSQL数据库 "无法删除数据库 "***",因为该数据库当前正在使用" 解决方案

    --1 创建数据库 create database AAA --2 使用数据库 use AAA --3 在AAA数据库下创建table create table BBB ( bId ,) primar ...

  7. Part1-HttpClient快速入门案例

    前言 最近这段时间在学习爬虫方面的知识,接触了几个优秀的爬虫框架,也爬取了一些自己喜欢网站的信息.通过官网学习HttpClient的过程中,希望通过写此博客来巩固自己的学习,也为有需要的人提供学习帮助 ...

  8. 阿波罗11号登月飞船电脑控制系统源码(AGC)

    阿波罗11号登月飞船电脑控制系统源码(AGC) http://download.csdn.net/detail/downiis6/9574926 down url: https://github.co ...

  9. 【bzoj3224】普通平衡树

    看有没有人能发现咯. #include<bits/stdc++.h> #define N 300005 #define rat 4 #define pushup(o) if(o->l ...

  10. VI编辑,backspace无法删除解决方法

    系统ubuntu 1,sudo apt-get install vim  安装vim 2, sudo vi  /etc/vim/vimrc.tiny 修改 set compatible为set noc ...