wsgiproxy2_0.4.5.orig/.travis.yml0000644000000000000000000000021313051524570015133 0ustar 00000000000000language: python python: 3.5 sudo: false install: - pip install tox script: - tox env: - TOXENV=py27 - TOXENV=py34 - TOXENV=py35 wsgiproxy2_0.4.5.orig/CHANGES.rst0000644000000000000000000000146413350516754014644 0ustar 00000000000000Changes ======= 0.4.5 (2018-09-19) ------------------ - Allow to use URIs with no path 0.4.4 (2017-06-02) ------------------ - Clean up connection before returning result. This removes some ResourceWarnings when testing 0.4.3 (2017-02-17) ------------------ - Add OPTIONS to defaults allowed methods - Drop restkit support - Drop py26 support 0.4.2 (2014-12-20) ------------------ - Undo webob's unquoting to handle paths with percent quoted utf8 characters [Laurence Rowe] 0.4.1 (2013-12-21) ------------------ - Include README_fixt.py in release 0.4 (2013-12-21) ---------------- - fix tests. - change the way requests iter response 0.3 (2013-09-12) ---------------- Make allowed_methods check optional 0.2 --- Return the data not gzip decoded when using request 0.1 --- Initial release wsgiproxy2_0.4.5.orig/COPYING0000644000000000000000000000177712657767142014114 0ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. wsgiproxy2_0.4.5.orig/MANIFEST.in0000644000000000000000000000031513051525214014557 0ustar 00000000000000graft docs prune docs/_build graft wsgiproxy include *.rst include *_fixt.py global-exclude *.pyc global-exclude __pycache__ include *.py include *.txt include COPYING include buildout.cfg include tox.ini wsgiproxy2_0.4.5.orig/README.rst0000644000000000000000000000241512074320002014503 0ustar 00000000000000Installation ============ With pip:: $ pip install WSGIProxy2 Install optionnal backends:: $ pip install requests restkit urllib3 Usage ===== Create a proxy:: >>> from wsgiproxy import HostProxy >>> proxy = HostProxy(application_url) Then use it. Here is an example with WebOb but you can use it like a classic WSGI application:: >>> from webob import Request >>> req = Request.blank('/form.html') >>> resp = req.get_response(proxy) >>> print(resp.text) ... ... The Proxy application accept some keyword arguments. Those arguments are passed to the client during the process. If no client as specified then python httplib is used. It's recommended to use a more robust client able to manage a connection pool and stuff. Use `urllib3 `_:: >>> proxy = HostProxy(application_url, client='urllib3') Use `requests `_. This client support response streaming:: >>> proxy = HostProxy(application_url, client='requests') Use `restkit `_. This client support request and response streaming but does not support python3 (will be fixed with the next release):: >>> proxy = HostProxy(application_url, client='restkit') # doctest: +SKIP wsgiproxy2_0.4.5.orig/README_fixt.py0000644000000000000000000000072712065341110015364 0ustar 00000000000000# -*- coding: utf-8 -*- from doctest import ELLIPSIS from webtest.debugapp import debug_app from webtest.http import StopableWSGIServer def setup_test(test): test.globs['server'] = StopableWSGIServer.create(debug_app) test.globs['application_url'] = test.globs['server'].application_url for example in test.examples: example.options.setdefault(ELLIPSIS, 1) setup_test.__test__ = False def teardown_test(test): test.globs['server'].shutdown() wsgiproxy2_0.4.5.orig/bootstrap.py0000755000000000000000000002357312064447425015440 0ustar 00000000000000############################################################################## # # Copyright (c) 2006 Zope Foundation 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. """ import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) 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's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir) wsgiproxy2_0.4.5.orig/buildout.cfg0000644000000000000000000000040212074316601015330 0ustar 00000000000000[buildout] newest = false prefer-final = true parts = docs tox develop = . [docs] recipe = z3c.recipe.scripts script-initialization = initialization = entry-points = eggs = WSGIProxy2 urllib3 requests restkit Sphinx [tox] recipe = gp.recipe.tox wsgiproxy2_0.4.5.orig/docs/0000755000000000000000000000000012065352632013760 5ustar 00000000000000wsgiproxy2_0.4.5.orig/requirements.txt0000644000000000000000000000003112065352632016306 0ustar 00000000000000urllib3 requests restkit wsgiproxy2_0.4.5.orig/setup.cfg0000644000000000000000000000027112215642623014650 0ustar 00000000000000[nosetests] with-coverage = true cover-package = wsgiproxy with-doctest = true doctest-extension = rst doctest-fixtures = _fixt verbosity = 3 [aliases] release = register sdist upload wsgiproxy2_0.4.5.orig/setup.py0000644000000000000000000000215513350516754014552 0ustar 00000000000000from setuptools import setup, find_packages version = '0.4.5' def read(name): try: with open(name) as fd: return fd.read() except: return '' setup(name='WSGIProxy2', version=version, long_description=read('README.rst') + '\n' + read('CHANGES.rst'), description='A WSGI Proxy with various http client backends', classifiers=[ 'License :: OSI Approved :: MIT License', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], keywords='wsgi proxy', author='Gael Pasgrimaud', author_email='gael@gawel.org', url='https://github.com/gawel/WSGIProxy2/', license='MIT', packages=find_packages(exclude=['ez_setup', 'README_fixt', 'tests']), include_package_data=True, zip_safe=False, install_requires=['webob', 'six'], entry_points=""" # -*- Entry points: -*- """, ) wsgiproxy2_0.4.5.orig/tox.ini0000644000000000000000000000027513051524570014345 0ustar 00000000000000[tox] envlist = py27,py34,py35 [testenv] changedir={toxinidir} commands = {envbindir}/pytest [] deps = git+git://github.com/Pylons/webtest.git requests urllib3 coverage pytest wsgiproxy2_0.4.5.orig/wsgiproxy/0000755000000000000000000000000012074315743015105 5ustar 00000000000000wsgiproxy2_0.4.5.orig/docs/Makefile0000644000000000000000000001272312065352632015425 0ustar 00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = ../bin/sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/wsgi_proxy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/wsgi_proxy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/wsgi_proxy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/wsgi_proxy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." wsgiproxy2_0.4.5.orig/docs/clients.rst0000644000000000000000000000115312074316162016151 0ustar 00000000000000============================== Available http client adapters ============================== .. autoclass:: wsgiproxy.proxies.HttpClient .. autoclass:: wsgiproxy.urllib3_client.HttpClient .. autoclass:: wsgiproxy.requests_client.HttpClient .. autoclass:: wsgiproxy.restkit_client.HttpClient Use your own HTTP client:: >>> def client(uri, method, body, headers): ... headers = [('Content-Length', '0')] ... location = None # the Location header if any ... body_iter = [''] ... return '200 Ok', location, headers, body_iter >>> proxy = HostProxy(application_url, client=client) wsgiproxy2_0.4.5.orig/docs/conf.py0000644000000000000000000001720012074315743015261 0ustar 00000000000000# -*- coding: utf-8 -*- # # WSGIProxy2 documentation build configuration file, created by # sphinx-quickstart on Sat Dec 22 15:44:24 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'WSGIProxy2' copyright = u'2012, Gael Pasgrimaud' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'WSGIProxy2doc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'WSGIProxy2.tex', u'wsgi\\_proxy Documentation', u'Gael Pasgrimaud', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'WSGIProxy2', u'WSGIProxy2 Documentation', [u'Gael Pasgrimaud'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'WSGIProxy2', u'WSGIProxy2 Documentation', u'Gael Pasgrimaud', 'WSGIProxy2', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' wsgiproxy2_0.4.5.orig/docs/index.rst0000644000000000000000000000072312074320774015625 0ustar 00000000000000.. WSGIProxy2 documentation master file, created by sphinx-quickstart on Sat Dec 22 15:44:24 2012. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. ====================================== Welcome to WSGIProxy2's documentation! ====================================== .. include:: ../README.rst Contents ======== .. toctree:: :maxdepth: 2 proxies clients .. include:: ../CHANGES.rst wsgiproxy2_0.4.5.orig/docs/proxies.rst0000644000000000000000000000025212074316162016200 0ustar 00000000000000================= Available proxies ================= .. automodule:: wsgiproxy.proxies .. autoclass:: Proxy .. autoclass:: TransparentProxy .. autoclass:: HostProxy wsgiproxy2_0.4.5.orig/wsgiproxy/__init__.py0000644000000000000000000000022012074315743017210 0ustar 00000000000000# -*- coding: utf-8 -*- from .proxies import Proxy # NOQA from .proxies import HostProxy # NOQA from .proxies import TransparentProxy # NOQA wsgiproxy2_0.4.5.orig/wsgiproxy/proxies.py0000644000000000000000000002166213350515270017152 0ustar 00000000000000# -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. from webob import exc from webob.compat import PY3, url_quote import logging import socket import six import re try: import urlparse except ImportError: # pragma: nocover import urllib.parse as urlparse # NOQA try: import httplib except ImportError: # pragma: nocover import http.client as httplib # NOQA LOW_CHAR_SAFE = ''.join(chr(n) for n in range(128)) ABSOLUTE_URL_RE = re.compile(r"^https?://", re.I) ALLOWED_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS'] WEBOB_ERROR = ( "Content-Length is set to -1. This usually mean that WebOb has " "already parsed the content body. You should set the Content-Length " "header to the correct value before forwarding your request to the " "proxy: ``req.content_length = str(len(req.body));`` " "req.get_response(proxy)") def rewrite_location(host_uri, location, prefix_path=None): prefix_path = prefix_path or '' url = urlparse.urlparse(location) host_url = urlparse.urlparse(host_uri) if not ABSOLUTE_URL_RE.match(location): # remote server doesn't follow rfc2616 location = urlparse.urljoin(host_uri, location.lstrip('/')) prefix_path = prefix_path.strip('/') if prefix_path: location = location.replace(host_uri, host_uri + '/' + prefix_path) return location elif url.scheme == host_url.scheme and url.netloc == host_url.netloc: return urlparse.urlunparse((host_url.scheme, host_url.netloc, prefix_path + url.path, url.params, url.query, url.fragment)) return location class HttpClient(object): """A HTTP client using stdlib's httplib (Default client)""" HTTPConnection = httplib.HTTPConnection HTTPSConnection = httplib.HTTPSConnection def __init__(self, **connection_options): self.options = connection_options def __call__(self, uri, method, body, headers): ssl = uri.startswith('https://') ConnClass = ssl and self.HTTPSConnection or self.HTTPConnection uri = ssl and uri[8:] or uri[7:] port = ssl and 443 or 80 try: host, path = uri.split('/', 1) except ValueError: host = uri path = '' path = '/' + path if ':' in host: host, port = host.split(':') conn = ConnClass('%s:%s' % (host, port)) if 'Transfer-Encoding' in headers: del headers['Transfer-Encoding'] if headers.get('Content-Length'): body = body.read(int(headers['Content-Length'])) else: body = None conn.request(method, path, body, headers, **self.options) response = conn.getresponse() status = '%s %s' % (response.status, response.reason) length = response.getheader('content-length') body = response.read(int(length)) if length else response.read() result = (status, response.getheader('location', None), response.getheaders(), [body]) conn.close() return result class Proxy(object): """A proxy which redirect the request to SERVER_NAME:SERVER_PORT and send HTTP_HOST header""" header_map = { 'HTTP_HOST': 'X_FORWARDED_SERVER', 'SCRIPT_NAME': 'X_FORWARDED_SCRIPT_NAME', 'wsgi.url_scheme': 'X_FORWARDED_SCHEME', 'REMOTE_ADDR': 'X_FORWARDED_FOR', } def __init__(self, client=None, allowed_methods=ALLOWED_METHODS, strip_script_name=True, **client_options): self.allowed_methods = allowed_methods self.strip_script_name = strip_script_name if client is None or client == 'httplib': self.http = HttpClient(**client_options) elif hasattr(client, '__call__'): self.http = client else: mod = __import__('wsgiproxy.%s_client' % client, globals(), locals(), ['']) self.http = mod.HttpClient(**client_options) self.logger = logging.getLogger(__name__) def extract_uri(self, environ): port = None scheme = environ['wsgi.url_scheme'] if 'SERVER_NAME' in environ: host = environ['SERVER_NAME'] else: host = environ['HTTP_HOST'] if ':' in host: host, port = host.split(':') if not port: if 'SERVER_PORT' in environ: port = environ['SERVER_PORT'] else: port = scheme == 'https' and '443' or '80' uri = '%s://%s:%s' % (scheme, host, port) return uri def process_request(self, uri, method, headers, environ): return self.http(uri, method, environ['wsgi.input'], headers) def __call__(self, environ, start_response): method = environ['REQUEST_METHOD'] if (self.allowed_methods is not None and method not in self.allowed_methods): return exc.HTTPMethodNotAllowed()(environ, start_response) if 'RAW_URI' in environ: path_info = environ['RAW_URI'] elif 'REQUEST_URI' in environ: path_info = environ['REQUEST_URI'] else: if self.strip_script_name: path_info = '' else: path_info = environ['SCRIPT_NAME'] path_info += environ['PATH_INFO'] if PY3: path_info = url_quote(path_info.encode('latin-1'), LOW_CHAR_SAFE) query_string = environ['QUERY_STRING'] if query_string: path_info += '?' + query_string for key, dest in self.header_map.items(): value = environ.get(key) if value: environ['HTTP_%s' % dest] = value host_uri = self.extract_uri(environ) uri = host_uri + path_info new_headers = {} for k, v in environ.items(): if k.startswith('HTTP_'): k = k[5:].replace('_', '-').title() new_headers[k] = v content_type = environ.get("CONTENT_TYPE") if content_type and content_type is not None: new_headers['Content-Type'] = content_type content_length = environ.get('CONTENT_LENGTH') transfer_encoding = environ.get('Transfer-Encoding', '').lower() if not content_length and transfer_encoding != 'chunked': new_headers['Transfer-Encoding'] = 'chunked' elif content_length: new_headers['Content-Length'] = content_length if new_headers.get('Content-Length', '0') == '-1': resp = exc.HTTPInternalServerError(detail=WEBOB_ERROR) return resp(environ, start_response) try: response = self.process_request(uri, method, new_headers, environ) except socket.timeout: return exc.HTTPGatewayTimeout()(environ, start_response) except (socket.error, socket.gaierror): return exc.HTTPBadGateway()(environ, start_response) except Exception as e: self.logger.exception(e) return exc.HTTPInternalServerError()(environ, start_response) status, location, headerslist, app_iter = response if location: if self.strip_script_name: prefix_path = environ['SCRIPT_NAME'] else: prefix_path = None new_location = rewrite_location(host_uri, location, prefix_path=prefix_path) headers = [] for k, v in headerslist: if k.lower() == 'location': v = new_location headers.append((k, v)) else: headers = headerslist start_response(status, headers) if method == "HEAD": return [six.b('')] return app_iter class TransparentProxy(Proxy): """A proxy based on HTTP_HOST environ variable""" def extract_uri(self, environ): port = None scheme = environ['wsgi.url_scheme'] 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 class HostProxy(Proxy): """A proxy to redirect all request to a specific uri""" def __init__(self, uri, client=None, allowed_methods=ALLOWED_METHODS, strip_script_name=True, **client_options): super(HostProxy, self).__init__( client=client, allowed_methods=allowed_methods, strip_script_name=strip_script_name, **client_options) self.uri = str(uri.rstrip('/')) self.scheme, self.net_loc = urlparse.urlparse(self.uri)[0:2] def extract_uri(self, environ): environ['HTTP_HOST'] = self.net_loc return self.uri wsgiproxy2_0.4.5.orig/wsgiproxy/requests_client.py0000644000000000000000000000256212255171351020671 0ustar 00000000000000# -*- coding: utf-8 -*- import requests from functools import partial class HttpClient(object): """A HTTP client using requests""" default_options = dict(verify=False, allow_redirects=False) def __init__(self, chunk_size=1024 * 24, session=None, **requests_options): options = self.default_options.copy() options.update(requests_options) self.options = options self.chunk_size = chunk_size self.session = session def __call__(self, uri, method, body, headers): kwargs = self.options.copy() kwargs['headers'] = headers if 'Transfer-Encoding' in headers: del headers['Transfer-Encoding'] if headers.get('Content-Length'): kwargs['data'] = body.read(int(headers['Content-Length'])) elif not body: headers['Content-Length'] = '0' kwargs['stream'] = True if self.session is None: session = requests.sessions.Session() else: session = self.session response = session.request(method, uri, **kwargs) location = response.headers.get('location') or None status = '%s %s' % (response.status_code, response.reason) headers = [(k.title(), v) for k, v in response.headers.items()] return (status, location, headers, response.iter_content(self.chunk_size, False)) wsgiproxy2_0.4.5.orig/wsgiproxy/test_wsgiproxy.py0000644000000000000000000001342313051524570020570 0ustar 00000000000000# -*- coding: utf-8 -*- import unittest from wsgiproxy import proxies from webtest import TestApp from webtest.debugapp import debug_app from webtest.http import StopableWSGIServer from webob import Request import logging import socket logging.getLogger('waitress').setLevel(logging.DEBUG) def start_response(*args): pass class TestHttplib(unittest.TestCase): client = 'httplib' client_options = {} def setUp(self): self.server = StopableWSGIServer.create(debug_app) self.application_url = self.server.application_url.rstrip('/') self.proxy = proxies.HostProxy(self.application_url, client=self.client, **self.client_options) self.app = TestApp(self.proxy) def test_form(self): resp = self.app.get('/form.html') resp.mustcontain('') form = resp.form form['name'] = 'gawel' resp = form.submit() resp.mustcontain('name=gawel') def test_head(self): resp = self.app.head('/form.html') self.assertEqual(resp.status_int, 200) self.assertEqual(len(resp.body), 0) def test_webob_error(self): req = Request.blank('/') req.content_length = '-1' resp = req.get_response(self.proxy) self.assertEqual(resp.status_int, 500, resp) def test_status(self): resp = self.app.get('/?status=404', status='*') self.assertEqual(resp.status_int, 404) def test_redirect(self): location = self.application_url + '/form.html' resp = self.app.get( '/?status=301%20Redirect&header-location=' + location, status='*') self.assertEqual(resp.status_int, 301, resp) self.assertEqual(resp.location, location) location = 'http://foo.com' resp = self.app.get( '/?status=301%20Redirect&header-location=' + location, status='*') self.assertEqual(resp.status_int, 301, resp) self.assertEqual(resp.location, location) location = '/foo' resp = self.app.get( '/?status=301%20Redirect&header-location=' + location, status='*') self.assertEqual(resp.status_int, 301, resp) self.assertEqual(resp.location, self.application_url + location) location = self.application_url + '/script_name/form.html' self.proxy.strip_script_name = False resp = self.app.get( '/?status=301%20Redirect&header-Location=' + location, status='*', extra_environ={'SCRIPT_NAME': '/script_name'}) self.assertEqual(resp.status_int, 301, resp) self.assertEqual(resp.location, location) def test_chunked(self): resp = self.app.get('/', headers=[('Transfer-Encoding', 'chunked')]) resp.mustcontain(no='chunked') def test_quoted_utf8_url(self): path = '/targets/NR2F1%C3%82-human/' resp = self.app.get(path) resp.mustcontain(b'PATH_INFO: /targets/NR2F1\xc3\x82-human/') def tearDown(self): self.server.shutdown() class TestUrllib3(TestHttplib): client = 'urllib3' class TestRequests(TestHttplib): client = 'requests' class TestExtractUri(unittest.TestCase): def test_proxy(self): environ = Request.blank('/').environ.copy() proxy = proxies.Proxy() if 'SERVER_NAME' in environ: del environ['SERVER_NAME'] uri = proxy.extract_uri(environ) self.assertEqual(uri, 'http://localhost:80') environ['SERVER_NAME'] = 'foo' environ['SERVER_PORT'] = '8080' uri = proxy.extract_uri(environ) self.assertEqual(uri, 'http://foo:8080') del environ['SERVER_PORT'] del environ['HTTP_HOST'] environ['SERVER_NAME'] = 'foo' environ['wsgi.url_scheme'] = 'https' uri = proxy.extract_uri(environ) self.assertEqual(uri, 'https://foo:443') def test_transparent_proxy(self): req = Request.blank('/') proxy = proxies.TransparentProxy() uri = proxy.extract_uri(req.environ) self.assertEqual(uri, 'http://localhost:80') req.scheme = 'https' req.environ['HTTP_HOST'] = 'foo' uri = proxy.extract_uri(req.environ) self.assertEqual(uri, 'https://foo:443') class TestMisc(unittest.TestCase): def test_socket_gaierror(self): def client(*args): raise socket.gaierror() proxy = proxies.Proxy(client) app = TestApp(proxy) resp = app.get('/', status='*') self.assertEqual(resp.status_int, 502) def test_socket_timeout(self): def client(*args): raise socket.timeout() proxy = proxies.Proxy(client) app = TestApp(proxy) resp = app.get('/', status='*') self.assertEqual(resp.status_int, 504) def test_exception(self): def client(*args): raise ValueError() proxy = proxies.Proxy(client) app = TestApp(proxy) resp = app.get('/', status='*') self.assertEqual(resp.status_int, 500) def test_rewrite_location(self): location = proxies.rewrite_location('http://localhost:80', '/foo') self.assertEqual(location, 'http://localhost:80/foo') location = proxies.rewrite_location('http://localhost:80', '/foo', '/path') self.assertEqual(location, 'http://localhost:80/path/foo') location = proxies.rewrite_location('http://localhost:80', 'http://localhost:80/foo', '/path') self.assertEqual(location, 'http://localhost:80/path/foo') class DummyConnection(object): def __init__(self, *args, **kwargs): pass def request(self, *args, **kwargs): raise kwargs['exc'] wsgiproxy2_0.4.5.orig/wsgiproxy/urllib3_client.py0000644000000000000000000000205512074315743020373 0ustar 00000000000000# -*- coding: utf-8 -*- import urllib3 class HttpClient(object): """A HTTP client using urllib3""" default_options = dict(redirect=False) def __init__(self, pool=None, **urlopen_options): self.pool = pool or urllib3.PoolManager(10) options = self.default_options.copy() options.update(urlopen_options) self.options = options def __call__(self, uri, method, body, headers): if 'Transfer-Encoding' in headers: del headers['Transfer-Encoding'] if headers.get('Content-Length'): body = body.read(int(headers['Content-Length'])) elif body is not None: body = body.read() kwargs = self.options.copy() kwargs.update(body=body, headers=headers) response = self.pool.urlopen(method, uri, **kwargs) status = '%s %s' % (response.status, response.reason) headers = [(k.title(), v) for k, v in response.getheaders().items()] return (status, response.getheader('location', None), headers, [response.data])