├── .gitignore ├── LICENSE ├── README.md ├── bin └── aiohttpproxy ├── lib └── aiohttpproxy │ ├── __init__.py │ ├── cache.py │ ├── error.py │ └── server.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | parts/ 17 | sdist/ 18 | var/ 19 | *.egg-info/ 20 | .installed.cfg 21 | *.egg 22 | 23 | # PyInstaller 24 | # Usually these files are written by a python script from a template 25 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 26 | *.manifest 27 | *.spec 28 | 29 | # Installer logs 30 | pip-log.txt 31 | pip-delete-this-directory.txt 32 | 33 | # Unit test / coverage reports 34 | htmlcov/ 35 | .tox/ 36 | .coverage 37 | .cache 38 | nosetests.xml 39 | coverage.xml 40 | 41 | # Translations 42 | *.mo 43 | *.pot 44 | 45 | # Django stuff: 46 | *.log 47 | 48 | # Sphinx documentation 49 | docs/_build/ 50 | 51 | # PyBuilder 52 | target/ 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | aiohttpproxy 2 | ============ 3 | 4 | Simple caching HTTP proxy based on the Python aiohttp asynchronous-I/O HTTP module. 5 | 6 | Currently only GET requests to HTTP URLs are proxied. 7 | 8 | Installation 9 | ------------ 10 | 11 | aiohttpproxy requires Python 3.4 or later. 12 | 13 | Install using your favorite Python packager: 14 | 15 | $ easy_install-3.4 aiohttpproxy-0.0.1/ 16 | $ pip-3.4 install git+https://github.com/jmehnle/aiohttpproxy.git 17 | 18 | Usage 19 | ----- 20 | 21 | The proxy is controlled entirely from the command-line, with the following syntax: 22 | 23 | usage: aiohttpproxy [-h] [-l LEVEL] [--port PORT] --cache-path PATH 24 | [--cache-max-size SIZE] [--cache-max-entries COUNT] 25 | [--cache-max-age SECONDS] 26 | 27 | optional arguments: 28 | -h, --help show this help message and exit 29 | -l LEVEL, --log-level LEVEL 30 | Log level (critical, error, warning, info, debug) 31 | --port PORT TCP port to listen on (default: 8080) 32 | --cache-path PATH Cache directory 33 | --cache-max-size SIZE 34 | Max total cache size in bytes 35 | --cache-max-entries COUNT 36 | Max number of cache entries 37 | --cache-max-age SECONDS 38 | Max age of cache entries 39 | 40 | Sample invocation: 41 | 42 | $ mkdir /var/tmp/aiohttpproxy.cache 43 | $ aiohttpproxy --log-level info \ 44 | --cache-path /var/tmp/aiohttpproxy.cache \ 45 | --cache-max-size 1048576 --cache-max-entries 1000 --cache-max-age 60 46 | 47 | ... limits the number of cached responses to 1000 and their total content size to 1MB, and expires cache entries after 60 seconds. 48 | 49 | Terminate the proxy with `Ctrl+C` or by sending SIGINT. 50 | 51 | Copyright 52 | --------- 53 | 54 | (C) 2014 Julian Mehnle 55 | -------------------------------------------------------------------------------- /bin/aiohttpproxy: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3.4 2 | 3 | import argparse 4 | import logging 5 | import asyncio 6 | 7 | from aiohttpproxy.error import * 8 | import aiohttpproxy.server 9 | import aiohttpproxy.cache 10 | 11 | def parse_options(): 12 | parser = argparse.ArgumentParser() 13 | parser.add_argument( 14 | '-l', '--log-level', dest = 'log_level', type = str, default = 'WARNING', 15 | help = 'Log level (critical, error, warning, info, debug)', metavar = 'LEVEL') 16 | parser.add_argument( 17 | '--port', dest = 'listen_port', type = int, default = 8080, 18 | help = 'TCP port to listen on (default: 8080)', metavar = 'PORT') 19 | parser.add_argument( 20 | '--cache-path', dest = 'cache_path', type = str, required = True, 21 | help = 'Cache directory', metavar = 'PATH') 22 | parser.add_argument( 23 | '--cache-max-size', dest = 'cache_max_size', type = int, default = 1024**2, 24 | help = 'Max total cache size in bytes', metavar = 'SIZE') 25 | parser.add_argument( 26 | '--cache-max-entries', dest = 'cache_max_entries', type = int, default = None, 27 | help = 'Max number of cache entries', metavar = 'COUNT') 28 | parser.add_argument( 29 | '--cache-max-age', dest = 'cache_max_age', type = float, default = None, 30 | help = 'Max age of cache entries', metavar = 'SECONDS') 31 | return parser.parse_args() 32 | 33 | def main(options): 34 | numeric_log_level = getattr(logging, options.log_level.upper()) 35 | if not isinstance(numeric_log_level, int): 36 | raise OptionsError('Invalid log level: {0}'.format(options.log_level)) 37 | logging.basicConfig(level = numeric_log_level) 38 | 39 | port = options.listen_port 40 | 41 | cache = aiohttpproxy.cache.LRUCache( 42 | options.cache_path, 43 | options.cache_max_size, 44 | options.cache_max_entries, 45 | options.cache_max_age 46 | ) 47 | 48 | loop = asyncio.get_event_loop() 49 | 50 | server_future = loop.create_server( 51 | lambda: aiohttpproxy.server.ProxyRequestHandler(cache), '', port) 52 | server = loop.run_until_complete(server_future) 53 | print('Accepting HTTP proxy requests on {0}:{1} ...'.format(*server.sockets[0].getsockname())) 54 | 55 | try: 56 | loop.run_forever() 57 | except KeyboardInterrupt: 58 | print() 59 | finally: 60 | cache.clear() 61 | 62 | if __name__ == '__main__': 63 | options = parse_options() 64 | main(options) 65 | 66 | # vim:sw=4 sts=4 67 | -------------------------------------------------------------------------------- /lib/aiohttpproxy/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.0.1' 2 | -------------------------------------------------------------------------------- /lib/aiohttpproxy/cache.py: -------------------------------------------------------------------------------- 1 | import os, os.path 2 | import time 3 | import hashlib 4 | import collections 5 | import logging 6 | from contextlib import suppress 7 | 8 | class CacheError(Exception): pass 9 | 10 | class CacheSizeExceededError(CacheError): pass 11 | 12 | class CacheEntry: 13 | @classmethod 14 | def filename(cls, key): 15 | return hashlib.sha1(bytes(key, 'utf-8')).hexdigest() 16 | 17 | def __init__(self, cache, key, metadata = None): 18 | self.cache = cache 19 | self.key = key 20 | self.metadata = metadata 21 | self.filename = os.path.join(cache.path, type(self).filename(key)) 22 | 23 | # Initialize state: 24 | self.dirty() 25 | 26 | def dirty(self): 27 | self.__size = None 28 | self.__atime, self.__mtime = None, None 29 | 30 | @property 31 | def size(self): 32 | if self.__size is None: 33 | self.__size = os.stat(self.filename).st_size 34 | return self.__size 35 | 36 | @property 37 | def mtime(self): 38 | if self.__mtime is None: 39 | stat = os.stat(self.filename) 40 | self.__atime, self.__mtime = stat.st_atime, stat.st_mtime 41 | return self.__mtime 42 | 43 | @mtime.setter 44 | def mtime(self, value): 45 | self.__mtime = value 46 | os.utime(self.filename, (self.__atime, self.__mtime)) 47 | 48 | def delete(self): 49 | os.remove(self.filename) 50 | 51 | class LRUCache: 52 | def __init__(self, path, max_size = None, max_entries = None, max_age = None): 53 | path = str(path) 54 | if not os.path.isdir(path): 55 | raise ValueError('Cache path not a directory: {0}'.format(path)) 56 | if not os.access(path, os.W_OK | os.X_OK): 57 | raise ValueError('Cache path is not writable: {0}'.format(path)) 58 | 59 | logging.debug( 60 | 'Creating cache at {0} with max size {1}, max entries {2}, max age {3}s'.format( 61 | path, max_size, max_entries, max_age)) 62 | 63 | # Configuration: 64 | self.path = path 65 | self.max_size = max_size 66 | self.max_entries = max_entries 67 | self.max_age = max_age 68 | 69 | # State: 70 | self.clear() 71 | 72 | def __getitem__(self, key): 73 | entry = self.entries[key] 74 | if self.max_age and time.time() > entry.mtime + self.max_age: 75 | del self[key] 76 | raise KeyError 77 | self.entries.move_to_end(key) # Update access order. 78 | return entry 79 | 80 | def __setitem__(self, key, entry): 81 | with suppress(KeyError): 82 | del self[key] 83 | if entry.size > self.max_size: 84 | raise CacheSizeExceededError('Requested entry size ({0}) exceeds overall cache size ({1})'.format(entry.size, self.max_size)) 85 | if ( 86 | (self.max_entries and self.max_entries < len(self.entries) + 1) or 87 | (self.max_size and self.max_size < self.size + entry.size) 88 | ): 89 | self.expire() 90 | while ( 91 | (self.max_entries and self.max_entries < len(self.entries) + 1) or 92 | (self.max_size and self.max_size < self.size + entry.size) 93 | ): 94 | self.discard_one() 95 | self.entries[key] = entry 96 | 97 | def __delitem__(self, key): 98 | entry = self.entries.pop(key) 99 | self.size = self.size - entry.size 100 | entry.delete() 101 | 102 | def __iter__(self): 103 | return self.entries.itervalues() 104 | 105 | def __contains__(self, key): 106 | return key in self.entries 107 | 108 | def new_entry(self, key, metadata = None, size = None): 109 | if size and size > self.max_size: 110 | raise CacheSizeExceededError('Requested entry size ({0}) exceeds overall cache size ({1})'.format(size, self.max_size)) 111 | return CacheEntry(self, key, metadata) 112 | 113 | def clear(self): 114 | with suppress(AttributeError): 115 | for entry in self.entries.values(): 116 | entry.delete() 117 | self.entries = collections.OrderedDict() 118 | self.size = 0 119 | 120 | def expire(self): 121 | if self.max_age is None: 122 | return 123 | now = time.time() 124 | expired_entries = [] 125 | for key, entry in self.entries.items(): 126 | if now > entry.mtime + self.max_age: 127 | del self[key] 128 | expired_entries.append(entry) 129 | return expired_entries 130 | 131 | def discard_one(self): 132 | key, entry = next(iter(self.entries.items())) # Determine LRU entry. 133 | del self[key] 134 | return entry 135 | 136 | # vim:sw=2 sts=2 137 | -------------------------------------------------------------------------------- /lib/aiohttpproxy/error.py: -------------------------------------------------------------------------------- 1 | class Error(Exception): 2 | def __init__(self, message = None, original_exception = None, exception_location = None): 3 | StandardError.__init__(self) 4 | self.message = message 5 | self.original_exception = original_exception 6 | self.filename, self.lineno, self.scope, self.line = exception_location \ 7 | if exception_location \ 8 | else (None, None, None, None) 9 | 10 | class OptionsError(Error): pass # Options error. 11 | 12 | # vim:sw=4 sts=4 13 | -------------------------------------------------------------------------------- /lib/aiohttpproxy/server.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os, os.path 3 | import logging 4 | import time 5 | import asyncio 6 | import aiohttp 7 | import aiohttp.server 8 | import urllib.parse 9 | import json 10 | from contextlib import suppress 11 | 12 | import aiohttpproxy 13 | from aiohttpproxy import cache 14 | 15 | class ProxyRequestHandler(aiohttp.server.ServerHttpProtocol): 16 | def __init__(self, cache = None): 17 | super(ProxyRequestHandler, self).__init__() 18 | self.cache = cache 19 | 20 | @asyncio.coroutine 21 | def handle_request(self, message, payload): 22 | now = time.time() 23 | 24 | url = message.path 25 | url_parsed = urllib.parse.urlparse(url) 26 | 27 | logging.info('{0} {1}'.format(message.method, url)) 28 | 29 | if message.method == 'GET' and url == '/ping': 30 | # Generate pong. 31 | logging.info('Ping, Pong.') 32 | yield from self.send_pong_response(200, message.version) 33 | return 34 | 35 | if message.method != 'GET' or url_parsed.scheme.lower() != 'http': 36 | # Only GET method and http: scheme supported. 37 | logging.info('Refusing non-GET/HTTP request: {0}'.format(url)) 38 | yield from self.send_response(501, message.version) 39 | return 40 | 41 | if self.cache: 42 | try: 43 | cache_entry = self.cache[url] 44 | except KeyError: 45 | cache_entry = None 46 | 47 | serve_from_cache = self.cache and bool(cache_entry) 48 | store_in_cache = self.cache and not bool(cache_entry) 49 | 50 | if serve_from_cache: 51 | cache_metadata = cache_entry.metadata 52 | cache_file = open(cache_entry.filename, 'rb') 53 | logging.debug('Serving response from cache (filename = {0}, age = {1:.3}s).'.format( 54 | cache_entry.filename, now - cache_entry.mtime)) 55 | 56 | response = cache_metadata['response'] 57 | else: 58 | # Execute request and cache response: 59 | logging.debug('Executing request.') 60 | 61 | response = yield from aiohttp.request('GET', url, headers = message.headers) 62 | response_content = response.content 63 | 64 | if store_in_cache: 65 | try: 66 | size = int(response.headers['Content-Length']) 67 | except (ValueError, KeyError): 68 | size = None 69 | try: 70 | cache_metadata = { 'response': response } 71 | cache_entry = self.cache.new_entry(url, cache_metadata, size) 72 | cache_file = open(cache_entry.filename, 'wb') 73 | logging.debug('Storing response in cache (filename = {0}).'.format( 74 | cache_entry.filename)) 75 | except cache.CacheSizeExceededError: 76 | # Do not cache responses larger than cache size. 77 | store_in_cache = False 78 | logging.debug('Not caching response exceeding overall cache size ({0} > {1}).'.format( 79 | size, self.cache.max_size)) 80 | 81 | proxy_response = aiohttp.Response( 82 | self.writer, response.status, http_version = response.version) 83 | proxy_response_headers = [ 84 | (name, value) 85 | for name, value 86 | in response.headers.items(getall = True) 87 | if name not in ('CONTENT-ENCODING') 88 | ] 89 | # Copy response headers, except for Content-Encoding header, 90 | # since unfortunately aiohttp transparently decodes content. 91 | proxy_response.add_headers(*proxy_response_headers) 92 | proxy_response.send_headers() 93 | 94 | try: 95 | while True: 96 | if serve_from_cache: 97 | chunk = cache_file.read(io.DEFAULT_BUFFER_SIZE) 98 | else: 99 | chunk = yield from response_content.read(io.DEFAULT_BUFFER_SIZE) 100 | if not chunk: 101 | break 102 | proxy_response.write(chunk) 103 | if store_in_cache: 104 | cache_file.write(chunk) 105 | 106 | yield from proxy_response.write_eof() 107 | 108 | finally: 109 | if serve_from_cache or store_in_cache: 110 | cache_file.close() 111 | if store_in_cache: 112 | self.cache[url] = cache_entry 113 | 114 | @asyncio.coroutine 115 | def send_response(self, status, http_version, headers = None, text = b''): 116 | response = aiohttp.Response(self.writer, status, http_version = http_version) 117 | if isinstance(headers, list): 118 | for name, value in headers: 119 | response.add_header(name, value) 120 | response.add_header('Content-Length', str(len(text))) 121 | response.send_headers() 122 | response.write(text) 123 | yield from response.write_eof() 124 | 125 | @asyncio.coroutine 126 | def send_pong_response(self, status, http_version): 127 | response_text = json.dumps( 128 | { 129 | 'version': aiohttpproxy.__version__ 130 | }, 131 | indent = 4 132 | ).encode('ascii') 133 | yield from self.send_response(status, http_version, text = response_text) 134 | 135 | # vim:sw=4 sts=4 136 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import re 4 | from setuptools import setup 5 | 6 | if not sys.hexversion >= 0x30400f0: 7 | raise RuntimeError("Python 3.4 or later required") 8 | 9 | with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 10 | 'lib', 'aiohttpproxy', '__init__.py'), 'r') as f: 11 | try: 12 | version = re.findall(r"^__version__ = '([^']+)'$", f.read(), re.M)[0] 13 | except IndexError: 14 | raise RuntimeError('Unable to determine version') 15 | 16 | install_requires = ['aiohttp'] 17 | 18 | tests_require = install_requires + ['nose'] 19 | 20 | setup( 21 | name = 'aiohttpproxy', 22 | version = version, 23 | description = 'Simple aiohttp HTTP Proxy', 24 | url = 'https://github.com/jmehnle/aiohttpproxy', 25 | author = 'Julian Mehnle', 26 | author_email = 'julian@mehnle.net', 27 | license = 'Apache-2.0', 28 | package_dir = {'': 'lib'}, 29 | packages = ['aiohttpproxy'], 30 | install_requires = install_requires, 31 | tests_require = tests_require, 32 | test_suite = 'nose.collector', 33 | scripts = ['bin/aiohttpproxy'] 34 | ) 35 | 36 | # vim:sw=4 sts=4 37 | --------------------------------------------------------------------------------