Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

initial commit

  • Loading branch information...
commit 88a8d475b59624e36adaef965e692d6aa5837e15 0 parents
Gael Pasgrimaud authored December 20, 2012
262  bootstrap.py
... ...
@@ -0,0 +1,262 @@
  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, shutil, sys, tempfile, urllib, urllib2, subprocess
  22
+from optparse import OptionParser
  23
+
  24
+if sys.platform == 'win32':
  25
+    def quote(c):
  26
+        if ' ' in c:
  27
+            return '"%s"' % c  # work around spawn lamosity on windows
  28
+        else:
  29
+            return c
  30
+else:
  31
+    quote = str
  32
+
  33
+# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
  34
+stdout, stderr = subprocess.Popen(
  35
+    [sys.executable, '-Sc',
  36
+     'try:\n'
  37
+     '    import ConfigParser\n'
  38
+     'except ImportError:\n'
  39
+     '    print 1\n'
  40
+     'else:\n'
  41
+     '    print 0\n'],
  42
+    stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  43
+has_broken_dash_S = bool(int(stdout.strip()))
  44
+
  45
+# In order to be more robust in the face of system Pythons, we want to
  46
+# run without site-packages loaded.  This is somewhat tricky, in
  47
+# particular because Python 2.6's distutils imports site, so starting
  48
+# with the -S flag is not sufficient.  However, we'll start with that:
  49
+if not has_broken_dash_S and 'site' in sys.modules:
  50
+    # We will restart with python -S.
  51
+    args = sys.argv[:]
  52
+    args[0:0] = [sys.executable, '-S']
  53
+    args = map(quote, args)
  54
+    os.execv(sys.executable, args)
  55
+# Now we are running with -S.  We'll get the clean sys.path, import site
  56
+# because distutils will do it later, and then reset the path and clean
  57
+# out any namespace packages from site-packages that might have been
  58
+# loaded by .pth files.
  59
+clean_path = sys.path[:]
  60
+import site  # imported because of its side effects
  61
+sys.path[:] = clean_path
  62
+for k, v in sys.modules.items():
  63
+    if k in ('setuptools', 'pkg_resources') or (
  64
+        hasattr(v, '__path__') and
  65
+        len(v.__path__) == 1 and
  66
+        not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))):
  67
+        # This is a namespace package.  Remove it.
  68
+        sys.modules.pop(k)
  69
+
  70
+is_jython = sys.platform.startswith('java')
  71
+
  72
+setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
  73
+distribute_source = 'http://python-distribute.org/distribute_setup.py'
  74
+
  75
+
  76
+# parsing arguments
  77
+def normalize_to_url(option, opt_str, value, parser):
  78
+    if value:
  79
+        if '://' not in value:  # It doesn't smell like a URL.
  80
+            value = 'file://%s' % (
  81
+                urllib.pathname2url(
  82
+                    os.path.abspath(os.path.expanduser(value))),)
  83
+        if opt_str == '--download-base' and not value.endswith('/'):
  84
+            # Download base needs a trailing slash to make the world happy.
  85
+            value += '/'
  86
+    else:
  87
+        value = None
  88
+    name = opt_str[2:].replace('-', '_')
  89
+    setattr(parser.values, name, value)
  90
+
  91
+usage = '''\
  92
+[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
  93
+
  94
+Bootstraps a buildout-based project.
  95
+
  96
+Simply run this script in a directory containing a buildout.cfg, using the
  97
+Python that you want bin/buildout to use.
  98
+
  99
+Note that by using --setup-source and --download-base to point to
  100
+local resources, you can keep this script from going over the network.
  101
+'''
  102
+
  103
+parser = OptionParser(usage=usage)
  104
+parser.add_option("-v", "--version", dest="version",
  105
+                          help="use a specific zc.buildout version")
  106
+parser.add_option("-d", "--distribute",
  107
+                   action="store_true", dest="use_distribute", default=False,
  108
+                   help="Use Distribute rather than Setuptools.")
  109
+parser.add_option("--setup-source", action="callback", dest="setup_source",
  110
+                  callback=normalize_to_url, nargs=1, type="string",
  111
+                  help=("Specify a URL or file location for the setup file. "
  112
+                        "If you use Setuptools, this will default to " +
  113
+                        setuptools_source + "; if you use Distribute, this "
  114
+                        "will default to " + distribute_source + "."))
  115
+parser.add_option("--download-base", action="callback", dest="download_base",
  116
+                  callback=normalize_to_url, nargs=1, type="string",
  117
+                  help=("Specify a URL or directory for downloading "
  118
+                        "zc.buildout and either Setuptools or Distribute. "
  119
+                        "Defaults to PyPI."))
  120
+parser.add_option("--eggs",
  121
+                  help=("Specify a directory for storing eggs.  Defaults to "
  122
+                        "a temporary directory that is deleted when the "
  123
+                        "bootstrap script completes."))
  124
+parser.add_option("-t", "--accept-buildout-test-releases",
  125
+                  dest='accept_buildout_test_releases',
  126
+                  action="store_true", default=False,
  127
+                  help=("Normally, if you do not specify a --version, the "
  128
+                        "bootstrap script and buildout gets the newest "
  129
+                        "*final* versions of zc.buildout and its recipes and "
  130
+                        "extensions for you.  If you use this flag, "
  131
+                        "bootstrap and buildout will get the newest releases "
  132
+                        "even if they are alphas or betas."))
  133
+parser.add_option("-c", None, action="store", dest="config_file",
  134
+                   help=("Specify the path to the buildout configuration "
  135
+                         "file to be used."))
  136
+
  137
+options, args = parser.parse_args()
  138
+
  139
+# if -c was provided, we push it back into args for buildout's main function
  140
+if options.config_file is not None:
  141
+    args += ['-c', options.config_file]
  142
+
  143
+if options.eggs:
  144
+    eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
  145
+else:
  146
+    eggs_dir = tempfile.mkdtemp()
  147
+
  148
+if options.setup_source is None:
  149
+    if options.use_distribute:
  150
+        options.setup_source = distribute_source
  151
+    else:
  152
+        options.setup_source = setuptools_source
  153
+
  154
+if options.accept_buildout_test_releases:
  155
+    args.append('buildout:accept-buildout-test-releases=true')
  156
+args.append('bootstrap')
  157
+
  158
+try:
  159
+    import pkg_resources
  160
+    import setuptools  # A flag.  Sometimes pkg_resources is installed alone.
  161
+    if not hasattr(pkg_resources, '_distribute'):
  162
+        raise ImportError
  163
+except ImportError:
  164
+    ez_code = urllib2.urlopen(
  165
+        options.setup_source).read().replace('\r\n', '\n')
  166
+    ez = {}
  167
+    exec ez_code in ez
  168
+    setup_args = dict(to_dir=eggs_dir, download_delay=0)
  169
+    if options.download_base:
  170
+        setup_args['download_base'] = options.download_base
  171
+    if options.use_distribute:
  172
+        setup_args['no_fake'] = True
  173
+    ez['use_setuptools'](**setup_args)
  174
+    if 'pkg_resources' in sys.modules:
  175
+        reload(sys.modules['pkg_resources'])
  176
+    import pkg_resources
  177
+    # This does not (always?) update the default working set.  We will
  178
+    # do it.
  179
+    for path in sys.path:
  180
+        if path not in pkg_resources.working_set.entries:
  181
+            pkg_resources.working_set.add_entry(path)
  182
+
  183
+cmd = [quote(sys.executable),
  184
+       '-c',
  185
+       quote('from setuptools.command.easy_install import main; main()'),
  186
+       '-mqNxd',
  187
+       quote(eggs_dir)]
  188
+
  189
+if not has_broken_dash_S:
  190
+    cmd.insert(1, '-S')
  191
+
  192
+find_links = options.download_base
  193
+if not find_links:
  194
+    find_links = os.environ.get('bootstrap-testing-find-links')
  195
+if find_links:
  196
+    cmd.extend(['-f', quote(find_links)])
  197
+
  198
+if options.use_distribute:
  199
+    setup_requirement = 'distribute'
  200
+else:
  201
+    setup_requirement = 'setuptools'
  202
+ws = pkg_resources.working_set
  203
+setup_requirement_path = ws.find(
  204
+    pkg_resources.Requirement.parse(setup_requirement)).location
  205
+env = dict(
  206
+    os.environ,
  207
+    PYTHONPATH=setup_requirement_path)
  208
+
  209
+requirement = 'zc.buildout'
  210
+version = options.version
  211
+if version is None and not options.accept_buildout_test_releases:
  212
+    # Figure out the most recent final version of zc.buildout.
  213
+    import setuptools.package_index
  214
+    _final_parts = '*final-', '*final'
  215
+
  216
+    def _final_version(parsed_version):
  217
+        for part in parsed_version:
  218
+            if (part[:1] == '*') and (part not in _final_parts):
  219
+                return False
  220
+        return True
  221
+    index = setuptools.package_index.PackageIndex(
  222
+        search_path=[setup_requirement_path])
  223
+    if find_links:
  224
+        index.add_find_links((find_links,))
  225
+    req = pkg_resources.Requirement.parse(requirement)
  226
+    if index.obtain(req) is not None:
  227
+        best = []
  228
+        bestv = None
  229
+        for dist in index[req.project_name]:
  230
+            distv = dist.parsed_version
  231
+            if _final_version(distv):
  232
+                if bestv is None or distv > bestv:
  233
+                    best = [dist]
  234
+                    bestv = distv
  235
+                elif distv == bestv:
  236
+                    best.append(dist)
  237
+        if best:
  238
+            best.sort()
  239
+            version = best[-1].version
  240
+if version:
  241
+    requirement = '=='.join((requirement, version))
  242
+cmd.append(requirement)
  243
+
  244
+if is_jython:
  245
+    import subprocess
  246
+    exitcode = subprocess.Popen(cmd, env=env).wait()
  247
+else:  # Windows prefers this, apparently; otherwise we would prefer subprocess
  248
+    exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
  249
+if exitcode != 0:
  250
+    sys.stdout.flush()
  251
+    sys.stderr.flush()
  252
+    print ("An error occurred when trying to install zc.buildout. "
  253
+           "Look above this message for any errors that "
  254
+           "were output by easy_install.")
  255
+    sys.exit(exitcode)
  256
+
  257
+ws.add_entry(eggs_dir)
  258
+ws.require(requirement)
  259
+import zc.buildout.buildout
  260
+zc.buildout.buildout.main(args)
  261
+if not options.eggs:  # clean up temporary egg directory
  262
+    shutil.rmtree(eggs_dir)
17  buildout.cfg
... ...
@@ -0,0 +1,17 @@
  1
+[buildout]
  2
+newest = false
  3
+prefer-final = true
  4
+parts = eggs
  5
+develop = .
  6
+
  7
+[eggs]
  8
+recipe = z3c.recipe.scripts
  9
+script-initialization =
  10
+initialization =
  11
+entry-points =
  12
+eggs =
  13
+  nose
  14
+
  15
+[tox]
  16
+recipe = gp.recipe.tox
  17
+
10  setup.cfg
... ...
@@ -0,0 +1,10 @@
  1
+[nosetests]
  2
+with-coverage = true
  3
+cover-package = wsgi_proxy
  4
+with-doctest = true
  5
+doctest-extension = rst
  6
+doctest-fixtures = _fixt
  7
+verbosity = 3
  8
+
  9
+[aliases]
  10
+release = register sdist upload
23  setup.py
... ...
@@ -0,0 +1,23 @@
  1
+from setuptools import setup, find_packages
  2
+
  3
+version = '0.1'
  4
+
  5
+setup(name='wsgi_proxy',
  6
+      version=version,
  7
+      description="",
  8
+      long_description="""\
  9
+""",
  10
+      classifiers=[],
  11
+      keywords='',
  12
+      author='Gael Pasgrimaud',
  13
+      author_email='gael@gawel.org',
  14
+      url='',
  15
+      license='',
  16
+      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
  17
+      include_package_data=True,
  18
+      zip_safe=False,
  19
+      install_requires=['webob', 'six'],
  20
+      entry_points="""
  21
+      # -*- Entry points: -*-
  22
+      """,
  23
+      )
14  tox.ini
... ...
@@ -0,0 +1,14 @@
  1
+[tox]
  2
+envlist = py26,py27,py32,py33
  3
+
  4
+[testenv]
  5
+changedir={toxinidir}
  6
+commands =
  7
+  {envbindir}/nosetests []
  8
+deps =
  9
+  git+git://github.com/Pylons/webtest.git
  10
+  restkit
  11
+  requests
  12
+  urllib3
  13
+  coverage
  14
+  nose
1  wsgi_proxy/__init__.py
... ...
@@ -0,0 +1 @@
  1
+# -*- coding: utf-8 -*-
240  wsgi_proxy/proxies.py
... ...
@@ -0,0 +1,240 @@
  1
+# -*- coding: utf-8 -
  2
+#
  3
+# This file is part of restkit released under the MIT license.
  4
+# See the NOTICE for more information.
  5
+from webob import exc
  6
+import logging
  7
+import socket
  8
+import six
  9
+import re
  10
+
  11
+try:
  12
+    import urlparse
  13
+except ImportError:  # pragma: nocover
  14
+    import urllib.parse as urlparse  # NOQA
  15
+
  16
+try:
  17
+    import httplib
  18
+except ImportError:  # pragma: nocover
  19
+    import http.client as httplib  # NOQA
  20
+
  21
+
  22
+ABSOLUTE_URL_RE = re.compile(r"^https?://", re.I)
  23
+
  24
+ALLOWED_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE']
  25
+
  26
+WEBOB_ERROR = ("Content-Length is set to -1. This usually mean that WebOb has "
  27
+        "already parsed the content body. You should set the Content-Length "
  28
+        "header to the correct value before forwarding your request to the "
  29
+        "proxy: ``req.content_length = str(len(req.body));`` "
  30
+        "req.get_response(proxy)")
  31
+
  32
+
  33
+def rewrite_location(host_uri, location, prefix_path=None):
  34
+    prefix_path = prefix_path or ''
  35
+    url = urlparse.urlparse(location)
  36
+    host_url = urlparse.urlparse(host_uri)
  37
+
  38
+    if not ABSOLUTE_URL_RE.match(location):
  39
+        # remote server doesn't follow rfc2616
  40
+        location = urlparse.urljoin(host_uri, location.lstrip('/'))
  41
+        prefix_path = prefix_path.strip('/')
  42
+        if prefix_path:
  43
+            location = location.replace(host_uri,
  44
+                                        host_uri + '/' + prefix_path)
  45
+        return location
  46
+    elif url.scheme == host_url.scheme and url.netloc == host_url.netloc:
  47
+        return urlparse.urlunparse((host_url.scheme, host_url.netloc,
  48
+            prefix_path + url.path, url.params, url.query, url.fragment))
  49
+    return location
  50
+
  51
+
  52
+class HttpClient(object):
  53
+
  54
+    HTTPConnection = httplib.HTTPConnection
  55
+    HTTPSConnection = httplib.HTTPSConnection
  56
+
  57
+    def __init__(self, **connection_options):
  58
+        self.options = connection_options
  59
+
  60
+    def __call__(self, uri, method, body, headers):
  61
+        ssl = uri.startswith('https://')
  62
+        ConnClass = ssl and self.HTTPSConnection or self.HTTPConnection
  63
+        uri = ssl and uri[8:] or uri[7:]
  64
+        port = ssl and 443 or 80
  65
+        host, path = uri.split('/', 1)
  66
+        path = '/' + path
  67
+        if ':' in host:
  68
+            host, port = host.split(':')
  69
+        conn = ConnClass('%s:%s' % (host, port))
  70
+        if 'Transfer-Encoding' in headers:
  71
+            del headers['Transfer-Encoding']
  72
+        if headers.get('Content-Length'):
  73
+            body = body.read(int(headers['Content-Length']))
  74
+        else:
  75
+            body = None
  76
+        conn.request(method, path, body, headers, **self.options)
  77
+        response = conn.getresponse()
  78
+        status = '%s %s' % (response.status, response.reason)
  79
+        length = response.getheader('content-length')
  80
+        body = response.read(int(length)) if length else response.read()
  81
+        return (status, response.getheader('location', None),
  82
+                response.getheaders(), [body])
  83
+
  84
+
  85
+class Proxy(object):
  86
+    """A proxy which redirect the request to SERVER_NAME:SERVER_PORT
  87
+    and send HTTP_HOST header"""
  88
+
  89
+    header_map = {
  90
+        'HTTP_HOST': 'X_FORWARDED_SERVER',
  91
+        'SCRIPT_NAME': 'X_FORWARDED_SCRIPT_NAME',
  92
+        'wsgi.url_scheme': 'X_FORWARDED_SCHEME',
  93
+        'REMOTE_ADDR': 'X_FORWARDED_FOR',
  94
+        }
  95
+
  96
+    def __init__(self, client=None, allowed_methods=ALLOWED_METHODS,
  97
+            strip_script_name=True, **client_options):
  98
+        self.allowed_methods = allowed_methods
  99
+        self.strip_script_name = strip_script_name
  100
+        if client is None or client == 'httplib':
  101
+            self.http = HttpClient(**client_options)
  102
+        elif hasattr(client, '__call__'):
  103
+            self.http = client
  104
+        else:
  105
+            mod = __import__('wsgi_proxy.%s_client' % client,
  106
+                             globals(), locals(), [''])
  107
+            self.http = mod.HttpClient(**client_options)
  108
+        self.logger = logging.getLogger(__name__)
  109
+
  110
+    def extract_uri(self, environ):
  111
+        port = None
  112
+        scheme = environ['wsgi.url_scheme']
  113
+        if 'SERVER_NAME' in environ:
  114
+            host = environ['SERVER_NAME']
  115
+        else:
  116
+            host = environ['HTTP_HOST']
  117
+        if ':' in host:
  118
+            host, port = host.split(':')
  119
+
  120
+        if not port:
  121
+            if 'SERVER_PORT' in environ:
  122
+                port = environ['SERVER_PORT']
  123
+            else:
  124
+                port = scheme == 'https' and '443' or '80'
  125
+
  126
+        uri = '%s://%s:%s' % (scheme, host, port)
  127
+        return uri
  128
+
  129
+    def process_request(self, uri, method, headers, environ):
  130
+        return self.http(uri, method, environ['wsgi.input'], headers)
  131
+
  132
+    def __call__(self, environ, start_response):
  133
+        method = environ['REQUEST_METHOD']
  134
+        if method not in self.allowed_methods:
  135
+            return exc.HTTPMethodNotAllowed()(environ, start_response)
  136
+
  137
+        if self.strip_script_name:
  138
+            path_info = ''
  139
+        else:
  140
+            path_info = environ['SCRIPT_NAME']
  141
+        path_info += environ['PATH_INFO']
  142
+
  143
+        query_string = environ['QUERY_STRING']
  144
+        if query_string:
  145
+            path_info += '?' + query_string
  146
+
  147
+        for key, dest in self.header_map.items():
  148
+            value = environ.get(key)
  149
+            if value:
  150
+                environ['HTTP_%s' % dest] = value
  151
+
  152
+        host_uri = self.extract_uri(environ)
  153
+        uri = host_uri + path_info
  154
+
  155
+        new_headers = {}
  156
+        for k, v in environ.items():
  157
+            if k.startswith('HTTP_'):
  158
+                k = k[5:].replace('_', '-').title()
  159
+                new_headers[k] = v
  160
+
  161
+        content_type = environ.get("CONTENT_TYPE")
  162
+        if content_type and content_type is not None:
  163
+            new_headers['Content-Type'] = content_type
  164
+
  165
+        content_length = environ.get('CONTENT_LENGTH')
  166
+        transfer_encoding = environ.get('Transfer-Encoding', '').lower()
  167
+        if not content_length and transfer_encoding != 'chunked':
  168
+            new_headers['Transfer-Encoding'] = 'chunked'
  169
+        elif content_length:
  170
+            new_headers['Content-Length'] = content_length
  171
+
  172
+        if new_headers.get('Content-Length', '0') == '-1':
  173
+            resp = exc.HTTPInternalServerError(detail=WEBOB_ERROR)
  174
+            return resp(environ, start_response)
  175
+
  176
+        try:
  177
+            response = self.process_request(uri, method, new_headers, environ)
  178
+        except socket.timeout:
  179
+            return exc.HTTPGatewayTimeout()(environ, start_response)
  180
+        except (socket.error, socket.gaierror):
  181
+            return exc.HTTPBadGateway()(environ, start_response)
  182
+        except Exception as e:
  183
+            self.logger.exception(e)
  184
+            return exc.HTTPInternalServerError()(environ, start_response)
  185
+
  186
+        status, location, headerslist, app_iter = response
  187
+
  188
+        if location:
  189
+            if self.strip_script_name:
  190
+                prefix_path = environ['SCRIPT_NAME']
  191
+            else:
  192
+                prefix_path = None
  193
+
  194
+            new_location = rewrite_location(host_uri, location,
  195
+                    prefix_path=prefix_path)
  196
+
  197
+            headers = []
  198
+            for k, v in headerslist:
  199
+                if k.lower() == 'location':
  200
+                    v = new_location
  201
+                headers.append((k, v))
  202
+        else:
  203
+            headers = headerslist
  204
+
  205
+        start_response(status, headers)
  206
+
  207
+        if method == "HEAD":
  208
+            return [six.b('')]
  209
+
  210
+        return app_iter
  211
+
  212
+
  213
+class TransparentProxy(Proxy):
  214
+    """A proxy based on HTTP_HOST environ variable"""
  215
+
  216
+    def extract_uri(self, environ):
  217
+        port = None
  218
+        scheme = environ['wsgi.url_scheme']
  219
+        host = environ['HTTP_HOST']
  220
+        if ':' in host:
  221
+            host, port = host.split(':')
  222
+
  223
+        if not port:
  224
+            port = scheme == 'https' and '443' or '80'
  225
+
  226
+        uri = '%s://%s:%s' % (scheme, host, port)
  227
+        return uri
  228
+
  229
+
  230
+class HostProxy(Proxy):
  231
+    """A proxy to redirect all request to a specific uri"""
  232
+
  233
+    def __init__(self, uri, **kwargs):
  234
+        super(HostProxy, self).__init__(**kwargs)
  235
+        self.uri = uri.rstrip('/')
  236
+        self.scheme, self.net_loc = urlparse.urlparse(self.uri)[0:2]
  237
+
  238
+    def extract_uri(self, environ):
  239
+        environ['HTTP_HOST'] = self.net_loc
  240
+        return self.uri
27  wsgi_proxy/requests_client.py
... ...
@@ -0,0 +1,27 @@
  1
+# -*- coding: utf-8 -*-
  2
+import requests
  3
+
  4
+
  5
+class HttpClient(object):
  6
+
  7
+    default_options = dict(verify=False, allow_redirects=False)
  8
+
  9
+    def __init__(self, chunk_size=1024 * 24, **requests_options):
  10
+        options = self.default_options.copy()
  11
+        options.update(requests_options)
  12
+        self.options = options
  13
+        self.chunk_size = chunk_size
  14
+
  15
+    def __call__(self, uri, method, body, headers):
  16
+        kwargs = self.options.copy()
  17
+        kwargs['headers'] = headers
  18
+        if 'Transfer-Encoding' in headers:
  19
+            del headers['Transfer-Encoding']
  20
+        if headers.get('Content-Length'):
  21
+            kwargs['data'] = body.read(int(headers['Content-Length']))
  22
+        response = requests.request(method, uri, **kwargs)
  23
+        location = response.headers.get('location') or None
  24
+        status = '%s %s' % (response.status_code, response.reason)
  25
+        headers = [(k.title(), v) for k, v in response.headers.items()]
  26
+        return (status, location, headers,
  27
+                response.iter_content(chunk_size=self.chunk_size))
14  wsgi_proxy/restkit_client.py
... ...
@@ -0,0 +1,14 @@
  1
+# -*- coding: utf-8 -*-
  2
+from restkit.client import Client
  3
+
  4
+
  5
+class HttpClient(object):
  6
+
  7
+    def __init__(self, client=None, **kwargs):
  8
+        self.client = client or Client(**kwargs)
  9
+
  10
+    def __call__(self, uri, method, body, headers):
  11
+        response = self.client.request(uri, method, body=body, headers=headers)
  12
+        location = response.headers.get('location') or None
  13
+        return (response.status, location,
  14
+                response.headerslist, response.tee())
213  wsgi_proxy/tests.py
... ...
@@ -0,0 +1,213 @@
  1
+# -*- coding: utf-8 -*-
  2
+import unittest
  3
+from wsgi_proxy import proxies
  4
+from webtest import TestApp
  5
+from webtest.debugapp import debug_app
  6
+from webtest.http import StopableWSGIServer
  7
+from webob import Request
  8
+import logging
  9
+import socket
  10
+import sys
  11
+
  12
+logging.getLogger('waitress').setLevel(logging.DEBUG)
  13
+
  14
+
  15
+def skip(klass):
  16
+    if sys.version_info[0] > 2:
  17
+        print(sys.version_info)
  18
+        return None
  19
+    return klass
  20
+
  21
+
  22
+def start_response(*args):
  23
+    pass
  24
+
  25
+
  26
+class TestHttplib(unittest.TestCase):
  27
+
  28
+    client = 'httplib'
  29
+    client_options = {}
  30
+
  31
+    def setUp(self):
  32
+        self.server = StopableWSGIServer.create(debug_app)
  33
+        self.application_url = self.server.application_url.rstrip('/')
  34
+        self.proxy = proxies.HostProxy(self.application_url,
  35
+                                       client=self.client,
  36
+                                       **self.client_options)
  37
+        self.app = TestApp(self.proxy)
  38
+
  39
+    def test_form(self):
  40
+        resp = self.app.get('/form.html')
  41
+        resp.mustcontain('</form>')
  42
+        form = resp.form
  43
+        form['name'] = 'gawel'
  44
+        resp = form.submit()
  45
+        resp.mustcontain('name=gawel')
  46
+
  47
+    def test_head(self):
  48
+        resp = self.app.head('/form.html')
  49
+        self.assertEqual(resp.status_int, 200)
  50
+        self.assertEqual(len(resp.body), 0)
  51
+
  52
+    def test_webob_error(self):
  53
+        req = Request.blank('/')
  54
+        req.content_length = '-1'
  55
+        resp = req.get_response(self.proxy)
  56
+        self.assertEqual(resp.status_int, 500, resp)
  57
+
  58
+    def test_not_allowed_method(self):
  59
+        resp = self.app.options('/', status='*')
  60
+        self.assertEqual(resp.status_int, 405)
  61
+
  62
+    def test_status(self):
  63
+        resp = self.app.get('/?status=404', status='*')
  64
+        self.assertEqual(resp.status_int, 404)
  65
+
  66
+    def test_redirect(self):
  67
+        location = self.application_url + '/form.html'
  68
+        resp = self.app.get(
  69
+                '/?status=301%20Redirect&header-location=' + location,
  70
+                status='*')
  71
+        self.assertEqual(resp.status_int, 301, resp)
  72
+        self.assertEqual(resp.location, location)
  73
+
  74
+        location = 'http://foo.com'
  75
+        resp = self.app.get(
  76
+                '/?status=301%20Redirect&header-location=' + location,
  77
+                status='*')
  78
+        self.assertEqual(resp.status_int, 301, resp)
  79
+        self.assertEqual(resp.location, location)
  80
+
  81
+        location = '/foo'
  82
+        resp = self.app.get(
  83
+                '/?status=301%20Redirect&header-location=' + location,
  84
+                status='*')
  85
+        self.assertEqual(resp.status_int, 301, resp)
  86
+        self.assertEqual(resp.location, self.application_url + location)
  87
+
  88
+        location = self.application_url + '/script_name/form.html'
  89
+        self.proxy.strip_script_name = False
  90
+        resp = self.app.get(
  91
+                '/?status=301%20Redirect&header-Location=' + location,
  92
+                status='*', extra_environ={'SCRIPT_NAME': '/script_name'})
  93
+        self.assertEqual(resp.status_int, 301, resp)
  94
+        self.assertEqual(resp.location, location)
  95
+
  96
+    def test_chunked(self):
  97
+        resp = self.app.get('/',
  98
+                            headers=[('Transfer-Encoding', 'chunked')])
  99
+        resp.mustcontain(no='chunked')
  100
+
  101
+    def tearDown(self):
  102
+        self.server.shutdown()
  103
+
  104
+
  105
+class TestUrllib3(TestHttplib):
  106
+
  107
+    client = 'urllib3'
  108
+
  109
+
  110
+class TestRequests(TestHttplib):
  111
+
  112
+    client = 'requests'
  113
+
  114
+
  115
+@skip
  116
+class TestRestkit(TestHttplib):
  117
+
  118
+    client = 'restkit'
  119
+
  120
+    def setUp(self):
  121
+        # we set a pool to not keep connection opened during testing
  122
+        from socketpool import ConnectionPool
  123
+        from restkit.conn import Connection
  124
+        self.client_options = dict(pool=ConnectionPool(factory=Connection,
  125
+                                                       max_lifetime=.001))
  126
+        super(TestRestkit, self).setUp()
  127
+
  128
+    def test_chunked(self):
  129
+        resp = self.app.get('/',
  130
+                            headers=[('Transfer-Encoding', 'chunked')])
  131
+        resp.mustcontain('chunked')
  132
+
  133
+
  134
+class TestExtractUri(unittest.TestCase):
  135
+
  136
+    def test_proxy(self):
  137
+        environ = Request.blank('/').environ.copy()
  138
+        proxy = proxies.Proxy()
  139
+        if 'SERVER_NAME' in environ:
  140
+            del environ['SERVER_NAME']
  141
+        uri = proxy.extract_uri(environ)
  142
+        self.assertEqual(uri, 'http://localhost:80')
  143
+
  144
+        environ['SERVER_NAME'] = 'foo'
  145
+        environ['SERVER_PORT'] = '8080'
  146
+        uri = proxy.extract_uri(environ)
  147
+        self.assertEqual(uri, 'http://foo:8080')
  148
+
  149
+        del environ['SERVER_PORT']
  150
+        del environ['HTTP_HOST']
  151
+        environ['SERVER_NAME'] = 'foo'
  152
+        environ['wsgi.url_scheme'] = 'https'
  153
+        uri = proxy.extract_uri(environ)
  154
+        self.assertEqual(uri, 'https://foo:443')
  155
+
  156
+    def test_transparent_proxy(self):
  157
+        req = Request.blank('/')
  158
+        proxy = proxies.TransparentProxy()
  159
+        uri = proxy.extract_uri(req.environ)
  160
+        self.assertEqual(uri, 'http://localhost:80')
  161
+
  162
+        req.scheme = 'https'
  163
+        req.environ['HTTP_HOST'] = 'foo'
  164
+        uri = proxy.extract_uri(req.environ)
  165
+        self.assertEqual(uri, 'https://foo:443')
  166
+
  167
+
  168
+class TestMisc(unittest.TestCase):
  169
+
  170
+    def test_socket_gaierror(self):
  171
+        def client(*args):
  172
+            raise socket.gaierror()
  173
+        proxy = proxies.Proxy(client)
  174
+        app = TestApp(proxy)
  175
+        resp = app.get('/', status='*')
  176
+        self.assertEqual(resp.status_int, 502)
  177
+
  178
+    def test_socket_timeout(self):
  179
+        def client(*args):
  180
+            raise socket.timeout()
  181
+        proxy = proxies.Proxy(client)
  182
+        app = TestApp(proxy)
  183
+        resp = app.get('/', status='*')
  184
+        self.assertEqual(resp.status_int, 504)
  185
+
  186
+    def test_exception(self):
  187
+        def client(*args):
  188
+            raise ValueError()
  189
+        proxy = proxies.Proxy(client)
  190
+        app = TestApp(proxy)
  191
+        resp = app.get('/', status='*')
  192
+        self.assertEqual(resp.status_int, 500)
  193
+
  194
+    def test_rewrite_location(self):
  195
+        location = proxies.rewrite_location('http://localhost:80', '/foo')
  196
+        self.assertEqual(location, 'http://localhost:80/foo')
  197
+
  198
+        location = proxies.rewrite_location('http://localhost:80',
  199
+                                            '/foo', '/path')
  200
+        self.assertEqual(location, 'http://localhost:80/path/foo')
  201
+
  202
+        location = proxies.rewrite_location('http://localhost:80',
  203
+                                            'http://localhost:80/foo', '/path')
  204
+        self.assertEqual(location, 'http://localhost:80/path/foo')
  205
+
  206
+
  207
+class DummyConnection(object):
  208
+
  209
+    def __init__(self, *args, **kwargs):
  210
+        pass
  211
+
  212
+    def request(self, *args, **kwargs):
  213
+        raise kwargs['exc']
28  wsgi_proxy/urllib3_client.py
... ...
@@ -0,0 +1,28 @@
  1
+# -*- coding: utf-8 -*-
  2
+import urllib3
  3
+
  4
+
  5
+class HttpClient(object):
  6
+
  7
+    default_options = dict(redirect=False)
  8
+
  9
+    def __init__(self, pool=None, **urlopen_options):
  10
+        self.pool = pool or urllib3.PoolManager(10)
  11
+        options = self.default_options.copy()
  12
+        options.update(urlopen_options)
  13
+        self.options = options
  14
+
  15
+    def __call__(self, uri, method, body, headers):
  16
+        if 'Transfer-Encoding' in headers:
  17
+            del headers['Transfer-Encoding']
  18
+        if headers.get('Content-Length'):
  19
+            body = body.read(int(headers['Content-Length']))
  20
+        elif body is not None:
  21
+            body = body.read()
  22
+        kwargs = self.options.copy()
  23
+        kwargs.update(body=body, headers=headers)
  24
+        response = self.pool.urlopen(method, uri, **kwargs)
  25
+        status = '%s %s' % (response.status, response.reason)
  26
+        headers = [(k.title(), v) for k, v in response.getheaders().items()]
  27
+        return (status, response.getheader('location', None),
  28
+                headers, [response.data])

0 notes on commit 88a8d47

Please sign in to comment.
Something went wrong with that request. Please try again.