Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

add wsgi_proxy

  • Loading branch information...
commit 93925a6ac632f8f70240af02c1b51507508c9109 1 parent d1ca415
@gawel gawel authored benoitc committed
View
121 bootstrap.py
@@ -0,0 +1,121 @@
+##############################################################################
+#
+# Copyright (c) 2006 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Bootstrap a buildout-based project
+
+Simply run this script in a directory containing a buildout.cfg.
+The script accepts buildout command-line options, so you can
+use the -c option to specify an alternate configuration file.
+
+$Id$
+"""
+
+import os, shutil, sys, tempfile, urllib2
+from optparse import OptionParser
+
+tmpeggs = tempfile.mkdtemp()
+
+is_jython = sys.platform.startswith('java')
+
+# parsing arguments
+parser = OptionParser()
+parser.add_option("-v", "--version", dest="version",
+ help="use a specific zc.buildout version")
+parser.add_option("-d", "--distribute",
+ action="store_true", dest="distribute", default=False,
+ help="Use Distribute rather than Setuptools.")
+
+parser.add_option("-c", None, action="store", dest="config_file",
+ help=("Specify the path to the buildout configuration "
+ "file to be used."))
+
+options, args = parser.parse_args()
+
+# if -c was provided, we push it back into args for buildout' main function
+if options.config_file is not None:
+ args += ['-c', options.config_file]
+
+if options.version is not None:
+ VERSION = '==%s' % options.version
+else:
+ VERSION = ''
+
+USE_DISTRIBUTE = options.distribute
+args = args + ['bootstrap']
+
+to_reload = False
+try:
+ import pkg_resources
+ if not hasattr(pkg_resources, '_distribute'):
+ to_reload = True
+ raise ImportError
+except ImportError:
+ ez = {}
+ if USE_DISTRIBUTE:
+ exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
+ ).read() in ez
+ ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
+ else:
+ exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
+ ).read() in ez
+ ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
+
+ if to_reload:
+ reload(pkg_resources)
+ else:
+ import pkg_resources
+
+if sys.platform == 'win32':
+ def quote(c):
+ if ' ' in c:
+ return '"%s"' % c # work around spawn lamosity on windows
+ else:
+ return c
+else:
+ def quote (c):
+ return c
+
+cmd = 'from setuptools.command.easy_install import main; main()'
+ws = pkg_resources.working_set
+
+if USE_DISTRIBUTE:
+ requirement = 'distribute'
+else:
+ requirement = 'setuptools'
+
+if is_jython:
+ import subprocess
+
+ assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
+ quote(tmpeggs), 'zc.buildout' + VERSION],
+ env=dict(os.environ,
+ PYTHONPATH=
+ ws.find(pkg_resources.Requirement.parse(requirement)).location
+ ),
+ ).wait() == 0
+
+else:
+ assert os.spawnle(
+ os.P_WAIT, sys.executable, quote (sys.executable),
+ '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
+ dict(os.environ,
+ PYTHONPATH=
+ ws.find(pkg_resources.Requirement.parse(requirement)).location
+ ),
+ ) == 0
+
+ws.add_entry(tmpeggs)
+ws.require('zc.buildout' + VERSION)
+import zc.buildout.buildout
+zc.buildout.buildout.main(args)
+shutil.rmtree(tmpeggs)
View
13 buildout.cfg
@@ -0,0 +1,13 @@
+[buildout]
+newest = false
+parts = eggs
+develop = .
+
+[eggs]
+recipe = zc.recipe.egg
+eggs =
+ pastescript
+ restkit
+ webob
+ nose
+
View
7 proxy.ini
@@ -0,0 +1,7 @@
+[server:main]
+use = egg:Paste#http
+port = 4969
+
+[app:main]
+use = egg:restkit#host_proxy
+uri = http://bitbucket.org
View
100 restkit/ext/wsgi_proxy.py
@@ -0,0 +1,100 @@
+# -*- coding: utf-8 -*-
+from restkit import ConnectionPool
+from restkit import request
+from restkit import ResourceNotFound
+from restkit.sock import CHUNK_SIZE
+
+ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'DELETE']
+
+class IterBody(object):
+
+ def __init__(self, response):
+ self.response = response
+ self.length = int(self.response.headers['content-length'])
+ self.read = 0
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if self.read >= self.length:
+ raise StopIteration
+ elif self.read + CHUNK_SIZE > self.length:
+ size = self.length - self.read
+ self.read = self.length
+ return self.response.body_file.read(size)
+ else:
+ self.read += CHUNK_SIZE
+ return self.response.body_file.read(CHUNK_SIZE)
+
+ def close(self):
+ pass
+
+class Proxy(object):
+
+ def __init__(self, pool=None, allowed_methods=ALLOWED_METHODS, **kwargs):
+ self.pool = pool or ConnectionPool(**kwargs)
+ self.allowed_methods = allowed_methods
+
+ def extract_uri(self, environ):
+ port = None
+ scheme = environ.get('wsgi.url_scheme', 'http')
+ host = environ['HTTP_HOST']
+ if ':' in host:
+ host, port = host.split(':')
+
+ if not port:
+ port = scheme == 'https' and '443' or '80'
+
+ uri = '%s://%s:%s' % (scheme, host, port)
+ return uri
+
+ def __call__(self, environ, start_response):
+ method = environ['REQUEST_METHOD']
+ if method not in self.allowed_methods:
+ start_response('403 Forbidden', ())
+ return ['']
+
+ new_headers = {}
+ for k, v in environ.items():
+ if k.startswith('HTTP_') and k not in ('HTTP_CONNECTION', 'PROXY_CONNECTION'):
+ splited = k.split('_')[1:]
+ k = '-'.join([part.title() for part in splited])
+ new_headers[k] = v
+
+ if method in ('POST', 'PUT'):
+ body = environ['wsgi.input'].read()
+ else:
+ body=None
+
+ path_info = environ['PATH_INFO']
+ query_string = environ['QUERY_STRING']
+ if query_string:
+ path_info += '?' + query_string
+
+ response = request(self.extract_uri(environ)+path_info, method,
+ body=body, headers=new_headers,
+ pool_instance=self.pool)
+
+ start_response(response.status, response.http_client.parser.headers)
+
+ if 'content-length' in response:
+ return IterBody(response)
+ else:
+ return [response.body]
+
+class HostProxy(Proxy):
+
+ def __init__(self, uri=None, **kwargs):
+ super(HostProxy, self).__init__(**kwargs)
+ self.uri = uri.lstrip('/')
+
+ def extract_uri(self, environ):
+ return self.uri
+
+def make_proxy(global_config, **local_config):
+ return Proxy(max_connections=20)
+
+def make_host_proxy(global_config, **local_config):
+ return HostProxy(max_connections=20, **local_config)
+
View
6 setup.py
@@ -44,7 +44,11 @@
entry_points = {
'console_scripts': [
'restcli = restkit.console:main',
- ]
+ ],
+ 'paste.app_factory': [
+ 'proxy = restkit.ext.wsgi_proxy:make_proxy',
+ 'host_proxy = restkit.ext.wsgi_proxy:make_host_proxy',
+ ],
},
test_suite = 'nose.collector',
Please sign in to comment.
Something went wrong with that request. Please try again.