├── .coveragerc ├── .gitignore ├── .travis.yml ├── CHANGES.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── aiowsgi ├── __init__.py ├── compat.py ├── task.py └── thread.py ├── bootstrap.py ├── buildout.cfg ├── docs ├── Makefile ├── conf.py └── index.rst ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── apps.py ├── test_aiowsgi.py └── test_thread.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | include = 3 | */aiowsgi/*.py 4 | omit = 5 | */docs* 6 | */tests* 7 | */examples* 8 | */lib_pypy* 9 | */lib/python* 10 | */lib-python* 11 | */site-packages* 12 | 13 | [report] 14 | exclude_lines = 15 | pragma: no cover 16 | def __repr__ 17 | raise NotImplementedError 18 | if __name__ == .__main__.: 19 | def parse_args 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.bck 3 | bin 4 | build 5 | _build 6 | .bzr 7 | .bzrignore 8 | .chutifab 9 | .coverage 10 | coverage* 11 | develop-eggs 12 | dist 13 | downloads 14 | *.egg 15 | *.EGG 16 | *.egg-info 17 | *.EGG-INFO 18 | eggs 19 | fake-eggs 20 | .hg 21 | .hgignore 22 | .idea 23 | .installed.cfg 24 | *.jar 25 | *.mo 26 | .mr.developer.cfg 27 | nosetest* 28 | *.old 29 | *.orig 30 | parts 31 | *.pyc 32 | *.pyd 33 | *.pyo 34 | *.so 35 | src 36 | .svn 37 | *.swp 38 | .tox 39 | *.tmp* 40 | var 41 | *.wpr 42 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: false 3 | 4 | matrix: 5 | include: 6 | - python: 3.5 7 | - python: 3.6 8 | 9 | install: 10 | - pip install tox-travis coveralls 11 | 12 | script: 13 | - tox 14 | 15 | after_success: 16 | - coveralls 17 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | 0.9 (unreleased) 2 | ================ 3 | 4 | - Nothing changed yet. 5 | 6 | 7 | 0.8 (2022-08-18) 8 | ================ 9 | 10 | - Remove py2 support 11 | 12 | - Waitress 2.x compatibility 13 | 14 | 15 | 0.7 (2018-11-02) 16 | ================ 17 | 18 | - remove deprecated asyncio.async calls 19 | 20 | 21 | 0.6 (2016-06-30) 22 | ================ 23 | 24 | - Small changes to work with latest waitress release (force encoding data to utf8) 25 | 26 | 27 | 0.5 (2015-03-19) 28 | ================ 29 | 30 | - Use executor iif application is not a coroutine 31 | 32 | 33 | 0.4 (2015-03-13) 34 | ================ 35 | 36 | - Added thread.WSGIServer 37 | 38 | 39 | 0.3 (2014-06-19) 40 | ================ 41 | 42 | - Compat with latest trollius 43 | 44 | 45 | 0.2 (2014-05-10) 46 | ================ 47 | 48 | - Use waitress's tasks to parse request and send response 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Gael Pasgrimaud 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | graft docs 2 | prune docs/_build 3 | graft aiowsgi 4 | graft tests 5 | include .coveragerc LICENSE 6 | include *.py *.rst *.cfg *.ini 7 | exclude .installed.cfg 8 | global-exclude *.pyc 9 | global-exclude __pycache__ 10 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ================================================ 2 | aiowsgi - minimalist wsgi server using asyncio 3 | ================================================ 4 | 5 | .. image:: https://travis-ci.org/gawel/aiowsgi.png?branch=master 6 | :target: https://travis-ci.org/gawel/aiowsgi 7 | .. image:: https://coveralls.io/repos/gawel/aiowsgi/badge.png?branch=master 8 | :target: https://coveralls.io/r/gawel/aiowsgi?branch=master 9 | .. image:: https://img.shields.io/pypi/v/aiowsgi.svg 10 | :target: https://crate.io/packages/aiowsgi/ 11 | .. image:: https://img.shields.io/pypi/dm/aiowsgi.svg 12 | :target: https://crate.io/packages/aiowsgi/ 13 | 14 | Require python 2.7, 3.3+ 15 | 16 | Source: https://github.com/gawel/aiowsgi/ 17 | 18 | Docs: https://aiowsgi.readthedocs.org/ 19 | 20 | You like it ? => https://www.gittip.com/gawel/ 21 | -------------------------------------------------------------------------------- /aiowsgi/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | from __future__ import print_function 4 | from concurrent.futures import ThreadPoolExecutor 5 | from waitress.parser import HTTPRequestParser 6 | from waitress import utilities 7 | from .compat import asyncio 8 | from aiowsgi import task 9 | import waitress 10 | import sys 11 | 12 | 13 | class WSGIProtocol(asyncio.Protocol): 14 | 15 | request_class = HTTPRequestParser 16 | 17 | def connection_made(self, transport): 18 | self.transport = transport 19 | self.request = None 20 | 21 | def data_received(self, data): 22 | if self.request is None: 23 | request = self.request_class(self.adj) 24 | else: 25 | request = self.request 26 | 27 | pos = request.received(data) 28 | if self.request is None and len(data) > pos: 29 | request.received(data[pos:]) 30 | 31 | if request.completed or request.error: 32 | self.request = None 33 | task_class = task.ErrorTask if request.error else task.WSGITask 34 | channel = Channel(self.server, self.transport) 35 | t = task_class(channel, request) 36 | asyncio.ensure_future(asyncio.coroutine(t.service)(), 37 | loop=self.server.loop) 38 | if task_class is task.ErrorTask: 39 | channel.done.set_result(True) 40 | return channel 41 | else: 42 | self.request = request 43 | 44 | @classmethod 45 | def run(cls): 46 | cls.loop.run_forever() 47 | 48 | 49 | class Channel(object): 50 | 51 | def __init__(self, server, transport): 52 | self.loop = server.loop 53 | self.server = server 54 | self.transport = transport 55 | self.write = transport.write 56 | self.addr = transport.get_extra_info('peername')[0] 57 | self.done = asyncio.Future(loop=self.loop) 58 | 59 | def write_soon(self, data): 60 | if data: 61 | if 'Buffer' in data.__class__.__name__: 62 | for v in data: 63 | self.write(v) 64 | else: 65 | if not isinstance(data, bytes): 66 | data = data.encode('utf8') 67 | self.write(data) 68 | return len(data) 69 | return 0 70 | 71 | def check_client_disconnected(self): 72 | return self.transport.is_closing() 73 | 74 | 75 | def create_server(application, ssl=None, **adj): 76 | """Create a wsgi server: 77 | 78 | .. code-block:: 79 | 80 | >>> async def application(environ, start_response): 81 | ... pass 82 | >>> loop = asyncio.get_event_loop() 83 | >>> srv = create_server(application, loop=loop, port=2345) 84 | >>> srv.close() 85 | 86 | Then use ``srv.run()`` or ``loop.run_forever()`` 87 | """ 88 | if 'loop' in adj: 89 | loop = adj.pop('loop') 90 | else: 91 | loop = asyncio.get_event_loop() 92 | if 'ident' not in adj: 93 | adj['ident'] = 'aiowsgi' 94 | 95 | server = waitress.create_server(application, _start=False, **adj) 96 | 97 | adj = server.adj 98 | 99 | server.executor = None 100 | if not asyncio.iscoroutine(application) and \ 101 | not asyncio.iscoroutinefunction(application): 102 | server.executor = ThreadPoolExecutor(max_workers=adj.threads) 103 | 104 | server.run = loop.run_forever 105 | server.loop = loop 106 | 107 | args = dict(app=[application], 108 | aioserver=None, 109 | adj=adj, 110 | loop=loop, 111 | server=server, 112 | server_name=server.server_name, 113 | effective_host=server.effective_host, 114 | effective_port=server.effective_port) 115 | proto = type(str('BoundedWSGIProtocol'), (WSGIProtocol,), args) 116 | server.proto = proto 117 | 118 | if adj.unix_socket: 119 | utilities.cleanup_unix_socket(adj.unix_socket) 120 | f = loop.create_unix_server 121 | else: 122 | f = loop.create_server 123 | 124 | def done(future): 125 | result = future.result() 126 | server.aioserver = result 127 | 128 | task = asyncio.ensure_future( 129 | f(proto, sock=server.socket, backlog=adj.backlog, ssl=ssl), loop=loop) 130 | task.add_done_callback(done) 131 | return server 132 | 133 | 134 | def serve(application, **kw): # pragma: no cover 135 | """Serve a wsgi application""" 136 | no_async = kw.pop('no_async', False) 137 | if not no_async: 138 | kw['_server'] = create_server 139 | return waitress.serve(application, **kw) 140 | 141 | 142 | def serve_paste(app, global_conf, **kw): 143 | serve(app, **kw) 144 | return 0 145 | 146 | 147 | def run(argv=sys.argv): 148 | from waitress import runner 149 | runner.run(argv=argv, _serve=serve) 150 | -------------------------------------------------------------------------------- /aiowsgi/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | try: 3 | import trollius as asyncio 4 | except ImportError: 5 | import asyncio # NOQA 6 | -------------------------------------------------------------------------------- /aiowsgi/task.py: -------------------------------------------------------------------------------- 1 | from .compat import asyncio 2 | from waitress.task import hop_by_hop 3 | from waitress.task import ErrorTask # NOQA 4 | from waitress.task import WSGITask as Task 5 | from waitress.task import ReadOnlyFileBasedBuffer as ROBuffer 6 | 7 | 8 | class WSGITask(Task): 9 | """A WSGI task produces a response from a WSGI application. 10 | """ 11 | environ = None 12 | 13 | def execute(self): 14 | env = self.get_environment() 15 | env['aiowsgi.loop'] = self.channel.server.loop 16 | 17 | def start_response(status, headers, exc_info=None): 18 | if self.complete and not exc_info: 19 | raise AssertionError("start_response called a second time " 20 | "without providing exc_info.") 21 | if exc_info: # pragma: no cover 22 | try: 23 | if self.complete: 24 | # higher levels will catch and handle raised exception: 25 | # 1. "service" method in task.py 26 | # 2. "service" method in channel.py 27 | # 3. "handler_thread" method in task.py 28 | raise exc_info[1] 29 | else: 30 | # As per WSGI spec existing headers must be cleared 31 | self.response_headers = [] 32 | finally: 33 | exc_info = None 34 | 35 | self.complete = True 36 | 37 | if status.__class__ is not str: # pragma: no cover 38 | raise AssertionError('status %s is not a string' % status) 39 | 40 | self.status = status 41 | 42 | # Prepare the headers for output 43 | for k, v in headers: 44 | if k.__class__ is not str: 45 | raise AssertionError( 46 | 'Header name %r is not a string in %r' % (k, (k, v)) 47 | ) 48 | if v.__class__ is not str: 49 | raise AssertionError( 50 | 'Header value %r is not a string in %r' % (v, (k, v)) 51 | ) 52 | kl = k.lower() 53 | if kl == 'content-length': 54 | self.content_length = int(v) 55 | elif kl in hop_by_hop: # pragma: no cover 56 | raise AssertionError( 57 | '%s is a "hop-by-hop" header; it cannot be used by ' 58 | 'a WSGI application (see PEP 3333)' % k) 59 | 60 | self.response_headers.extend(headers) 61 | 62 | # Return a method used to write the response data. 63 | return self.write 64 | 65 | # Call the application to handle the request and write a response 66 | loop = self.channel.server.loop 67 | if self.channel.server.executor is not None: 68 | coro = loop.run_in_executor( 69 | self.channel.server.executor, 70 | self.channel.server.application, env, start_response) 71 | else: 72 | coro = self.channel.server.application(env, start_response) 73 | t = asyncio.ensure_future(coro, loop=loop) 74 | t.add_done_callback(self.aiofinish) 75 | 76 | def finish(self): 77 | pass 78 | 79 | def aiofinish(self, f): 80 | app_iter = f.result() 81 | self.aioexecute(app_iter) 82 | Task.finish(self) 83 | if self.close_on_finish: # pragma: no cover 84 | self.channel.transport.close() 85 | 86 | def aioexecute(self, app_iter): 87 | try: 88 | if app_iter.__class__ is ROBuffer: # pragma: no cover 89 | cl = self.content_length 90 | size = app_iter.prepare(cl) 91 | if size: 92 | if cl != size: 93 | if cl is not None: 94 | self.remove_content_length_header() 95 | self.content_length = size 96 | self.write(b'') # generate headers 97 | self.channel.write_soon(app_iter) 98 | return 99 | 100 | first_chunk_len = None 101 | for chunk in app_iter: 102 | if first_chunk_len is None: 103 | first_chunk_len = len(chunk) 104 | # Set a Content-Length header if one is not supplied. 105 | # start_response may not have been called until first 106 | # iteration as per PEP, so we must reinterrogate 107 | # self.content_length here 108 | if self.content_length is None: # pragma: no cover 109 | app_iter_len = None 110 | if hasattr(app_iter, '__len__'): 111 | app_iter_len = len(app_iter) 112 | if app_iter_len == 1: 113 | self.content_length = first_chunk_len 114 | # transmit headers only after first iteration of the iterable 115 | # that returns a non-empty bytestring (PEP 3333) 116 | if chunk: 117 | self.write(chunk) 118 | 119 | cl = self.content_length 120 | if cl is not None: 121 | if self.content_bytes_written != cl: # pragma: no cover 122 | # close the connection so the client isn't sitting around 123 | # waiting for more data when there are too few bytes 124 | # to service content-length 125 | self.close_on_finish = True 126 | if self.request.command != 'HEAD': 127 | self.logger.warning( 128 | 'application returned too few bytes (%s) ' 129 | 'for specified Content-Length (%s) via app_iter' 130 | '' % ( 131 | self.content_bytes_written, cl), 132 | ) 133 | finally: 134 | if hasattr(app_iter, 'close'): # pragma: no cover 135 | app_iter.close() 136 | self.channel.done.set_result(True) 137 | -------------------------------------------------------------------------------- /aiowsgi/thread.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import time 3 | import socket 4 | import threading 5 | from . import asyncio 6 | from . import create_server 7 | from six.moves import http_client 8 | 9 | 10 | def get_free_port(): 11 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | s.bind(('', 0)) 13 | ip, port = s.getsockname() 14 | s.close() 15 | return ip, port 16 | 17 | 18 | def check_server(host, port, path_info='/', timeout=3, retries=30): 19 | """Perform a request until the server reply""" 20 | if retries < 0: 21 | return 0 22 | time.sleep(.3) 23 | for i in range(retries): 24 | try: 25 | conn = http_client.HTTPConnection(host, int(port), timeout=timeout) 26 | conn.request('GET', path_info) 27 | res = conn.getresponse() 28 | return res.status 29 | except (socket.error, http_client.HTTPException): 30 | print('wait') 31 | time.sleep(.3) 32 | return 0 33 | 34 | 35 | class WSGIServer(threading.Thread): 36 | """Stopable WSGI server running in a thread (not main thread). 37 | Usefull for functionnal testing. 38 | 39 | Usage: 40 | 41 | .. code-block:: 42 | 43 | >>> async def application(environ, start_response): 44 | ... start_response('200 OK', []) 45 | ... return ['Hello world'] 46 | >>> loop = asyncio.get_event_loop() 47 | >>> server = WSGIServer(application) 48 | >>> server.start() 49 | >>> server.stop() 50 | 51 | ``server.url`` will contain the url to request 52 | """ 53 | 54 | def __init__(self, app, host='127.0.0.1', port=None): 55 | super(WSGIServer, self).__init__() 56 | self.server = None 57 | self.app = app 58 | _, self.port = port or get_free_port() 59 | self.host = host 60 | self.url = 'http://%s:%s' % (self.host, self.port) 61 | self.loop = asyncio.new_event_loop() 62 | 63 | def run(self): 64 | asyncio.set_event_loop(self.loop) 65 | self.server = create_server( 66 | self.app, loop=self.loop, host=self.host, port=self.port) 67 | self.server.run() 68 | 69 | def wait(self): 70 | info = (self.host, self.port) 71 | status = check_server(*info) 72 | if status not in (200, 399): 73 | self.loop.call_soon_threadsafe(self._stop) 74 | info += (status,) 75 | raise RuntimeError( 76 | 'Not able to connect to server at %s:%s (%s)' % info) 77 | 78 | def _stop(self): 79 | if self.server is not None: 80 | if getattr(self.server, 'aioserver', None) is not None: 81 | try: 82 | self.server.aioserver.close() 83 | except TypeError: 84 | pass 85 | self.server.close() 86 | self.loop.stop() 87 | 88 | def start(self): 89 | super(WSGIServer, self).start() 90 | self.wait() 91 | 92 | def stop(self): 93 | self.loop.call_soon_threadsafe(self._stop) 94 | -------------------------------------------------------------------------------- /bootstrap.py: -------------------------------------------------------------------------------- 1 | ############################################################################## 2 | # 3 | # Copyright (c) 2006 Zope Foundation and Contributors. 4 | # All Rights Reserved. 5 | # 6 | # This software is subject to the provisions of the Zope Public License, 7 | # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. 8 | # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED 9 | # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 10 | # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS 11 | # FOR A PARTICULAR PURPOSE. 12 | # 13 | ############################################################################## 14 | """Bootstrap a buildout-based project 15 | 16 | Simply run this script in a directory containing a buildout.cfg. 17 | The script accepts buildout command-line options, so you can 18 | use the -c option to specify an alternate configuration file. 19 | """ 20 | 21 | import os 22 | import shutil 23 | import sys 24 | import tempfile 25 | 26 | from optparse import OptionParser 27 | 28 | tmpeggs = tempfile.mkdtemp() 29 | 30 | usage = '''\ 31 | [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] 32 | 33 | Bootstraps a buildout-based project. 34 | 35 | Simply run this script in a directory containing a buildout.cfg, using the 36 | Python that you want bin/buildout to use. 37 | 38 | Note that by using --find-links to point to local resources, you can keep 39 | this script from going over the network. 40 | ''' 41 | 42 | parser = OptionParser(usage=usage) 43 | parser.add_option("-v", "--version", help="use a specific zc.buildout version") 44 | 45 | parser.add_option("-t", "--accept-buildout-test-releases", 46 | dest='accept_buildout_test_releases', 47 | action="store_true", default=False, 48 | help=("Normally, if you do not specify a --version, the " 49 | "bootstrap script and buildout gets the newest " 50 | "*final* versions of zc.buildout and its recipes and " 51 | "extensions for you. If you use this flag, " 52 | "bootstrap and buildout will get the newest releases " 53 | "even if they are alphas or betas.")) 54 | parser.add_option("-c", "--config-file", 55 | help=("Specify the path to the buildout configuration " 56 | "file to be used.")) 57 | parser.add_option("-f", "--find-links", 58 | help=("Specify a URL to search for buildout releases")) 59 | parser.add_option("--allow-site-packages", 60 | action="store_true", default=False, 61 | help=("Let bootstrap.py use existing site packages")) 62 | 63 | 64 | options, args = parser.parse_args() 65 | 66 | ###################################################################### 67 | # load/install setuptools 68 | 69 | try: 70 | if options.allow_site_packages: 71 | import setuptools 72 | import pkg_resources 73 | from urllib.request import urlopen 74 | except ImportError: 75 | from urllib2 import urlopen 76 | 77 | ez = {} 78 | exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) 79 | 80 | if not options.allow_site_packages: 81 | # ez_setup imports site, which adds site packages 82 | # this will remove them from the path to ensure that incompatible versions 83 | # of setuptools are not in the path 84 | import site 85 | # inside a virtualenv, there is no 'getsitepackages'. 86 | # We can't remove these reliably 87 | if hasattr(site, 'getsitepackages'): 88 | for sitepackage_path in site.getsitepackages(): 89 | sys.path[:] = [x for x in sys.path if sitepackage_path not in x] 90 | 91 | setup_args = dict(to_dir=tmpeggs, download_delay=0) 92 | ez['use_setuptools'](**setup_args) 93 | import setuptools 94 | import pkg_resources 95 | 96 | # This does not (always?) update the default working set. We will 97 | # do it. 98 | for path in sys.path: 99 | if path not in pkg_resources.working_set.entries: 100 | pkg_resources.working_set.add_entry(path) 101 | 102 | ###################################################################### 103 | # Install buildout 104 | 105 | ws = pkg_resources.working_set 106 | 107 | cmd = [sys.executable, '-c', 108 | 'from setuptools.command.easy_install import main; main()', 109 | '-mZqNxd', tmpeggs] 110 | 111 | find_links = os.environ.get( 112 | 'bootstrap-testing-find-links', 113 | options.find_links or 114 | ('http://downloads.buildout.org/' 115 | if options.accept_buildout_test_releases else None) 116 | ) 117 | if find_links: 118 | cmd.extend(['-f', find_links]) 119 | 120 | setuptools_path = ws.find( 121 | pkg_resources.Requirement.parse('setuptools')).location 122 | 123 | requirement = 'zc.buildout' 124 | version = options.version 125 | if version is None and not options.accept_buildout_test_releases: 126 | # Figure out the most recent final version of zc.buildout. 127 | import setuptools.package_index 128 | _final_parts = '*final-', '*final' 129 | 130 | def _final_version(parsed_version): 131 | for part in parsed_version: 132 | if (part[:1] == '*') and (part not in _final_parts): 133 | return False 134 | return True 135 | index = setuptools.package_index.PackageIndex( 136 | search_path=[setuptools_path]) 137 | if find_links: 138 | index.add_find_links((find_links,)) 139 | req = pkg_resources.Requirement.parse(requirement) 140 | if index.obtain(req) is not None: 141 | best = [] 142 | bestv = None 143 | for dist in index[req.project_name]: 144 | distv = dist.parsed_version 145 | if _final_version(distv): 146 | if bestv is None or distv > bestv: 147 | best = [dist] 148 | bestv = distv 149 | elif distv == bestv: 150 | best.append(dist) 151 | if best: 152 | best.sort() 153 | version = best[-1].version 154 | if version: 155 | requirement = '=='.join((requirement, version)) 156 | cmd.append(requirement) 157 | 158 | import subprocess 159 | if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: 160 | raise Exception( 161 | "Failed to execute command:\n%s" % repr(cmd)[1:-1]) 162 | 163 | ###################################################################### 164 | # Import and run buildout 165 | 166 | ws.add_entry(tmpeggs) 167 | ws.require(requirement) 168 | import zc.buildout.buildout 169 | 170 | if not [a for a in args if '=' not in a]: 171 | args.append('bootstrap') 172 | 173 | # if -c was provided, we push it back into args for buildout' main function 174 | if options.config_file is not None: 175 | args[0:0] = ['-c', options.config_file] 176 | 177 | zc.buildout.buildout.main(args) 178 | shutil.rmtree(tmpeggs) 179 | -------------------------------------------------------------------------------- /buildout.cfg: -------------------------------------------------------------------------------- 1 | [buildout] 2 | newest = false 3 | extensions = gp.vcsdevelop 4 | parts = eggs 5 | develop = . 6 | 7 | [eggs] 8 | recipe = zc.recipe.egg 9 | eggs = 10 | Sphinx 11 | waitress 12 | aiowsgi 13 | 14 | [tests] 15 | recipe = zc.recipe.egg 16 | eggs = 17 | aiowsgi[test] 18 | dependent-scripts = true 19 | scripts = nosetests 20 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = ../bin/sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/aiowsgi.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/aiowsgi.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/aiowsgi" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/aiowsgi" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # aiowsgi documentation build configuration file, created by 4 | # sphinx-quickstart on Thu May 8 23:21:43 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'aiowsgi' 44 | copyright = u'2014, Gael Pasgrimaud' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '' 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = ['_build'] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | #html_title = None 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = None 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'aiowsgidoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | latex_elements = { 173 | # The paper size ('letterpaper' or 'a4paper'). 174 | #'papersize': 'letterpaper', 175 | 176 | # The font size ('10pt', '11pt' or '12pt'). 177 | #'pointsize': '10pt', 178 | 179 | # Additional stuff for the LaTeX preamble. 180 | #'preamble': '', 181 | } 182 | 183 | # Grouping the document tree into LaTeX files. List of tuples 184 | # (source start file, target name, title, author, documentclass [howto/manual]). 185 | latex_documents = [ 186 | ('index', 'aiowsgi.tex', u'aiowsgi Documentation', 187 | u'Gael Pasgrimaud', 'manual'), 188 | ] 189 | 190 | # The name of an image file (relative to this directory) to place at the top of 191 | # the title page. 192 | #latex_logo = None 193 | 194 | # For "manual" documents, if this is true, then toplevel headings are parts, 195 | # not chapters. 196 | #latex_use_parts = False 197 | 198 | # If true, show page references after internal links. 199 | #latex_show_pagerefs = False 200 | 201 | # If true, show URL addresses after external links. 202 | #latex_show_urls = False 203 | 204 | # Documents to append as an appendix to all manuals. 205 | #latex_appendices = [] 206 | 207 | # If false, no module index is generated. 208 | #latex_domain_indices = True 209 | 210 | 211 | # -- Options for manual page output -------------------------------------------- 212 | 213 | # One entry per manual page. List of tuples 214 | # (source start file, name, description, authors, manual section). 215 | man_pages = [ 216 | ('index', 'aiowsgi', u'aiowsgi Documentation', 217 | [u'Gael Pasgrimaud'], 1) 218 | ] 219 | 220 | # If true, show URL addresses after external links. 221 | #man_show_urls = False 222 | 223 | 224 | # -- Options for Texinfo output ------------------------------------------------ 225 | 226 | # Grouping the document tree into Texinfo files. List of tuples 227 | # (source start file, target name, title, author, 228 | # dir menu entry, description, category) 229 | texinfo_documents = [ 230 | ('index', 'aiowsgi', u'aiowsgi Documentation', 231 | u'Gael Pasgrimaud', 'aiowsgi', 'One line description of project.', 232 | 'Miscellaneous'), 233 | ] 234 | 235 | # Documents to append as an appendix to all manuals. 236 | #texinfo_appendices = [] 237 | 238 | # If false, no module index is generated. 239 | #texinfo_domain_indices = True 240 | 241 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 242 | #texinfo_show_urls = 'footnote' 243 | 244 | html_theme = 'nature' 245 | import pkg_resources 246 | version = pkg_resources.get_distribution("aiowsgi").version 247 | release = version 248 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. aiowsgi documentation master file, created by 2 | sphinx-quickstart on Thu May 8 23:21:43 2014. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | .. include:: ../README.rst 7 | 8 | Usage 9 | ===== 10 | 11 | Install the software: 12 | 13 | .. code-block:: sh 14 | 15 | $ pip install aiowsgi 16 | 17 | Launch the server: 18 | 19 | .. code-block:: sh 20 | 21 | $ aiowsgi-serve yourmodule:application 22 | $ aiowsgi-serve -h 23 | 24 | You can also use a paste factory 25 | 26 | .. code-block:: ini 27 | 28 | [server:main] 29 | use = egg:aiowsgi 30 | 31 | Notice that all options will not work. aiowsgi just use ``waitress`` with a 32 | custom server factory but not all adjustments are implemented. 33 | 34 | 35 | API 36 | === 37 | 38 | .. autofunction:: aiowsgi.serve 39 | 40 | .. autofunction:: aiowsgi.create_server 41 | 42 | .. autoclass:: aiowsgi.thread.WSGIServer 43 | 44 | 45 | 46 | Indices and tables 47 | ================== 48 | 49 | * :ref:`genindex` 50 | * :ref:`modindex` 51 | * :ref:`search` 52 | 53 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [tool:pytest] 2 | addopts = --doctest-modules 3 | --ignore=setup.py 4 | --ignore=bootstrap.py 5 | 6 | [aliases] 7 | dev = develop easy_install aiowsgi[test] 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | from setuptools import setup 4 | from setuptools import find_packages 5 | 6 | version = '0.9.dev0' 7 | 8 | install_requires = ['six', 'waitress', 'webob'] 9 | test_requires = [ 10 | 'pytest', 'six', 'webtest', 'coverage', 'coveralls', 'WSGIProxy2', 11 | ] 12 | 13 | 14 | def read(*rnames): 15 | return open(os.path.join(os.path.dirname(__file__), *rnames)).read() 16 | 17 | 18 | setup( 19 | name='aiowsgi', 20 | version=version, 21 | description="minimalist wsgi server using asyncio", 22 | long_description=read('README.rst'), 23 | classifiers=[ 24 | 'Intended Audience :: Developers', 25 | 'Programming Language :: Python :: 3', 26 | 'License :: OSI Approved :: MIT License', 27 | ], 28 | keywords='', 29 | author='Gael Pasgrimaud', 30 | author_email='gael@gawel.org', 31 | url='https://github.com/gawel/aiowsgi/', 32 | license='MIT', 33 | packages=find_packages(exclude=['docs', 'tests']), 34 | include_package_data=True, 35 | zip_safe=False, 36 | install_requires=install_requires, 37 | extras_require={ 38 | 'test': test_requires, 39 | }, 40 | entry_points=""" 41 | [paste.server_runner] 42 | main = aiowsgi:serve_paste 43 | [console_scripts] 44 | aiowsgi-serve = aiowsgi:run 45 | """, 46 | ) 47 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # package 2 | -------------------------------------------------------------------------------- /tests/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import webob 3 | resp = webob.Response('It works!') 4 | 5 | 6 | async def aioapp(environ, start_response): 7 | return resp(environ, start_response) 8 | 9 | 10 | def app(environ, start_response): 11 | return resp(environ, start_response) 12 | -------------------------------------------------------------------------------- /tests/test_aiowsgi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from webtest.debugapp import debug_app 3 | from webtest import http 4 | from unittest import TestCase 5 | from aiowsgi.compat import asyncio 6 | import aiowsgi 7 | import socket 8 | 9 | 10 | class Transport(object): 11 | 12 | _sock = socket.socket() 13 | 14 | def __init__(self): 15 | self.data = b'' 16 | self.closed = False 17 | 18 | def get_extra_info(self, *args): 19 | return ('1.1.1.1', 5678) 20 | 21 | def write(self, data): 22 | self.data += data 23 | 24 | def close(self): 25 | self.closed = True 26 | 27 | 28 | class TestHttp(TestCase): 29 | 30 | loop = asyncio.new_event_loop() 31 | app = debug_app 32 | 33 | def callFTU(self, **kw): 34 | kw['host'], kw['port'] = http.get_free_port() 35 | s = aiowsgi.create_server(self.app, 36 | threads=1, loop=self.loop, **kw).proto() 37 | s.connection_made(Transport()) 38 | return s 39 | 40 | def test_get(self): 41 | p = self.callFTU() 42 | t = p.transport 43 | channel = p.data_received(b'GET / HTTP/1.1\r\n\r\n') 44 | self.loop.run_until_complete(channel.done) 45 | self.assertFalse(p.request) 46 | self.assertIn(b'REQUEST_METHOD: GET', t.data) 47 | 48 | def test_post(self): 49 | p = self.callFTU() 50 | t = p.transport 51 | channel = p.data_received( 52 | b'POST / HTTP/1.1\r\nContent-Length: 1\r\n\r\nX') 53 | self.loop.run_until_complete(channel.done) 54 | self.assertFalse(p.request) 55 | self.assertIn(b'REQUEST_METHOD: POST', t.data) 56 | self.assertIn(b'CONTENT_LENGTH: 1', t.data) 57 | 58 | def test_post_error(self): 59 | p = self.callFTU(max_request_body_size=1) 60 | p.data_received( 61 | b'POST / HTTP/1.1\r\nContent-Length: 1025\r\n\r\nB') 62 | self.assertFalse(p.request) 63 | 64 | 65 | class TestAsyncHttp(TestHttp): 66 | 67 | async def app(self, *args): 68 | resp = list(debug_app.__call__(*args)) 69 | return resp 70 | 71 | 72 | class Loop(asyncio.get_event_loop().__class__): 73 | 74 | def get_debug(self): 75 | return True 76 | 77 | async def create_server(self, *args, **kwargs): 78 | pass 79 | 80 | async def create_unix_server(self, *args, **kwargs): 81 | pass 82 | 83 | def call_soon(self, callback, *args, context=None): 84 | if context: 85 | context.run(callback, *args) 86 | else: 87 | callback(*args) 88 | 89 | def run_forever(self): 90 | pass 91 | 92 | 93 | class TestServe(TestCase): 94 | 95 | def setUp(self): 96 | loop = asyncio.get_event_loop() 97 | self.addCleanup(asyncio.set_event_loop, loop) 98 | asyncio.set_event_loop(Loop()) 99 | 100 | def test_serve(self): 101 | aiowsgi.serve(debug_app) 102 | 103 | def test_serve_unix(self): 104 | aiowsgi.serve(debug_app, unix_socket='/tmp/sock') 105 | 106 | def test_serve_paste(self): 107 | aiowsgi.serve_paste(debug_app, {}) 108 | 109 | def test_run(self): 110 | aiowsgi.run(['', 'tests.apps:aioapp']) 111 | -------------------------------------------------------------------------------- /tests/test_thread.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from aiowsgi.thread import WSGIServer 3 | from webtest.debugapp import debug_app 4 | from webtest import TestApp 5 | from unittest import TestCase 6 | 7 | 8 | class TestHttp(TestCase): 9 | 10 | def setUp(self): 11 | server = WSGIServer(debug_app) 12 | server.start() 13 | self.addCleanup(server.stop) 14 | self.app = TestApp(server.url) 15 | 16 | def test_page(self): 17 | resp = self.app.get('/') 18 | resp.mustcontain('SERVER_SOFTWARE: aiowsgi') 19 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py37,py38,py39,py310 3 | 4 | [testenv] 5 | skip_install = true 6 | commands = 7 | {envbindir}/py.test [] 8 | deps = 9 | -e .[test] 10 | --------------------------------------------------------------------------------