summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJason R. Coombs <jaraco@jaraco.com>2017-12-17 12:34:32 -0500
committerJason R. Coombs <jaraco@jaraco.com>2017-12-17 12:38:41 -0500
commit661dc06ffa9a872824d628975657b21325654f2e (patch)
tree36027d71593578354faf50c5a227cf637388a4ff
parent49bc467811b74e100a6f5e007409e9d9baaa5f6a (diff)
parent0e4542295a33fd776f2ca5f1bb151eb8ddf919a0 (diff)
downloadcherrypy-git-archive/1285-always-bytes.tar.gz
Merge branch 'master' into bb-pr-85archive/1285-always-bytes
-rw-r--r--.circleci/config.yml9
-rw-r--r--.codecov.yml28
-rw-r--r--.github/CONTRIBUTING.rst28
-rw-r--r--.github/ISSUE_TEMPLATE.md47
-rw-r--r--.github/PULL_REQUEST_TEMPLATE.md17
-rw-r--r--.gitignore40
-rw-r--r--.hgignore15
-rw-r--r--.hgtags55
-rw-r--r--.mention-bot17
-rw-r--r--.pre-commit-config-pep257.yaml5
-rw-r--r--.pre-commit-config.yaml65
-rw-r--r--.travis.yml184
-rw-r--r--CHANGES.rst552
-rw-r--r--CHANGES.txt96
-rw-r--r--CONTRIBUTING.txt6
-rw-r--r--LICENSE.md30
-rw-r--r--MANIFEST.in13
-rw-r--r--README.rst78
-rw-r--r--README.txt16
-rw-r--r--appveyor.yml35
-rw-r--r--cherrypy/LICENSE.txt25
-rw-r--r--cherrypy/__init__.py415
-rwxr-xr-xcherrypy/__main__.py7
-rw-r--r--cherrypy/_cpchecker.py191
-rw-r--r--cherrypy/_cpcompat.py302
-rw-r--r--cherrypy/_cpcompat_subprocess.py1544
-rw-r--r--cherrypy/_cpconfig.py122
-rw-r--r--cherrypy/_cpdispatch.py100
-rw-r--r--cherrypy/_cperror.py188
-rw-r--r--cherrypy/_cplogging.py102
-rw-r--r--cherrypy/_cpmodpy.py81
-rw-r--r--cherrypy/_cpnative_server.py54
-rw-r--r--cherrypy/_cpreqbody.py146
-rw-r--r--cherrypy/_cprequest.py314
-rw-r--r--cherrypy/_cpserver.py61
-rw-r--r--cherrypy/_cpthreadinglocal.py241
-rw-r--r--cherrypy/_cptools.py109
-rw-r--r--cherrypy/_cptree.py112
-rw-r--r--cherrypy/_cpwsgi.py218
-rw-r--r--cherrypy/_cpwsgi_server.py84
-rw-r--r--cherrypy/_helper.py341
-rwxr-xr-xcherrypy/cherryd6
-rwxr-xr-xcherrypy/daemon.py49
-rw-r--r--cherrypy/lib/__init__.py47
-rw-r--r--cherrypy/lib/auth.py16
-rw-r--r--cherrypy/lib/auth_basic.py19
-rw-r--r--cherrypy/lib/auth_digest.py55
-rw-r--r--cherrypy/lib/caching.py31
-rw-r--r--cherrypy/lib/covercp.py64
-rw-r--r--cherrypy/lib/cpstats.py59
-rw-r--r--cherrypy/lib/cptools.py138
-rw-r--r--cherrypy/lib/encoding.py66
-rw-r--r--cherrypy/lib/gctools.py63
-rw-r--r--cherrypy/lib/http.py6
-rw-r--r--cherrypy/lib/httpauth.py137
-rw-r--r--cherrypy/lib/httputil.py282
-rw-r--r--cherrypy/lib/jsontools.py16
-rw-r--r--cherrypy/lib/lockfile.py290
-rw-r--r--cherrypy/lib/locking.py6
-rw-r--r--cherrypy/lib/profiler.py77
-rw-r--r--cherrypy/lib/reprconf.py70
-rw-r--r--cherrypy/lib/sessions.py263
-rw-r--r--cherrypy/lib/static.py101
-rw-r--r--cherrypy/lib/xmlrpcutil.py38
-rw-r--r--cherrypy/process/__init__.py7
-rw-r--r--cherrypy/process/plugins.py163
-rw-r--r--cherrypy/process/servers.py235
-rw-r--r--cherrypy/process/win32.py14
-rw-r--r--cherrypy/process/wspbus.py260
-rw-r--r--cherrypy/scaffold/__init__.py36
-rw-r--r--cherrypy/scaffold/apache-fcgi.conf2
-rw-r--r--cherrypy/scaffold/example.conf2
-rw-r--r--cherrypy/scaffold/static/made_with_cherrypy_small.pngbin7455 -> 6347 bytes
-rw-r--r--cherrypy/test/__init__.py10
-rw-r--r--cherrypy/test/_test_decorators.py27
-rw-r--r--cherrypy/test/_test_states_demo.py35
-rw-r--r--cherrypy/test/benchmark.py135
-rw-r--r--cherrypy/test/checkerdemo.py1
-rw-r--r--cherrypy/test/helper.py199
-rw-r--r--cherrypy/test/logtest.py89
-rw-r--r--cherrypy/test/modfastcgi.py25
-rw-r--r--cherrypy/test/modfcgid.py23
-rw-r--r--cherrypy/test/modpy.py35
-rw-r--r--cherrypy/test/modwsgi.py44
-rwxr-xr-xcherrypy/test/sessiondemo.py19
-rw-r--r--cherrypy/test/static/dirback.jpgbin18238 -> 16585 bytes
-rw-r--r--cherrypy/test/test_auth_basic.py16
-rw-r--r--cherrypy/test/test_auth_digest.py20
-rw-r--r--cherrypy/test/test_bus.py33
-rw-r--r--cherrypy/test/test_caching.py321
-rw-r--r--cherrypy/test/test_compat.py50
-rw-r--r--cherrypy/test/test_config.py157
-rw-r--r--cherrypy/test/test_config_server.py70
-rw-r--r--cherrypy/test/test_conn.py444
-rw-r--r--cherrypy/test/test_core.py440
-rw-r--r--cherrypy/test/test_dynamicobjectmapping.py181
-rw-r--r--cherrypy/test/test_encoding.py260
-rw-r--r--cherrypy/test/test_etags.py58
-rw-r--r--cherrypy/test/test_http.py118
-rw-r--r--cherrypy/test/test_httpauth.py28
-rw-r--r--cherrypy/test/test_httplib.py29
-rw-r--r--cherrypy/test/test_httputil.py80
-rw-r--r--cherrypy/test/test_iterator.py45
-rw-r--r--cherrypy/test/test_json.py58
-rw-r--r--cherrypy/test/test_logging.py117
-rw-r--r--cherrypy/test/test_mime.py45
-rw-r--r--cherrypy/test/test_misc_tools.py91
-rw-r--r--cherrypy/test/test_objectmapping.py255
-rw-r--r--cherrypy/test/test_params.py60
-rw-r--r--cherrypy/test/test_proxy.py115
-rw-r--r--cherrypy/test/test_refleaks.py37
-rw-r--r--cherrypy/test/test_request_obj.py546
-rw-r--r--cherrypy/test/test_routes.py71
-rwxr-xr-xcherrypy/test/test_session.py217
-rw-r--r--cherrypy/test/test_sessionauthenticate.py8
-rw-r--r--cherrypy/test/test_states.py200
-rw-r--r--cherrypy/test/test_static.py261
-rw-r--r--cherrypy/test/test_tools.py236
-rw-r--r--cherrypy/test/test_tutorials.py154
-rw-r--r--cherrypy/test/test_virtualhost.py73
-rw-r--r--cherrypy/test/test_wsgi_ns.py12
-rw-r--r--cherrypy/test/test_wsgi_unix_socket.py49
-rw-r--r--cherrypy/test/test_wsgi_vhost.py12
-rw-r--r--cherrypy/test/test_wsgiapps.py36
-rw-r--r--cherrypy/test/test_xmlrpc.py77
-rw-r--r--cherrypy/test/webtest.py592
-rw-r--r--cherrypy/tutorial/README.rst16
-rw-r--r--cherrypy/tutorial/README.txt16
-rw-r--r--cherrypy/tutorial/tut01_helloworld.py15
-rw-r--r--cherrypy/tutorial/tut02_expose_methods.py13
-rw-r--r--cherrypy/tutorial/tut03_get_and_post.py10
-rw-r--r--cherrypy/tutorial/tut04_complex_site.py14
-rw-r--r--cherrypy/tutorial/tut05_derived_objects.py10
-rw-r--r--cherrypy/tutorial/tut06_default_method.py18
-rw-r--r--cherrypy/tutorial/tut07_sessions.py8
-rw-r--r--cherrypy/tutorial/tut08_generators_and_yield.py16
-rw-r--r--cherrypy/tutorial/tut09_files.py22
-rw-r--r--cherrypy/tutorial/tut10_http_errors.py24
-rw-r--r--cherrypy/wsgiserver/__init__.py14
-rw-r--r--cherrypy/wsgiserver/ssl_builtin.py92
-rw-r--r--cherrypy/wsgiserver/ssl_pyopenssl.py253
-rw-r--r--cherrypy/wsgiserver/wsgiserver2.py2471
-rw-r--r--cherrypy/wsgiserver/wsgiserver3.py2197
-rw-r--r--docs/.gitignore1
-rw-r--r--docs/_static/bgsides.pngbin6498 -> 6434 bytes
-rw-r--r--docs/_static/cpdocmain.css2
-rw-r--r--docs/_static/images/cherrypy_logo_big.pngbin0 -> 17835 bytes
-rw-r--r--docs/_static/images/cpreturn.gifbin6088 -> 5172 bytes
-rw-r--r--docs/_static/images/cpyield.gifbin9112 -> 8069 bytes
-rw-r--r--docs/_static/images/sushibelt.JPGbin161186 -> 153268 bytes
-rw-r--r--docs/_templates/python_2_eol.html49
-rw-r--r--docs/advanced.rst194
-rw-r--r--docs/basics.rst24
-rw-r--r--docs/conf.py273
-rw-r--r--docs/config.rst11
-rw-r--r--docs/contribute.rst56
-rw-r--r--docs/deploy.rst65
-rw-r--r--docs/development.rst20
-rw-r--r--docs/extend.rst114
-rw-r--r--docs/glossary.rst18
-rw-r--r--docs/history.rst6
-rw-r--r--docs/index.rst26
-rw-r--r--docs/install.rst22
-rw-r--r--docs/intro.rst16
-rw-r--r--docs/pkg/cherrypy.lib.rst16
-rw-r--r--docs/pkg/cherrypy.rst135
-rw-r--r--docs/pkg/cherrypy.test.rst40
-rw-r--r--docs/pkg/cherrypy.wsgiserver.rst46
-rw-r--r--docs/pkg/modules.rst4
-rw-r--r--docs/requirements.txt1
-rw-r--r--docs/support.rst51
-rw-r--r--docs/tutorials.rst952
-rw-r--r--docs/util/convert-trac.py134
-rw-r--r--docs/util/test-doc.py23
-rw-r--r--make-sdist2
-rw-r--r--man/cherryd.16
-rw-r--r--pytest.ini4
-rw-r--r--setup.cfg27
-rwxr-xr-x[-rw-r--r--]setup.py221
-rw-r--r--tests/dist-check.py59
-rw-r--r--tox.ini46
-rw-r--r--visuals/cherrypy_logo_big.pngbin21527 -> 17835 bytes
-rw-r--r--visuals/cherrypy_logo_small.jpgbin3437 -> 3059 bytes
-rw-r--r--visuals/made_with_cherrypy_big.pngbin24450 -> 20525 bytes
-rw-r--r--visuals/made_with_cherrypy_small.pngbin7455 -> 6347 bytes
185 files changed, 8465 insertions, 14433 deletions
diff --git a/.circleci/config.yml b/.circleci/config.yml
new file mode 100644
index 00000000..ca1e0dec
--- /dev/null
+++ b/.circleci/config.yml
@@ -0,0 +1,9 @@
+version: 2
+jobs:
+ build:
+ docker:
+ - image: randomknowledge/docker-pyenv-tox
+ steps:
+ - checkout
+ - run: pip install tox
+ - run: tox -e py27,py33,py34,py35,py36
diff --git a/.codecov.yml b/.codecov.yml
new file mode 100644
index 00000000..9fff0529
--- /dev/null
+++ b/.codecov.yml
@@ -0,0 +1,28 @@
+codecov:
+ bot: codecov
+ notify:
+ require_ci_to_pass: yes
+
+coverage:
+ precision: 2
+ round: down
+ range: "70...100"
+
+ status:
+ # Only consider coverage of the code snippet changed in PR
+ project: no
+ patch: yes
+ changes: no
+
+parsers:
+ gcov:
+ branch_detection:
+ conditional: yes
+ loop: yes
+ method: no
+ macro: no
+
+comment:
+ layout: "header, diff"
+ behavior: default
+ require_changes: no
diff --git a/.github/CONTRIBUTING.rst b/.github/CONTRIBUTING.rst
new file mode 100644
index 00000000..427ee4c9
--- /dev/null
+++ b/.github/CONTRIBUTING.rst
@@ -0,0 +1,28 @@
+Read and contribute to CherryPy
+-------------------------------
+
+Make sure you read the `README
+<https://github.com/cherrypy/cherrypy/blob/master/README.rst>`_. Also **ensure
+you set up pre-commit utility correctly** and TravisCI tests pass.
+
+Submitting Pull Requests
+------------------------
+If you're changing the structure of the repository please create an issue
+first. Don't forget to write appropriate test cases, add them into CI process
+if applicable and make the TravisCI build pass.
+
+Sync (preferably rebase) your feature branch with upstream regularly to make
+us able to merge your PR seamlessly.
+
+Submitting bug reports
+----------------------
+
+Make sure you are on latest changes and that you re-ran this command `tox`
+after updating your local repository. If you can, please provide more
+information about your environment such as browser, operating system,
+python version, and any other related software versions.
+
+Also
+----
+See `Contributing <http://docs.cherrypy.org/en/latest/contribute.html>`_ in
+the docs.
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 00000000..c7a77b63
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,47 @@
+<!--
+**** DELETE THIS BLOCK ****
+
+Thanks for filing an issue! Please keep keep issues limited to bug reports,
+feature requests, and other general issues. For support questions, please feel
+free to reach out on stackoverflow:
+http://stackoverflow.com/questions/tagged/cherrypy
+
+**** /DELETE THIS BLOCK ****
+-->
+
+* **I'm submitting a ...**
+[ ] bug report
+[ ] feature request
+[ ] question about the decisions made in the repository
+
+* **Do you want to request a *feature* or report a *bug*?**
+
+
+
+* **What is the current behavior?**
+
+
+
+* **If the current behavior is a bug, please provide the steps to reproduce and if possible a screenshots and logs of the problem**.
+
+
+
+* **What is the expected behavior?**
+
+
+
+* **What is the motivation / use case for changing the behavior?**
+
+
+
+* **Please tell us about your environment:**
+
+- Cheroot version: X.X.X
+- CherryPy version: X.X.X
+- Python version: 3.6.X
+- OS: XXX
+- Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]
+
+
+
+* **Other information** (e.g. detailed explanation, stacktraces, related issues, suggestions how to fix, links for us to have context, e.g. stackoverflow, gitter, etc.)
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 00000000..44e7b231
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,17 @@
+* **What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...)
+
+
+
+* **What is the related issue number (starting with `#`)**
+
+
+
+* **What is the current behavior?** (You can also link to an open issue here)
+
+
+
+* **What is the new behavior (if this is a feature change)?**
+
+
+
+* **Other information**:
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..fe9a20b5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,40 @@
+*.egg-info
+*.pyc
+*.orig
+build/*
+dist/*
+*.swp
+*.log
+lib
+share
+bin
+*.kdev4
+include
+sphinx/source/_build
+.tox
+
+/.eggs/
+/.ropeproject/
+/cherrypy/test/static/has space.html
+/cherrypy/test/test.conf
+
+# pyenv local config:
+.python-version
+
+# Ignore useless OS X's dirs:
+.DS_Store
+
+# Py.test
+/.cache/
+
+# Eclipse, PyDev
+.project
+.pydevproject
+
+# test results in junit format for Appveyor
+/junit-test-results.xml
+
+# coverage results
+/.coverage
+/coverage.xml
+/graph_Request_*.png
diff --git a/.hgignore b/.hgignore
deleted file mode 100644
index d207c898..00000000
--- a/.hgignore
+++ /dev/null
@@ -1,15 +0,0 @@
-syntax: glob
-*.egg-info
-*.pyc
-*.orig
-build/*
-dist/*
-*.swp
-*.log
-lib
-share
-bin
-*.kdev4
-include
-sphinx/source/_build
-.tox
diff --git a/.hgtags b/.hgtags
deleted file mode 100644
index 16c3267e..00000000
--- a/.hgtags
+++ /dev/null
@@ -1,55 +0,0 @@
-042fb7cd21ac688e130e769b9953b251ae5801b7 cherrypy-3.0.3
-042fb7cd21ac688e130e769b9953b251ae5801b7 cherrypy-3.0.x
-07ee4ae0b172d20f9bd9f57070f97d9190d629bd cherrypy-2.1.0-alpha
-0a188d869da86c0c54511d03b3627565e6f4849b cherrypy-2.1.0-rc2
-1a9c712014f578a207a01320c15c9c93198f6a1e cherrypy-3.0.1
-27d0463814cc41d2c9c94e22b00bdc96a08c4047 cherrypy-3.1.0beta2
-3f42c2d6c0a02093795fc3112c6d5e9bf7ee7008 cherrypy-3.2.0
-42811c156ae671de7e9981dc81658b564f396018 cherrypy-3.0.0beta
-44b1f63393f1847ab7b6e703468c157193b97bb1 trunk
-499fb651cbb2ccdbdb9d23e3424fd69d336336ec cherrypy-2.2.0beta
-4abdbc4b44ddfb70c6847689022b4cf9edddcf62 cherrypy-3.0.0beta2
-56ba66d6036f6323a0e4f62712e3a876e94e6b40 cherrypy-3.2.0beta
-579308a9c96a67d76420faf8f28bb90df388038e cherrypy-3.0.4
-5e9dc0e89dc4900ac68a10583f85d8e1f54ab40d cherrypy-3.2.0rc1
-6908b7089cd2d6783563bc5bd1d5bd09a209df59 cherrypy-3.1.0beta3
-7390f197028ee16e1477b8dc3418dc0c0ce01f80 cherrypy-2.1.1
-7b4e22c49989eb53ea2922e91e4eb895e0bc28b4 cherrypy-3.1.1
-7ce560c7b264e8590e82f4ab7a8dbb6c795178f7 cherrypy-3.0.2
-7ecb02148ee3d53194f895c3f741f4b58959a54d cherrypy-2.2.0
-8ebb9dae65d836a824ba70f95cd17369541c5de6 cherrypy-3.1.2
-91f8cfbd2e27a9cde283eebd96144366017bc6e7 cherrypy-3.2.1
-a53c617d65decfeedaaf21424a6382760070933f cherrypy-3.1.0
-a6eb85f3f1f17bfd0e043fe60c86570438b35f69 cherrypy-2.0.0-beta
-b1fb111e22932167d6d89130c3353d038f35cb35 cherrypy-2.1.0-rc1
-b27597c8a576b465edc7ab87d8993fe8b6715854 cherrypy-3.1.0beta
-baef3c53a2cde0d4fa641c6a94635df0294fa8a4 cherrypy-3.0.0
-c1d9bd4298bf49f4a2cc121b86cf1939ed3b7b4a rdelon-experimental
-d88df34b5808ebd0b929eae5af6168bd1828fd64 cherrypy-2.2.1
-d935e88dc4fc28f26bc327d6a5db23fd8f30eaa9 cherrypy-2.2.0rc1
-d9c097bbc8ec0f1e47782d06d6f1bc7fade2d0ef cherrypy-2.0.0
-dca45ccb647914fcd2f8429ed780f17bf849528a cherrypy-2.3.0
-eb153a3656fd1b5309d3d48ce498baf3517c4342 cherrypy-3.0.0RC1
-ee66c594632b75b458065ef0256af5ffc7eb307c cherrypy-3.2.2rc1
-80d84626b74687f961cf828ccd216405e66ebeba cherrypy-3.2.2
-80d84626b74687f961cf828ccd216405e66ebeba cherrypy-3.2.2
-81c92cbcf2302f83efa739970a35ec48733b177c cherrypy-3.2.2
-c9d13db2b4331474b768b3ed156ddae5030e7f2c 3.2.3
-cd8acbc5f2b3914d396f2925b2d5e2561cfd39a4 3.2.4
-052f32b1d56309115c8f4fe48f4bf25a15b87706 3.2.5
-3dab916fa0f7fdc59b374e8d31624de59c086f33 3.2.6
-71c81abe37fc2ab5ccf85dc86826e5ec63cf2dbe 3.3.0
-08e6819ecabd6333fccfce4252eac7cc776b0358 3.4.0
-fd745f2e7c4469e76de6c925e6c7e625cfd5be01 3.5.0
-c8088a7e7502f049910740957372e47f971ca6a7 3.6.0
-4aa828891193bb5efea2b38dae7d055e4c6680d0 3.7.0
-222f6f086e9a981f26163e3940fb3456880bd51c 3.8.0
-422d82bb8b30e10827b06c1bacbe1a2886562c9c 3.8.1
-5c1c16af8ad52e698fde38d58b6aee15756ce1c6 3.8.2
-e6dae695ea9bdb52d7b1f786bb8bfcb41c6b908e 4.0.0
-83cdefd46296c85de50b5a72cd8a319056074e2d 5.0.0
-3b2ca4b3bb853d456cd684f609929ebde5958a47 5.0.1
-e27e0832a5221a4042b9a4fec05b0c0dceaf0c2c 5.1.0
-e47026e58ebb7e2ae38a9e26a94843169827659c v5.2.0
-e47026e58ebb7e2ae38a9e26a94843169827659c v5.2.0
-7ba84ba9a85fc0f570c2aa55cbd715c7a242f1d9 v5.2.0
diff --git a/.mention-bot b/.mention-bot
new file mode 100644
index 00000000..4e34e1e2
--- /dev/null
+++ b/.mention-bot
@@ -0,0 +1,17 @@
+{
+ "maxReviewers": 5,
+ "numFilesToCheck": 10,
+ "findPotentialReviewers": true,
+ "fileBlacklist": ["*.md"],
+ "userBlacklist": [],
+ "userBlacklistForPR": [],
+ "requiredOrgs": [],
+ "actions": ["opened"],
+ "branches": [],
+ "skipAlreadyAssignedPR": false,
+ "skipAlreadyMentionedPR": false,
+ "assignToReviewer": true,
+ "createReviewRequest": true,
+ "createComment": true,
+ "skipCollaboratorPR": false
+}
diff --git a/.pre-commit-config-pep257.yaml b/.pre-commit-config-pep257.yaml
new file mode 100644
index 00000000..b2124e40
--- /dev/null
+++ b/.pre-commit-config-pep257.yaml
@@ -0,0 +1,5 @@
+repos:
+- repo: git://github.com/FalconSocial/pre-commit-mirrors-pep257
+ sha: f464d46
+ hooks:
+ - id: pep257
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 00000000..4ade63b6
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,65 @@
+repos:
+- repo: git://github.com/pre-commit/pre-commit-hooks
+ sha: v1.1.1
+ hooks:
+ - id: trailing-whitespace
+ exclude: cherrypy/test/static/index.html
+ - id: flake8
+ args:
+ # W503 ignored for https://github.com/PyCQA/pycodestyle/issues/498
+ - --ignore=W503
+ - id: check-merge-conflict
+ - id: double-quote-string-fixer
+ - id: end-of-file-fixer
+ - id: name-tests-test
+ include: cherrypy/test/
+ args:
+ - --django
+ exclude: tests/dist-check.py
+ - id: debug-statements
+ - id: check-added-large-files
+ - id: check-ast
+ - id: check-byte-order-marker
+ - id: check-case-conflict
+ # disabled due to pre-commit/pre-commit-hooks#159
+ #- id: check-docstring-first
+ - id: check-json
+ include: .mention-bot
+ - id: pretty-format-json
+ - id: check-symlinks
+ - id: check-yaml
+ - id: detect-private-key
+ exclude: cherrypy/test/test.pem
+ - id: requirements-txt-fixer
+
+- repo: git://github.com/FalconSocial/pre-commit-mirrors-pep257
+ sha: f464d46
+ hooks:
+ - id: pep257
+ exclude: |
+ (?x)
+ tests/dist|
+ cherrypy/(
+ _cp(
+ compat|modpy|logging|error|wsgi|dispatch|tools|reqbody|request
+ )|
+ (
+ lib/(
+ auth|auth_basic|auth_digest|caching|covercp|
+ cpstats|cptools|encoding|gctools|httpauth|httputil|
+ jsontools|lockfile|locking|profiler|reprconf|sessions
+ )|
+ process/(plugins|servers|win32)
+ ).py|
+ test|tutorial
+ )
+
+- repo: git://github.com/Lucas-C/pre-commit-hooks
+ sha: v1.1.1
+ hooks:
+ - id: remove-tabs
+
+- repo: git://github.com/Lucas-C/pre-commit-hooks-lxml
+ sha: v1.0.2
+ hooks:
+ - id: forbid-html-img-without-alt-text
diff --git a/.travis.yml b/.travis.yml
index 18b91098..5d159793 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,20 +1,174 @@
language: python
+os: linux
+dist: trusty
+sudo: false
+group: edge
+_base_envs:
+- &stage_lint
+ stage: &stage_lint_name lint
+- &stage_test
+ stage: &stage_test_name test
+- &stage_test_priority
+ stage: &stage_test_priority_name test against latest Python versions first (under GNU/Linux)
+- &stage_test_osx
+ stage: &stage_test_osx_name test under OS X (last chance to fail before deploy available)
+- &stage_deploy
+ stage: &stage_deploy_name upload new version of python package to PYPI (only for tagged commits)
+- &pyenv_base
+ <<: *stage_test
+ language: generic
+ python: &pypy2 pypy2.7-5.8.0
+ env:
+ - PYTHON_VERSION=pypy2.7-5.8.0
+ - &env_pyenv PYENV_ROOT="$HOME/.pyenv"
+ - &env_path PATH="$PYENV_ROOT/bin:$PATH"
+ before_install:
+ - &ensure_pyenv_installed |
+ if [ ! -f "$PYENV_ROOT/bin/pyenv" ]
+ then
+ rm -rf "$PYENV_ROOT"
+ curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash
+ eval "$(pyenv init -)"
+ eval "$(pyenv virtualenv-init -)"
+ fi
+ eval "$(pyenv init -)"
+ eval "$(pyenv virtualenv-init -)"
+ pyenv update
+ - &install_python pyenv install --skip-existing --keep --verbose "$PYTHON_VERSION"
+ - &switch_python pyenv shell "$PYTHON_VERSION"
+ - &python_version python --version
+- &osx_python_base
+ <<: *pyenv_base
+ <<: *stage_test_osx
+ os: osx
+ language: generic
+ before_install:
+ - brew update
+ - brew install readline xz
+ - *ensure_pyenv_installed
+ - *install_python
+ - *switch_python
+ - *python_version
+ before_cache:
+ - brew --cache
+ script:
+ - travis_retry tox
+- &pure_python_base
+ <<: *stage_test
+ python: &mainstream_python 3.6
+- &pure_python_base_priority
+ <<: *pure_python_base
+ <<: *stage_test_priority
+- &lint_python_base
+ <<: *stage_lint
+ python: *mainstream_python
+ after_failure: skip
python:
-- 2.6
- 2.7
-- 3.2
-- 3.3
- 3.4
-- 3.5
+- 3.7-dev
+- *pypy2
+- &pypy3 pypy3.5-5.8.0
+jobs:
+ fast_finish: true
+ allow_failures:
+ # TODO: check what causes testing stuck
+ - python: *pypy2
+ # TODO: fix tests
+ - python: *pypy3
+ - env: TOXENV=pre-commit-pep257
+ include:
+ - <<: *lint_python_base
+ env: TOXENV=pre-commit
+ - <<: *lint_python_base
+ env: TOXENV=pre-commit-pep257
+ - <<: *lint_python_base
+ env: TOXENV=dist-check
+ - <<: *lint_python_base
+ env: TOXENV=setup-check
+ - <<: *pure_python_base_priority
+ # mainstream here (3.6)
+ - <<: *pure_python_base_priority
+ # mainstream here (3.6)
+ # run tests against the bleeding-edge cheroot
+ env: TOXENV=cheroot-master
+ - <<: *pure_python_base_priority
+ python: nightly
+ - <<: *osx_python_base
+ python: 2.7
+ env:
+ - PYTHON_VERSION=2.7.13
+ - *env_pyenv
+ - *env_path
+ - <<: *osx_python_base
+ python: 3.4
+ env:
+ - PYTHON_VERSION=3.4.4
+ - *env_pyenv
+ - *env_path
+ - <<: *osx_python_base
+ python: *mainstream_python
+ env:
+ - PYTHON_VERSION=3.6.1
+ - *env_pyenv
+ - *env_path
+ - <<: *osx_python_base
+ python: 3.7-dev
+ env:
+ - PYTHON_VERSION=3.7-dev
+ - *env_pyenv
+ - *env_path
+ - <<: *osx_python_base
+ # mainstream here (3.6)
+ python: *mainstream_python
+ env:
+ - PYTHON_VERSION=3.6.1
+ # run tests against the bleeding-edge cheroot
+ - TOXENV=cheroot-master
+ - *env_pyenv
+ - *env_path
+ - <<: *stage_deploy
+ python: *mainstream_python
+ install: skip
+ script: skip
+ deploy:
+ provider: pypi
+ skip_cleanup: true
+ on:
+ tags: true
+ all_branches: true
+ python: *mainstream_python
+ user: jaraco
+ distributions: release
+ password:
+ secure: CQqUvtssQ4wmRluPcxh6m5lIXi83Qu9dAFAvZLS/+AQNIG78XECXv5xFTEdGSLX9yncKDpDKI3xRJeCKyO4OJUN0t6W1MRycY72+R63i9e9wPjfvtRqYH1TBT+no7jj/DHqXIrWSlpjRNAt4XXeSv7OzKWT4PmTNkNQSKyS1DWCmZGlbCKlV774Z9PbrfltflxL0V6DiX6ZfoY1THBO4rIopjMk/MPLgS5zvwLgXVbT9sK/DcPOgOq47iSLCs0oScbwiFzYW4DbcVZrBMv4ALtQTjk6ZEaBQ7KtKgsyxgi/ToVhjRxYg4rwvhjsyjixUdECLUqL3WgWfzW/lo82lhb79ERwhnjf1DvPNexlXhv9hHwHsFROpaOmM0nyDJsJg0rCNPVfO4SpBHEnd/ujlHO6yorHj0S54jZWqqDwD5gN19v3hEMT48Pc8uvazE9K1kMQbNXEzqn+SJjVB+DG7qK5Jm9Kk7ZC4R88hJAJNsR+SlFCXMGzkS9WUefUGLHQFfezZk43sMPIXMnh9d2XqCQo4QpUawdg3pwaTukFfyaHlK39CIHhZNas5D/UFL5spQPAAkH1IMcPILiSUwYYnXIJFWJIiulfEQalJroAQjrzvst/NVB8BbeYuCfmVLVOZw8Y6GOYONGgiXjT3nfmw/dN+uw+GY3EgAV5jl+fa434=
+cache:
+ pip: true
+ directories:
+ - $HOME/.cache/pre-commit
+ - $HOME/Library/Caches/Homebrew
+install:
+- pip install tox "setuptools>=28.2"
script:
-- nosetests -s .
-deploy:
- provider: pypi
- on:
- tags: true
- all_branches: true
- python: 3.5
- user: jaraco
- password:
- secure: CQqUvtssQ4wmRluPcxh6m5lIXi83Qu9dAFAvZLS/+AQNIG78XECXv5xFTEdGSLX9yncKDpDKI3xRJeCKyO4OJUN0t6W1MRycY72+R63i9e9wPjfvtRqYH1TBT+no7jj/DHqXIrWSlpjRNAt4XXeSv7OzKWT4PmTNkNQSKyS1DWCmZGlbCKlV774Z9PbrfltflxL0V6DiX6ZfoY1THBO4rIopjMk/MPLgS5zvwLgXVbT9sK/DcPOgOq47iSLCs0oScbwiFzYW4DbcVZrBMv4ALtQTjk6ZEaBQ7KtKgsyxgi/ToVhjRxYg4rwvhjsyjixUdECLUqL3WgWfzW/lo82lhb79ERwhnjf1DvPNexlXhv9hHwHsFROpaOmM0nyDJsJg0rCNPVfO4SpBHEnd/ujlHO6yorHj0S54jZWqqDwD5gN19v3hEMT48Pc8uvazE9K1kMQbNXEzqn+SJjVB+DG7qK5Jm9Kk7ZC4R88hJAJNsR+SlFCXMGzkS9WUefUGLHQFfezZk43sMPIXMnh9d2XqCQo4QpUawdg3pwaTukFfyaHlK39CIHhZNas5D/UFL5spQPAAkH1IMcPILiSUwYYnXIJFWJIiulfEQalJroAQjrzvst/NVB8BbeYuCfmVLVOZw8Y6GOYONGgiXjT3nfmw/dN+uw+GY3EgAV5jl+fa434=
- distributions: release
+- tox
+after_failure:
+- echo "Here's a list of installed Python packages:"
+- pip list --format=columns
+- echo Dumping logs, because tests failed to succeed
+- |
+ for log in `ls cherrypy/test/*.log`
+ do
+ echo Outputting $log
+ cat $log
+ done
+- py_log=/home/travis/build/cherrypy/cherrypy/.tox/python/log/python-0.log
+- echo Outputting python invocation log from $py_log
+- cat $py_log
+stages:
+- *stage_lint_name
+- *stage_test_priority_name
+- *stage_test_name
+- name: *stage_test_osx_name
+ if: type IN (api, cron) OR tag IS present
+- name: *stage_deploy_name
+ if: tag IS present
diff --git a/CHANGES.rst b/CHANGES.rst
new file mode 100644
index 00000000..e381ff21
--- /dev/null
+++ b/CHANGES.rst
@@ -0,0 +1,552 @@
+v13.1.0
+-------
+
+* #1231 via #1654: CaseInsensitiveDict now re-uses the
+ generalized functionality from ``jaraco.collections`` to
+ provide a more complete interface for a CaseInsensitiveDict
+ and HeaderMap.
+
+ Users are encouraged to use the implementation from
+ `jaraco.collections <https://pypi.org/project/jaraco.collections>`_
+ except when dealing with headers in CherryPy.
+
+v13.0.1
+-------
+
+* #1671: Restore support for installing CherryPy into
+ environments hostile to namespace packages, broken since
+ the 11.1.0 release.
+
+v13.0.0
+-------
+
+* #1666: Drop support for Python 3.3.
+
+v12.0.2
+-------
+
+* #1665: In request processing, when an invalid cookie is
+ received, render the actual error message reported rather
+ than guessing (sometimes incorrectly) what error occurred.
+
+v12.0.1
+-------
+
+* Fixed issues importing cherrypy.test.webtest (by creating
+ a module and importing classes from cheroot) and added a
+ corresponding DeprecationWarning.
+
+v12.0.0
+-------
+
+* Drop support for Python 3.1 and 3.2.
+
+* #1625: Removed response timeout and timeout monitor and
+ related exceptions, as it not possible to interrupt a request.
+ Servers that wish to exit a request prematurely are
+ recommended to monitor ``response.time`` and raise an
+ exception or otherwise act accordingly.
+
+ Servers that previously disabled timeouts by invoking
+ ``cherrypy.engine.timeout_monitor.unsubscribe()`` will now
+ crash. For forward-compatibility with this release on older
+ versions of CherryPy, disable
+ timeouts using the config option::
+
+ 'engine.timeout_monitor.on': False,
+
+ Or test for the presence of the timeout_monitor attribute::
+
+ with contextlib2.suppress(AttributeError):
+ cherrypy.engine.timeout_monitor.unsubscribe()
+
+ Additionally, the ``TimeoutError`` exception has been removed,
+ as it's no longer called anywhere. If your application
+ benefits from this Exception, please comment in the linked
+ ticket describing the use case, and we'll help devise a
+ solution or bring the exception back.
+
+v11.3.0
+-------
+
+* Bump to cheroot 5.9.0.
+
+* ``cherrypy.test.webtest`` module is now merged with the
+ ``cheroot.test.webtest`` module. The CherryPy name is retained
+ for now for compatibility and will be removed eventually.
+
+v11.2.0
+-------
+
+* ``cherrypy.engine.subscribe`` now may be called without a
+ callback, in which case it returns a decorator expecting the
+ callback.
+
+* #1656: Images are now compressed using lossless compression
+ and consume less space.
+
+v11.1.0
+-------
+
+* #1611: Expose default status logic for a redirect as
+ ``HTTPRedirect.default_status``.
+
+* #1615: ``HTTPRedirect.status`` is now an instance property and
+ derived from the value in ``args``. Although it was previously
+ possible to set the property on an instance, and this change
+ prevents that possibilty, CherryPy never relied on that behavior
+ and we presume no applications depend on that interface.
+
+* #1627: Fixed issue in proxy tool where more than one port would
+ appear in the ``request.base`` and thus in ``cherrypy.url``.
+
+* #1645: Added new log format markers:
+
+ - ``i`` holds a per-request UUID4
+ - ``z`` outputs UTC time in format of RFC 3339
+ - ``cherrypy._cprequest.Request.unique_id.uuid4`` now has lazily
+ invocable UUID4
+
+* #1646: Improve http status conversion helper.
+
+* #1638: Always use backslash for path separator when processing
+ paths in staticdir.
+
+* #1190: Fix gzip, caching, and staticdir tools integration. Makes
+ cache of gzipped content valid.
+
+* Requires cheroot 5.8.3 or later.
+
+* Also, many improvements around continuous integration and code
+ quality checks.
+
+This release contained an unintentional regression in environments that
+are hostile to namespace packages, such as Pex, Celery, and py2exe.
+See #1671 for details.
+
+v11.0.0
+-------
+
+* #1607: Dropped support for Python 2.6.
+
+v10.2.2
+-------
+
+* #1595: Fixed over-eager normalization of paths in cherrypy.url.
+
+v10.2.1
+-------
+
+* Remove unintended dependency on ``graphviz`` in Python
+ 2.6.
+
+v10.2.0
+-------
+
+* #1580: CPWSGIServer.version now reported as
+ ``CherryPy/x.y.z Cheroot/x.y.z``. Bump to cheroot 5.2.0.
+* The codebase is now PEP8 complaint, flake8 linter is `enabled in TravisCI by
+ default <https://github.com/cherrypy/cherrypy/commit/b6e752b>`_.
+* Max line restriction is now set to 120 for flake8 linter.
+* PEP257 linter runs as separate allowed failure job in Travis CI.
+* A few bugs related to undeclared variables have been fixed.
+* ``pre-commit`` testing goes faster due to enabled caching.
+
+v10.1.1
+-------
+
+* #1342: Fix AssertionError on shutdown.
+
+v10.1.0
+-------
+
+* Bump to cheroot 5.1.0.
+
+* #794: Prefer setting max-age for session cookie
+ expiration, moving MSIE hack into a function
+ documenting its purpose.
+
+v10.0.0
+-------
+
+* #1332: CherryPy now uses `portend
+ <https://pypi.org/project/portend>`_ for checking and
+ waiting on ports for startup and teardown checks. The
+ following names are no longer present:
+
+ - cherrypy._cpserver.client_host
+ - cherrypy._cpserver.check_port
+ - cherrypy._cpserver.wait_for_free_port
+ - cherrypy._cpserver.wait_for_occupied_port
+ - cherrypy.process.servers.check_port
+ - cherrypy.process.servers.wait_for_free_port
+ - cherrypy.process.servers.wait_for_occupied_port
+
+ Use this functionality from the portend package directly.
+
+v9.0.0
+------
+
+* #1481: Move functionality from cherrypy.wsgiserver to
+ the `cheroot 5.0 <https://pypi.org/project/Cheroot/5.0.1/>`_
+ project.
+
+v8.9.1
+------
+
+* #1537: Restore dependency on pywin32 for Python 3.6.
+
+v8.9.0
+------
+
+* #1547: Replaced ``cherryd`` distutils script with a setuptools
+ console entry point.
+
+ When running CherryPy in daemon mode, the forked process no
+ longer changes directory to ``/``. If that behavior is something
+ on which your application relied and should rely, please file
+ a ticket with the project.
+
+v8.8.0
+------
+
+* #1528: Allow a timeout of 0 to server.
+
+v8.7.0
+------
+
+* #645: Setting a bind port of 0 will bind to an ephemeral port.
+
+v8.6.0
+------
+
+* #1538 and #1090: Removed cruft from the setup script and
+ instead rely on `include_package_data
+ <http://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=include_package_data#new-and-changed-setup-keywords>`_
+ to ensure the relevant files are included in the package.
+ Note, this change does cause LICENSE.md no longer to
+ be included in the installed package.
+
+v8.5.0
+------
+
+* The pyOpenSSL support is now included on Python 3 builds,
+ removing the last disparity between Python 2 and Python 3
+ in the CherryPy package. This change is one small step
+ in consideration of #1399. This change also fixes RPM
+ builds, as reported in #1149.
+
+v8.4.0
+------
+
+* #1532: Also release wheels for Python 2, enabling
+ offline installation.
+
+v8.3.1
+------
+
+* #1537: Disable dependency on pypiwin32 on Python 3.6
+ until a viable build of pypiwin32 can be made on that
+ Python version.
+
+v8.3.0
+------
+
+* Consolidated some documentation and include the more
+ concise readme in the package long description, as found
+ on PyPI.
+
+v8.2.0
+------
+
+* #1463: CherryPy tests are now run under pytest and
+ invoked using tox.
+
+v8.1.3
+------
+
+* #1530: Fix the issue with TypeError being swallowed by
+ decorated handlers.
+
+v8.1.2
+------
+
+* #1508
+
+v8.1.1
+------
+
+* #1497: Handle errors thrown by ``ssl_module: 'builtin'``
+ when client opens connection to HTTPS port using HTTP.
+
+* #1350: Fix regression introduced in v6.1.0 where environment
+ construction for WSGIGateway_u0 was passing one parameter
+ and not two.
+
+* Other miscellaneous fixes.
+
+v8.1.0
+------
+
+* #1473: ``HTTPError`` now also works as a context manager.
+
+* #1487: The sessions tool now accepts a ``storage_class``
+ parameter, which supersedes the new deprecated
+ ``storage_type`` parameter. The ``storage_class`` should
+ be the actual Session subclass to be used.
+
+* Releases now use ``setuptools_scm`` to track the release
+ versions. Therefore, releases can be cut by simply tagging
+ a commit in the repo. Versions numbers are now stored in
+ exactly one place.
+
+v8.0.1
+------
+
+* #1489 via #1493: Additionally reject anything else that's
+ not bytes.
+* #1492: systemd socket activation.
+
+v8.0.0
+------
+
+* #1483: Remove Deprecated constructs:
+
+ - ``cherrypy.lib.http`` module.
+ - ``unrepr``, ``modules``, and ``attributes`` in
+ ``cherrypy.lib``.
+
+* #1476: Drop support for python-memcached<1.58
+* #1401: Handle NoSSLErrors.
+* #1489: In ``wsgiserver.WSGIGateway.respond``, the application
+ must now yield bytes and not text, as the spec requires.
+ If text is received, it will now raise a ValueError instead
+ of silently encoding using ISO-8859-1.
+* Removed unicode filename from the package, working around
+ pip #3894 and setuptools #704.
+
+v7.1.0
+------
+
+# 1458: Implement systemd's socket activation mechanism for
+ CherryPy servers, based on work sponsored by Endless Computers.
+
+ Socket Activation allows one to setup a system so that
+ systemd will sit on a port and start services
+ 'on demand' (a little bit like inetd and xinetd
+ used to do).
+
+v7.0.0
+------
+
+Removed the long-deprecated backward compatibility for
+legacy config keys in the engine. Use the config for the
+namespaced-plugins instead:
+
+ - autoreload_on -> autoreload.on
+ - autoreload_frequency -> autoreload.frequency
+ - autoreload_match -> autoreload.match
+ - reload_files -> autoreload.files
+ - deadlock_poll_frequency -> timeout_monitor.frequency
+
+v6.2.1
+------
+
+# 1460: Fix KeyError in Bus.publish when signal handlers
+ set in config.
+
+v6.2.0
+------
+
+* #1441: Added tool to automatically convert request
+ params based on type annotations (primarily in
+ Python 3). For example::
+
+ @cherrypy.tools.params()
+ def resource(self, limit: int):
+ assert isinstance(limit, int)
+
+v6.1.1
+------
+
+* Issue #1411: Fix issue where autoreload fails when
+ the host interpreter for CherryPy was launched using
+ ``python -m``.
+
+v6.1.0
+------
+
+* Combined wsgiserver2 and wsgiserver3 modules into a
+ single module, ``cherrypy.wsgiserver``.
+
+v6.0.2
+------
+
+* Issue #1445: Correct additional typos.
+
+v6.0.1
+------
+
+* Issue #1444: Correct typos in ``@cherrypy.expose``
+ decorators.
+
+v6.0.0
+------
+
+* Setuptools is now required to build CherryPy. Pure
+ distutils installs are no longer supported. This change
+ allows CherryPy to depend on other packages and re-use
+ code from them. It's still possible to install
+ pre-built CherryPy packages (wheels) using pip without
+ Setuptools.
+* `six <https://pypi.io/project/six>`_ is now a
+ requirement and subsequent requirements will be
+ declared in the project metadata.
+* #1440: Back out changes from #1432 attempting to
+ fix redirects with Unicode URLs, as it also had the
+ unintended consequence of causing the 'Location'
+ to be ``bytes`` on Python 3.
+* ``cherrypy.expose`` now works on classes.
+* ``cherrypy.config`` decorator is now used throughout
+ the code internally.
+
+v5.6.0
+------
+
+* ``@cherrypy.expose`` now will also set the exposed
+ attribute on a class.
+* Rewrote all tutorials and internal usage to prefer
+ the decorator usage of ``expose`` rather than setting
+ the attribute explicitly.
+* Removed test-specific code from tutorials.
+
+v5.5.0
+------
+
+* #1397: Fix for filenames with semicolons and quote
+ characters in filenames found in headers.
+* #1311: Added decorator for registering tools.
+* #1194: Use simpler encoding rules for SCRIPT_NAME
+ and PATH_INFO environment variables in CherryPy Tree
+ allowing non-latin characters to pass even when
+ ``wsgi.version`` is not ``u.0``.
+* #1352: Ensure that multipart fields are decoded even
+ when cached in a file.
+
+v5.4.0
+------
+
+* ``cherrypy.test.webtest.WebCase`` now honors a
+ 'WEBTEST_INTERACTIVE' environment variable to disable
+ interactive tests (still enabled by default). Set to '0'
+ or 'false' or 'False' to disable interactive tests.
+* #1408: Fix AttributeError when listiterator was accessed
+ using the ``next`` attribute.
+* #748: Removed ``cherrypy.lib.sessions.PostgresqlSession``.
+* #1432: Fix errors with redirects to Unicode URLs.
+
+v5.3.0
+------
+
+* #1202: Add support for specifying a certificate authority when
+ serving SSL using the built-in SSL support.
+* Use ssl.create_default_context when available.
+* #1392: Catch platform-specific socket errors on OS X.
+* #1386: Fix parsing of URIs containing ``://`` in the path part.
+
+v5.2.0
+------
+
+* #1410: Moved hosting to Github (
+ `cherrypy/cherrypy <https://github.com/cherrypy/cherrypy>`_.
+
+v5.1.0
+------
+
+* Bugfix issue #1315 for ``test_HTTP11_pipelining`` test in Python 3.5
+* Bugfix issue #1382 regarding the keyword arguments support for Python 3
+ on the config file.
+* Bugfix issue #1406 for ``test_2_KeyboardInterrupt`` test in Python 3.5.
+ by monkey patching the HTTPRequest given a bug on CPython
+ that is affecting the testsuite (https://bugs.python.org/issue23377).
+* Add additional parameter ``raise_subcls`` to the tests helpers
+ `openURL` and ``CPWebCase.getPage`` to have finer control on
+ which exceptions can be raised.
+* Add support for direct keywords on the calls (e.g. ``foo=bar``) on
+ the config file under Python 3.
+* Add additional validation to determine if the process is running
+ as a daemon on ``cherrypy.process.plugins.SignalHandler`` to allow
+ the execution of the testsuite under CI tools.
+
+v5.0.1
+------
+
+* Bugfix for NameError following #94.
+
+v5.0.0
+------
+
+* Removed deprecated support for ``ssl_certificate`` and
+ ``ssl_private_key`` attributes and implicit construction
+ of SSL adapter on Python 2 WSGI servers.
+* Default SSL Adapter on Python 2 is the builtin SSL adapter,
+ matching Python 3 behavior.
+* Pull request #94: In proxy tool, defer to Host header for
+ resolving the base if no base is supplied.
+
+v4.0.0
+------
+
+* Drop support for Python 2.5 and earlier.
+* No longer build Windows installers by default.
+
+v3.8.2
+------
+
+* Pull Request #116: Correct InternalServerError when null bytes in
+ static file path. Now responds with 404 instead.
+
+v3.8.0
+------
+
+* Pull Request #96: Pass ``exc_info`` to logger as keyword rather than
+ formatting the error and injecting into the message.
+
+v3.7.0
+------
+
+* CherryPy daemon may now be invoked with ``python -m cherrypy`` in
+ addition to the ``cherryd`` script.
+* Issue #1298: Fix SSL handling on CPython 2.7 with builtin SSL module
+ and pyOpenSSL 0.14. This change will break PyPy for now.
+* Several documentation fixes.
+
+v3.6.0
+------
+
+* Fixed HTTP range headers for negative length larger than content size.
+* Disabled universal wheel generation as wsgiserver has Python duality.
+* Pull Request #42: Correct TypeError in ``check_auth`` when encrypt is used.
+* Pull Request #59: Correct signature of HandlerWrapperTool.
+* Pull Request #60: Fix error in SessionAuth where login_screen was
+ incorrectly used.
+* Issue #1077: Support keyword-only arguments in dispatchers (Python 3).
+* Issue #1019: Allow logging host name in the access log.
+* Pull Request #50: Fixed race condition in session cleanup.
+
+v3.5.0
+------
+
+* Issue #1301: When the incoming queue is full, now reject additional
+ connections. This functionality was added to CherryPy 3.0, but
+ unintentionally lost in 3.1.
+
+v3.4.0
+------
+
+* Miscellaneous quality improvements.
+
+v3.3.0
+------
+
+CherryPy adopts semver.
diff --git a/CHANGES.txt b/CHANGES.txt
deleted file mode 100644
index 291f8c9a..00000000
--- a/CHANGES.txt
+++ /dev/null
@@ -1,96 +0,0 @@
-5.2.0
------
-
-* #1410: Moved hosting to Github (
- `cherrypy/cherrypy <https://github.com/cherrypy/cherrypy>`_.
-
-5.1.0
------
-
-* Bugfix issue #1315 for ``test_HTTP11_pipelining`` test in Python 3.5
-* Bugfix issue #1382 regarding the keyword arguments support for Python 3
- on the config file.
-* Bugfix issue #1406 for ``test_2_KeyboardInterrupt`` test in Python 3.5.
- by monkey patching the HTTPRequest given a bug on CPython
- that is affecting the testsuite (https://bugs.python.org/issue23377).
-* Add additional parameter ``raise_subcls`` to the tests helpers
- `openURL` and ``CPWebCase.getPage`` to have finer control on
- which exceptions can be raised.
-* Add support for direct keywords on the calls (e.g. ``foo=bar``) on
- the config file under Python 3.
-* Add additional validation to determine if the process is running
- as a daemon on ``cherrypy.process.plugins.SignalHandler`` to allow
- the execution of the testsuite under CI tools.
-
-5.0.1
------
-
-* Bugfix for NameError following #94.
-
-5.0.0
------
-
-* Removed deprecated support for ``ssl_certificate`` and
- ``ssl_private_key`` attributes and implicit construction
- of SSL adapter on Python 2 WSGI servers.
-* Default SSL Adapter on Python 2 is the builtin SSL adapter,
- matching Python 3 behavior.
-* Pull request #94: In proxy tool, defer to Host header for
- resolving the base if no base is supplied.
-
-4.0.0
------
-
-* Drop support for Python 2.5 and earlier.
-* No longer build Windows installers by default.
-
-3.8.2
------
-
-* Pull Request #116: Correct InternalServerError when null bytes in
- static file path. Now responds with 404 instead.
-
-3.8.0
------
-
-* Pull Request #96: Pass ``exc_info`` to logger as keyword rather than
- formatting the error and injecting into the message.
-
-3.7.0
------
-
-* CherryPy daemon may now be invoked with ``python -m cherrypy`` in
- addition to the ``cherryd`` script.
-* Issue #1298: Fix SSL handling on CPython 2.7 with builtin SSL module
- and pyOpenSSL 0.14. This change will break PyPy for now.
-* Several documentation fixes.
-
-3.6.0
------
-
-* Fixed HTTP range headers for negative length larger than content size.
-* Disabled universal wheel generation as wsgiserver has Python duality.
-* Pull Request #42: Correct TypeError in ``check_auth`` when encrypt is used.
-* Pull Request #59: Correct signature of HandlerWrapperTool.
-* Pull Request #60: Fix error in SessionAuth where login_screen was
- incorrectly used.
-* Issue #1077: Support keyword-only arguments in dispatchers (Python 3).
-* Issue #1019: Allow logging host name in the access log.
-* Pull Request #50: Fixed race condition in session cleanup.
-
-3.5.0
------
-
-* Issue #1301: When the incoming queue is full, now reject additional
- connections. This functionality was added to CherryPy 3.0, but
- unintentionally lost in 3.1.
-
-3.4.0
------
-
-* Miscellaneous quality improvements.
-
-3.3.0
------
-
-CherryPy adopts semver.
diff --git a/CONTRIBUTING.txt b/CONTRIBUTING.txt
deleted file mode 100644
index c321e13a..00000000
--- a/CONTRIBUTING.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-CherryPy is a community-maintained, open-source project hosted at Bitbucket.
-
-To contribute, first read `How to write the perfect pull request
-<http://blog.jaraco.com/2014/04/how-to-write-perfect-pull-request.html>`_
-and file your contribution with the `CherryPy Project page
-<https://github.com/cherrypy/cherrypy>`_.
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 00000000..ed321f5b
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,30 @@
+**Copyright &copy; 2004-2016, CherryPy Team (team@cherrypy.org)**
+
+**All rights reserved.**
+
+* * *
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of CherryPy nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/MANIFEST.in b/MANIFEST.in
deleted file mode 100644
index 83d99d19..00000000
--- a/MANIFEST.in
+++ /dev/null
@@ -1,13 +0,0 @@
-include cherrypy/cherryd
-include cherrypy/favicon.ico
-include cherrypy/LICENSE.txt
-include cherrypy/scaffold/*.conf
-include cherrypy/scaffold/static/*.png
-include cherrypy/test/style.css
-include cherrypy/test/test.pem
-include cherrypy/test/static/*.html
-include cherrypy/test/static/*.jpg
-include cherrypy/tutorial/*.conf
-include cherrypy/tutorial/*.pdf
-include cherrypy/tutorial/*.html
-include cherrypy/tutorial/README.txt
diff --git a/README.rst b/README.rst
new file mode 100644
index 00000000..40590512
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,78 @@
+.. image:: https://img.shields.io/pypi/v/cherrypy.svg
+ :target: https://pypi.org/project/cherrypy
+
+.. image:: https://readthedocs.org/projects/cherrypy/badge/?version=latest
+ :target: http://docs.cherrypy.org/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/travis/cherrypy/cherrypy/master.svg?label=Linux%20build%20%40%20Travis%20CI
+ :target: http://travis-ci.org/cherrypy/cherrypy
+
+.. image:: https://img.shields.io/appveyor/ci/CherryPy/cherrypy/master.svg?label=Windows%20build%20%40%20Appveyor
+ :target: https://ci.appveyor.com/project/CherryPy/cherrypy/branch/master
+
+.. image:: https://img.shields.io/pypi/pyversions/cherrypy.svg
+
+.. image:: http://badges.github.io/stability-badges/dist/stable.svg
+ :target: http://github.com/badges/stability-badges
+ :alt: stable
+
+.. image:: https://api.codacy.com/project/badge/Grade/48b11060b5d249dc86e52dac2be2c715
+ :target: https://www.codacy.com/app/webknjaz/cherrypy-upstream?utm_source=github.com&utm_medium=referral&utm_content=cherrypy/cherrypy&utm_campaign=Badge_Grade
+
+.. image:: https://codecov.io/gh/cherrypy/cherrypy/branch/master/graph/badge.svg
+ :target: https://codecov.io/gh/cherrypy/cherrypy
+ :alt: codecov
+
+Welcome to the GitHub repository of `CherryPy <http://cherrypy.org/>`_!
+
+CherryPy is a pythonic, object-oriented HTTP framework.
+
+1. It allows building web applications in much the same way one would
+ build any other object-oriented program.
+2. This design results in less and more readable code being developed faster.
+ It's all just properties and methods.
+3. It is now more than ten years old and has proven fast and very
+ stable.
+4. It is being used in production by many sites, from the simplest to
+ the most demanding.
+5. And perhaps most importantly, it is fun to work with :-)
+
+Here's how easy it is to write "Hello World" in CherryPy:
+
+.. code:: python
+
+ import cherrypy
+
+ class HelloWorld(object):
+ @cherrypy.expose
+ def index(self):
+ return "Hello World!"
+
+ cherrypy.quickstart(HelloWorld())
+
+And it continues to work that intuitively when systems grow, allowing
+for the Python object model to be dynamically presented as a web site
+and/or API.
+
+While CherryPy is one of the easiest and most intuitive frameworks out
+there, the prerequisite for understanding the `CherryPy
+documentation <http://docs.cherrypy.org/en/latest/>`_ is that you have
+a general understanding of Python and web development.
+Additionally:
+
+- Tutorials are included in the repository:
+ https://github.com/cherrypy/cherrypy/tree/master/cherrypy/tutorial
+- A general wiki at:
+ https://github.com/cherrypy/cherrypy/wiki
+
+If the docs are insufficient to address your needs, the CherryPy
+community has several `avenues for support
+<http://docs.cherrypy.org/en/latest/support.html>`_.
+
+Contributing
+------------
+
+Please follow the `contribution guidelines
+<http://docs.cherrypy.org/en/latest/contribute.html>`_.
+And by all means, absorb the `Zen of
+CherryPy <https://github.com/cherrypy/cherrypy/wiki/The-Zen-of-CherryPy>`_.
diff --git a/README.txt b/README.txt
deleted file mode 100644
index 3c145146..00000000
--- a/README.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-* To install, change to the directory where setup.py is located and type
- (Python 2.6 or later needed):
-
- python setup.py install
-
-* To learn how to use it, look at the examples under cherrypy/tutorial/
- or go to http://www.cherrypy.org for more info.
-
-* To run the regression tests, just go to the cherrypy/test/ directory
- and type:
-
- nosetests -s ./
-
- Or to run individual tests type:
-
- nosetests -s test_foo.py
diff --git a/appveyor.yml b/appveyor.yml
new file mode 100644
index 00000000..d0fc1b70
--- /dev/null
+++ b/appveyor.yml
@@ -0,0 +1,35 @@
+environment:
+ matrix:
+ - PYTHON: "C:\\Python36-x64"
+ - PYTHON: "C:\\Python27-x64"
+
+install:
+ # symlink python from a directory with a space
+ - "mklink /d \"C:\\Program Files\\Python\" %PYTHON%"
+ - "SET PYTHON=\"C:\\Program Files\\Python\""
+ - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
+ - "python -m pip install tox"
+
+
+before_build:
+ - "python -m pip install wheel"
+
+build_script:
+ - python -m setup bdist_wheel
+
+test_script:
+ - tox
+
+after_test:
+ - ps: |
+ $wc = New-Object 'System.Net.WebClient'
+ $wc.UploadFile("https://ci.appveyor.com/api/testresults/junit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\junit-test-results.xml))
+
+#deploy_script:
+# - ps: >-
+# if($env:appveyor_repo_tag -eq 'True') {
+# Invoke-Expression "python -m twine upload dist/* --username $env:PYPI_USERNAME --password $env:PYPI_PASSWORD"
+# }
+
+artifacts:
+ - path: dist\*
diff --git a/cherrypy/LICENSE.txt b/cherrypy/LICENSE.txt
deleted file mode 100644
index 87c8bd02..00000000
--- a/cherrypy/LICENSE.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (c) 2004-2015, CherryPy Team (team@cherrypy.org)
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
- * Neither the name of the CherryPy Team nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/cherrypy/__init__.py b/cherrypy/__init__.py
index 30a8cadf..694d91ef 100644
--- a/cherrypy/__init__.py
+++ b/cherrypy/__init__.py
@@ -1,6 +1,5 @@
"""CherryPy is a pythonic, object-oriented HTTP framework.
-
CherryPy consists of not one, but four separate API layers.
The APPLICATION LAYER is the simplest. CherryPy applications are written as
@@ -53,7 +52,8 @@ with customized or extended components. The core API's are:
* Server API
* WSGI API
-These API's are described in the `CherryPy specification <https://bitbucket.org/cherrypy/cherrypy/wiki/CherryPySpec>`_.
+These API's are described in the `CherryPy specification
+<https://github.com/cherrypy/cherrypy/wiki/CherryPySpec>`_.
"""
try:
@@ -61,35 +61,52 @@ try:
except ImportError:
pass
-from cherrypy._cpcompat import urljoin as _urljoin, urlencode as _urlencode
-from cherrypy._cpcompat import basestring, unicodestr
+from threading import local as _local
-from cherrypy._cperror import HTTPError, HTTPRedirect, InternalRedirect
-from cherrypy._cperror import NotFound, CherryPyException, TimeoutError
+from ._cperror import (
+ HTTPError, HTTPRedirect, InternalRedirect,
+ NotFound, CherryPyException,
+)
-from cherrypy import _cpdispatch as dispatch
+from . import _cpdispatch as dispatch
-from cherrypy import _cptools
-tools = _cptools.default_toolbox
-Tool = _cptools.Tool
+from ._cptools import default_toolbox as tools, Tool
+from ._helper import expose, popargs, url
-from cherrypy import _cprequest
-from cherrypy.lib import httputil as _httputil
+from . import _cprequest, _cpserver, _cptree, _cplogging, _cpconfig
-from cherrypy import _cptree
-tree = _cptree.Tree()
-from cherrypy._cptree import Application
-from cherrypy import _cpwsgi as wsgi
+import cherrypy.lib.httputil as _httputil
+
+from ._cptree import Application
+from . import _cpwsgi as wsgi
-from cherrypy import process
+from . import process
try:
- from cherrypy.process import win32
+ from .process import win32
engine = win32.Win32Bus()
engine.console_control_handler = win32.ConsoleCtrlHandler(engine)
del win32
except ImportError:
engine = process.bus
+from . import _cpchecker
+
+__all__ = (
+ 'HTTPError', 'HTTPRedirect', 'InternalRedirect',
+ 'NotFound', 'CherryPyException',
+ 'dispatch', 'tools', 'Tool', 'Application',
+ 'wsgi', 'process', 'tree', 'engine',
+ 'quickstart', 'serving', 'request', 'response', 'thread_data',
+ 'log', 'expose', 'popargs', 'url', 'config',
+)
+
+
+__import__('cherrypy._cptools')
+__import__('cherrypy._cprequest')
+
+
+tree = _cptree.Tree()
+
try:
__version__ = pkg_resources.require('cherrypy')[0].version
@@ -97,34 +114,10 @@ except Exception:
__version__ = 'unknown'
-# Timeout monitor. We add two channels to the engine
-# to which cherrypy.Application will publish.
engine.listeners['before_request'] = set()
engine.listeners['after_request'] = set()
-class _TimeoutMonitor(process.plugins.Monitor):
-
- def __init__(self, bus):
- self.servings = []
- process.plugins.Monitor.__init__(self, bus, self.run)
-
- def before_request(self):
- self.servings.append((serving.request, serving.response))
-
- def after_request(self):
- try:
- self.servings.remove((serving.request, serving.response))
- except ValueError:
- pass
-
- def run(self):
- """Check timeout on all responses. (Internal)"""
- for req, resp in self.servings:
- resp.check_timeout()
-engine.timeout_monitor = _TimeoutMonitor(engine)
-engine.timeout_monitor.subscribe()
-
engine.autoreload = process.plugins.Autoreloader(engine)
engine.autoreload.subscribe()
@@ -135,29 +128,30 @@ engine.signal_handler = process.plugins.SignalHandler(engine)
class _HandleSignalsPlugin(object):
+ """Handle signals from other processes.
- """Handle signals from other processes based on the configured
- platform handlers above."""
+ Based on the configured platform handlers above.
+ """
def __init__(self, bus):
self.bus = bus
def subscribe(self):
- """Add the handlers based on the platform"""
- if hasattr(self.bus, "signal_handler"):
+ """Add the handlers based on the platform."""
+ if hasattr(self.bus, 'signal_handler'):
self.bus.signal_handler.subscribe()
- if hasattr(self.bus, "console_control_handler"):
+ if hasattr(self.bus, 'console_control_handler'):
self.bus.console_control_handler.subscribe()
+
engine.signals = _HandleSignalsPlugin(engine)
-from cherrypy import _cpserver
server = _cpserver.Server()
server.subscribe()
-def quickstart(root=None, script_name="", config=None):
+def quickstart(root=None, script_name='', config=None):
"""Mount the given root, start the builtin server (and engine), then block.
root: an instance of a "controller class" (a collection of page handler
@@ -184,11 +178,7 @@ def quickstart(root=None, script_name="", config=None):
engine.block()
-from cherrypy._cpcompat import threadlocal as _local
-
-
class _Serving(_local):
-
"""An interface for registering request and response objects.
Rather than have a separate "thread local" object for the request and
@@ -199,8 +189,8 @@ class _Serving(_local):
thread-safe way.
"""
- request = _cprequest.Request(_httputil.Host("127.0.0.1", 80),
- _httputil.Host("127.0.0.1", 1111))
+ request = _cprequest.Request(_httputil.Host('127.0.0.1', 80),
+ _httputil.Host('127.0.0.1', 1111))
"""
The request object for the current thread. In the main thread,
and any threads which are not receiving HTTP requests, this is None."""
@@ -218,6 +208,7 @@ class _Serving(_local):
"""Remove all attributes of self."""
self.__dict__.clear()
+
serving = _Serving()
@@ -233,7 +224,7 @@ class _ThreadLocalProxy(object):
return getattr(child, name)
def __setattr__(self, name, value):
- if name in ("__attrname__", ):
+ if name in ('__attrname__', ):
object.__setattr__(self, name, value)
else:
child = getattr(serving, self.__attrname__)
@@ -276,6 +267,7 @@ class _ThreadLocalProxy(object):
# Python 3
__bool__ = __nonzero__
+
# Create request and response object (the same objects will be used
# throughout the entire life of the webserver, but will redirect
# to the "serving" object)
@@ -286,8 +278,9 @@ response = _ThreadLocalProxy('response')
class _ThreadData(_local):
-
"""A container for thread-specific data."""
+
+
thread_data = _ThreadData()
@@ -301,6 +294,7 @@ def _cherrypy_pydoc_resolve(thing, forceload=0):
thing = getattr(serving, thing.__attrname__)
return _pydoc._builtin_resolve(thing, forceload)
+
try:
import pydoc as _pydoc
_pydoc._builtin_resolve = _pydoc.resolve
@@ -309,11 +303,7 @@ except ImportError:
pass
-from cherrypy import _cplogging
-
-
class _GlobalLogManager(_cplogging.LogManager):
-
"""A site-wide LogManager; routes to app.log or global log as appropriate.
This :class:`LogManager<cherrypy._cplogging.LogManager>` implements
@@ -324,7 +314,10 @@ class _GlobalLogManager(_cplogging.LogManager):
"""
def __call__(self, *args, **kwargs):
- """Log the given message to the app.log or global log as appropriate.
+ """Log the given message to the app.log or global log.
+
+ Log the given message to the app.log or global
+ log as appropriate.
"""
# Do NOT use try/except here. See
# https://github.com/cherrypy/cherrypy/issues/945
@@ -335,7 +328,10 @@ class _GlobalLogManager(_cplogging.LogManager):
return log.error(*args, **kwargs)
def access(self):
- """Log an access message to the app.log or global log as appropriate.
+ """Log an access message to the app.log or global log.
+
+ Log the given message to the app.log or global
+ log as appropriate.
"""
try:
return request.app.log.access()
@@ -351,297 +347,11 @@ log.error_file = ''
log.access_file = ''
+@engine.subscribe('log')
def _buslog(msg, level):
log.error(msg, 'ENGINE', severity=level)
-engine.subscribe('log', _buslog)
-
-# Helper functions for CP apps #
-
-
-def expose(func=None, alias=None):
- """Expose the function, optionally providing an alias or set of aliases."""
- def expose_(func):
- func.exposed = True
- if alias is not None:
- if isinstance(alias, basestring):
- parents[alias.replace(".", "_")] = func
- else:
- for a in alias:
- parents[a.replace(".", "_")] = func
- return func
-
- import sys
- import types
- if isinstance(func, (types.FunctionType, types.MethodType)):
- if alias is None:
- # @expose
- func.exposed = True
- return func
- else:
- # func = expose(func, alias)
- parents = sys._getframe(1).f_locals
- return expose_(func)
- elif func is None:
- if alias is None:
- # @expose()
- parents = sys._getframe(1).f_locals
- return expose_
- else:
- # @expose(alias="alias") or
- # @expose(alias=["alias1", "alias2"])
- parents = sys._getframe(1).f_locals
- return expose_
- else:
- # @expose("alias") or
- # @expose(["alias1", "alias2"])
- parents = sys._getframe(1).f_locals
- alias = func
- return expose_
-
-
-def popargs(*args, **kwargs):
- """A decorator for _cp_dispatch
- (cherrypy.dispatch.Dispatcher.dispatch_method_name).
-
- Optional keyword argument: handler=(Object or Function)
-
- Provides a _cp_dispatch function that pops off path segments into
- cherrypy.request.params under the names specified. The dispatch
- is then forwarded on to the next vpath element.
-
- Note that any existing (and exposed) member function of the class that
- popargs is applied to will override that value of the argument. For
- instance, if you have a method named "list" on the class decorated with
- popargs, then accessing "/list" will call that function instead of popping
- it off as the requested parameter. This restriction applies to all
- _cp_dispatch functions. The only way around this restriction is to create
- a "blank class" whose only function is to provide _cp_dispatch.
-
- If there are path elements after the arguments, or more arguments
- are requested than are available in the vpath, then the 'handler'
- keyword argument specifies the next object to handle the parameterized
- request. If handler is not specified or is None, then self is used.
- If handler is a function rather than an instance, then that function
- will be called with the args specified and the return value from that
- function used as the next object INSTEAD of adding the parameters to
- cherrypy.request.args.
-
- This decorator may be used in one of two ways:
-
- As a class decorator:
- @cherrypy.popargs('year', 'month', 'day')
- class Blog:
- def index(self, year=None, month=None, day=None):
- #Process the parameters here; any url like
- #/, /2009, /2009/12, or /2009/12/31
- #will fill in the appropriate parameters.
-
- def create(self):
- #This link will still be available at /create. Defined functions
- #take precedence over arguments.
-
- Or as a member of a class:
- class Blog:
- _cp_dispatch = cherrypy.popargs('year', 'month', 'day')
- #...
-
- The handler argument may be used to mix arguments with built in functions.
- For instance, the following setup allows different activities at the
- day, month, and year level:
-
- class DayHandler:
- def index(self, year, month, day):
- #Do something with this day; probably list entries
-
- def delete(self, year, month, day):
- #Delete all entries for this day
-
- @cherrypy.popargs('day', handler=DayHandler())
- class MonthHandler:
- def index(self, year, month):
- #Do something with this month; probably list entries
-
- def delete(self, year, month):
- #Delete all entries for this month
-
- @cherrypy.popargs('month', handler=MonthHandler())
- class YearHandler:
- def index(self, year):
- #Do something with this year
-
- #...
-
- @cherrypy.popargs('year', handler=YearHandler())
- class Root:
- def index(self):
- #...
-
- """
-
- # Since keyword arg comes after *args, we have to process it ourselves
- # for lower versions of python.
-
- handler = None
- handler_call = False
- for k, v in kwargs.items():
- if k == 'handler':
- handler = v
- else:
- raise TypeError(
- "cherrypy.popargs() got an unexpected keyword argument '{0}'"
- .format(k)
- )
-
- import inspect
-
- if handler is not None \
- and (hasattr(handler, '__call__') or inspect.isclass(handler)):
- handler_call = True
-
- def decorated(cls_or_self=None, vpath=None):
- if inspect.isclass(cls_or_self):
- # cherrypy.popargs is a class decorator
- cls = cls_or_self
- setattr(cls, dispatch.Dispatcher.dispatch_method_name, decorated)
- return cls
-
- # We're in the actual function
- self = cls_or_self
- parms = {}
- for arg in args:
- if not vpath:
- break
- parms[arg] = vpath.pop(0)
-
- if handler is not None:
- if handler_call:
- return handler(**parms)
- else:
- request.params.update(parms)
- return handler
-
- request.params.update(parms)
-
- # If we are the ultimate handler, then to prevent our _cp_dispatch
- # from being called again, we will resolve remaining elements through
- # getattr() directly.
- if vpath:
- return getattr(self, vpath.pop(0), None)
- else:
- return self
-
- return decorated
-def url(path="", qs="", script_name=None, base=None, relative=None):
- """Create an absolute URL for the given path.
-
- If 'path' starts with a slash ('/'), this will return
- (base + script_name + path + qs).
- If it does not start with a slash, this returns
- (base + script_name [+ request.path_info] + path + qs).
-
- If script_name is None, cherrypy.request will be used
- to find a script_name, if available.
-
- If base is None, cherrypy.request.base will be used (if available).
- Note that you can use cherrypy.tools.proxy to change this.
-
- Finally, note that this function can be used to obtain an absolute URL
- for the current request path (minus the querystring) by passing no args.
- If you call url(qs=cherrypy.request.query_string), you should get the
- original browser URL (assuming no internal redirections).
-
- If relative is None or not provided, request.app.relative_urls will
- be used (if available, else False). If False, the output will be an
- absolute URL (including the scheme, host, vhost, and script_name).
- If True, the output will instead be a URL that is relative to the
- current request path, perhaps including '..' atoms. If relative is
- the string 'server', the output will instead be a URL that is
- relative to the server root; i.e., it will start with a slash.
- """
- if isinstance(qs, (tuple, list, dict)):
- qs = _urlencode(qs)
- if qs:
- qs = '?' + qs
-
- if request.app:
- if not path.startswith("/"):
- # Append/remove trailing slash from path_info as needed
- # (this is to support mistyped URL's without redirecting;
- # if you want to redirect, use tools.trailing_slash).
- pi = request.path_info
- if request.is_index is True:
- if not pi.endswith('/'):
- pi = pi + '/'
- elif request.is_index is False:
- if pi.endswith('/') and pi != '/':
- pi = pi[:-1]
-
- if path == "":
- path = pi
- else:
- path = _urljoin(pi, path)
-
- if script_name is None:
- script_name = request.script_name
- if base is None:
- base = request.base
-
- newurl = base + script_name + path + qs
- else:
- # No request.app (we're being called outside a request).
- # We'll have to guess the base from server.* attributes.
- # This will produce very different results from the above
- # if you're using vhosts or tools.proxy.
- if base is None:
- base = server.base()
-
- path = (script_name or "") + path
- newurl = base + path + qs
-
- if './' in newurl:
- # Normalize the URL by removing ./ and ../
- atoms = []
- for atom in newurl.split('/'):
- if atom == '.':
- pass
- elif atom == '..':
- atoms.pop()
- else:
- atoms.append(atom)
- newurl = '/'.join(atoms)
-
- # At this point, we should have a fully-qualified absolute URL.
-
- if relative is None:
- relative = getattr(request.app, "relative_urls", False)
-
- # See http://www.ietf.org/rfc/rfc2396.txt
- if relative == 'server':
- # "A relative reference beginning with a single slash character is
- # termed an absolute-path reference, as defined by <abs_path>..."
- # This is also sometimes called "server-relative".
- newurl = '/' + '/'.join(newurl.split('/', 3)[3:])
- elif relative:
- # "A relative reference that does not begin with a scheme name
- # or a slash character is termed a relative-path reference."
- old = url(relative=False).split('/')[:-1]
- new = newurl.split('/')
- while old and new:
- a, b = old[0], new[0]
- if a != b:
- break
- old.pop(0)
- new.pop(0)
- new = (['..'] * len(old)) + new
- newurl = '/'.join(new)
-
- return newurl
-
-
-# import _cpconfig last so it can reference other top-level objects
-from cherrypy import _cpconfig
# Use _global_conf_alias so quickstart can use 'config' as an arg
# without shadowing cherrypy.config.
config = _global_conf_alias = _cpconfig.Config()
@@ -651,11 +361,10 @@ config.defaults = {
'tools.trailing_slash.on': True,
'tools.encode.on': True
}
-config.namespaces["log"] = lambda k, v: setattr(log, k, v)
-config.namespaces["checker"] = lambda k, v: setattr(checker, k, v)
+config.namespaces['log'] = lambda k, v: setattr(log, k, v)
+config.namespaces['checker'] = lambda k, v: setattr(checker, k, v)
# Must reset to get our defaults applied.
config.reset()
-from cherrypy import _cpchecker
checker = _cpchecker.Checker()
engine.subscribe('start', checker)
diff --git a/cherrypy/__main__.py b/cherrypy/__main__.py
index b1c9c012..6674f7cb 100755
--- a/cherrypy/__main__.py
+++ b/cherrypy/__main__.py
@@ -1,4 +1,5 @@
-import cherrypy.daemon
+"""CherryPy'd cherryd daemon runner."""
+from cherrypy.daemon import run
-if __name__ == '__main__':
- cherrypy.daemon.run()
+
+__name__ == '__main__' and run()
diff --git a/cherrypy/_cpchecker.py b/cherrypy/_cpchecker.py
index 4ef82597..0066cd5a 100644
--- a/cherrypy/_cpchecker.py
+++ b/cherrypy/_cpchecker.py
@@ -1,12 +1,14 @@
+"""Checker for CherryPy sites and mounted apps."""
import os
import warnings
+import six
+from six.moves import builtins
+
import cherrypy
-from cherrypy._cpcompat import iteritems, copykeys, builtins
class Checker(object):
-
"""A checker for CherryPy sites and their mounted applications.
When this object is called at engine startup, it executes each
@@ -24,6 +26,7 @@ class Checker(object):
"""If True (the default), run all checks; if False, turn off all checks."""
def __init__(self):
+ """Initialize Checker instance."""
self._populate_known_types()
def __call__(self):
@@ -33,7 +36,7 @@ class Checker(object):
warnings.formatwarning = self.formatwarning
try:
for name in dir(self):
- if name.startswith("check_"):
+ if name.startswith('check_'):
method = getattr(self, name)
if method and hasattr(method, '__call__'):
method()
@@ -42,14 +45,13 @@ class Checker(object):
def formatwarning(self, message, category, filename, lineno, line=None):
"""Function to format a warning."""
- return "CherryPy Checker:\n%s\n\n" % message
+ return 'CherryPy Checker:\n%s\n\n' % message
# This value should be set inside _cpconfig.
global_config_contained_paths = False
def check_app_config_entries_dont_start_with_script_name(self):
- """Check for Application config with sections that repeat script_name.
- """
+ """Check for App config with sections that repeat script_name."""
for sn, app in cherrypy.tree.apps.items():
if not isinstance(app, cherrypy.Application):
continue
@@ -57,36 +59,36 @@ class Checker(object):
continue
if sn == '':
continue
- sn_atoms = sn.strip("/").split("/")
+ sn_atoms = sn.strip('/').split('/')
for key in app.config.keys():
- key_atoms = key.strip("/").split("/")
+ key_atoms = key.strip('/').split('/')
if key_atoms[:len(sn_atoms)] == sn_atoms:
warnings.warn(
- "The application mounted at %r has config "
- "entries that start with its script name: %r" % (sn,
+ 'The application mounted at %r has config '
+ 'entries that start with its script name: %r' % (sn,
key))
def check_site_config_entries_in_app_config(self):
"""Check for mounted Applications that have site-scoped config."""
- for sn, app in iteritems(cherrypy.tree.apps):
+ for sn, app in six.iteritems(cherrypy.tree.apps):
if not isinstance(app, cherrypy.Application):
continue
msg = []
- for section, entries in iteritems(app.config):
+ for section, entries in six.iteritems(app.config):
if section.startswith('/'):
- for key, value in iteritems(entries):
- for n in ("engine.", "server.", "tree.", "checker."):
+ for key, value in six.iteritems(entries):
+ for n in ('engine.', 'server.', 'tree.', 'checker.'):
if key.startswith(n):
- msg.append("[%s] %s = %s" %
+ msg.append('[%s] %s = %s' %
(section, key, value))
if msg:
msg.insert(0,
- "The application mounted at %r contains the "
- "following config entries, which are only allowed "
- "in site-wide config. Move them to a [global] "
- "section and pass them to cherrypy.config.update() "
- "instead of tree.mount()." % sn)
+ 'The application mounted at %r contains the '
+ 'following config entries, which are only allowed '
+ 'in site-wide config. Move them to a [global] '
+ 'section and pass them to cherrypy.config.update() '
+ 'instead of tree.mount().' % sn)
warnings.warn(os.linesep.join(msg))
def check_skipped_app_config(self):
@@ -95,32 +97,30 @@ class Checker(object):
if not isinstance(app, cherrypy.Application):
continue
if not app.config:
- msg = "The Application mounted at %r has an empty config." % sn
+ msg = 'The Application mounted at %r has an empty config.' % sn
if self.global_config_contained_paths:
- msg += (" It looks like the config you passed to "
- "cherrypy.config.update() contains application-"
- "specific sections. You must explicitly pass "
- "application config via "
- "cherrypy.tree.mount(..., config=app_config)")
+ msg += (' It looks like the config you passed to '
+ 'cherrypy.config.update() contains application-'
+ 'specific sections. You must explicitly pass '
+ 'application config via '
+ 'cherrypy.tree.mount(..., config=app_config)')
warnings.warn(msg)
return
def check_app_config_brackets(self):
- """Check for Application config with extraneous brackets in section
- names.
- """
+ """Check for App config with extraneous brackets in section names."""
for sn, app in cherrypy.tree.apps.items():
if not isinstance(app, cherrypy.Application):
continue
if not app.config:
continue
for key in app.config.keys():
- if key.startswith("[") or key.endswith("]"):
+ if key.startswith('[') or key.endswith(']'):
warnings.warn(
- "The application mounted at %r has config "
- "section names with extraneous brackets: %r. "
- "Config *files* need brackets; config *dicts* "
- "(e.g. passed to tree.mount) do not." % (sn, key))
+ 'The application mounted at %r has config '
+ 'section names with extraneous brackets: %r. '
+ 'Config *files* need brackets; config *dicts* '
+ '(e.g. passed to tree.mount) do not.' % (sn, key))
def check_static_paths(self):
"""Check Application config for incorrect static paths."""
@@ -132,47 +132,47 @@ class Checker(object):
request.app = app
for section in app.config:
# get_resource will populate request.config
- request.get_resource(section + "/dummy.html")
+ request.get_resource(section + '/dummy.html')
conf = request.config.get
- if conf("tools.staticdir.on", False):
- msg = ""
- root = conf("tools.staticdir.root")
- dir = conf("tools.staticdir.dir")
+ if conf('tools.staticdir.on', False):
+ msg = ''
+ root = conf('tools.staticdir.root')
+ dir = conf('tools.staticdir.dir')
if dir is None:
- msg = "tools.staticdir.dir is not set."
+ msg = 'tools.staticdir.dir is not set.'
else:
- fulldir = ""
+ fulldir = ''
if os.path.isabs(dir):
fulldir = dir
if root:
- msg = ("dir is an absolute path, even "
- "though a root is provided.")
+ msg = ('dir is an absolute path, even '
+ 'though a root is provided.')
testdir = os.path.join(root, dir[1:])
if os.path.exists(testdir):
msg += (
- "\nIf you meant to serve the "
- "filesystem folder at %r, remove the "
- "leading slash from dir." % (testdir,))
+ '\nIf you meant to serve the '
+ 'filesystem folder at %r, remove the '
+ 'leading slash from dir.' % (testdir,))
else:
if not root:
msg = (
- "dir is a relative path and "
- "no root provided.")
+ 'dir is a relative path and '
+ 'no root provided.')
else:
fulldir = os.path.join(root, dir)
if not os.path.isabs(fulldir):
- msg = ("%r is not an absolute path." % (
+ msg = ('%r is not an absolute path.' % (
fulldir,))
if fulldir and not os.path.exists(fulldir):
if msg:
- msg += "\n"
- msg += ("%r (root + dir) is not an existing "
- "filesystem path." % fulldir)
+ msg += '\n'
+ msg += ('%r (root + dir) is not an existing '
+ 'filesystem path.' % fulldir)
if msg:
- warnings.warn("%s\nsection: [%s]\nroot: %r\ndir: %r"
+ warnings.warn('%s\nsection: [%s]\nroot: %r\ndir: %r'
% (msg, section, root, dir))
# -------------------------- Compatibility -------------------------- #
@@ -196,21 +196,21 @@ class Checker(object):
"""Process config and warn on each obsolete or deprecated entry."""
for section, conf in config.items():
if isinstance(conf, dict):
- for k, v in conf.items():
+ for k in conf:
if k in self.obsolete:
- warnings.warn("%r is obsolete. Use %r instead.\n"
- "section: [%s]" %
+ warnings.warn('%r is obsolete. Use %r instead.\n'
+ 'section: [%s]' %
(k, self.obsolete[k], section))
elif k in self.deprecated:
- warnings.warn("%r is deprecated. Use %r instead.\n"
- "section: [%s]" %
+ warnings.warn('%r is deprecated. Use %r instead.\n'
+ 'section: [%s]' %
(k, self.deprecated[k], section))
else:
if section in self.obsolete:
- warnings.warn("%r is obsolete. Use %r instead."
+ warnings.warn('%r is obsolete. Use %r instead.'
% (section, self.obsolete[section]))
elif section in self.deprecated:
- warnings.warn("%r is deprecated. Use %r instead."
+ warnings.warn('%r is deprecated. Use %r instead.'
% (section, self.deprecated[section]))
def check_compatibility(self):
@@ -225,40 +225,40 @@ class Checker(object):
extra_config_namespaces = []
def _known_ns(self, app):
- ns = ["wsgi"]
- ns.extend(copykeys(app.toolboxes))
- ns.extend(copykeys(app.namespaces))
- ns.extend(copykeys(app.request_class.namespaces))
- ns.extend(copykeys(cherrypy.config.namespaces))
+ ns = ['wsgi']
+ ns.extend(app.toolboxes)
+ ns.extend(app.namespaces)
+ ns.extend(app.request_class.namespaces)
+ ns.extend(cherrypy.config.namespaces)
ns += self.extra_config_namespaces
for section, conf in app.config.items():
- is_path_section = section.startswith("/")
+ is_path_section = section.startswith('/')
if is_path_section and isinstance(conf, dict):
- for k, v in conf.items():
- atoms = k.split(".")
+ for k in conf:
+ atoms = k.split('.')
if len(atoms) > 1:
if atoms[0] not in ns:
# Spit out a special warning if a known
# namespace is preceded by "cherrypy."
- if atoms[0] == "cherrypy" and atoms[1] in ns:
+ if atoms[0] == 'cherrypy' and atoms[1] in ns:
msg = (
- "The config entry %r is invalid; "
- "try %r instead.\nsection: [%s]"
- % (k, ".".join(atoms[1:]), section))
+ 'The config entry %r is invalid; '
+ 'try %r instead.\nsection: [%s]'
+ % (k, '.'.join(atoms[1:]), section))
else:
msg = (
- "The config entry %r is invalid, "
- "because the %r config namespace "
- "is unknown.\n"
- "section: [%s]" % (k, atoms[0], section))
+ 'The config entry %r is invalid, '
+ 'because the %r config namespace '
+ 'is unknown.\n'
+ 'section: [%s]' % (k, atoms[0], section))
warnings.warn(msg)
- elif atoms[0] == "tools":
+ elif atoms[0] == 'tools':
if atoms[1] not in dir(cherrypy.tools):
msg = (
- "The config entry %r may be invalid, "
- "because the %r tool was not found.\n"
- "section: [%s]" % (k, atoms[1], section))
+ 'The config entry %r may be invalid, '
+ 'because the %r tool was not found.\n'
+ 'section: [%s]' % (k, atoms[1], section))
warnings.warn(msg)
def check_config_namespaces(self):
@@ -282,29 +282,22 @@ class Checker(object):
continue
vtype = type(getattr(obj, name, None))
if vtype in b:
- self.known_config_types[namespace + "." + name] = vtype
+ self.known_config_types[namespace + '.' + name] = vtype
- traverse(cherrypy.request, "request")
- traverse(cherrypy.response, "response")
- traverse(cherrypy.server, "server")
- traverse(cherrypy.engine, "engine")
- traverse(cherrypy.log, "log")
+ traverse(cherrypy.request, 'request')
+ traverse(cherrypy.response, 'response')
+ traverse(cherrypy.server, 'server')
+ traverse(cherrypy.engine, 'engine')
+ traverse(cherrypy.log, 'log')
def _known_types(self, config):
- msg = ("The config entry %r in section %r is of type %r, "
- "which does not match the expected type %r.")
+ msg = ('The config entry %r in section %r is of type %r, '
+ 'which does not match the expected type %r.')
for section, conf in config.items():
- if isinstance(conf, dict):
- for k, v in conf.items():
- if v is not None:
- expected_type = self.known_config_types.get(k, None)
- vtype = type(v)
- if expected_type and vtype != expected_type:
- warnings.warn(msg % (k, section, vtype.__name__,
- expected_type.__name__))
- else:
- k, v = section, conf
+ if not isinstance(conf, dict):
+ conf = {section: conf}
+ for k, v in conf.items():
if v is not None:
expected_type = self.known_config_types.get(k, None)
vtype = type(v)
@@ -326,7 +319,7 @@ class Checker(object):
for k, v in cherrypy.config.items():
if k == 'server.socket_host' and v == 'localhost':
warnings.warn("The use of 'localhost' as a socket host can "
- "cause problems on newer systems, since "
+ 'cause problems on newer systems, since '
"'localhost' can map to either an IPv4 or an "
"IPv6 address. You should use '127.0.0.1' "
"or '[::1]' instead.")
diff --git a/cherrypy/_cpcompat.py b/cherrypy/_cpcompat.py
index 97aa7a9b..252de10b 100644
--- a/cherrypy/_cpcompat.py
+++ b/cherrypy/_cpcompat.py
@@ -1,32 +1,27 @@
"""Compatibility code for using CherryPy with various versions of Python.
-CherryPy 3.2 is compatible with Python versions 2.3+. This module provides a
+To retain compatibility with older Python versions, this module provides a
useful abstraction over the differences between Python versions, sometimes by
preferring a newer idiom, sometimes an older one, and sometimes a custom one.
In particular, Python 2 uses str and '' for byte strings, while Python 3
uses str and '' for unicode strings. We will call each of these the 'native
string' type for each version. Because of this major difference, this module
-provides new 'bytestr', 'unicodestr', and 'nativestr' attributes, as well as
+provides
two functions: 'ntob', which translates native strings (of type 'str') into
byte strings regardless of Python version, and 'ntou', which translates native
-strings to unicode strings. This also provides a 'BytesIO' name for dealing
-specifically with bytes, and a 'StringIO' name for dealing with native strings.
-It also provides a 'base64_decode' function with native strings as input and
-output.
+strings to unicode strings.
"""
-import os
+
import re
import sys
import threading
+import base64
-if sys.version_info >= (3, 0):
- py3k = True
- bytestr = bytes
- unicodestr = str
- nativestr = unicodestr
- basestring = (bytes, str)
+import six
+from six.moves import urllib
+if six.PY3:
def ntob(n, encoding='ISO-8859-1'):
"""Return the given native string as a byte string in the given
encoding.
@@ -49,18 +44,8 @@ if sys.version_info >= (3, 0):
if isinstance(n, bytes):
return n.decode(encoding)
return n
- # type("")
- from io import StringIO
- # bytes:
- from io import BytesIO as BytesIO
else:
# Python 2
- py3k = False
- bytestr = str
- unicodestr = unicode
- nativestr = bytestr
- basestring = basestring
-
def ntob(n, encoding='ISO-8859-1'):
"""Return the given native string as a byte string in the given
encoding.
@@ -82,9 +67,9 @@ else:
# escapes, but without having to prefix it with u'' for Python 2,
# but no prefix for Python 3.
if encoding == 'escape':
- return unicode(
+ return six.text_type( # unicode for Python 2
re.sub(r'\\u([0-9a-zA-Z]{4})',
- lambda m: unichr(int(m.group(1), 16)),
+ lambda m: six.unichr(int(m.group(1), 16)),
n.decode('ISO-8859-1')))
# Assume it's already in the given encoding, which for ISO-8859-1
# is almost always what was intended.
@@ -93,254 +78,65 @@ else:
def tonative(n, encoding='ISO-8859-1'):
"""Return the given string as a native string in the given encoding."""
# In Python 2, the native string type is bytes.
- if isinstance(n, unicode):
+ if isinstance(n, six.text_type): # unicode for Python 2
return n.encode(encoding)
return n
- try:
- # type("")
- from cStringIO import StringIO
- except ImportError:
- # type("")
- from StringIO import StringIO
- # bytes:
- BytesIO = StringIO
def always_bytes(s, encoding='ISO-8859-1'):
- if isinstance(s, unicodestr):
+ if isinstance(s, six.text_type):
return s.encode(encoding)
else:
assert_native(s)
return s # Assume this bytestring is already in the correct encoding.
-def assert_native(n):
- if not isinstance(n, nativestr):
- raise TypeError("n must be a native str (got %s)" % type(n).__name__)
-try:
- # Python 3.1+
- from base64 import decodebytes as _base64_decodebytes
-except ImportError:
- # Python 3.0-
- # since CherryPy claims compability with Python 2.3, we must use
- # the legacy API of base64
- from base64 import decodestring as _base64_decodebytes
+def assert_native(n):
+ if not isinstance(n, str):
+ raise TypeError('n must be a native str (got %s)' % type(n).__name__)
def base64_decode(n, encoding='ISO-8859-1'):
"""Return the native string base64-decoded (as a native string)."""
- if isinstance(n, unicodestr):
- b = n.encode(encoding)
- else:
- b = n
- b = _base64_decodebytes(b)
- if nativestr is unicodestr:
- return b.decode(encoding)
- else:
- return b
-
-
-try:
- sorted = sorted
-except NameError:
- def sorted(i):
- i = i[:]
- i.sort()
- return i
-
-try:
- reversed = reversed
-except NameError:
- def reversed(x):
- i = len(x)
- while i > 0:
- i -= 1
- yield x[i]
-
-try:
- # Python 3
- from urllib.parse import urljoin, urlencode
- from urllib.parse import quote, quote_plus
- from urllib.request import unquote, urlopen
- from urllib.request import parse_http_list, parse_keqv_list
-except ImportError:
- # Python 2
- from urlparse import urljoin
- from urllib import urlencode, urlopen
- from urllib import quote, quote_plus
- from urllib import unquote
- from urllib2 import parse_http_list, parse_keqv_list
-
-try:
- from threading import local as threadlocal
-except ImportError:
- from cherrypy._cpthreadinglocal import local as threadlocal
-
-try:
- dict.iteritems
- # Python 2
- iteritems = lambda d: d.iteritems()
- copyitems = lambda d: d.items()
-except AttributeError:
- # Python 3
- iteritems = lambda d: d.items()
- copyitems = lambda d: list(d.items())
-
-try:
- dict.iterkeys
- # Python 2
- iterkeys = lambda d: d.iterkeys()
- copykeys = lambda d: d.keys()
-except AttributeError:
- # Python 3
- iterkeys = lambda d: d.keys()
- copykeys = lambda d: list(d.keys())
-
-try:
- dict.itervalues
- # Python 2
- itervalues = lambda d: d.itervalues()
- copyvalues = lambda d: d.values()
-except AttributeError:
- # Python 3
- itervalues = lambda d: d.values()
- copyvalues = lambda d: list(d.values())
+ decoded = base64.decodestring(n.encode('ascii'))
+ return tonative(decoded, encoding)
-try:
- # Python 3
- import builtins
-except ImportError:
- # Python 2
- import __builtin__ as builtins
-
-try:
- # Python 2. We try Python 2 first clients on Python 2
- # don't try to import the 'http' module from cherrypy.lib
- from Cookie import SimpleCookie, CookieError
- from httplib import BadStatusLine, HTTPConnection, IncompleteRead
- from httplib import NotConnected
- from BaseHTTPServer import BaseHTTPRequestHandler
-except ImportError:
- # Python 3
- from http.cookies import SimpleCookie, CookieError
- from http.client import BadStatusLine, HTTPConnection, IncompleteRead
- from http.client import NotConnected
- from http.server import BaseHTTPRequestHandler
# Some platforms don't expose HTTPSConnection, so handle it separately
-if py3k:
- try:
- from http.client import HTTPSConnection
- except ImportError:
- # Some platforms which don't have SSL don't expose HTTPSConnection
- HTTPSConnection = None
-else:
- try:
- from httplib import HTTPSConnection
- except ImportError:
- HTTPSConnection = None
-
-try:
- # Python 2
- xrange = xrange
-except NameError:
- # Python 3
- xrange = range
-
-import threading
-if hasattr(threading.Thread, "daemon"):
- # Python 2.6+
- def get_daemon(t):
- return t.daemon
-
- def set_daemon(t, val):
- t.daemon = val
-else:
- def get_daemon(t):
- return t.isDaemon()
+HTTPSConnection = getattr(six.moves.http_client, 'HTTPSConnection', None)
- def set_daemon(t, val):
- t.setDaemon(val)
-try:
- from email.utils import formatdate
+def unquote_qs(atom, encoding, errors='strict'):
+ atom_spc = atom.replace('+', ' ')
+ return (
+ urllib.parse.unquote(atom_spc, encoding=encoding, errors=errors)
+ if six.PY3 else
+ urllib.parse.unquote(atom_spc).decode(encoding, errors)
+ )
- def HTTPDate(timeval=None):
- return formatdate(timeval, usegmt=True)
-except ImportError:
- from rfc822 import formatdate as HTTPDate
try:
- # Python 3
- from urllib.parse import unquote as parse_unquote
-
- def unquote_qs(atom, encoding, errors='strict'):
- return parse_unquote(
- atom.replace('+', ' '),
- encoding=encoding,
- errors=errors)
-except ImportError:
- # Python 2
- from urllib import unquote as parse_unquote
-
- def unquote_qs(atom, encoding, errors='strict'):
- return parse_unquote(atom.replace('+', ' ')).decode(encoding, errors)
-
-try:
- # Prefer simplejson, which is usually more advanced than the builtin
- # module.
+ # Prefer simplejson
import simplejson as json
- json_decode = json.JSONDecoder().decode
- _json_encode = json.JSONEncoder().iterencode
except ImportError:
- if sys.version_info >= (2, 6):
- # Python >=2.6 : json is part of the standard library
- import json
- json_decode = json.JSONDecoder().decode
- _json_encode = json.JSONEncoder().iterencode
- else:
- json = None
-
- def json_decode(s):
- raise ValueError('No JSON library is available')
-
- def _json_encode(s):
- raise ValueError('No JSON library is available')
-finally:
- if json and py3k:
- # The two Python 3 implementations (simplejson/json)
- # outputs str. We need bytes.
- def json_encode(value):
- for chunk in _json_encode(value):
- yield chunk.encode('utf8')
- else:
- json_encode = _json_encode
+ import json
-try:
- import cPickle as pickle
-except ImportError:
- # In Python 2, pickle is a Python version.
- # In Python 3, pickle is the sped-up C version.
- import pickle
+json_decode = json.JSONDecoder().decode
+_json_encode = json.JSONEncoder().iterencode
-import binascii
-def random20():
- return binascii.hexlify(os.urandom(20)).decode('ascii')
+if six.PY3:
+ # Encode to bytes on Python 3
+ def json_encode(value):
+ for chunk in _json_encode(value):
+ yield chunk.encode('utf-8')
+else:
+ json_encode = _json_encode
-try:
- from _thread import get_ident as get_thread_ident
-except ImportError:
- from thread import get_ident as get_thread_ident
-try:
- # Python 3
- next = next
-except NameError:
- # Python 2
- def next(i):
- return i.next()
+text_or_bytes = six.text_type, six.binary_type
+
if sys.version_info >= (3, 3):
Timer = threading.Timer
@@ -350,17 +146,19 @@ else:
Timer = threading._Timer
Event = threading._Event
-# Prior to Python 2.6, the Thread class did not have a .daemon property.
-# This mix-in adds that property.
-
+# html module come in 3.2 version
+try:
+ from html import escape
+except ImportError:
+ from cgi import escape
-class SetDaemonProperty:
- def __get_daemon(self):
- return self.isDaemon()
+# html module needed the argument quote=False because in cgi the default
+# is False. With quote=True the results differ.
- def __set_daemon(self, daemon):
- self.setDaemon(daemon)
+def escape_html(s, escape_quote=False):
+ """Replace special characters "&", "<" and ">" to HTML-safe sequences.
- if sys.version_info < (2, 6):
- daemon = property(__get_daemon, __set_daemon)
+ When escape_quote=True, escape (') and (") chars.
+ """
+ return escape(s, quote=escape_quote)
diff --git a/cherrypy/_cpcompat_subprocess.py b/cherrypy/_cpcompat_subprocess.py
deleted file mode 100644
index 517b8d44..00000000
--- a/cherrypy/_cpcompat_subprocess.py
+++ /dev/null
@@ -1,1544 +0,0 @@
-# subprocess - Subprocesses with accessible I/O streams
-#
-# For more information about this module, see PEP 324.
-#
-# This module should remain compatible with Python 2.2, see PEP 291.
-#
-# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
-#
-# Licensed to PSF under a Contributor Agreement.
-# See http://www.python.org/2.4/license for licensing details.
-
-r"""subprocess - Subprocesses with accessible I/O streams
-
-This module allows you to spawn processes, connect to their
-input/output/error pipes, and obtain their return codes. This module
-intends to replace several other, older modules and functions, like:
-
-os.system
-os.spawn*
-os.popen*
-popen2.*
-commands.*
-
-Information about how the subprocess module can be used to replace these
-modules and functions can be found below.
-
-
-
-Using the subprocess module
-===========================
-This module defines one class called Popen:
-
-class Popen(args, bufsize=0, executable=None,
- stdin=None, stdout=None, stderr=None,
- preexec_fn=None, close_fds=False, shell=False,
- cwd=None, env=None, universal_newlines=False,
- startupinfo=None, creationflags=0):
-
-
-Arguments are:
-
-args should be a string, or a sequence of program arguments. The
-program to execute is normally the first item in the args sequence or
-string, but can be explicitly set by using the executable argument.
-
-On UNIX, with shell=False (default): In this case, the Popen class
-uses os.execvp() to execute the child program. args should normally
-be a sequence. A string will be treated as a sequence with the string
-as the only item (the program to execute).
-
-On UNIX, with shell=True: If args is a string, it specifies the
-command string to execute through the shell. If args is a sequence,
-the first item specifies the command string, and any additional items
-will be treated as additional shell arguments.
-
-On Windows: the Popen class uses CreateProcess() to execute the child
-program, which operates on strings. If args is a sequence, it will be
-converted to a string using the list2cmdline method. Please note that
-not all MS Windows applications interpret the command line the same
-way: The list2cmdline is designed for applications using the same
-rules as the MS C runtime.
-
-bufsize, if given, has the same meaning as the corresponding argument
-to the built-in open() function: 0 means unbuffered, 1 means line
-buffered, any other positive value means use a buffer of
-(approximately) that size. A negative bufsize means to use the system
-default, which usually means fully buffered. The default value for
-bufsize is 0 (unbuffered).
-
-stdin, stdout and stderr specify the executed programs' standard
-input, standard output and standard error file handles, respectively.
-Valid values are PIPE, an existing file descriptor (a positive
-integer), an existing file object, and None. PIPE indicates that a
-new pipe to the child should be created. With None, no redirection
-will occur; the child's file handles will be inherited from the
-parent. Additionally, stderr can be STDOUT, which indicates that the
-stderr data from the applications should be captured into the same
-file handle as for stdout.
-
-If preexec_fn is set to a callable object, this object will be called
-in the child process just before the child is executed.
-
-If close_fds is true, all file descriptors except 0, 1 and 2 will be
-closed before the child process is executed.
-
-if shell is true, the specified command will be executed through the
-shell.
-
-If cwd is not None, the current directory will be changed to cwd
-before the child is executed.
-
-If env is not None, it defines the environment variables for the new
-process.
-
-If universal_newlines is true, the file objects stdout and stderr are
-opened as a text files, but lines may be terminated by any of '\n',
-the Unix end-of-line convention, '\r', the Macintosh convention or
-'\r\n', the Windows convention. All of these external representations
-are seen as '\n' by the Python program. Note: This feature is only
-available if Python is built with universal newline support (the
-default). Also, the newlines attribute of the file objects stdout,
-stdin and stderr are not updated by the communicate() method.
-
-The startupinfo and creationflags, if given, will be passed to the
-underlying CreateProcess() function. They can specify things such as
-appearance of the main window and priority for the new process.
-(Windows only)
-
-
-This module also defines some shortcut functions:
-
-call(*popenargs, **kwargs):
- Run command with arguments. Wait for command to complete, then
- return the returncode attribute.
-
- The arguments are the same as for the Popen constructor. Example:
-
- retcode = call(["ls", "-l"])
-
-check_call(*popenargs, **kwargs):
- Run command with arguments. Wait for command to complete. If the
- exit code was zero then return, otherwise raise
- CalledProcessError. The CalledProcessError object will have the
- return code in the returncode attribute.
-
- The arguments are the same as for the Popen constructor. Example:
-
- check_call(["ls", "-l"])
-
-check_output(*popenargs, **kwargs):
- Run command with arguments and return its output as a byte string.
-
- If the exit code was non-zero it raises a CalledProcessError. The
- CalledProcessError object will have the return code in the returncode
- attribute and output in the output attribute.
-
- The arguments are the same as for the Popen constructor. Example:
-
- output = check_output(["ls", "-l", "/dev/null"])
-
-
-Exceptions
-----------
-Exceptions raised in the child process, before the new program has
-started to execute, will be re-raised in the parent. Additionally,
-the exception object will have one extra attribute called
-'child_traceback', which is a string containing traceback information
-from the childs point of view.
-
-The most common exception raised is OSError. This occurs, for
-example, when trying to execute a non-existent file. Applications
-should prepare for OSErrors.
-
-A ValueError will be raised if Popen is called with invalid arguments.
-
-check_call() and check_output() will raise CalledProcessError, if the
-called process returns a non-zero return code.
-
-
-Security
---------
-Unlike some other popen functions, this implementation will never call
-/bin/sh implicitly. This means that all characters, including shell
-metacharacters, can safely be passed to child processes.
-
-
-Popen objects
-=============
-Instances of the Popen class have the following methods:
-
-poll()
- Check if child process has terminated. Returns returncode
- attribute.
-
-wait()
- Wait for child process to terminate. Returns returncode attribute.
-
-communicate(input=None)
- Interact with process: Send data to stdin. Read data from stdout
- and stderr, until end-of-file is reached. Wait for process to
- terminate. The optional input argument should be a string to be
- sent to the child process, or None, if no data should be sent to
- the child.
-
- communicate() returns a tuple (stdout, stderr).
-
- Note: The data read is buffered in memory, so do not use this
- method if the data size is large or unlimited.
-
-The following attributes are also available:
-
-stdin
- If the stdin argument is PIPE, this attribute is a file object
- that provides input to the child process. Otherwise, it is None.
-
-stdout
- If the stdout argument is PIPE, this attribute is a file object
- that provides output from the child process. Otherwise, it is
- None.
-
-stderr
- If the stderr argument is PIPE, this attribute is file object that
- provides error output from the child process. Otherwise, it is
- None.
-
-pid
- The process ID of the child process.
-
-returncode
- The child return code. A None value indicates that the process
- hasn't terminated yet. A negative value -N indicates that the
- child was terminated by signal N (UNIX only).
-
-
-Replacing older functions with the subprocess module
-====================================================
-In this section, "a ==> b" means that b can be used as a replacement
-for a.
-
-Note: All functions in this section fail (more or less) silently if
-the executed program cannot be found; this module raises an OSError
-exception.
-
-In the following examples, we assume that the subprocess module is
-imported with "from subprocess import *".
-
-
-Replacing /bin/sh shell backquote
----------------------------------
-output=`mycmd myarg`
-==>
-output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
-
-
-Replacing shell pipe line
--------------------------
-output=`dmesg | grep hda`
-==>
-p1 = Popen(["dmesg"], stdout=PIPE)
-p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
-output = p2.communicate()[0]
-
-
-Replacing os.system()
----------------------
-sts = os.system("mycmd" + " myarg")
-==>
-p = Popen("mycmd" + " myarg", shell=True)
-pid, sts = os.waitpid(p.pid, 0)
-
-Note:
-
-* Calling the program through the shell is usually not required.
-
-* It's easier to look at the returncode attribute than the
- exitstatus.
-
-A more real-world example would look like this:
-
-try:
- retcode = call("mycmd" + " myarg", shell=True)
- if retcode < 0:
- print >>sys.stderr, "Child was terminated by signal", -retcode
- else:
- print >>sys.stderr, "Child returned", retcode
-except OSError, e:
- print >>sys.stderr, "Execution failed:", e
-
-
-Replacing os.spawn*
--------------------
-P_NOWAIT example:
-
-pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
-==>
-pid = Popen(["/bin/mycmd", "myarg"]).pid
-
-
-P_WAIT example:
-
-retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
-==>
-retcode = call(["/bin/mycmd", "myarg"])
-
-
-Vector example:
-
-os.spawnvp(os.P_NOWAIT, path, args)
-==>
-Popen([path] + args[1:])
-
-
-Environment example:
-
-os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
-==>
-Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
-
-
-Replacing os.popen*
--------------------
-pipe = os.popen("cmd", mode='r', bufsize)
-==>
-pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
-
-pipe = os.popen("cmd", mode='w', bufsize)
-==>
-pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
-
-
-(child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
-==>
-p = Popen("cmd", shell=True, bufsize=bufsize,
- stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdin, child_stdout) = (p.stdin, p.stdout)
-
-
-(child_stdin,
- child_stdout,
- child_stderr) = os.popen3("cmd", mode, bufsize)
-==>
-p = Popen("cmd", shell=True, bufsize=bufsize,
- stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
-(child_stdin,
- child_stdout,
- child_stderr) = (p.stdin, p.stdout, p.stderr)
-
-
-(child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
- bufsize)
-==>
-p = Popen("cmd", shell=True, bufsize=bufsize,
- stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
-(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
-
-On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
-the command to execute, in which case arguments will be passed
-directly to the program without shell intervention. This usage can be
-replaced as follows:
-
-(child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
- bufsize)
-==>
-p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
-(child_stdin, child_stdout) = (p.stdin, p.stdout)
-
-Return code handling translates as follows:
-
-pipe = os.popen("cmd", 'w')
-...
-rc = pipe.close()
-if rc is not None and rc % 256:
- print "There were some errors"
-==>
-process = Popen("cmd", 'w', shell=True, stdin=PIPE)
-...
-process.stdin.close()
-if process.wait() != 0:
- print "There were some errors"
-
-
-Replacing popen2.*
-------------------
-(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
-==>
-p = Popen(["somestring"], shell=True, bufsize=bufsize
- stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdout, child_stdin) = (p.stdout, p.stdin)
-
-On Unix, popen2 also accepts a sequence as the command to execute, in
-which case arguments will be passed directly to the program without
-shell intervention. This usage can be replaced as follows:
-
-(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
- mode)
-==>
-p = Popen(["mycmd", "myarg"], bufsize=bufsize,
- stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdout, child_stdin) = (p.stdout, p.stdin)
-
-The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
-except that:
-
-* subprocess.Popen raises an exception if the execution fails
-* the capturestderr argument is replaced with the stderr argument.
-* stdin=PIPE and stdout=PIPE must be specified.
-* popen2 closes all filedescriptors by default, but you have to specify
- close_fds=True with subprocess.Popen.
-"""
-
-import sys
-mswindows = (sys.platform == "win32")
-
-import os
-import types
-import traceback
-import gc
-import signal
-import errno
-
-try:
- set
-except NameError:
- from sets import Set as set
-
-# Exception classes used by this module.
-
-
-class CalledProcessError(Exception):
-
- """This exception is raised when a process run by check_call() or
- check_output() returns a non-zero exit status.
- The exit status will be stored in the returncode attribute;
- check_output() will also store the output in the output attribute.
- """
-
- def __init__(self, returncode, cmd, output=None):
- self.returncode = returncode
- self.cmd = cmd
- self.output = output
-
- def __str__(self):
- return "Command '%s' returned non-zero exit status %d" % (
- self.cmd, self.returncode)
-
-
-if mswindows:
- import threading
- import msvcrt
- import _subprocess
-
- class STARTUPINFO:
- dwFlags = 0
- hStdInput = None
- hStdOutput = None
- hStdError = None
- wShowWindow = 0
-
- class pywintypes:
- error = IOError
-else:
- import select
- _has_poll = hasattr(select, 'poll')
- import fcntl
- import pickle
-
- # When select or poll has indicated that the file is writable,
- # we can write up to _PIPE_BUF bytes without risk of blocking.
- # POSIX defines PIPE_BUF as >= 512.
- _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
-
-
-__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
- "check_output", "CalledProcessError"]
-
-if mswindows:
- from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, \
- STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, \
- STD_ERROR_HANDLE, SW_HIDE, \
- STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW
-
- __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
- "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
- "STD_ERROR_HANDLE", "SW_HIDE",
- "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
-try:
- MAXFD = os.sysconf("SC_OPEN_MAX")
-except:
- MAXFD = 256
-
-_active = []
-
-
-def _cleanup():
- for inst in _active[:]:
- res = inst._internal_poll(_deadstate=sys.maxint)
- if res is not None:
- try:
- _active.remove(inst)
- except ValueError:
- # This can happen if two threads create a new Popen instance.
- # It's harmless that it was already removed, so ignore.
- pass
-
-PIPE = -1
-STDOUT = -2
-
-
-def _eintr_retry_call(func, *args):
- while True:
- try:
- return func(*args)
- except (OSError, IOError), e:
- if e.errno == errno.EINTR:
- continue
- raise
-
-
-def call(*popenargs, **kwargs):
- """Run command with arguments. Wait for command to complete, then
- return the returncode attribute.
-
- The arguments are the same as for the Popen constructor. Example:
-
- retcode = call(["ls", "-l"])
- """
- return Popen(*popenargs, **kwargs).wait()
-
-
-def check_call(*popenargs, **kwargs):
- """Run command with arguments. Wait for command to complete. If
- the exit code was zero then return, otherwise raise
- CalledProcessError. The CalledProcessError object will have the
- return code in the returncode attribute.
-
- The arguments are the same as for the Popen constructor. Example:
-
- check_call(["ls", "-l"])
- """
- retcode = call(*popenargs, **kwargs)
- if retcode:
- cmd = kwargs.get("args")
- if cmd is None:
- cmd = popenargs[0]
- raise CalledProcessError(retcode, cmd)
- return 0
-
-
-def check_output(*popenargs, **kwargs):
- r"""Run command with arguments and return its output as a byte string.
-
- If the exit code was non-zero it raises a CalledProcessError. The
- CalledProcessError object will have the return code in the returncode
- attribute and output in the output attribute.
-
- The arguments are the same as for the Popen constructor. Example:
-
- >>> check_output(["ls", "-l", "/dev/null"])
- 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
-
- The stdout argument is not allowed as it is used internally.
- To capture standard error in the result, use stderr=STDOUT.
-
- >>> check_output(["/bin/sh", "-c",
- ... "ls -l non_existent_file ; exit 0"],
- ... stderr=STDOUT)
- 'ls: non_existent_file: No such file or directory\n'
- """
- if 'stdout' in kwargs:
- raise ValueError('stdout argument not allowed, it will be overridden.')
- process = Popen(stdout=PIPE, *popenargs, **kwargs)
- output, unused_err = process.communicate()
- retcode = process.poll()
- if retcode:
- cmd = kwargs.get("args")
- if cmd is None:
- cmd = popenargs[0]
- raise CalledProcessError(retcode, cmd, output=output)
- return output
-
-
-def list2cmdline(seq):
- """
- Translate a sequence of arguments into a command line
- string, using the same rules as the MS C runtime:
-
- 1) Arguments are delimited by white space, which is either a
- space or a tab.
-
- 2) A string surrounded by double quotation marks is
- interpreted as a single argument, regardless of white space
- contained within. A quoted string can be embedded in an
- argument.
-
- 3) A double quotation mark preceded by a backslash is
- interpreted as a literal double quotation mark.
-
- 4) Backslashes are interpreted literally, unless they
- immediately precede a double quotation mark.
-
- 5) If backslashes immediately precede a double quotation mark,
- every pair of backslashes is interpreted as a literal
- backslash. If the number of backslashes is odd, the last
- backslash escapes the next double quotation mark as
- described in rule 3.
- """
-
- # See
- # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
- # or search http://msdn.microsoft.com for
- # "Parsing C++ Command-Line Arguments"
- result = []
- needquote = False
- for arg in seq:
- bs_buf = []
-
- # Add a space to separate this argument from the others
- if result:
- result.append(' ')
-
- needquote = (" " in arg) or ("\t" in arg) or not arg
- if needquote:
- result.append('"')
-
- for c in arg:
- if c == '\\':
- # Don't know if we need to double yet.
- bs_buf.append(c)
- elif c == '"':
- # Double backslashes.
- result.append('\\' * len(bs_buf) * 2)
- bs_buf = []
- result.append('\\"')
- else:
- # Normal char
- if bs_buf:
- result.extend(bs_buf)
- bs_buf = []
- result.append(c)
-
- # Add remaining backslashes, if any.
- if bs_buf:
- result.extend(bs_buf)
-
- if needquote:
- result.extend(bs_buf)
- result.append('"')
-
- return ''.join(result)
-
-
-class Popen(object):
-
- def __init__(self, args, bufsize=0, executable=None,
- stdin=None, stdout=None, stderr=None,
- preexec_fn=None, close_fds=False, shell=False,
- cwd=None, env=None, universal_newlines=False,
- startupinfo=None, creationflags=0):
- """Create new Popen instance."""
- _cleanup()
-
- self._child_created = False
- if not isinstance(bufsize, (int, long)):
- raise TypeError("bufsize must be an integer")
-
- if mswindows:
- if preexec_fn is not None:
- raise ValueError("preexec_fn is not supported on Windows "
- "platforms")
- if close_fds and (stdin is not None or stdout is not None or
- stderr is not None):
- raise ValueError("close_fds is not supported on Windows "
- "platforms if you redirect "
- "stdin/stdout/stderr")
- else:
- # POSIX
- if startupinfo is not None:
- raise ValueError("startupinfo is only supported on Windows "
- "platforms")
- if creationflags != 0:
- raise ValueError("creationflags is only supported on Windows "
- "platforms")
-
- self.stdin = None
- self.stdout = None
- self.stderr = None
- self.pid = None
- self.returncode = None
- self.universal_newlines = universal_newlines
-
- # Input and output objects. The general principle is like
- # this:
- #
- # Parent Child
- # ------ -----
- # p2cwrite ---stdin---> p2cread
- # c2pread <--stdout--- c2pwrite
- # errread <--stderr--- errwrite
- #
- # On POSIX, the child objects are file descriptors. On
- # Windows, these are Windows file handles. The parent objects
- # are file descriptors on both platforms. The parent objects
- # are None when not using PIPEs. The child objects are None
- # when not redirecting.
-
- (p2cread, p2cwrite,
- c2pread, c2pwrite,
- errread, errwrite) = self._get_handles(stdin, stdout, stderr)
-
- self._execute_child(args, executable, preexec_fn, close_fds,
- cwd, env, universal_newlines,
- startupinfo, creationflags, shell,
- p2cread, p2cwrite,
- c2pread, c2pwrite,
- errread, errwrite)
-
- if mswindows:
- if p2cwrite is not None:
- p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
- if c2pread is not None:
- c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
- if errread is not None:
- errread = msvcrt.open_osfhandle(errread.Detach(), 0)
-
- if p2cwrite is not None:
- self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
- if c2pread is not None:
- if universal_newlines:
- self.stdout = os.fdopen(c2pread, 'rU', bufsize)
- else:
- self.stdout = os.fdopen(c2pread, 'rb', bufsize)
- if errread is not None:
- if universal_newlines:
- self.stderr = os.fdopen(errread, 'rU', bufsize)
- else:
- self.stderr = os.fdopen(errread, 'rb', bufsize)
-
- def _translate_newlines(self, data):
- data = data.replace("\r\n", "\n")
- data = data.replace("\r", "\n")
- return data
-
- def __del__(self, _maxint=sys.maxint, _active=_active):
- # If __init__ hasn't had a chance to execute (e.g. if it
- # was passed an undeclared keyword argument), we don't
- # have a _child_created attribute at all.
- if not getattr(self, '_child_created', False):
- # We didn't get to successfully create a child process.
- return
- # In case the child hasn't been waited on, check if it's done.
- self._internal_poll(_deadstate=_maxint)
- if self.returncode is None and _active is not None:
- # Child is still running, keep us alive until we can wait on it.
- _active.append(self)
-
- def communicate(self, input=None):
- """Interact with process: Send data to stdin. Read data from
- stdout and stderr, until end-of-file is reached. Wait for
- process to terminate. The optional input argument should be a
- string to be sent to the child process, or None, if no data
- should be sent to the child.
-
- communicate() returns a tuple (stdout, stderr)."""
-
- # Optimization: If we are only using one pipe, or no pipe at
- # all, using select() or threads is unnecessary.
- if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
- stdout = None
- stderr = None
- if self.stdin:
- if input:
- try:
- self.stdin.write(input)
- except IOError, e:
- if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
- raise
- self.stdin.close()
- elif self.stdout:
- stdout = _eintr_retry_call(self.stdout.read)
- self.stdout.close()
- elif self.stderr:
- stderr = _eintr_retry_call(self.stderr.read)
- self.stderr.close()
- self.wait()
- return (stdout, stderr)
-
- return self._communicate(input)
-
- def poll(self):
- return self._internal_poll()
-
- if mswindows:
- #
- # Windows methods
- #
- def _get_handles(self, stdin, stdout, stderr):
- """Construct and return tuple with IO objects:
- p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
- """
- if stdin is None and stdout is None and stderr is None:
- return (None, None, None, None, None, None)
-
- p2cread, p2cwrite = None, None
- c2pread, c2pwrite = None, None
- errread, errwrite = None, None
-
- if stdin is None:
- p2cread = _subprocess.GetStdHandle(
- _subprocess.STD_INPUT_HANDLE)
- if p2cread is None:
- p2cread, _ = _subprocess.CreatePipe(None, 0)
- elif stdin == PIPE:
- p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
- elif isinstance(stdin, int):
- p2cread = msvcrt.get_osfhandle(stdin)
- else:
- # Assuming file-like object
- p2cread = msvcrt.get_osfhandle(stdin.fileno())
- p2cread = self._make_inheritable(p2cread)
-
- if stdout is None:
- c2pwrite = _subprocess.GetStdHandle(
- _subprocess.STD_OUTPUT_HANDLE)
- if c2pwrite is None:
- _, c2pwrite = _subprocess.CreatePipe(None, 0)
- elif stdout == PIPE:
- c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
- elif isinstance(stdout, int):
- c2pwrite = msvcrt.get_osfhandle(stdout)
- else:
- # Assuming file-like object
- c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
- c2pwrite = self._make_inheritable(c2pwrite)
-
- if stderr is None:
- errwrite = _subprocess.GetStdHandle(
- _subprocess.STD_ERROR_HANDLE)
- if errwrite is None:
- _, errwrite = _subprocess.CreatePipe(None, 0)
- elif stderr == PIPE:
- errread, errwrite = _subprocess.CreatePipe(None, 0)
- elif stderr == STDOUT:
- errwrite = c2pwrite
- elif isinstance(stderr, int):
- errwrite = msvcrt.get_osfhandle(stderr)
- else:
- # Assuming file-like object
- errwrite = msvcrt.get_osfhandle(stderr.fileno())
- errwrite = self._make_inheritable(errwrite)
-
- return (p2cread, p2cwrite,
- c2pread, c2pwrite,
- errread, errwrite)
-
- def _make_inheritable(self, handle):
- """Return a duplicate of handle, which is inheritable"""
- return _subprocess.DuplicateHandle(
- _subprocess.GetCurrentProcess(),
- handle,
- _subprocess.GetCurrentProcess(),
- 0,
- 1,
- _subprocess.DUPLICATE_SAME_ACCESS
- )
-
- def _find_w9xpopen(self):
- """Find and return absolut path to w9xpopen.exe"""
- w9xpopen = os.path.join(
- os.path.dirname(_subprocess.GetModuleFileName(0)),
- "w9xpopen.exe")
- if not os.path.exists(w9xpopen):
- # Eeek - file-not-found - possibly an embedding
- # situation - see if we can locate it in sys.exec_prefix
- w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
- "w9xpopen.exe")
- if not os.path.exists(w9xpopen):
- raise RuntimeError("Cannot locate w9xpopen.exe, which is "
- "needed for Popen to work with your "
- "shell or platform.")
- return w9xpopen
-
- def _execute_child(self, args, executable, preexec_fn, close_fds,
- cwd, env, universal_newlines,
- startupinfo, creationflags, shell,
- p2cread, p2cwrite,
- c2pread, c2pwrite,
- errread, errwrite):
- """Execute program (MS Windows version)"""
-
- if not isinstance(args, types.StringTypes):
- args = list2cmdline(args)
-
- # Process startup details
- if startupinfo is None:
- startupinfo = STARTUPINFO()
- if None not in (p2cread, c2pwrite, errwrite):
- startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
- startupinfo.hStdInput = p2cread
- startupinfo.hStdOutput = c2pwrite
- startupinfo.hStdError = errwrite
-
- if shell:
- startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
- startupinfo.wShowWindow = _subprocess.SW_HIDE
- comspec = os.environ.get("COMSPEC", "cmd.exe")
- args = '{0} /c "{1}"'.format(comspec, args)
- if (_subprocess.GetVersion() >= 0x80000000 or
- os.path.basename(comspec).lower() == "command.com"):
- # Win9x, or using command.com on NT. We need to
- # use the w9xpopen intermediate program. For more
- # information, see KB Q150956
- # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
- w9xpopen = self._find_w9xpopen()
- args = '"%s" %s' % (w9xpopen, args)
- # Not passing CREATE_NEW_CONSOLE has been known to
- # cause random failures on win9x. Specifically a
- # dialog: "Your program accessed mem currently in
- # use at xxx" and a hopeful warning about the
- # stability of your system. Cost is Ctrl+C wont
- # kill children.
- creationflags |= _subprocess.CREATE_NEW_CONSOLE
-
- # Start the process
- try:
- try:
- hp, ht, pid, tid = _subprocess.CreateProcess(
- executable, args,
- # no special
- # security
- None, None,
- int(not close_fds),
- creationflags,
- env,
- cwd,
- startupinfo)
- except pywintypes.error, e:
- # Translate pywintypes.error to WindowsError, which is
- # a subclass of OSError. FIXME: We should really
- # translate errno using _sys_errlist (or similar), but
- # how can this be done from Python?
- raise WindowsError(*e.args)
- finally:
- # Child is launched. Close the parent's copy of those pipe
- # handles that only the child should have open. You need
- # to make sure that no handles to the write end of the
- # output pipe are maintained in this process or else the
- # pipe will not close when the child process exits and the
- # ReadFile will hang.
- if p2cread is not None:
- p2cread.Close()
- if c2pwrite is not None:
- c2pwrite.Close()
- if errwrite is not None:
- errwrite.Close()
-
- # Retain the process handle, but close the thread handle
- self._child_created = True
- self._handle = hp
- self.pid = pid
- ht.Close()
-
- def _internal_poll(
- self, _deadstate=None,
- _WaitForSingleObject=_subprocess.WaitForSingleObject,
- _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
- _GetExitCodeProcess=_subprocess.GetExitCodeProcess
- ):
- """Check if child process has terminated. Returns returncode
- attribute.
-
- This method is called by __del__, so it can only refer to objects
- in its local scope.
-
- """
- if self.returncode is None:
- if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
- self.returncode = _GetExitCodeProcess(self._handle)
- return self.returncode
-
- def wait(self):
- """Wait for child process to terminate. Returns returncode
- attribute."""
- if self.returncode is None:
- _subprocess.WaitForSingleObject(self._handle,
- _subprocess.INFINITE)
- self.returncode = _subprocess.GetExitCodeProcess(self._handle)
- return self.returncode
-
- def _readerthread(self, fh, buffer):
- buffer.append(fh.read())
-
- def _communicate(self, input):
- stdout = None # Return
- stderr = None # Return
-
- if self.stdout:
- stdout = []
- stdout_thread = threading.Thread(target=self._readerthread,
- args=(self.stdout, stdout))
- stdout_thread.setDaemon(True)
- stdout_thread.start()
- if self.stderr:
- stderr = []
- stderr_thread = threading.Thread(target=self._readerthread,
- args=(self.stderr, stderr))
- stderr_thread.setDaemon(True)
- stderr_thread.start()
-
- if self.stdin:
- if input is not None:
- try:
- self.stdin.write(input)
- except IOError, e:
- if e.errno != errno.EPIPE:
- raise
- self.stdin.close()
-
- if self.stdout:
- stdout_thread.join()
- if self.stderr:
- stderr_thread.join()
-
- # All data exchanged. Translate lists into strings.
- if stdout is not None:
- stdout = stdout[0]
- if stderr is not None:
- stderr = stderr[0]
-
- # Translate newlines, if requested. We cannot let the file
- # object do the translation: It is based on stdio, which is
- # impossible to combine with select (unless forcing no
- # buffering).
- if self.universal_newlines and hasattr(file, 'newlines'):
- if stdout:
- stdout = self._translate_newlines(stdout)
- if stderr:
- stderr = self._translate_newlines(stderr)
-
- self.wait()
- return (stdout, stderr)
-
- def send_signal(self, sig):
- """Send a signal to the process
- """
- if sig == signal.SIGTERM:
- self.terminate()
- elif sig == signal.CTRL_C_EVENT:
- os.kill(self.pid, signal.CTRL_C_EVENT)
- elif sig == signal.CTRL_BREAK_EVENT:
- os.kill(self.pid, signal.CTRL_BREAK_EVENT)
- else:
- raise ValueError("Unsupported signal: {0}".format(sig))
-
- def terminate(self):
- """Terminates the process
- """
- _subprocess.TerminateProcess(self._handle, 1)
-
- kill = terminate
-
- else:
- #
- # POSIX methods
- #
- def _get_handles(self, stdin, stdout, stderr):
- """Construct and return tuple with IO objects:
- p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
- """
- p2cread, p2cwrite = None, None
- c2pread, c2pwrite = None, None
- errread, errwrite = None, None
-
- if stdin is None:
- pass
- elif stdin == PIPE:
- p2cread, p2cwrite = self.pipe_cloexec()
- elif isinstance(stdin, int):
- p2cread = stdin
- else:
- # Assuming file-like object
- p2cread = stdin.fileno()
-
- if stdout is None:
- pass
- elif stdout == PIPE:
- c2pread, c2pwrite = self.pipe_cloexec()
- elif isinstance(stdout, int):
- c2pwrite = stdout
- else:
- # Assuming file-like object
- c2pwrite = stdout.fileno()
-
- if stderr is None:
- pass
- elif stderr == PIPE:
- errread, errwrite = self.pipe_cloexec()
- elif stderr == STDOUT:
- errwrite = c2pwrite
- elif isinstance(stderr, int):
- errwrite = stderr
- else:
- # Assuming file-like object
- errwrite = stderr.fileno()
-
- return (p2cread, p2cwrite,
- c2pread, c2pwrite,
- errread, errwrite)
-
- def _set_cloexec_flag(self, fd, cloexec=True):
- try:
- cloexec_flag = fcntl.FD_CLOEXEC
- except AttributeError:
- cloexec_flag = 1
-
- old = fcntl.fcntl(fd, fcntl.F_GETFD)
- if cloexec:
- fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
- else:
- fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
-
- def pipe_cloexec(self):
- """Create a pipe with FDs set CLOEXEC."""
- # Pipes' FDs are set CLOEXEC by default because we don't want them
- # to be inherited by other subprocesses: the CLOEXEC flag is
- # removed from the child's FDs by _dup2(), between fork() and
- # exec().
- # This is not atomic: we would need the pipe2() syscall for that.
- r, w = os.pipe()
- self._set_cloexec_flag(r)
- self._set_cloexec_flag(w)
- return r, w
-
- def _close_fds(self, but):
- if hasattr(os, 'closerange'):
- os.closerange(3, but)
- os.closerange(but + 1, MAXFD)
- else:
- for i in xrange(3, MAXFD):
- if i == but:
- continue
- try:
- os.close(i)
- except:
- pass
-
- def _execute_child(self, args, executable, preexec_fn, close_fds,
- cwd, env, universal_newlines,
- startupinfo, creationflags, shell,
- p2cread, p2cwrite,
- c2pread, c2pwrite,
- errread, errwrite):
- """Execute program (POSIX version)"""
-
- if isinstance(args, types.StringTypes):
- args = [args]
- else:
- args = list(args)
-
- if shell:
- args = ["/bin/sh", "-c"] + args
- if executable:
- args[0] = executable
-
- if executable is None:
- executable = args[0]
-
- # For transferring possible exec failure from child to parent
- # The first char specifies the exception type: 0 means
- # OSError, 1 means some other error.
- errpipe_read, errpipe_write = self.pipe_cloexec()
- try:
- try:
- gc_was_enabled = gc.isenabled()
- # Disable gc to avoid bug where gc -> file_dealloc ->
- # write to stderr -> hang.
- # http://bugs.python.org/issue1336
- gc.disable()
- try:
- self.pid = os.fork()
- except:
- if gc_was_enabled:
- gc.enable()
- raise
- self._child_created = True
- if self.pid == 0:
- # Child
- try:
- # Close parent's pipe ends
- if p2cwrite is not None:
- os.close(p2cwrite)
- if c2pread is not None:
- os.close(c2pread)
- if errread is not None:
- os.close(errread)
- os.close(errpipe_read)
-
- # When duping fds, if there arises a situation
- # where one of the fds is either 0, 1 or 2, it
- # is possible that it is overwritten (#12607).
- if c2pwrite == 0:
- c2pwrite = os.dup(c2pwrite)
- if errwrite == 0 or errwrite == 1:
- errwrite = os.dup(errwrite)
-
- # Dup fds for child
- def _dup2(a, b):
- # dup2() removes the CLOEXEC flag but
- # we must do it ourselves if dup2()
- # would be a no-op (issue #10806).
- if a == b:
- self._set_cloexec_flag(a, False)
- elif a is not None:
- os.dup2(a, b)
- _dup2(p2cread, 0)
- _dup2(c2pwrite, 1)
- _dup2(errwrite, 2)
-
- # Close pipe fds. Make sure we don't close the
- # same fd more than once, or standard fds.
- closed = set([None])
- for fd in [p2cread, c2pwrite, errwrite]:
- if fd not in closed and fd > 2:
- os.close(fd)
- closed.add(fd)
-
- # Close all other fds, if asked for
- if close_fds:
- self._close_fds(but=errpipe_write)
-
- if cwd is not None:
- os.chdir(cwd)
-
- if preexec_fn:
- preexec_fn()
-
- if env is None:
- os.execvp(executable, args)
- else:
- os.execvpe(executable, args, env)
-
- except:
- exc_type, exc_value, tb = sys.exc_info()
- # Save the traceback and attach it to the exception
- # object
- exc_lines = traceback.format_exception(exc_type,
- exc_value,
- tb)
- exc_value.child_traceback = ''.join(exc_lines)
- os.write(errpipe_write, pickle.dumps(exc_value))
-
- # This exitcode won't be reported to applications,
- # so it really doesn't matter what we return.
- os._exit(255)
-
- # Parent
- if gc_was_enabled:
- gc.enable()
- finally:
- # be sure the FD is closed no matter what
- os.close(errpipe_write)
-
- if p2cread is not None and p2cwrite is not None:
- os.close(p2cread)
- if c2pwrite is not None and c2pread is not None:
- os.close(c2pwrite)
- if errwrite is not None and errread is not None:
- os.close(errwrite)
-
- # Wait for exec to fail or succeed; possibly raising exception
- # Exception limited to 1M
- data = _eintr_retry_call(os.read, errpipe_read, 1048576)
- finally:
- # be sure the FD is closed no matter what
- os.close(errpipe_read)
-
- if data != "":
- try:
- _eintr_retry_call(os.waitpid, self.pid, 0)
- except OSError, e:
- if e.errno != errno.ECHILD:
- raise
- child_exception = pickle.loads(data)
- for fd in (p2cwrite, c2pread, errread):
- if fd is not None:
- os.close(fd)
- raise child_exception
-
- def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
- _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
- _WEXITSTATUS=os.WEXITSTATUS):
- # This method is called (indirectly) by __del__, so it cannot
- # refer to anything outside of its local scope."""
- if _WIFSIGNALED(sts):
- self.returncode = -_WTERMSIG(sts)
- elif _WIFEXITED(sts):
- self.returncode = _WEXITSTATUS(sts)
- else:
- # Should never happen
- raise RuntimeError("Unknown child exit status!")
-
- def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
- _WNOHANG=os.WNOHANG, _os_error=os.error):
- """Check if child process has terminated. Returns returncode
- attribute.
-
- This method is called by __del__, so it cannot reference anything
- outside of the local scope (nor can any methods it calls).
-
- """
- if self.returncode is None:
- try:
- pid, sts = _waitpid(self.pid, _WNOHANG)
- if pid == self.pid:
- self._handle_exitstatus(sts)
- except _os_error:
- if _deadstate is not None:
- self.returncode = _deadstate
- return self.returncode
-
- def wait(self):
- """Wait for child process to terminate. Returns returncode
- attribute."""
- if self.returncode is None:
- try:
- pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
- except OSError, e:
- if e.errno != errno.ECHILD:
- raise
- # This happens if SIGCLD is set to be ignored or waiting
- # for child processes has otherwise been disabled for our
- # process. This child is dead, we can't get the status.
- sts = 0
- self._handle_exitstatus(sts)
- return self.returncode
-
- def _communicate(self, input):
- if self.stdin:
- # Flush stdio buffer. This might block, if the user has
- # been writing to .stdin in an uncontrolled fashion.
- self.stdin.flush()
- if not input:
- self.stdin.close()
-
- if _has_poll:
- stdout, stderr = self._communicate_with_poll(input)
- else:
- stdout, stderr = self._communicate_with_select(input)
-
- # All data exchanged. Translate lists into strings.
- if stdout is not None:
- stdout = ''.join(stdout)
- if stderr is not None:
- stderr = ''.join(stderr)
-
- # Translate newlines, if requested. We cannot let the file
- # object do the translation: It is based on stdio, which is
- # impossible to combine with select (unless forcing no
- # buffering).
- if self.universal_newlines and hasattr(file, 'newlines'):
- if stdout:
- stdout = self._translate_newlines(stdout)
- if stderr:
- stderr = self._translate_newlines(stderr)
-
- self.wait()
- return (stdout, stderr)
-
- def _communicate_with_poll(self, input):
- stdout = None # Return
- stderr = None # Return
- fd2file = {}
- fd2output = {}
-
- poller = select.poll()
-
- def register_and_append(file_obj, eventmask):
- poller.register(file_obj.fileno(), eventmask)
- fd2file[file_obj.fileno()] = file_obj
-
- def close_unregister_and_remove(fd):
- poller.unregister(fd)
- fd2file[fd].close()
- fd2file.pop(fd)
-
- if self.stdin and input:
- register_and_append(self.stdin, select.POLLOUT)
-
- select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
- if self.stdout:
- register_and_append(self.stdout, select_POLLIN_POLLPRI)
- fd2output[self.stdout.fileno()] = stdout = []
- if self.stderr:
- register_and_append(self.stderr, select_POLLIN_POLLPRI)
- fd2output[self.stderr.fileno()] = stderr = []
-
- input_offset = 0
- while fd2file:
- try:
- ready = poller.poll()
- except select.error, e:
- if e.args[0] == errno.EINTR:
- continue
- raise
-
- for fd, mode in ready:
- if mode & select.POLLOUT:
- chunk = input[input_offset: input_offset + _PIPE_BUF]
- try:
- input_offset += os.write(fd, chunk)
- except OSError, e:
- if e.errno == errno.EPIPE:
- close_unregister_and_remove(fd)
- else:
- raise
- else:
- if input_offset >= len(input):
- close_unregister_and_remove(fd)
- elif mode & select_POLLIN_POLLPRI:
- data = os.read(fd, 4096)
- if not data:
- close_unregister_and_remove(fd)
- fd2output[fd].append(data)
- else:
- # Ignore hang up or errors.
- close_unregister_and_remove(fd)
-
- return (stdout, stderr)
-
- def _communicate_with_select(self, input):
- read_set = []
- write_set = []
- stdout = None # Return
- stderr = None # Return
-
- if self.stdin and input:
- write_set.append(self.stdin)
- if self.stdout:
- read_set.append(self.stdout)
- stdout = []
- if self.stderr:
- read_set.append(self.stderr)
- stderr = []
-
- input_offset = 0
- while read_set or write_set:
- try:
- rlist, wlist, xlist = select.select(
- read_set, write_set, [])
- except select.error, e:
- if e.args[0] == errno.EINTR:
- continue
- raise
-
- if self.stdin in wlist:
- chunk = input[input_offset: input_offset + _PIPE_BUF]
- try:
- bytes_written = os.write(self.stdin.fileno(), chunk)
- except OSError, e:
- if e.errno == errno.EPIPE:
- self.stdin.close()
- write_set.remove(self.stdin)
- else:
- raise
- else:
- input_offset += bytes_written
- if input_offset >= len(input):
- self.stdin.close()
- write_set.remove(self.stdin)
-
- if self.stdout in rlist:
- data = os.read(self.stdout.fileno(), 1024)
- if data == "":
- self.stdout.close()
- read_set.remove(self.stdout)
- stdout.append(data)
-
- if self.stderr in rlist:
- data = os.read(self.stderr.fileno(), 1024)
- if data == "":
- self.stderr.close()
- read_set.remove(self.stderr)
- stderr.append(data)
-
- return (stdout, stderr)
-
- def send_signal(self, sig):
- """Send a signal to the process
- """
- os.kill(self.pid, sig)
-
- def terminate(self):
- """Terminate the process with SIGTERM
- """
- self.send_signal(signal.SIGTERM)
-
- def kill(self):
- """Kill the process with SIGKILL
- """
- self.send_signal(signal.SIGKILL)
-
-
-def _demo_posix():
- #
- # Example 1: Simple redirection: Get process list
- #
- plist = Popen(["ps"], stdout=PIPE).communicate()[0]
- print "Process list:"
- print plist
-
- #
- # Example 2: Change uid before executing child
- #
- if os.getuid() == 0:
- p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
- p.wait()
-
- #
- # Example 3: Connecting several subprocesses
- #
- print "Looking for 'hda'..."
- p1 = Popen(["dmesg"], stdout=PIPE)
- p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
- print repr(p2.communicate()[0])
-
- #
- # Example 4: Catch execution error
- #
- print
- print "Trying a weird file..."
- try:
- print Popen(["/this/path/does/not/exist"]).communicate()
- except OSError, e:
- if e.errno == errno.ENOENT:
- print "The file didn't exist. I thought so..."
- print "Child traceback:"
- print e.child_traceback
- else:
- print "Error", e.errno
- else:
- print >>sys.stderr, "Gosh. No error."
-
-
-def _demo_windows():
- #
- # Example 1: Connecting several subprocesses
- #
- print "Looking for 'PROMPT' in set output..."
- p1 = Popen("set", stdout=PIPE, shell=True)
- p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
- print repr(p2.communicate()[0])
-
- #
- # Example 2: Simple execution of program
- #
- print "Executing calc..."
- p = Popen("calc")
- p.wait()
-
-
-if __name__ == "__main__":
- if mswindows:
- _demo_windows()
- else:
- _demo_posix()
diff --git a/cherrypy/_cpconfig.py b/cherrypy/_cpconfig.py
index 00207723..af6c18e2 100644
--- a/cherrypy/_cpconfig.py
+++ b/cherrypy/_cpconfig.py
@@ -46,21 +46,21 @@ To declare global configuration entries, place them in a [global] section.
You may also declare config entries directly on the classes and methods
(page handlers) that make up your CherryPy application via the ``_cp_config``
-attribute. For example::
+attribute, set with the ``cherrypy.config`` decorator. For example::
+ @cherrypy.config(**{'tools.gzip.on': True})
class Demo:
- _cp_config = {'tools.gzip.on': True}
+ @cherrypy.expose
+ @cherrypy.config(**{'request.show_tracebacks': False})
def index(self):
return "Hello world"
- index.exposed = True
- index._cp_config = {'request.show_tracebacks': False}
.. note::
This behavior is only guaranteed for the default dispatcher.
Other dispatchers may have different restrictions on where
- you can attach _cp_config attributes.
+ you can attach config attributes.
Namespaces
@@ -119,12 +119,9 @@ style) context manager.
"""
import cherrypy
-from cherrypy._cpcompat import basestring
+from cherrypy._cpcompat import text_or_bytes
from cherrypy.lib import reprconf
-# Deprecated in CherryPy 3.2--remove in 3.3
-NamespaceSet = reprconf.NamespaceSet
-
def merge(base, other):
"""Merge one app config (from a dict, file, or filename) into another.
@@ -132,67 +129,76 @@ def merge(base, other):
If the given config is a filename, it will be appended to
the list of files to monitor for "autoreload" changes.
"""
- if isinstance(other, basestring):
+ if isinstance(other, text_or_bytes):
cherrypy.engine.autoreload.files.add(other)
# Load other into base
for section, value_map in reprconf.as_dict(other).items():
if not isinstance(value_map, dict):
raise ValueError(
- "Application config must include section headers, but the "
+ 'Application config must include section headers, but the '
"config you tried to merge doesn't have any sections. "
- "Wrap your config in another dict with paths as section "
+ 'Wrap your config in another dict with paths as section '
"headers, for example: {'/': config}.")
base.setdefault(section, {}).update(value_map)
class Config(reprconf.Config):
-
"""The 'global' configuration data for the entire CherryPy process."""
def update(self, config):
"""Update self from a dict, file or filename."""
- if isinstance(config, basestring):
+ if isinstance(config, text_or_bytes):
# Filename
cherrypy.engine.autoreload.files.add(config)
reprconf.Config.update(self, config)
def _apply(self, config):
"""Update self from a dict."""
- if isinstance(config.get("global"), dict):
+ if isinstance(config.get('global'), dict):
if len(config) > 1:
cherrypy.checker.global_config_contained_paths = True
- config = config["global"]
+ config = config['global']
if 'tools.staticdir.dir' in config:
- config['tools.staticdir.section'] = "global"
+ config['tools.staticdir.section'] = 'global'
reprconf.Config._apply(self, config)
- def __call__(self, *args, **kwargs):
+ @staticmethod
+ def __call__(*args, **kwargs):
"""Decorator for page handlers to set _cp_config."""
if args:
raise TypeError(
- "The cherrypy.config decorator does not accept positional "
- "arguments; you must use keyword arguments.")
+ 'The cherrypy.config decorator does not accept positional '
+ 'arguments; you must use keyword arguments.')
def tool_decorator(f):
- if not hasattr(f, "_cp_config"):
- f._cp_config = {}
- for k, v in kwargs.items():
- f._cp_config[k] = v
+ _Vars(f).setdefault('_cp_config', {}).update(kwargs)
return f
return tool_decorator
+class _Vars(object):
+ """Adapter allowing setting a default attribute on a function or class."""
+
+ def __init__(self, target):
+ self.target = target
+
+ def setdefault(self, key, default):
+ if not hasattr(self.target, key):
+ setattr(self.target, key, default)
+ return getattr(self.target, key)
+
+
# Sphinx begin config.environments
Config.environments = environments = {
- "staging": {
+ 'staging': {
'engine.autoreload.on': False,
'checker.on': False,
'tools.log_headers.on': False,
'request.show_tracebacks': False,
'request.show_mismatched_params': False,
},
- "production": {
+ 'production': {
'engine.autoreload.on': False,
'checker.on': False,
'tools.log_headers.on': False,
@@ -200,7 +206,7 @@ Config.environments = environments = {
'request.show_mismatched_params': False,
'log.screen': False,
},
- "embedded": {
+ 'embedded': {
# For use with CherryPy embedded in another deployment stack.
'engine.autoreload.on': False,
'checker.on': False,
@@ -211,7 +217,7 @@ Config.environments = environments = {
'engine.SIGHUP': None,
'engine.SIGTERM': None,
},
- "test_suite": {
+ 'test_suite': {
'engine.autoreload.on': False,
'checker.on': False,
'tools.log_headers.on': False,
@@ -225,11 +231,11 @@ Config.environments = environments = {
def _server_namespace_handler(k, v):
"""Config handler for the "server" namespace."""
- atoms = k.split(".", 1)
+ atoms = k.split('.', 1)
if len(atoms) > 1:
# Special-case config keys of the form 'server.servername.socket_port'
# to configure additional HTTP servers.
- if not hasattr(cherrypy, "servers"):
+ if not hasattr(cherrypy, 'servers'):
cherrypy.servers = {}
servername, k = atoms
@@ -248,45 +254,21 @@ def _server_namespace_handler(k, v):
setattr(cherrypy.servers[servername], k, v)
else:
setattr(cherrypy.server, k, v)
-Config.namespaces["server"] = _server_namespace_handler
+
+
+Config.namespaces['server'] = _server_namespace_handler
def _engine_namespace_handler(k, v):
- """Backward compatibility handler for the "engine" namespace."""
+ """Config handler for the "engine" namespace."""
engine = cherrypy.engine
- deprecated = {
- 'autoreload_on': 'autoreload.on',
- 'autoreload_frequency': 'autoreload.frequency',
- 'autoreload_match': 'autoreload.match',
- 'reload_files': 'autoreload.files',
- 'deadlock_poll_freq': 'timeout_monitor.frequency'
- }
-
- if k in deprecated:
- engine.log(
- 'WARNING: Use of engine.%s is deprecated and will be removed in a '
- 'future version. Use engine.%s instead.' % (k, deprecated[k]))
-
- if k == 'autoreload_on':
- if v:
- engine.autoreload.subscribe()
- else:
- engine.autoreload.unsubscribe()
- elif k == 'autoreload_frequency':
- engine.autoreload.frequency = v
- elif k == 'autoreload_match':
- engine.autoreload.match = v
- elif k == 'reload_files':
- engine.autoreload.files = set(v)
- elif k == 'deadlock_poll_freq':
- engine.timeout_monitor.frequency = v
- elif k == 'SIGHUP':
- engine.listeners['SIGHUP'] = set([v])
+ if k == 'SIGHUP':
+ engine.subscribe('SIGHUP', v)
elif k == 'SIGTERM':
- engine.listeners['SIGTERM'] = set([v])
- elif "." in k:
- plugin, attrname = k.split(".", 1)
+ engine.subscribe('SIGTERM', v)
+ elif '.' in k:
+ plugin, attrname = k.split('.', 1)
plugin = getattr(engine, plugin)
if attrname == 'on':
if v and hasattr(getattr(plugin, 'subscribe', None), '__call__'):
@@ -301,7 +283,9 @@ def _engine_namespace_handler(k, v):
setattr(plugin, attrname, v)
else:
setattr(engine, k, v)
-Config.namespaces["engine"] = _engine_namespace_handler
+
+
+Config.namespaces['engine'] = _engine_namespace_handler
def _tree_namespace_handler(k, v):
@@ -309,9 +293,11 @@ def _tree_namespace_handler(k, v):
if isinstance(v, dict):
for script_name, app in v.items():
cherrypy.tree.graft(app, script_name)
- cherrypy.engine.log("Mounted: %s on %s" %
- (app, script_name or "/"))
+ msg = 'Mounted: %s on %s' % (app, script_name or '/')
+ cherrypy.engine.log(msg)
else:
cherrypy.tree.graft(v, v.script_name)
- cherrypy.engine.log("Mounted: %s on %s" % (v, v.script_name or "/"))
-Config.namespaces["tree"] = _tree_namespace_handler
+ cherrypy.engine.log('Mounted: %s on %s' % (v, v.script_name or '/'))
+
+
+Config.namespaces['tree'] = _tree_namespace_handler
diff --git a/cherrypy/_cpdispatch.py b/cherrypy/_cpdispatch.py
index 2cb03c7e..d7de8733 100644
--- a/cherrypy/_cpdispatch.py
+++ b/cherrypy/_cpdispatch.py
@@ -39,7 +39,7 @@ class PageHandler(object):
args = property(
get_args,
set_args,
- doc="The ordered args should be accessible from post dispatch hooks"
+ doc='The ordered args should be accessible from post dispatch hooks'
)
def get_kwargs(self):
@@ -52,7 +52,7 @@ class PageHandler(object):
kwargs = property(
get_kwargs,
set_kwargs,
- doc="The named kwargs should be accessible from post dispatch hooks"
+ doc='The named kwargs should be accessible from post dispatch hooks'
)
def __call__(self):
@@ -64,7 +64,7 @@ class PageHandler(object):
test_callable_spec(self.callable, self.args, self.kwargs)
except cherrypy.HTTPError:
raise sys.exc_info()[1]
- except:
+ except Exception:
raise x
raise
@@ -102,7 +102,13 @@ def test_callable_spec(callable, callable_args, callable_kwargs):
# the original error
raise
- if args and args[0] == 'self':
+ if args and (
+ # For callable objects, which have a __call__(self) method
+ hasattr(callable, '__call__') or
+ # For normal methods
+ inspect.ismethod(callable)
+ ):
+ # Strip 'self'
args = args[1:]
arg_usage = dict([(arg, 0,) for arg in args])
@@ -153,7 +159,7 @@ def test_callable_spec(callable, callable_args, callable_kwargs):
# arguments it's definitely a 404.
message = None
if show_mismatched_params:
- message = "Missing parameters: %s" % ",".join(missing_args)
+ message = 'Missing parameters: %s' % ','.join(missing_args)
raise cherrypy.HTTPError(404, message=message)
# the extra positional arguments come from the path - 404 Not Found
@@ -175,8 +181,8 @@ def test_callable_spec(callable, callable_args, callable_kwargs):
message = None
if show_mismatched_params:
- message = "Multiple values for parameters: "\
- "%s" % ",".join(multiple_args)
+ message = 'Multiple values for parameters: '\
+ '%s' % ','.join(multiple_args)
raise cherrypy.HTTPError(error, message=message)
if not varkw and varkw_usage > 0:
@@ -186,8 +192,8 @@ def test_callable_spec(callable, callable_args, callable_kwargs):
if extra_qs_params:
message = None
if show_mismatched_params:
- message = "Unexpected query string "\
- "parameters: %s" % ", ".join(extra_qs_params)
+ message = 'Unexpected query string '\
+ 'parameters: %s' % ', '.join(extra_qs_params)
raise cherrypy.HTTPError(404, message=message)
# If there were any extra body parameters, it's a 400 Not Found
@@ -195,18 +201,20 @@ def test_callable_spec(callable, callable_args, callable_kwargs):
if extra_body_params:
message = None
if show_mismatched_params:
- message = "Unexpected body parameters: "\
- "%s" % ", ".join(extra_body_params)
+ message = 'Unexpected body parameters: '\
+ '%s' % ', '.join(extra_body_params)
raise cherrypy.HTTPError(400, message=message)
try:
import inspect
except ImportError:
- test_callable_spec = lambda callable, args, kwargs: None
+ def test_callable_spec(callable, args, kwargs): # noqa: F811
+ return None
else:
getargspec = inspect.getargspec
- # Python 3 requires using getfullargspec if keyword-only arguments are present
+ # Python 3 requires using getfullargspec if
+ # keyword-only arguments are present
if hasattr(inspect, 'getfullargspec'):
def getargspec(callable):
return inspect.getfullargspec(callable)[:4]
@@ -244,14 +252,14 @@ if sys.version_info < (3, 0):
def validate_translator(t):
if not isinstance(t, str) or len(t) != 256:
raise ValueError(
- "The translate argument must be a str of len 256.")
+ 'The translate argument must be a str of len 256.')
else:
punctuation_to_underscores = str.maketrans(
string.punctuation, '_' * len(string.punctuation))
def validate_translator(t):
if not isinstance(t, dict):
- raise ValueError("The translate argument must be a dict.")
+ raise ValueError('The translate argument must be a dict.')
class Dispatcher(object):
@@ -289,7 +297,7 @@ class Dispatcher(object):
if func:
# Decode any leftover %2F in the virtual_path atoms.
- vpath = [x.replace("%2F", "/") for x in vpath]
+ vpath = [x.replace('%2F', '/') for x in vpath]
request.handler = LateParamPageHandler(func, *vpath)
else:
request.handler = cherrypy.NotFound()
@@ -323,10 +331,10 @@ class Dispatcher(object):
fullpath_len = len(fullpath)
segleft = fullpath_len
nodeconf = {}
- if hasattr(root, "_cp_config"):
+ if hasattr(root, '_cp_config'):
nodeconf.update(root._cp_config)
- if "/" in app.config:
- nodeconf.update(app.config["/"])
+ if '/' in app.config:
+ nodeconf.update(app.config['/'])
object_trail = [['root', root, nodeconf, segleft]]
node = root
@@ -361,9 +369,9 @@ class Dispatcher(object):
if segleft > pre_len:
# No path segment was removed. Raise an error.
raise cherrypy.CherryPyException(
- "A vpath segment was added. Custom dispatchers may only "
- + "remove elements. While trying to process "
- + "{0} in {1}".format(name, fullpath)
+ 'A vpath segment was added. Custom dispatchers may only '
+ 'remove elements. While trying to process '
+ '{0} in {1}'.format(name, fullpath)
)
elif segleft == pre_len:
# Assume that the handler used the current path segment, but
@@ -375,7 +383,7 @@ class Dispatcher(object):
if node is not None:
# Get _cp_config attached to this node.
- if hasattr(node, "_cp_config"):
+ if hasattr(node, '_cp_config'):
nodeconf.update(node._cp_config)
# Mix in values from app.config for this path.
@@ -414,16 +422,16 @@ class Dispatcher(object):
continue
# Try a "default" method on the current leaf.
- if hasattr(candidate, "default"):
+ if hasattr(candidate, 'default'):
defhandler = candidate.default
if getattr(defhandler, 'exposed', False):
# Insert any extra _cp_config from the default handler.
- conf = getattr(defhandler, "_cp_config", {})
+ conf = getattr(defhandler, '_cp_config', {})
object_trail.insert(
- i + 1, ["default", defhandler, conf, segleft])
+ i + 1, ['default', defhandler, conf, segleft])
request.config = set_conf()
# See https://github.com/cherrypy/cherrypy/issues/613
- request.is_index = path.endswith("/")
+ request.is_index = path.endswith('/')
return defhandler, fullpath[fullpath_len - segleft:-1]
# Uncomment the next line to restrict positional params to
@@ -470,23 +478,23 @@ class MethodDispatcher(Dispatcher):
if resource:
# Set Allow header
avail = [m for m in dir(resource) if m.isupper()]
- if "GET" in avail and "HEAD" not in avail:
- avail.append("HEAD")
+ if 'GET' in avail and 'HEAD' not in avail:
+ avail.append('HEAD')
avail.sort()
- cherrypy.serving.response.headers['Allow'] = ", ".join(avail)
+ cherrypy.serving.response.headers['Allow'] = ', '.join(avail)
# Find the subhandler
meth = request.method.upper()
func = getattr(resource, meth, None)
- if func is None and meth == "HEAD":
- func = getattr(resource, "GET", None)
+ if func is None and meth == 'HEAD':
+ func = getattr(resource, 'GET', None)
if func:
# Grab any _cp_config on the subhandler.
- if hasattr(func, "_cp_config"):
+ if hasattr(func, '_cp_config'):
request.config.update(func._cp_config)
# Decode any leftover %2F in the virtual_path atoms.
- vpath = [x.replace("%2F", "/") for x in vpath]
+ vpath = [x.replace('%2F', '/') for x in vpath]
request.handler = LateParamPageHandler(func, *vpath)
else:
request.handler = cherrypy.HTTPError(405)
@@ -554,28 +562,28 @@ class RoutesDispatcher(object):
# Get config for the root object/path.
request.config = base = cherrypy.config.copy()
- curpath = ""
+ curpath = ''
def merge(nodeconf):
if 'tools.staticdir.dir' in nodeconf:
- nodeconf['tools.staticdir.section'] = curpath or "/"
+ nodeconf['tools.staticdir.section'] = curpath or '/'
base.update(nodeconf)
app = request.app
root = app.root
- if hasattr(root, "_cp_config"):
+ if hasattr(root, '_cp_config'):
merge(root._cp_config)
- if "/" in app.config:
- merge(app.config["/"])
+ if '/' in app.config:
+ merge(app.config['/'])
# Mix in values from app.config.
- atoms = [x for x in path_info.split("/") if x]
+ atoms = [x for x in path_info.split('/') if x]
if atoms:
last = atoms.pop()
else:
last = None
for atom in atoms:
- curpath = "/".join((curpath, atom))
+ curpath = '/'.join((curpath, atom))
if curpath in app.config:
merge(app.config[curpath])
@@ -587,14 +595,14 @@ class RoutesDispatcher(object):
if isinstance(controller, classtype):
controller = controller()
# Get config from the controller.
- if hasattr(controller, "_cp_config"):
+ if hasattr(controller, '_cp_config'):
merge(controller._cp_config)
action = result.get('action')
if action is not None:
handler = getattr(controller, action, None)
# Get config from the handler
- if hasattr(handler, "_cp_config"):
+ if hasattr(handler, '_cp_config'):
merge(handler._cp_config)
else:
handler = controller
@@ -602,7 +610,7 @@ class RoutesDispatcher(object):
# Do the last path atom here so it can
# override the controller's _cp_config.
if last:
- curpath = "/".join((curpath, last))
+ curpath = '/'.join((curpath, last))
if curpath in app.config:
merge(app.config[curpath])
@@ -666,9 +674,9 @@ def VirtualHost(next_dispatcher=Dispatcher(), use_x_forwarded_host=True,
domain = header('Host', '')
if use_x_forwarded_host:
- domain = header("X-Forwarded-Host", domain)
+ domain = header('X-Forwarded-Host', domain)
- prefix = domains.get(domain, "")
+ prefix = domains.get(domain, '')
if prefix:
path_info = httputil.urljoin(prefix, path_info)
diff --git a/cherrypy/_cperror.py b/cherrypy/_cperror.py
index dffb86f6..ab669552 100644
--- a/cherrypy/_cperror.py
+++ b/cherrypy/_cperror.py
@@ -29,8 +29,9 @@ user:
300 Multiple Choices Confirm with the user
301 Moved Permanently Confirm with the user
302 Found (Object moved temporarily) Confirm with the user
-303 See Other GET the new URI--no confirmation
-304 Not modified (for conditional GET only--POST should not raise this error)
+303 See Other GET the new URI; no confirmation
+304 Not modified for conditional GET only;
+ POST should not raise this error
305 Use Proxy Confirm with the user
307 Temporary Redirect Confirm with the user
===== ================================= ===========
@@ -58,7 +59,8 @@ The 'error_page' config namespace can be used to provide custom HTML output for
expected responses (like 404 Not Found). Supply a filename from which the
output will be read. The contents will be interpolated with the values
%(status)s, %(message)s, %(traceback)s, and %(version)s using plain old Python
-`string formatting <http://docs.python.org/2/library/stdtypes.html#string-formatting-operations>`_.
+`string formatting
+<http://docs.python.org/2/library/stdtypes.html#string-formatting-operations>`_.
::
@@ -100,26 +102,34 @@ send an e-mail containing the error::
def handle_error():
cherrypy.response.status = 500
cherrypy.response.body = [
- "<html><body>Sorry, an error occured</body></html>"
+ "<html><body>Sorry, an error occurred</body></html>"
]
sendMail('error@domain.com',
'Error in your web app',
_cperror.format_exc())
+ @cherrypy.config(**{'request.error_response': handle_error})
class Root:
- _cp_config = {'request.error_response': handle_error}
-
+ pass
Note that you have to explicitly set
:attr:`response.body <cherrypy._cprequest.Response.body>`
and not simply return an error message as a result.
"""
-from cgi import escape as _escape
+import contextlib
from sys import exc_info as _exc_info
from traceback import format_exception as _format_exception
-from cherrypy._cpcompat import basestring, bytestr, iteritems, ntob, always_bytes
-from cherrypy._cpcompat import tonative, urljoin as _urljoin
+from xml.sax import saxutils
+
+import six
+from six.moves import urllib
+
+import cherrypy
+from cherrypy._cpcompat import escape_html
+from cherrypy._cpcompat import text_or_bytes, ntob
+from cherrypy._cpcompat import tonative
+from cherrypy._helper import classproperty
from cherrypy.lib import httputil as _httputil
@@ -129,12 +139,6 @@ class CherryPyException(Exception):
pass
-class TimeoutError(CherryPyException):
-
- """Exception raised when Response.timed_out is detected."""
- pass
-
-
class InternalRedirect(CherryPyException):
"""Exception raised to switch to the handler for a different URL.
@@ -145,20 +149,19 @@ class InternalRedirect(CherryPyException):
URL.
"""
- def __init__(self, path, query_string=""):
- import cherrypy
+ def __init__(self, path, query_string=''):
self.request = cherrypy.serving.request
self.query_string = query_string
- if "?" in path:
+ if '?' in path:
# Separate any params included in the path
- path, self.query_string = path.split("?", 1)
+ path, self.query_string = path.split('?', 1)
# Note that urljoin will "do the right thing" whether url is:
# 1. a URL relative to root (e.g. "/dummy")
# 2. a URL relative to the current path
# Note that any query string will be discarded.
- path = _urljoin(self.request.path_info, path)
+ path = urllib.parse.urljoin(self.request.path_info, path)
# Set a 'path' member attribute so that code which traps this
# error can have access to it.
@@ -193,9 +196,6 @@ class HTTPRedirect(CherryPyException):
See :ref:`redirectingpost` for additional caveats.
"""
- status = None
- """The integer HTTP status code to emit."""
-
urls = None
"""The list of URL's to emit."""
@@ -203,10 +203,7 @@ class HTTPRedirect(CherryPyException):
"""The encoding when passed urls are not native strings"""
def __init__(self, urls, status=None, encoding=None):
- import cherrypy
- request = cherrypy.serving.request
-
- if isinstance(urls, basestring):
+ if isinstance(urls, text_or_bytes):
urls = [urls]
abs_urls = []
@@ -218,26 +215,37 @@ class HTTPRedirect(CherryPyException):
# 2. a URL relative to root (e.g. "/dummy")
# 3. a URL relative to the current path
# Note that any query string in cherrypy.request is discarded.
- url = _urljoin(cherrypy.url(), url)
+ url = urllib.parse.urljoin(cherrypy.url(), url)
abs_urls.append(url)
self.urls = abs_urls
- # RFC 2616 indicates a 301 response code fits our goal; however,
- # browser support for 301 is quite messy. Do 302/303 instead. See
- # http://www.alanflavell.org.uk/www/post-redirect.html
- if status is None:
- if request.protocol >= (1, 1):
- status = 303
- else:
- status = 302
- else:
- status = int(status)
- if status < 300 or status > 399:
- raise ValueError("status must be between 300 and 399.")
+ status = (
+ int(status)
+ if status is not None
+ else self.default_status
+ )
+ if not 300 <= status <= 399:
+ raise ValueError('status must be between 300 and 399.')
- self.status = status
CherryPyException.__init__(self, abs_urls, status)
+ @classproperty
+ def default_status(cls):
+ """
+ The default redirect status for the request.
+
+ RFC 2616 indicates a 301 response code fits our goal; however,
+ browser support for 301 is quite messy. Use 302/303 instead. See
+ http://www.alanflavell.org.uk/www/post-redirect.html
+ """
+ return 303 if cherrypy.serving.request.protocol >= (1, 1) else 302
+
+ @property
+ def status(self):
+ """The integer HTTP status code to emit."""
+ _, status = self.args[:2]
+ return status
+
def set_response(self):
"""Modify cherrypy.response status, headers, and body to represent
self.
@@ -245,12 +253,11 @@ class HTTPRedirect(CherryPyException):
CherryPy uses this internally, but you can also use it to create an
HTTPRedirect object and set its output without *raising* the exception.
"""
- import cherrypy
response = cherrypy.serving.response
response.status = status = self.status
if status in (300, 301, 302, 303, 307):
- response.headers['Content-Type'] = "text/html;charset=utf-8"
+ response.headers['Content-Type'] = 'text/html;charset=utf-8'
# "The ... URI SHOULD be given by the Location field
# in the response."
response.headers['Location'] = self.urls[0]
@@ -259,16 +266,18 @@ class HTTPRedirect(CherryPyException):
# SHOULD contain a short hypertext note with a hyperlink to the
# new URI(s)."
msg = {
- 300: "This resource can be found at ",
- 301: "This resource has permanently moved to ",
- 302: "This resource resides temporarily at ",
- 303: "This resource can be found at ",
- 307: "This resource has moved temporarily to ",
+ 300: 'This resource can be found at ',
+ 301: 'This resource has permanently moved to ',
+ 302: 'This resource resides temporarily at ',
+ 303: 'This resource can be found at ',
+ 307: 'This resource has moved temporarily to ',
}[status]
msg += '<a href=%s>%s</a>.'
- from xml.sax import saxutils
- msgs = [msg % (saxutils.quoteattr(u), u) for u in self.urls]
- response.body = always_bytes("<br />\n".join(msgs), 'utf-8')
+ msgs = [
+ msg % (saxutils.quoteattr(u), escape_html(u))
+ for u in self.urls
+ ]
+ response.body = always_bytes('<br />\n'.join(msgs), 'utf-8')
# Previous code may have set C-L, so we have to reset it
# (allow finalize to set it).
response.headers.pop('Content-Length', None)
@@ -293,12 +302,12 @@ class HTTPRedirect(CherryPyException):
elif status == 305:
# Use Proxy.
# self.urls[0] should be the URI of the proxy.
- response.headers['Location'] = self.urls[0]
+ response.headers['Location'] = ntob(self.urls[0], 'utf-8')
response.body = None
# Previous code may have set C-L, so we have to reset it.
response.headers.pop('Content-Length', None)
else:
- raise ValueError("The %s status code is unknown." % status)
+ raise ValueError('The %s status code is unknown.' % status)
def __call__(self):
"""Use this exception as a request.handler (raise self)."""
@@ -307,16 +316,14 @@ class HTTPRedirect(CherryPyException):
def clean_headers(status):
"""Remove any headers which should not apply to an error response."""
- import cherrypy
-
response = cherrypy.serving.response
# Remove headers which applied to the original content,
# but do not apply to the error page.
respheaders = response.headers
- for key in ["Accept-Ranges", "Age", "ETag", "Location", "Retry-After",
- "Vary", "Content-Encoding", "Content-Length", "Expires",
- "Content-Location", "Content-MD5", "Last-Modified"]:
+ for key in ['Accept-Ranges', 'Age', 'ETag', 'Location', 'Retry-After',
+ 'Vary', 'Content-Encoding', 'Content-Length', 'Expires',
+ 'Content-Location', 'Content-MD5', 'Last-Modified']:
if key in respheaders:
del respheaders[key]
@@ -327,8 +334,8 @@ def clean_headers(status):
# specifies the current length of the selected resource.
# A response with status code 206 (Partial Content) MUST NOT
# include a Content-Range field with a byte-range- resp-spec of "*".
- if "Content-Range" in respheaders:
- del respheaders["Content-Range"]
+ if 'Content-Range' in respheaders:
+ del respheaders['Content-Range']
class HTTPError(CherryPyException):
@@ -368,7 +375,7 @@ class HTTPError(CherryPyException):
raise self.__class__(500, _exc_info()[1].args[0])
if self.code < 400 or self.code > 599:
- raise ValueError("status must be between 400 and 599.")
+ raise ValueError('status must be between 400 and 599.')
# See http://www.python.org/dev/peps/pep-0352/
# self.message = message
@@ -382,8 +389,6 @@ class HTTPError(CherryPyException):
CherryPy uses this internally, but you can also use it to create an
HTTPError object and set its output without *raising* the exception.
"""
- import cherrypy
-
response = cherrypy.serving.response
clean_headers(self.code)
@@ -410,6 +415,15 @@ class HTTPError(CherryPyException):
"""Use this exception as a request.handler (raise self)."""
raise self
+ @classmethod
+ @contextlib.contextmanager
+ def handle(cls, exception, status=500, message=''):
+ """Translate exception into an HTTPError."""
+ try:
+ yield
+ except exception as exc:
+ raise cls(status, message or str(exc))
+
class NotFound(HTTPError):
@@ -421,7 +435,6 @@ class NotFound(HTTPError):
def __init__(self, path=None):
if path is None:
- import cherrypy
request = cherrypy.serving.request
path = request.script_name + request.path_info
self.args = (path,)
@@ -467,8 +480,6 @@ def get_error_page(status, **kwargs):
status should be an int or a str.
kwargs will be interpolated into the page template.
"""
- import cherrypy
-
try:
code, reason, message = _httputil.valid_status(status)
except ValueError:
@@ -477,7 +488,7 @@ def get_error_page(status, **kwargs):
# We can't use setdefault here, because some
# callers send None for kwarg values.
if kwargs.get('status') is None:
- kwargs['status'] = "%s %s" % (code, reason)
+ kwargs['status'] = '%s %s' % (code, reason)
if kwargs.get('message') is None:
kwargs['message'] = message
if kwargs.get('traceback') is None:
@@ -485,11 +496,11 @@ def get_error_page(status, **kwargs):
if kwargs.get('version') is None:
kwargs['version'] = cherrypy.__version__
- for k, v in iteritems(kwargs):
+ for k, v in six.iteritems(kwargs):
if v is None:
- kwargs[k] = ""
+ kwargs[k] = ''
else:
- kwargs[k] = _escape(kwargs[k])
+ kwargs[k] = escape_html(kwargs[k])
# Use a custom template or callable for the error page?
pages = cherrypy.serving.request.error_page
@@ -509,33 +520,33 @@ def get_error_page(status, **kwargs):
if cherrypy.lib.is_iterator(result):
from cherrypy.lib.encoding import UTF8StreamEncoder
return UTF8StreamEncoder(result)
- elif isinstance(result, cherrypy._cpcompat.unicodestr):
+ elif isinstance(result, six.text_type):
return result.encode('utf-8')
else:
- if not isinstance(result, cherrypy._cpcompat.bytestr):
- raise ValueError('error page function did not '
- 'return a bytestring, unicodestring or an '
+ if not isinstance(result, bytes):
+ raise ValueError(
+ 'error page function did not '
+ 'return a bytestring, six.text_type or an '
'iterator - returned object of type %s.'
% (type(result).__name__))
return result
else:
# Load the template from this path.
template = tonative(open(error_page, 'rb').read())
- except:
+ except Exception:
e = _format_exception(*_exc_info())[-1]
m = kwargs['message']
if m:
- m += "<br />"
- m += "In addition, the custom error page failed:\n<br />%s" % e
+ m += '<br />'
+ m += 'In addition, the custom error page failed:\n<br />%s' % e
kwargs['message'] = m
response = cherrypy.serving.response
- response.headers['Content-Type'] = "text/html;charset=utf-8"
+ response.headers['Content-Type'] = 'text/html;charset=utf-8'
result = template % kwargs
return result.encode('utf-8')
-
_ie_friendly_error_sizes = {
400: 512, 403: 256, 404: 512, 405: 256,
406: 512, 408: 512, 409: 512, 410: 256,
@@ -544,7 +555,6 @@ _ie_friendly_error_sizes = {
def _be_ie_unfriendly(status):
- import cherrypy
response = cherrypy.serving.response
# For some statuses, Internet Explorer 5+ shows "friendly error
@@ -558,11 +568,11 @@ def _be_ie_unfriendly(status):
# Since we are issuing an HTTP error status, we assume that
# the entity is short, and we should just collapse it.
content = response.collapse_body()
- l = len(content)
- if l and l < s:
+ content_length = len(content)
+ if content_length and content_length < s:
# IN ADDITION: the response must be written to IE
# in one chunk or it will still get replaced! Bah.
- content = content + (ntob(" ") * (s - l))
+ content = content + (ntob(' ') * (s - content_length))
response.body = content
response.headers['Content-Length'] = str(len(content))
@@ -573,9 +583,9 @@ def format_exc(exc=None):
if exc is None:
exc = _exc_info()
if exc == (None, None, None):
- return ""
+ return ''
import traceback
- return "".join(traceback.format_exception(*exc))
+ return ''.join(traceback.format_exception(*exc))
finally:
del exc
@@ -597,13 +607,13 @@ def bare_error(extrabody=None):
# it cannot be allowed to fail. Therefore, don't add to it!
# In particular, don't call any other CP functions.
- body = ntob("Unrecoverable error in the server.")
+ body = ntob('Unrecoverable error in the server.')
if extrabody is not None:
- if not isinstance(extrabody, bytestr):
+ if not isinstance(extrabody, bytes):
extrabody = extrabody.encode('utf-8')
- body += ntob("\n") + extrabody
+ body += ntob('\n') + extrabody
- return (ntob("500 Internal Server Error"),
+ return (ntob('500 Internal Server Error'),
[(ntob('Content-Type'), ntob('text/plain')),
(ntob('Content-Length'), ntob(str(len(body)), 'ISO-8859-1'))],
[body])
diff --git a/cherrypy/_cplogging.py b/cherrypy/_cplogging.py
index 19d1d91e..982d6f6e 100644
--- a/cherrypy/_cplogging.py
+++ b/cherrypy/_cplogging.py
@@ -59,7 +59,8 @@ tracebacks, if enabled).
If you are logging the access log and error log to the same source, then there
is a possibility that a specially crafted error message may replicate an access
log message as described in CWE-117. In this case it is the application
-developer's responsibility to manually escape data before using CherryPy's log()
+developer's responsibility to manually escape data before
+using CherryPy's log()
functionality, or they may create an application that is vulnerable to CWE-117.
This would be achieved by using a custom handler escape any special characters,
and attached as described below.
@@ -109,15 +110,19 @@ the "log.error_file" config entry, for example).
import datetime
import logging
-# Silence the no-handlers "warning" (stderr write!) in stdlib logging
-logging.Logger.manager.emittedNoHandlerWarning = 1
-logfmt = logging.Formatter("%(message)s")
import os
import sys
+import six
+
import cherrypy
from cherrypy import _cperror
-from cherrypy._cpcompat import ntob, py3k
+from cherrypy._cpcompat import ntob
+
+
+# Silence the no-handlers "warning" (stderr write!) in stdlib logging
+logging.Logger.manager.emittedNoHandlerWarning = 1
+logfmt = logging.Formatter('%(message)s')
class NullHandler(logging.Handler):
@@ -151,12 +156,11 @@ class LogManager(object):
access_log = None
"""The actual :class:`logging.Logger` instance for access messages."""
- if py3k:
- access_log_format = \
- '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"'
- else:
- access_log_format = \
- '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
+ access_log_format = (
+ '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"'
+ if six.PY3 else
+ '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
+ )
logger_root = None
"""The "top-level" logger name.
@@ -169,17 +173,17 @@ class LogManager(object):
cherrypy.access.<appid>
"""
- def __init__(self, appid=None, logger_root="cherrypy"):
+ def __init__(self, appid=None, logger_root='cherrypy'):
self.logger_root = logger_root
self.appid = appid
if appid is None:
- self.error_log = logging.getLogger("%s.error" % logger_root)
- self.access_log = logging.getLogger("%s.access" % logger_root)
+ self.error_log = logging.getLogger('%s.error' % logger_root)
+ self.access_log = logging.getLogger('%s.access' % logger_root)
else:
self.error_log = logging.getLogger(
- "%s.error.%s" % (logger_root, appid))
+ '%s.error.%s' % (logger_root, appid))
self.access_log = logging.getLogger(
- "%s.access.%s" % (logger_root, appid))
+ '%s.access.%s' % (logger_root, appid))
self.error_log.setLevel(logging.INFO)
self.access_log.setLevel(logging.INFO)
@@ -213,7 +217,11 @@ class LogManager(object):
if traceback:
exc_info = _cperror._exc_info()
- self.error_log.log(severity, ' '.join((self.time(), context, msg)), exc_info=exc_info)
+ self.error_log.log(
+ severity,
+ ' '.join((self.time(), context, msg)),
+ exc_info=exc_info,
+ )
def __call__(self, *args, **kwargs):
"""An alias for ``error``."""
@@ -223,7 +231,8 @@ class LogManager(object):
"""Write to the access log (in Apache/NCSA Combined Log format).
See the
- `apache documentation <http://httpd.apache.org/docs/current/logs.html#combined>`_
+ `apache documentation
+ <http://httpd.apache.org/docs/current/logs.html#combined>`_
for format details.
CherryPy calls this automatically for you. Note there are no arguments;
@@ -243,24 +252,26 @@ class LogManager(object):
outheaders = response.headers
inheaders = request.headers
if response.output_status is None:
- status = "-"
+ status = '-'
else:
- status = response.output_status.split(ntob(" "), 1)[0]
- if py3k:
+ status = response.output_status.split(ntob(' '), 1)[0]
+ if six.PY3:
status = status.decode('ISO-8859-1')
atoms = {'h': remote.name or remote.ip,
'l': '-',
- 'u': getattr(request, "login", None) or "-",
+ 'u': getattr(request, 'login', None) or '-',
't': self.time(),
'r': request.request_line,
's': status,
- 'b': dict.get(outheaders, 'Content-Length', '') or "-",
+ 'b': dict.get(outheaders, 'Content-Length', '') or '-',
'f': dict.get(inheaders, 'Referer', ''),
'a': dict.get(inheaders, 'User-Agent', ''),
'o': dict.get(inheaders, 'Host', '-'),
+ 'i': request.unique_id,
+ 'z': LazyRfc3339UtcTime(),
}
- if py3k:
+ if six.PY3:
for k, v in atoms.items():
if not isinstance(v, str):
v = str(v)
@@ -280,11 +291,11 @@ class LogManager(object):
try:
self.access_log.log(
logging.INFO, self.access_log_format.format(**atoms))
- except:
+ except Exception:
self(traceback=True)
else:
for k, v in atoms.items():
- if isinstance(v, unicode):
+ if isinstance(v, six.text_type):
v = v.encode('utf8')
elif not isinstance(v, str):
v = str(v)
@@ -297,7 +308,7 @@ class LogManager(object):
try:
self.access_log.log(
logging.INFO, self.access_log_format % atoms)
- except:
+ except Exception:
self(traceback=True)
def time(self):
@@ -311,26 +322,26 @@ class LogManager(object):
def _get_builtin_handler(self, log, key):
for h in log.handlers:
- if getattr(h, "_cpbuiltin", None) == key:
+ if getattr(h, '_cpbuiltin', None) == key:
return h
# ------------------------- Screen handlers ------------------------- #
def _set_screen_handler(self, log, enable, stream=None):
- h = self._get_builtin_handler(log, "screen")
+ h = self._get_builtin_handler(log, 'screen')
if enable:
if not h:
if stream is None:
stream = sys.stderr
h = logging.StreamHandler(stream)
h.setFormatter(logfmt)
- h._cpbuiltin = "screen"
+ h._cpbuiltin = 'screen'
log.addHandler(h)
elif h:
log.handlers.remove(h)
def _get_screen(self):
h = self._get_builtin_handler
- has_h = h(self.error_log, "screen") or h(self.access_log, "screen")
+ has_h = h(self.error_log, 'screen') or h(self.access_log, 'screen')
return bool(has_h)
def _set_screen(self, newvalue):
@@ -348,11 +359,11 @@ class LogManager(object):
def _add_builtin_file_handler(self, log, fname):
h = logging.FileHandler(fname)
h.setFormatter(logfmt)
- h._cpbuiltin = "file"
+ h._cpbuiltin = 'file'
log.addHandler(h)
def _set_file_handler(self, log, filename):
- h = self._get_builtin_handler(log, "file")
+ h = self._get_builtin_handler(log, 'file')
if filename:
if h:
if h.baseFilename != os.path.abspath(filename):
@@ -367,7 +378,7 @@ class LogManager(object):
log.handlers.remove(h)
def _get_error_file(self):
- h = self._get_builtin_handler(self.error_log, "file")
+ h = self._get_builtin_handler(self.error_log, 'file')
if h:
return h.baseFilename
return ''
@@ -382,7 +393,7 @@ class LogManager(object):
""")
def _get_access_file(self):
- h = self._get_builtin_handler(self.access_log, "file")
+ h = self._get_builtin_handler(self.access_log, 'file')
if h:
return h.baseFilename
return ''
@@ -399,18 +410,18 @@ class LogManager(object):
# ------------------------- WSGI handlers ------------------------- #
def _set_wsgi_handler(self, log, enable):
- h = self._get_builtin_handler(log, "wsgi")
+ h = self._get_builtin_handler(log, 'wsgi')
if enable:
if not h:
h = WSGIErrorHandler()
h.setFormatter(logfmt)
- h._cpbuiltin = "wsgi"
+ h._cpbuiltin = 'wsgi'
log.addHandler(h)
elif h:
log.handlers.remove(h)
def _get_wsgi(self):
- return bool(self._get_builtin_handler(self.error_log, "wsgi"))
+ return bool(self._get_builtin_handler(self.error_log, 'wsgi'))
def _set_wsgi(self, newvalue):
self._set_wsgi_handler(self.error_log, newvalue)
@@ -446,16 +457,23 @@ class WSGIErrorHandler(logging.Handler):
else:
try:
msg = self.format(record)
- fs = "%s\n"
+ fs = '%s\n'
import types
# if no unicode support...
- if not hasattr(types, "UnicodeType"):
+ if not hasattr(types, 'UnicodeType'):
stream.write(fs % msg)
else:
try:
stream.write(fs % msg)
except UnicodeError:
- stream.write(fs % msg.encode("UTF-8"))
+ stream.write(fs % msg.encode('UTF-8'))
self.flush()
- except:
+ except Exception:
self.handleError(record)
+
+
+class LazyRfc3339UtcTime(object):
+ def __str__(self):
+ """Return now() in RFC3339 UTC Format."""
+ now = datetime.datetime.now()
+ return now.isoformat('T') + 'Z'
diff --git a/cherrypy/_cpmodpy.py b/cherrypy/_cpmodpy.py
index 02154d69..559aa79a 100644
--- a/cherrypy/_cpmodpy.py
+++ b/cherrypy/_cpmodpy.py
@@ -55,11 +55,16 @@ resides in the global site-package this won't be needed.
Then restart apache2 and access http://127.0.0.1:8080
"""
+import io
import logging
+import os
+import re
import sys
+import six
+
import cherrypy
-from cherrypy._cpcompat import BytesIO, copyitems, ntob
+from cherrypy._cpcompat import ntob, text_or_bytes
from cherrypy._cperror import format_exc, bare_error
from cherrypy.lib import httputil
@@ -85,18 +90,19 @@ def setup(req):
func()
cherrypy.config.update({'log.screen': False,
- "tools.ignore_headers.on": True,
- "tools.ignore_headers.headers": ['Range'],
+ 'tools.ignore_headers.on': True,
+ 'tools.ignore_headers.headers': ['Range'],
})
engine = cherrypy.engine
- if hasattr(engine, "signal_handler"):
+ if hasattr(engine, 'signal_handler'):
engine.signal_handler.unsubscribe()
- if hasattr(engine, "console_control_handler"):
+ if hasattr(engine, 'console_control_handler'):
engine.console_control_handler.unsubscribe()
engine.autoreload.unsubscribe()
cherrypy.server.unsubscribe()
+ @engine.subscribe('log')
def _log(msg, level):
newlevel = apache.APLOG_ERR
if logging.DEBUG >= level:
@@ -109,7 +115,6 @@ def setup(req):
# http://www.modpython.org/pipermail/mod_python/2003-October/014291.html
# Also, "When server is not specified...LogLevel does not apply..."
apache.log_error(msg, newlevel, req.server)
- engine.subscribe('log', _log)
engine.start()
@@ -146,10 +151,10 @@ def handler(req):
# Obtain a Request object from CherryPy
local = req.connection.local_addr
local = httputil.Host(
- local[0], local[1], req.connection.local_host or "")
+ local[0], local[1], req.connection.local_host or '')
remote = req.connection.remote_addr
remote = httputil.Host(
- remote[0], remote[1], req.connection.remote_host or "")
+ remote[0], remote[1], req.connection.remote_host or '')
scheme = req.parsed_uri[0] or 'http'
req.get_basic_auth_pw()
@@ -162,7 +167,9 @@ def handler(req):
except AttributeError:
bad_value = ("You must provide a PythonOption '%s', "
"either 'on' or 'off', when running a version "
- "of mod_python < 3.1")
+ 'of mod_python < 3.1')
+
+ options = req.get_options()
threaded = options.get('multithread', '').lower()
if threaded == 'on':
@@ -170,7 +177,7 @@ def handler(req):
elif threaded == 'off':
threaded = False
else:
- raise ValueError(bad_value % "multithread")
+ raise ValueError(bad_value % 'multithread')
forked = options.get('multiprocess', '').lower()
if forked == 'on':
@@ -178,18 +185,18 @@ def handler(req):
elif forked == 'off':
forked = False
else:
- raise ValueError(bad_value % "multiprocess")
+ raise ValueError(bad_value % 'multiprocess')
- sn = cherrypy.tree.script_name(req.uri or "/")
+ sn = cherrypy.tree.script_name(req.uri or '/')
if sn is None:
send_response(req, '404 Not Found', [], '')
else:
app = cherrypy.tree.apps[sn]
method = req.method
path = req.uri
- qs = req.args or ""
+ qs = req.args or ''
reqproto = req.protocol
- headers = copyitems(req.headers_in)
+ headers = list(six.iteritems(req.headers_in))
rfile = _ReadOnlyRequest(req)
prev = None
@@ -197,7 +204,7 @@ def handler(req):
redirections = []
while True:
request, response = app.get_serving(local, remote, scheme,
- "HTTP/1.1")
+ 'HTTP/1.1')
request.login = req.user
request.multithread = bool(threaded)
request.multiprocess = bool(forked)
@@ -216,27 +223,27 @@ def handler(req):
if not recursive:
if ir.path in redirections:
raise RuntimeError(
- "InternalRedirector visited the same URL "
- "twice: %r" % ir.path)
+ 'InternalRedirector visited the same URL '
+ 'twice: %r' % ir.path)
else:
# Add the *previous* path_info + qs to
# redirections.
if qs:
- qs = "?" + qs
+ qs = '?' + qs
redirections.append(sn + path + qs)
# Munge environment and try again.
- method = "GET"
+ method = 'GET'
path = ir.path
qs = ir.query_string
- rfile = BytesIO()
+ rfile = io.BytesIO()
send_response(
req, response.output_status, response.header_list,
response.body, response.stream)
finally:
app.release_serving()
- except:
+ except Exception:
tb = format_exc()
cherrypy.log(tb, 'MOD_PYTHON', severity=logging.ERROR)
s, h, b = bare_error()
@@ -249,7 +256,7 @@ def send_response(req, status, headers, body, stream=False):
req.status = int(status[:3])
# Set response headers
- req.content_type = "text/plain"
+ req.content_type = 'text/plain'
for header, value in headers:
if header.lower() == 'content-type':
req.content_type = value
@@ -261,7 +268,7 @@ def send_response(req, status, headers, body, stream=False):
req.flush()
# Set response body
- if isinstance(body, basestring):
+ if isinstance(body, text_or_bytes):
req.write(body)
else:
for seg in body:
@@ -269,8 +276,6 @@ def send_response(req, status, headers, body, stream=False):
# --------------- Startup tools for CherryPy + mod_python --------------- #
-import os
-import re
try:
import subprocess
@@ -285,13 +290,13 @@ except ImportError:
return pipeout
-def read_process(cmd, args=""):
- fullcmd = "%s %s" % (cmd, args)
+def read_process(cmd, args=''):
+ fullcmd = '%s %s' % (cmd, args)
pipeout = popen(fullcmd)
try:
firstline = pipeout.readline()
cmd_not_found = re.search(
- ntob("(not recognized|No such file|not found)"),
+ ntob('(not recognized|No such file|not found)'),
firstline,
re.IGNORECASE
)
@@ -320,8 +325,8 @@ LoadModule python_module modules/mod_python.so
</Location>
"""
- def __init__(self, loc="/", port=80, opts=None, apache_path="apache",
- handler="cherrypy._cpmodpy::handler"):
+ def __init__(self, loc='/', port=80, opts=None, apache_path='apache',
+ handler='cherrypy._cpmodpy::handler'):
self.loc = loc
self.port = port
self.opts = opts
@@ -329,25 +334,25 @@ LoadModule python_module modules/mod_python.so
self.handler = handler
def start(self):
- opts = "".join([" PythonOption %s %s\n" % (k, v)
+ opts = ''.join([' PythonOption %s %s\n' % (k, v)
for k, v in self.opts])
- conf_data = self.template % {"port": self.port,
- "loc": self.loc,
- "opts": opts,
- "handler": self.handler,
+ conf_data = self.template % {'port': self.port,
+ 'loc': self.loc,
+ 'opts': opts,
+ 'handler': self.handler,
}
- mpconf = os.path.join(os.path.dirname(__file__), "cpmodpy.conf")
+ mpconf = os.path.join(os.path.dirname(__file__), 'cpmodpy.conf')
f = open(mpconf, 'wb')
try:
f.write(conf_data)
finally:
f.close()
- response = read_process(self.apache_path, "-k start -f %s" % mpconf)
+ response = read_process(self.apache_path, '-k start -f %s' % mpconf)
self.ready = True
return response
def stop(self):
- os.popen("apache -k stop")
+ os.popen('apache -k stop')
self.ready = False
diff --git a/cherrypy/_cpnative_server.py b/cherrypy/_cpnative_server.py
index e303573d..1fef37a7 100644
--- a/cherrypy/_cpnative_server.py
+++ b/cherrypy/_cpnative_server.py
@@ -2,36 +2,39 @@
import logging
import sys
+import io
+
+import cheroot.server
import cherrypy
-from cherrypy._cpcompat import BytesIO
from cherrypy._cperror import format_exc, bare_error
from cherrypy.lib import httputil
-from cherrypy import wsgiserver
-class NativeGateway(wsgiserver.Gateway):
+class NativeGateway(cheroot.server.Gateway):
+ """Native gateway implementation allowing to bypass WSGI."""
recursive = False
def respond(self):
+ """Obtain response from CherryPy machinery and then send it."""
req = self.req
try:
# Obtain a Request object from CherryPy
local = req.server.bind_addr
- local = httputil.Host(local[0], local[1], "")
+ local = httputil.Host(local[0], local[1], '')
remote = req.conn.remote_addr, req.conn.remote_port
- remote = httputil.Host(remote[0], remote[1], "")
+ remote = httputil.Host(remote[0], remote[1], '')
scheme = req.scheme
- sn = cherrypy.tree.script_name(req.uri or "/")
+ sn = cherrypy.tree.script_name(req.uri or '/')
if sn is None:
self.send_response('404 Not Found', [], [''])
else:
app = cherrypy.tree.apps[sn]
method = req.method
path = req.path
- qs = req.qs or ""
+ qs = req.qs or ''
headers = req.inheaders.items()
rfile = req.rfile
prev = None
@@ -40,7 +43,7 @@ class NativeGateway(wsgiserver.Gateway):
redirections = []
while True:
request, response = app.get_serving(
- local, remote, scheme, "HTTP/1.1")
+ local, remote, scheme, 'HTTP/1.1')
request.multithread = True
request.multiprocess = False
request.app = app
@@ -60,27 +63,27 @@ class NativeGateway(wsgiserver.Gateway):
if not self.recursive:
if ir.path in redirections:
raise RuntimeError(
- "InternalRedirector visited the same "
- "URL twice: %r" % ir.path)
+ 'InternalRedirector visited the same '
+ 'URL twice: %r' % ir.path)
else:
# Add the *previous* path_info + qs to
# redirections.
if qs:
- qs = "?" + qs
+ qs = '?' + qs
redirections.append(sn + path + qs)
# Munge environment and try again.
- method = "GET"
+ method = 'GET'
path = ir.path
qs = ir.query_string
- rfile = BytesIO()
+ rfile = io.BytesIO()
self.send_response(
response.output_status, response.header_list,
response.body)
finally:
app.release_serving()
- except:
+ except Exception:
tb = format_exc()
# print tb
cherrypy.log(tb, 'NATIVE_ADAPTER', severity=logging.ERROR)
@@ -88,10 +91,11 @@ class NativeGateway(wsgiserver.Gateway):
self.send_response(s, h, b)
def send_response(self, status, headers, body):
+ """Send response to HTTP request."""
req = self.req
# Set response status
- req.status = str(status or "500 Server Error")
+ req.status = str(status or '500 Server Error')
# Set response headers
for header, value in headers:
@@ -105,24 +109,24 @@ class NativeGateway(wsgiserver.Gateway):
req.write(seg)
-class CPHTTPServer(wsgiserver.HTTPServer):
-
- """Wrapper for wsgiserver.HTTPServer.
+class CPHTTPServer(cheroot.server.HTTPServer):
+ """Wrapper for cheroot.server.HTTPServer.
- wsgiserver has been designed to not reference CherryPy in any way,
+ cheroot has been designed to not reference CherryPy in any way,
so that it can be used in other frameworks and applications.
Therefore, we wrap it here, so we can apply some attributes
from config -> cherrypy.server -> HTTPServer.
"""
def __init__(self, server_adapter=cherrypy.server):
+ """Initialize CPHTTPServer."""
self.server_adapter = server_adapter
server_name = (self.server_adapter.socket_host or
self.server_adapter.socket_file or
None)
- wsgiserver.HTTPServer.__init__(
+ cheroot.server.HTTPServer.__init__(
self, server_adapter.bind_addr, NativeGateway,
minthreads=server_adapter.thread_pool,
maxthreads=server_adapter.thread_pool_max,
@@ -140,15 +144,17 @@ class CPHTTPServer(wsgiserver.HTTPServer):
ssl_module = self.server_adapter.ssl_module or 'pyopenssl'
if self.server_adapter.ssl_context:
- adapter_class = wsgiserver.get_ssl_adapter_class(ssl_module)
+ adapter_class = cheroot.server.get_ssl_adapter_class(ssl_module)
self.ssl_adapter = adapter_class(
self.server_adapter.ssl_certificate,
self.server_adapter.ssl_private_key,
- self.server_adapter.ssl_certificate_chain)
+ self.server_adapter.ssl_certificate_chain,
+ self.server_adapter.ssl_ciphers)
self.ssl_adapter.context = self.server_adapter.ssl_context
elif self.server_adapter.ssl_certificate:
- adapter_class = wsgiserver.get_ssl_adapter_class(ssl_module)
+ adapter_class = cheroot.server.get_ssl_adapter_class(ssl_module)
self.ssl_adapter = adapter_class(
self.server_adapter.ssl_certificate,
self.server_adapter.ssl_private_key,
- self.server_adapter.ssl_certificate_chain)
+ self.server_adapter.ssl_certificate_chain,
+ self.server_adapter.ssl_ciphers)
diff --git a/cherrypy/_cpreqbody.py b/cherrypy/_cpreqbody.py
index 13a8adb7..d2388897 100644
--- a/cherrypy/_cpreqbody.py
+++ b/cherrypy/_cpreqbody.py
@@ -61,7 +61,7 @@ Here's the built-in JSON tool for an example::
def json_in(force=True, debug=False):
request = cherrypy.serving.request
def json_processor(entity):
- \"""Read application/json data into request.json.\"""
+ '''Read application/json data into request.json.'''
if not entity.headers.get("Content-Length", ""):
raise cherrypy.HTTPError(411)
@@ -120,8 +120,8 @@ try:
except ImportError:
def unquote_plus(bs):
"""Bytes version of urllib.parse.unquote_plus."""
- bs = bs.replace(ntob('+'), ntob(' '))
- atoms = bs.split(ntob('%'))
+ bs = bs.replace(b'+', b' ')
+ atoms = bs.split(b'%')
for i in range(1, len(atoms)):
item = atoms[i]
try:
@@ -129,10 +129,13 @@ except ImportError:
atoms[i] = bytes([pct]) + item[2:]
except ValueError:
pass
- return ntob('').join(atoms)
+ return b''.join(atoms)
+
+import six
+import cheroot.server
import cherrypy
-from cherrypy._cpcompat import basestring, ntob, ntou
+from cherrypy._cpcompat import text_or_bytes, ntob, ntou
from cherrypy.lib import httputil
@@ -169,8 +172,8 @@ def process_urlencoded(entity):
break
else:
raise cherrypy.HTTPError(
- 400, "The request entity could not be decoded. The following "
- "charsets were attempted: %s" % repr(entity.attempt_charsets))
+ 400, 'The request entity could not be decoded. The following '
+ 'charsets were attempted: %s' % repr(entity.attempt_charsets))
# Now that all values have been successfully parsed and decoded,
# apply them to the entity.params dict.
@@ -185,7 +188,7 @@ def process_urlencoded(entity):
def process_multipart(entity):
"""Read all multipart parts into entity.parts."""
- ib = ""
+ ib = ''
if 'boundary' in entity.content_type.params:
# http://tools.ietf.org/html/rfc2046#section-5.1.1
# "The grammar for parameters on the Content-type field is such that it
@@ -193,7 +196,7 @@ def process_multipart(entity):
# on the Content-type line"
ib = entity.content_type.params['boundary'].strip('"')
- if not re.match("^[ -~]{0,200}[!-~]$", ib):
+ if not re.match('^[ -~]{0,200}[!-~]$', ib):
raise ValueError('Invalid boundary in multipart form: %r' % (ib,))
ib = ('--' + ib).encode('ascii')
@@ -315,7 +318,8 @@ class Entity(object):
:attr:`request.body.parts<cherrypy._cpreqbody.Entity.parts>`. You can
enable it with::
- cherrypy.request.body.processors['multipart'] = _cpreqbody.process_multipart
+ cherrypy.request.body.processors['multipart'] = \
+ _cpreqbody.process_multipart
in an ``on_start_resource`` tool.
"""
@@ -325,14 +329,15 @@ class Entity(object):
# absence of a charset parameter, is US-ASCII."
# However, many browsers send data in utf-8 with no charset.
attempt_charsets = ['utf-8']
- """A list of strings, each of which should be a known encoding.
+ r"""A list of strings, each of which should be a known encoding.
When the Content-Type of the request body warrants it, each of the given
encodings will be tried in order. The first one to successfully decode the
entity without raising an error is stored as
:attr:`entity.charset<cherrypy._cpreqbody.Entity.charset>`. This defaults
to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by
- `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_),
+ `HTTP/1.1
+ <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_),
but ``['us-ascii', 'utf-8']`` for multipart parts.
"""
@@ -428,7 +433,7 @@ class Entity(object):
# Copy the class 'attempt_charsets', prepending any Content-Type
# charset
- dec = self.content_type.params.get("charset", None)
+ dec = self.content_type.params.get('charset', None)
if dec:
self.attempt_charsets = [dec] + [c for c in self.attempt_charsets
if c != dec]
@@ -469,8 +474,8 @@ class Entity(object):
# The 'type' attribute is deprecated in 3.2; remove it in 3.3.
type = property(
lambda self: self.content_type,
- doc="A deprecated alias for "
- ":attr:`content_type<cherrypy._cpreqbody.Entity.content_type>`."
+ doc='A deprecated alias for '
+ ':attr:`content_type<cherrypy._cpreqbody.Entity.content_type>`.'
)
def read(self, size=None, fp_out=None):
@@ -520,8 +525,26 @@ class Entity(object):
self.file.seek(0)
else:
value = self.value
+ value = self.decode_entity(value)
return value
+ def decode_entity(self, value):
+ """Return a given byte encoded value as a string"""
+ for charset in self.attempt_charsets:
+ try:
+ value = value.decode(charset)
+ except UnicodeDecodeError:
+ pass
+ else:
+ self.charset = charset
+ return value
+ else:
+ raise cherrypy.HTTPError(
+ 400,
+ 'The request entity could not be decoded. The following '
+ 'charsets were attempted: %s' % repr(self.attempt_charsets)
+ )
+
def process(self):
"""Execute the best-match processor for the given media type."""
proc = None
@@ -556,14 +579,15 @@ class Part(Entity):
# "The default character set, which must be assumed in the absence of a
# charset parameter, is US-ASCII."
attempt_charsets = ['us-ascii', 'utf-8']
- """A list of strings, each of which should be a known encoding.
+ r"""A list of strings, each of which should be a known encoding.
When the Content-Type of the request body warrants it, each of the given
encodings will be tried in order. The first one to successfully decode the
entity without raising an error is stored as
:attr:`entity.charset<cherrypy._cpreqbody.Entity.charset>`. This defaults
to ``['utf-8']`` (plus 'ISO-8859-1' for "text/\*" types, as required by
- `HTTP/1.1 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_),
+ `HTTP/1.1
+ <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_),
but ``['us-ascii', 'utf-8']`` for multipart parts.
"""
@@ -595,40 +619,40 @@ class Part(Entity):
self.file = None
self.value = None
+ @classmethod
def from_fp(cls, fp, boundary):
headers = cls.read_headers(fp)
return cls(fp, headers, boundary)
- from_fp = classmethod(from_fp)
+ @classmethod
def read_headers(cls, fp):
headers = httputil.HeaderMap()
while True:
line = fp.readline()
if not line:
# No more data--illegal end of headers
- raise EOFError("Illegal end of headers.")
+ raise EOFError('Illegal end of headers.')
if line == ntob('\r\n'):
# Normal end of headers
break
if not line.endswith(ntob('\r\n')):
- raise ValueError("MIME requires CRLF terminators: %r" % line)
+ raise ValueError('MIME requires CRLF terminators: %r' % line)
if line[0] in ntob(' \t'):
# It's a continuation line.
v = line.strip().decode('ISO-8859-1')
else:
- k, v = line.split(ntob(":"), 1)
+ k, v = line.split(ntob(':'), 1)
k = k.strip().decode('ISO-8859-1')
v = v.strip().decode('ISO-8859-1')
existing = headers.get(k)
if existing:
- v = ", ".join((existing, v))
+ v = ', '.join((existing, v))
headers[k] = v
return headers
- read_headers = classmethod(read_headers)
def read_lines_to_boundary(self, fp_out=None):
"""Read bytes from self.fp and return or write them to a file.
@@ -640,16 +664,16 @@ class Part(Entity):
object that supports the 'write' method; all bytes read will be
written to the fp, and that fp is returned.
"""
- endmarker = self.boundary + ntob("--")
- delim = ntob("")
+ endmarker = self.boundary + ntob('--')
+ delim = ntob('')
prev_lf = True
lines = []
seen = 0
while True:
line = self.fp.readline(1 << 16)
if not line:
- raise EOFError("Illegal end of multipart body.")
- if line.startswith(ntob("--")) and prev_lf:
+ raise EOFError('Illegal end of multipart body.')
+ if line.startswith(ntob('--')) and prev_lf:
strippedline = line.strip()
if strippedline == self.boundary:
break
@@ -659,16 +683,16 @@ class Part(Entity):
line = delim + line
- if line.endswith(ntob("\r\n")):
- delim = ntob("\r\n")
+ if line.endswith(ntob('\r\n')):
+ delim = ntob('\r\n')
line = line[:-2]
prev_lf = True
- elif line.endswith(ntob("\n")):
- delim = ntob("\n")
+ elif line.endswith(ntob('\n')):
+ delim = ntob('\n')
line = line[:-1]
prev_lf = True
else:
- delim = ntob("")
+ delim = ntob('')
prev_lf = False
if fp_out is None:
@@ -683,20 +707,7 @@ class Part(Entity):
if fp_out is None:
result = ntob('').join(lines)
- for charset in self.attempt_charsets:
- try:
- result = result.decode(charset)
- except UnicodeDecodeError:
- pass
- else:
- self.charset = charset
- return result
- else:
- raise cherrypy.HTTPError(
- 400,
- "The request entity could not be decoded. The following "
- "charsets were attempted: %s" % repr(self.attempt_charsets)
- )
+ return result
else:
fp_out.seek(0)
return fp_out
@@ -710,7 +721,7 @@ class Part(Entity):
self.file = self.read_into_file()
else:
result = self.read_lines_to_boundary()
- if isinstance(result, basestring):
+ if isinstance(result, text_or_bytes):
self.value = result
else:
self.file = result
@@ -725,31 +736,10 @@ class Part(Entity):
self.read_lines_to_boundary(fp_out=fp_out)
return fp_out
-Entity.part_class = Part
-
-try:
- inf = float('inf')
-except ValueError:
- # Python 2.4 and lower
- class Infinity(object):
-
- def __cmp__(self, other):
- return 1
-
- def __sub__(self, other):
- return self
- inf = Infinity()
+Entity.part_class = Part
-comma_separated_headers = [
- 'Accept', 'Accept-Charset', 'Accept-Encoding',
- 'Accept-Language', 'Accept-Ranges', 'Allow',
- 'Cache-Control', 'Connection', 'Content-Encoding',
- 'Content-Language', 'Expect', 'If-Match',
- 'If-None-Match', 'Pragma', 'Proxy-Authenticate',
- 'Te', 'Trailer', 'Transfer-Encoding', 'Upgrade',
- 'Vary', 'Via', 'Warning', 'Www-Authenticate'
-]
+inf = float('inf')
class SizedReader:
@@ -834,7 +824,7 @@ class SizedReader:
if e.__class__.__name__ == 'MaxSizeExceeded':
# Post data is too big
raise cherrypy.HTTPError(
- 413, "Maximum request length: %r" % e.args[1])
+ 413, 'Maximum request length: %r' % e.args[1])
else:
raise
if not data:
@@ -910,23 +900,23 @@ class SizedReader:
v = line.strip()
else:
try:
- k, v = line.split(ntob(":"), 1)
+ k, v = line.split(ntob(':'), 1)
except ValueError:
- raise ValueError("Illegal header line.")
+ raise ValueError('Illegal header line.')
k = k.strip().title()
v = v.strip()
- if k in comma_separated_headers:
- existing = self.trailers.get(envname)
+ if k in cheroot.server.comma_separated_headers:
+ existing = self.trailers.get(k)
if existing:
- v = ntob(", ").join((existing, v))
+ v = ntob(', ').join((existing, v))
self.trailers[k] = v
except Exception:
e = sys.exc_info()[1]
if e.__class__.__name__ == 'MaxSizeExceeded':
# Post data is too big
raise cherrypy.HTTPError(
- 413, "Maximum request length: %r" % e.args[1])
+ 413, 'Maximum request length: %r' % e.args[1])
else:
raise
@@ -1002,7 +992,7 @@ class RequestBody(Entity):
# Python 2 only: keyword arguments must be byte strings (type
# 'str').
if sys.version_info < (3, 0):
- if isinstance(key, unicode):
+ if isinstance(key, six.text_type):
key = key.encode('ISO-8859-1')
if key in request_params:
diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py
index 290bd2eb..ddff3669 100644
--- a/cherrypy/_cprequest.py
+++ b/cherrypy/_cprequest.py
@@ -1,15 +1,16 @@
-
-import os
import sys
import time
import warnings
+import uuid
+import six
+from six.moves.http_cookies import SimpleCookie, CookieError
+
import cherrypy
-from cherrypy._cpcompat import basestring, copykeys, ntob, unicodestr
-from cherrypy._cpcompat import SimpleCookie, CookieError, py3k
-from cherrypy import _cpreqbody, _cpconfig
+from cherrypy._cpcompat import text_or_bytes, ntob
+from cherrypy import _cpreqbody
from cherrypy._cperror import format_exc, bare_error
-from cherrypy.lib import httputil, file_generator
+from cherrypy.lib import httputil, file_generator, reprconf
class Hook(object):
@@ -41,33 +42,32 @@ class Hook(object):
self.callback = callback
if failsafe is None:
- failsafe = getattr(callback, "failsafe", False)
+ failsafe = getattr(callback, 'failsafe', False)
self.failsafe = failsafe
if priority is None:
- priority = getattr(callback, "priority", 50)
+ priority = getattr(callback, 'priority', 50)
self.priority = priority
self.kwargs = kwargs
def __lt__(self, other):
- # Python 3
+ """
+ Hooks sort by priority, ascending, such that
+ hooks of lower priority are run first.
+ """
return self.priority < other.priority
- def __cmp__(self, other):
- # Python 2
- return cmp(self.priority, other.priority)
-
def __call__(self):
"""Run self.callback(**self.kwargs)."""
return self.callback(**self.kwargs)
def __repr__(self):
cls = self.__class__
- return ("%s.%s(callback=%r, failsafe=%r, priority=%r, %s)"
+ return ('%s.%s(callback=%r, failsafe=%r, priority=%r, %s)'
% (cls.__module__, cls.__name__, self.callback,
self.failsafe, self.priority,
- ", ".join(['%s=%r' % (k, v)
+ ', '.join(['%s=%r' % (k, v)
for k, v in self.kwargs.items()])))
@@ -107,7 +107,7 @@ class HookMap(dict):
except (cherrypy.HTTPError, cherrypy.HTTPRedirect,
cherrypy.InternalRedirect):
exc = sys.exc_info()[1]
- except:
+ except Exception:
exc = sys.exc_info()[1]
cherrypy.log(traceback=True, severity=40)
if exc:
@@ -124,10 +124,10 @@ class HookMap(dict):
def __repr__(self):
cls = self.__class__
- return "%s.%s(points=%r)" % (
+ return '%s.%s(points=%r)' % (
cls.__module__,
cls.__name__,
- copykeys(self)
+ list(self)
)
@@ -138,8 +138,8 @@ def hooks_namespace(k, v):
# Use split again to allow multiple hooks for a single
# hookpoint per path (e.g. "hooks.before_handler.1").
# Little-known fact you only get from reading source ;)
- hookpoint = k.split(".", 1)[0]
- if isinstance(v, basestring):
+ hookpoint = k.split('.', 1)[0]
+ if isinstance(v, text_or_bytes):
v = cherrypy.lib.attributes(v)
if not isinstance(v, Hook):
v = Hook(v)
@@ -199,23 +199,23 @@ class Request(object):
unless we are processing an InternalRedirect."""
# Conversation/connection attributes
- local = httputil.Host("127.0.0.1", 80)
- "An httputil.Host(ip, port, hostname) object for the server socket."
+ local = httputil.Host('127.0.0.1', 80)
+ 'An httputil.Host(ip, port, hostname) object for the server socket.'
- remote = httputil.Host("127.0.0.1", 1111)
- "An httputil.Host(ip, port, hostname) object for the client socket."
+ remote = httputil.Host('127.0.0.1', 1111)
+ 'An httputil.Host(ip, port, hostname) object for the client socket.'
- scheme = "http"
+ scheme = 'http'
"""
The protocol used between client and server. In most cases,
this will be either 'http' or 'https'."""
- server_protocol = "HTTP/1.1"
+ server_protocol = 'HTTP/1.1'
"""
The HTTP version for which the HTTP server is at least
conditionally compliant."""
- base = ""
+ base = ''
"""The (scheme://host) portion of the requested URL.
In some cases (e.g. when proxying via mod_rewrite), this may contain
path segments which cherrypy.url uses when constructing url's, but
@@ -223,13 +223,13 @@ class Request(object):
MUST NOT end in a slash."""
# Request-Line attributes
- request_line = ""
+ request_line = ''
"""
The complete Request-Line received from the client. This is a
single string consisting of the request method, URI, and protocol
version (joined by spaces). Any final CRLF is removed."""
- method = "GET"
+ method = 'GET'
"""
Indicates the HTTP method to be performed on the resource identified
by the Request-URI. Common methods include GET, HEAD, POST, PUT, and
@@ -237,7 +237,7 @@ class Request(object):
servers and gateways may restrict the set of allowable methods.
CherryPy applications SHOULD restrict the set (on a per-URI basis)."""
- query_string = ""
+ query_string = ''
"""
The query component of the Request-URI, a string of information to be
interpreted by the resource. The query portion of a URI follows the
@@ -312,7 +312,7 @@ class Request(object):
If True, the rfile (if any) is automatically read and parsed,
and the result placed into request.params or request.body."""
- methods_with_bodies = ("POST", "PUT")
+ methods_with_bodies = ('POST', 'PUT', 'PATCH')
"""
A sequence of HTTP methods for which CherryPy will automatically
attempt to read a body from the rfile. If you are going to change
@@ -341,7 +341,7 @@ class Request(object):
to a hierarchical arrangement of objects, starting at request.app.root.
See help(cherrypy.dispatch) for more information."""
- script_name = ""
+ script_name = ''
"""
The 'mount point' of the application which is handling this request.
@@ -349,7 +349,7 @@ class Request(object):
the root of the URI, it MUST be an empty string (not "/").
"""
- path_info = "/"
+ path_info = '/'
"""
The 'relative path' portion of the Request-URI. This is relative
to the script_name ('mount point') of the application which is
@@ -467,16 +467,19 @@ class Request(object):
A string containing the stage reached in the request-handling process.
This is useful when debugging a live server with hung requests."""
- namespaces = _cpconfig.NamespaceSet(
- **{"hooks": hooks_namespace,
- "request": request_namespace,
- "response": response_namespace,
- "error_page": error_page_namespace,
- "tools": cherrypy.tools,
+ unique_id = None
+ """A lazy object generating and memorizing UUID4 on ``str()`` render."""
+
+ namespaces = reprconf.NamespaceSet(
+ **{'hooks': hooks_namespace,
+ 'request': request_namespace,
+ 'response': response_namespace,
+ 'error_page': error_page_namespace,
+ 'tools': cherrypy.tools,
})
- def __init__(self, local_host, remote_host, scheme="http",
- server_protocol="HTTP/1.1"):
+ def __init__(self, local_host, remote_host, scheme='http',
+ server_protocol='HTTP/1.1'):
"""Populate a new Request object.
local_host should be an httputil.Host object with the server info.
@@ -498,6 +501,8 @@ class Request(object):
self.stage = None
+ self.unique_id = LazyUUID4()
+
def close(self):
"""Run cleanup code. (Core)"""
if not self.closed:
@@ -544,7 +549,7 @@ class Request(object):
self.error_response = cherrypy.HTTPError(500).set_response
self.method = method
- path = path or "/"
+ path = path or '/'
self.query_string = query_string or ''
self.params = {}
@@ -590,7 +595,7 @@ class Request(object):
except self.throws:
raise
- except:
+ except Exception:
if self.throw_errors:
raise
else:
@@ -600,22 +605,19 @@ class Request(object):
if self.show_tracebacks:
body = format_exc()
else:
- body = ""
+ body = ''
r = bare_error(body)
response.output_status, response.header_list, response.body = r
- if self.method == "HEAD":
+ if self.method == 'HEAD':
# HEAD requests MUST NOT return a message-body in the response.
response.body = []
try:
cherrypy.log.access()
- except:
+ except Exception:
cherrypy.log.error(traceback=True)
- if response.timed_out:
- raise cherrypy.TimeoutError()
-
return response
# Uncomment for stage debugging
@@ -623,72 +625,75 @@ class Request(object):
def respond(self, path_info):
"""Generate a response for the resource at self.path_info. (Core)"""
- response = cherrypy.serving.response
try:
try:
try:
- if self.app is None:
- raise cherrypy.NotFound()
-
- # Get the 'Host' header, so we can HTTPRedirect properly.
- self.stage = 'process_headers'
- self.process_headers()
-
- # Make a copy of the class hooks
- self.hooks = self.__class__.hooks.copy()
- self.toolmaps = {}
-
- self.stage = 'get_resource'
- self.get_resource(path_info)
-
- self.body = _cpreqbody.RequestBody(
- self.rfile, self.headers, request_params=self.params)
-
- self.namespaces(self.config)
-
- self.stage = 'on_start_resource'
- self.hooks.run('on_start_resource')
-
- # Parse the querystring
- self.stage = 'process_query_string'
- self.process_query_string()
-
- # Process the body
- if self.process_request_body:
- if self.method not in self.methods_with_bodies:
- self.process_request_body = False
- self.stage = 'before_request_body'
- self.hooks.run('before_request_body')
- if self.process_request_body:
- self.body.process()
-
- # Run the handler
- self.stage = 'before_handler'
- self.hooks.run('before_handler')
- if self.handler:
- self.stage = 'handler'
- response.body = self.handler()
-
- # Finalize
- self.stage = 'before_finalize'
- self.hooks.run('before_finalize')
- response.finalize()
+ self._do_respond(path_info)
except (cherrypy.HTTPRedirect, cherrypy.HTTPError):
inst = sys.exc_info()[1]
inst.set_response()
self.stage = 'before_finalize (HTTPError)'
self.hooks.run('before_finalize')
- response.finalize()
+ cherrypy.serving.response.finalize()
finally:
self.stage = 'on_end_resource'
self.hooks.run('on_end_resource')
except self.throws:
raise
- except:
+ except Exception:
if self.throw_errors:
raise
self.handle_error()
+ def _do_respond(self, path_info):
+ response = cherrypy.serving.response
+
+ if self.app is None:
+ raise cherrypy.NotFound()
+
+ self.hooks = self.__class__.hooks.copy()
+ self.toolmaps = {}
+
+ # Get the 'Host' header, so we can HTTPRedirect properly.
+ self.stage = 'process_headers'
+ self.process_headers()
+
+ self.stage = 'get_resource'
+ self.get_resource(path_info)
+
+ self.body = _cpreqbody.RequestBody(
+ self.rfile, self.headers, request_params=self.params)
+
+ self.namespaces(self.config)
+
+ self.stage = 'on_start_resource'
+ self.hooks.run('on_start_resource')
+
+ # Parse the querystring
+ self.stage = 'process_query_string'
+ self.process_query_string()
+
+ # Process the body
+ if self.process_request_body:
+ if self.method not in self.methods_with_bodies:
+ self.process_request_body = False
+ self.stage = 'before_request_body'
+ self.hooks.run('before_request_body')
+ if self.process_request_body:
+ self.body.process()
+
+ # Run the handler
+ self.stage = 'before_handler'
+ self.hooks.run('before_handler')
+ if self.handler:
+ self.stage = 'handler'
+ response.body = self.handler()
+
+ # Finalize
+ self.stage = 'before_finalize'
+ self.hooks.run('before_finalize')
+ response.finalize()
+
def process_query_string(self):
"""Parse the query string into Python structures. (Core)"""
try:
@@ -696,14 +701,14 @@ class Request(object):
self.query_string, encoding=self.query_string_encoding)
except UnicodeDecodeError:
raise cherrypy.HTTPError(
- 404, "The given query string could not be processed. Query "
- "strings for this resource must be encoded with %r." %
+ 404, 'The given query string could not be processed. Query '
+ 'strings for this resource must be encoded with %r.' %
self.query_string_encoding)
# Python 2 only: keyword arguments must be byte strings (type 'str').
- if not py3k:
+ if six.PY2:
for key, value in p.items():
- if isinstance(key, unicode):
+ if isinstance(key, six.text_type):
del p[key]
p[key.encode(self.query_string_encoding)] = value
self.params.update(p)
@@ -718,23 +723,16 @@ class Request(object):
name = name.title()
value = value.strip()
- # Warning: if there is more than one header entry for cookies
- # (AFAIK, only Konqueror does that), only the last one will
- # remain in headers (but they will be correctly stored in
- # request.cookie).
- if "=?" in value:
- dict.__setitem__(headers, name, httputil.decode_TEXT(value))
- else:
- dict.__setitem__(headers, name, value)
+ headers[name] = httputil.decode_TEXT_maybe(value)
- # Handle cookies differently because on Konqueror, multiple
- # cookies come on different lines with the same key
+ # Some clients, notably Konquoror, supply multiple
+ # cookies on different lines with the same key. To
+ # handle this case, store all cookies in self.cookie.
if name == 'Cookie':
try:
self.cookie.load(value)
- except CookieError:
- msg = "Illegal cookie name %s" % value.split('=')[0]
- raise cherrypy.HTTPError(400, msg)
+ except CookieError as exc:
+ raise cherrypy.HTTPError(400, str(exc))
if not dict.__contains__(headers, 'Host'):
# All Internet-based HTTP/1.1 servers MUST respond with a 400
@@ -746,7 +744,7 @@ class Request(object):
host = dict.get(headers, 'Host')
if not host:
host = self.local.name or self.local.ip
- self.base = "%s://%s" % (self.scheme, host)
+ self.base = '%s://%s' % (self.scheme, host)
def get_resource(self, path):
"""Call a dispatcher (which sets self.handler and .config). (Core)"""
@@ -754,7 +752,7 @@ class Request(object):
# dispatchers can only be specified in app.config, not in _cp_config
# (since custom dispatchers may not even have an app.root).
dispatch = self.app.find_config(
- path, "request.dispatch", self.dispatch)
+ path, 'request.dispatch', self.dispatch)
# dispatch() should set self.handler and self.config
dispatch(path)
@@ -762,10 +760,10 @@ class Request(object):
def handle_error(self):
"""Handle the last unanticipated exception. (Core)"""
try:
- self.hooks.run("before_error_response")
+ self.hooks.run('before_error_response')
if self.error_response:
self.error_response()
- self.hooks.run("after_error_response")
+ self.hooks.run('after_error_response')
cherrypy.serving.response.finalize()
except cherrypy.HTTPRedirect:
inst = sys.exc_info()[1]
@@ -776,8 +774,8 @@ class Request(object):
def _get_body_params(self):
warnings.warn(
- "body_params is deprecated in CherryPy 3.2, will be removed in "
- "CherryPy 3.3.",
+ 'body_params is deprecated in CherryPy 3.2, will be removed in '
+ 'CherryPy 3.3.',
DeprecationWarning
)
return self.body.params
@@ -799,9 +797,9 @@ class ResponseBody(object):
"""The body of the HTTP response (the response entity)."""
- if py3k:
- unicode_err = ("Page handlers MUST return bytes. Use tools.encode "
- "if you wish to return unicode.")
+ if six.PY3:
+ unicode_err = ('Page handlers MUST return bytes. Use tools.encode '
+ 'if you wish to return unicode.')
def __get__(self, obj, objclass=None):
if obj is None:
@@ -812,10 +810,10 @@ class ResponseBody(object):
def __set__(self, obj, value):
# Convert the given value to an iterable object.
- if py3k and isinstance(value, str):
+ if six.PY3 and isinstance(value, str):
raise ValueError(self.unicode_err)
- if isinstance(value, basestring):
+ if isinstance(value, text_or_bytes):
# strings get wrapped in a list because iterating over a single
# item list is much faster than iterating over every character
# in a long string.
@@ -824,7 +822,7 @@ class ResponseBody(object):
else:
# [''] doesn't evaluate to False, so replace it with [].
value = []
- elif py3k and isinstance(value, list):
+ elif six.PY3 and isinstance(value, list):
# every item in a list must be bytes...
for i, item in enumerate(value):
if isinstance(item, str):
@@ -842,7 +840,7 @@ class Response(object):
"""An HTTP Response, including status, headers, and body."""
- status = ""
+ status = ''
"""The HTTP Status-Code and Reason-Phrase."""
header_list = []
@@ -872,14 +870,6 @@ class Response(object):
time = None
"""The value of time.time() when created. Use in HTTP dates."""
- timeout = 300
- """Seconds after which the response will be aborted."""
-
- timed_out = False
- """
- Flag to indicate the response should be aborted, because it has
- exceeded its timeout."""
-
stream = False
"""If False, buffer the response body."""
@@ -893,20 +883,20 @@ class Response(object):
# Since we know all our keys are titled strings, we can
# bypass HeaderMap.update and get a big speed boost.
dict.update(self.headers, {
- "Content-Type": 'text/html',
- "Server": "CherryPy/" + cherrypy.__version__,
- "Date": httputil.HTTPDate(self.time),
+ 'Content-Type': 'text/html',
+ 'Server': 'CherryPy/' + cherrypy.__version__,
+ 'Date': httputil.HTTPDate(self.time),
})
self.cookie = SimpleCookie()
def collapse_body(self):
"""Collapse self.body to a single string; replace it and return it."""
- if isinstance(self.body, basestring):
+ if isinstance(self.body, text_or_bytes):
return self.body
newbody = []
for chunk in self.body:
- if py3k and not isinstance(chunk, bytes):
+ if six.PY3 and not isinstance(chunk, bytes):
raise TypeError("Chunk %s is not of type 'bytes'." %
repr(chunk))
newbody.append(chunk)
@@ -924,9 +914,9 @@ class Response(object):
headers = self.headers
- self.status = "%s %s" % (code, reason)
+ self.status = '%s %s' % (code, reason)
self.output_status = ntob(str(code), 'ascii') + \
- ntob(" ") + headers.encode(reason)
+ ntob(' ') + headers.encode(reason)
if self.stream:
# The upshot: wsgiserver will chunk the response if
@@ -939,7 +929,7 @@ class Response(object):
# and 304 (not modified) responses MUST NOT
# include a message-body."
dict.pop(headers, 'Content-Length', None)
- self.body = ntob("")
+ self.body = ntob('')
else:
# Responses which are not streamed should have a Content-Length,
# but allow user code to set Content-Length if desired.
@@ -952,22 +942,30 @@ class Response(object):
cookie = self.cookie.output()
if cookie:
- for line in cookie.split("\n"):
- if line.endswith("\r"):
- # Python 2.4 emits cookies joined by LF but 2.5+ by CRLF.
- line = line[:-1]
- name, value = line.split(": ", 1)
- if isinstance(name, unicodestr):
- name = name.encode("ISO-8859-1")
- if isinstance(value, unicodestr):
+ for line in cookie.split('\r\n'):
+ name, value = line.split(': ', 1)
+ if isinstance(name, six.text_type):
+ name = name.encode('ISO-8859-1')
+ if isinstance(value, six.text_type):
value = headers.encode(value)
h.append((name, value))
- def check_timeout(self):
- """If now > self.time + self.timeout, set self.timed_out.
- This purposefully sets a flag, rather than raising an error,
- so that a monitor thread can interrupt the Response thread.
+class LazyUUID4(object):
+ def __str__(self):
+ """Return UUID4 and keep it for future calls."""
+ return str(self.uuid4)
+
+ @property
+ def uuid4(self):
+ """Provide unique id on per-request basis using UUID4.
+
+ It's evaluated lazily on render.
"""
- if time.time() > self.time + self.timeout:
- self.timed_out = True
+ try:
+ self._uuid4
+ except AttributeError:
+ # evaluate on first access
+ self._uuid4 = uuid.uuid4()
+
+ return self._uuid4
diff --git a/cherrypy/_cpserver.py b/cherrypy/_cpserver.py
index a31e7428..c2523918 100644
--- a/cherrypy/_cpserver.py
+++ b/cherrypy/_cpserver.py
@@ -1,18 +1,17 @@
"""Manage HTTP servers with CherryPy."""
-import warnings
+import six
import cherrypy
-from cherrypy.lib import attributes
-from cherrypy._cpcompat import basestring, py3k
+from cherrypy.lib.reprconf import attributes
+from cherrypy._cpcompat import text_or_bytes
+from cherrypy.process.servers import ServerAdapter
-# We import * because we want to export check_port
-# et al as attributes of this module.
-from cherrypy.process.servers import *
+__all__ = ('Server', )
-class Server(ServerAdapter):
+class Server(ServerAdapter):
"""An adapter for an HTTP server.
You can set attributes (like socket_host and socket_port)
@@ -35,7 +34,7 @@ class Server(ServerAdapter):
if value == '':
raise ValueError("The empty string ('') is not an allowed value. "
"Use '0.0.0.0' instead to listen on all active "
- "interfaces (INADDR_ANY).")
+ 'interfaces (INADDR_ANY).')
self._socket_host = value
socket_host = property(
_get_socket_host,
@@ -61,11 +60,11 @@ class Server(ServerAdapter):
socket_timeout = 10
"""The timeout in seconds for accepted connections (default 10)."""
-
+
accepted_queue_size = -1
"""The maximum number of requests which will be queued up before
the server refuses to accept it (default -1, meaning no limit)."""
-
+
accepted_queue_timeout = 10
"""The timeout in seconds for attempting to add a request to the
queue when the queue is full (default 10)."""
@@ -96,7 +95,8 @@ class Server(ServerAdapter):
instance = None
"""If not None, this should be an HTTP server instance (such as
- CPWSGIServer) which cherrypy.server will control. Use this when you need
+ cheroot.wsgi.Server) which cherrypy.server will control.
+ Use this when you need
more control over object instantiation than is available in the various
configuration options."""
@@ -113,20 +113,23 @@ class Server(ServerAdapter):
ssl_private_key = None
"""The filename of the private key to use with SSL."""
- if py3k:
+ ssl_ciphers = None
+ """The ciphers list of SSL."""
+
+ if six.PY3:
ssl_module = 'builtin'
"""The name of a registered SSL adaptation module to use with
the builtin WSGI server. Builtin options are: 'builtin' (to
use the SSL library built into recent versions of Python).
You may also register your own classes in the
- wsgiserver.ssl_adapters dict."""
+ cheroot.server.ssl_adapters dict."""
else:
ssl_module = 'pyopenssl'
"""The name of a registered SSL adaptation module to use with the
builtin WSGI server. Builtin options are 'builtin' (to use the SSL
library built into recent versions of Python) and 'pyopenssl' (to
use the PyOpenSSL project, which you must install separately). You
- may also register your own classes in the wsgiserver.ssl_adapters
+ may also register your own classes in the cheroot.server.ssl_adapters
dict."""
statistics = False
@@ -141,9 +144,11 @@ class Server(ServerAdapter):
which declares it covers WSGI version 1.0.1 but still mandates the
wsgi.version (1, 0)] and ('u', 0), an experimental unicode version.
You may create and register your own experimental versions of the WSGI
- protocol by adding custom classes to the wsgiserver.wsgi_gateways dict."""
+ protocol by adding custom classes to the cheroot.server.wsgi_gateways dict.
+ """
def __init__(self):
+ """Initialize Server instance."""
self.bus = cherrypy.engine
self.httpserver = None
self.interrupt = None
@@ -156,7 +161,7 @@ class Server(ServerAdapter):
if httpserver is None:
from cherrypy import _cpwsgi_server
httpserver = _cpwsgi_server.CPWSGIServer(self)
- if isinstance(httpserver, basestring):
+ if isinstance(httpserver, text_or_bytes):
# Is anyone using this? Can I add an arg?
httpserver = attributes(httpserver)(self)
return httpserver, self.bind_addr
@@ -165,7 +170,7 @@ class Server(ServerAdapter):
"""Start the HTTP server."""
if not self.httpserver:
self.httpserver, self.bind_addr = self.httpserver_from_self()
- ServerAdapter.start(self)
+ super(Server, self).start()
start.priority = 75
def _get_bind_addr(self):
@@ -180,7 +185,7 @@ class Server(ServerAdapter):
self.socket_file = None
self.socket_host = None
self.socket_port = None
- elif isinstance(value, basestring):
+ elif isinstance(value, text_or_bytes):
self.socket_file = value
self.socket_host = None
self.socket_port = None
@@ -189,9 +194,9 @@ class Server(ServerAdapter):
self.socket_host, self.socket_port = value
self.socket_file = None
except ValueError:
- raise ValueError("bind_addr must be a (host, port) tuple "
- "(for TCP sockets) or a string (for Unix "
- "domain sockets), not %r" % value)
+ raise ValueError('bind_addr must be a (host, port) tuple '
+ '(for TCP sockets) or a string (for Unix '
+ 'domain sockets), not %r' % value)
bind_addr = property(
_get_bind_addr,
_set_bind_addr,
@@ -199,7 +204,9 @@ class Server(ServerAdapter):
'a str for Unix domain sockets.')
def base(self):
- """Return the base (scheme://host[:port] or sock file) for this server.
+ """Return the base for this server.
+
+ e.i. scheme://host[:port] or sock file
"""
if self.socket_file:
return self.socket_file
@@ -215,12 +222,12 @@ class Server(ServerAdapter):
port = self.socket_port
if self.ssl_certificate:
- scheme = "https"
+ scheme = 'https'
if port != 443:
- host += ":%s" % port
+ host += ':%s' % port
else:
- scheme = "http"
+ scheme = 'http'
if port != 80:
- host += ":%s" % port
+ host += ':%s' % port
- return "%s://%s" % (scheme, host)
+ return '%s://%s' % (scheme, host)
diff --git a/cherrypy/_cpthreadinglocal.py b/cherrypy/_cpthreadinglocal.py
deleted file mode 100644
index 238c3224..00000000
--- a/cherrypy/_cpthreadinglocal.py
+++ /dev/null
@@ -1,241 +0,0 @@
-# This is a backport of Python-2.4's threading.local() implementation
-
-"""Thread-local objects
-
-(Note that this module provides a Python version of thread
- threading.local class. Depending on the version of Python you're
- using, there may be a faster one available. You should always import
- the local class from threading.)
-
-Thread-local objects support the management of thread-local data.
-If you have data that you want to be local to a thread, simply create
-a thread-local object and use its attributes:
-
- >>> mydata = local()
- >>> mydata.number = 42
- >>> mydata.number
- 42
-
-You can also access the local-object's dictionary:
-
- >>> mydata.__dict__
- {'number': 42}
- >>> mydata.__dict__.setdefault('widgets', [])
- []
- >>> mydata.widgets
- []
-
-What's important about thread-local objects is that their data are
-local to a thread. If we access the data in a different thread:
-
- >>> log = []
- >>> def f():
- ... items = mydata.__dict__.items()
- ... items.sort()
- ... log.append(items)
- ... mydata.number = 11
- ... log.append(mydata.number)
-
- >>> import threading
- >>> thread = threading.Thread(target=f)
- >>> thread.start()
- >>> thread.join()
- >>> log
- [[], 11]
-
-we get different data. Furthermore, changes made in the other thread
-don't affect data seen in this thread:
-
- >>> mydata.number
- 42
-
-Of course, values you get from a local object, including a __dict__
-attribute, are for whatever thread was current at the time the
-attribute was read. For that reason, you generally don't want to save
-these values across threads, as they apply only to the thread they
-came from.
-
-You can create custom local objects by subclassing the local class:
-
- >>> class MyLocal(local):
- ... number = 2
- ... initialized = False
- ... def __init__(self, **kw):
- ... if self.initialized:
- ... raise SystemError('__init__ called too many times')
- ... self.initialized = True
- ... self.__dict__.update(kw)
- ... def squared(self):
- ... return self.number ** 2
-
-This can be useful to support default values, methods and
-initialization. Note that if you define an __init__ method, it will be
-called each time the local object is used in a separate thread. This
-is necessary to initialize each thread's dictionary.
-
-Now if we create a local object:
-
- >>> mydata = MyLocal(color='red')
-
-Now we have a default number:
-
- >>> mydata.number
- 2
-
-an initial color:
-
- >>> mydata.color
- 'red'
- >>> del mydata.color
-
-And a method that operates on the data:
-
- >>> mydata.squared()
- 4
-
-As before, we can access the data in a separate thread:
-
- >>> log = []
- >>> thread = threading.Thread(target=f)
- >>> thread.start()
- >>> thread.join()
- >>> log
- [[('color', 'red'), ('initialized', True)], 11]
-
-without affecting this thread's data:
-
- >>> mydata.number
- 2
- >>> mydata.color
- Traceback (most recent call last):
- ...
- AttributeError: 'MyLocal' object has no attribute 'color'
-
-Note that subclasses can define slots, but they are not thread
-local. They are shared across threads:
-
- >>> class MyLocal(local):
- ... __slots__ = 'number'
-
- >>> mydata = MyLocal()
- >>> mydata.number = 42
- >>> mydata.color = 'red'
-
-So, the separate thread:
-
- >>> thread = threading.Thread(target=f)
- >>> thread.start()
- >>> thread.join()
-
-affects what we see:
-
- >>> mydata.number
- 11
-
->>> del mydata
-"""
-
-# Threading import is at end
-
-
-class _localbase(object):
- __slots__ = '_local__key', '_local__args', '_local__lock'
-
- def __new__(cls, *args, **kw):
- self = object.__new__(cls)
- key = 'thread.local.' + str(id(self))
- object.__setattr__(self, '_local__key', key)
- object.__setattr__(self, '_local__args', (args, kw))
- object.__setattr__(self, '_local__lock', RLock())
-
- if args or kw and (cls.__init__ is object.__init__):
- raise TypeError("Initialization arguments are not supported")
-
- # We need to create the thread dict in anticipation of
- # __init__ being called, to make sure we don't call it
- # again ourselves.
- dict = object.__getattribute__(self, '__dict__')
- currentThread().__dict__[key] = dict
-
- return self
-
-
-def _patch(self):
- key = object.__getattribute__(self, '_local__key')
- d = currentThread().__dict__.get(key)
- if d is None:
- d = {}
- currentThread().__dict__[key] = d
- object.__setattr__(self, '__dict__', d)
-
- # we have a new instance dict, so call out __init__ if we have
- # one
- cls = type(self)
- if cls.__init__ is not object.__init__:
- args, kw = object.__getattribute__(self, '_local__args')
- cls.__init__(self, *args, **kw)
- else:
- object.__setattr__(self, '__dict__', d)
-
-
-class local(_localbase):
-
- def __getattribute__(self, name):
- lock = object.__getattribute__(self, '_local__lock')
- lock.acquire()
- try:
- _patch(self)
- return object.__getattribute__(self, name)
- finally:
- lock.release()
-
- def __setattr__(self, name, value):
- lock = object.__getattribute__(self, '_local__lock')
- lock.acquire()
- try:
- _patch(self)
- return object.__setattr__(self, name, value)
- finally:
- lock.release()
-
- def __delattr__(self, name):
- lock = object.__getattribute__(self, '_local__lock')
- lock.acquire()
- try:
- _patch(self)
- return object.__delattr__(self, name)
- finally:
- lock.release()
-
- def __del__():
- threading_enumerate = enumerate
- __getattribute__ = object.__getattribute__
-
- def __del__(self):
- key = __getattribute__(self, '_local__key')
-
- try:
- threads = list(threading_enumerate())
- except:
- # if enumerate fails, as it seems to do during
- # shutdown, we'll skip cleanup under the assumption
- # that there is nothing to clean up
- return
-
- for thread in threads:
- try:
- __dict__ = thread.__dict__
- except AttributeError:
- # Thread is dying, rest in peace
- continue
-
- if key in __dict__:
- try:
- del __dict__[key]
- except KeyError:
- pass # didn't have anything in this thread
-
- return __del__
- __del__ = __del__()
-
-from threading import currentThread, enumerate, RLock
diff --git a/cherrypy/_cptools.py b/cherrypy/_cptools.py
index af76ae06..92c2b656 100644
--- a/cherrypy/_cptools.py
+++ b/cherrypy/_cptools.py
@@ -26,6 +26,12 @@ import sys
import warnings
import cherrypy
+from cherrypy._helper import expose
+
+from cherrypy.lib import cptools, encoding, auth, static, jsontools
+from cherrypy.lib import sessions as _sessions, xmlrpcutil as _xmlrpc
+from cherrypy.lib import caching as _caching
+from cherrypy.lib import auth_basic, auth_digest
def _getargs(func):
@@ -44,8 +50,8 @@ def _getargs(func):
_attr_error = (
- "CherryPy Tools cannot be turned on directly. Instead, turn them "
- "on via config, or use them as decorators on your page handlers."
+ 'CherryPy Tools cannot be turned on directly. Instead, turn them '
+ 'on via config, or use them as decorators on your page handlers.'
)
@@ -56,7 +62,7 @@ class Tool(object):
help(tool.callable) should give you more information about this Tool.
"""
- namespace = "tools"
+ namespace = 'tools'
def __init__(self, point, callable, name=None, priority=50):
self._point = point
@@ -79,7 +85,7 @@ class Tool(object):
for arg in _getargs(self.callable):
setattr(self, arg, None)
except (TypeError, AttributeError):
- if hasattr(self.callable, "__call__"):
+ if hasattr(self.callable, '__call__'):
for arg in _getargs(self.callable.__call__):
setattr(self, arg, None)
# IronPython 1.0 raises NotImplementedError because
@@ -103,8 +109,8 @@ class Tool(object):
if self._name in tm:
conf.update(tm[self._name])
- if "on" in conf:
- del conf["on"]
+ if 'on' in conf:
+ del conf['on']
return conf
@@ -113,21 +119,21 @@ class Tool(object):
For example::
+ @expose
@tools.proxy()
def whats_my_base(self):
return cherrypy.request.base
- whats_my_base.exposed = True
"""
if args:
- raise TypeError("The %r Tool does not accept positional "
- "arguments; you must use keyword arguments."
+ raise TypeError('The %r Tool does not accept positional '
+ 'arguments; you must use keyword arguments.'
% self._name)
def tool_decorator(f):
- if not hasattr(f, "_cp_config"):
+ if not hasattr(f, '_cp_config'):
f._cp_config = {}
- subspace = self.namespace + "." + self._name + "."
- f._cp_config[subspace + "on"] = True
+ subspace = self.namespace + '.' + self._name + '.'
+ f._cp_config[subspace + 'on'] = True
for k, v in kwargs.items():
f._cp_config[subspace + k] = v
return f
@@ -140,9 +146,9 @@ class Tool(object):
method when the tool is "turned on" in config.
"""
conf = self._merged_args()
- p = conf.pop("priority", None)
+ p = conf.pop('priority', None)
if p is None:
- p = getattr(self.callable, "priority", self._priority)
+ p = getattr(self.callable, 'priority', self._priority)
cherrypy.serving.request.hooks.attach(self._point, self.callable,
priority=p, **conf)
@@ -171,12 +177,12 @@ class HandlerTool(Tool):
nav = tools.staticdir.handler(section="/nav", dir="nav",
root=absDir)
"""
+ @expose
def handle_func(*a, **kw):
handled = self.callable(*args, **self._merged_args(kwargs))
if not handled:
raise cherrypy.NotFound()
return cherrypy.serving.response.body
- handle_func.exposed = True
return handle_func
def _wrapper(self, **kwargs):
@@ -190,9 +196,9 @@ class HandlerTool(Tool):
method when the tool is "turned on" in config.
"""
conf = self._merged_args()
- p = conf.pop("priority", None)
+ p = conf.pop('priority', None)
if p is None:
- p = getattr(self.callable, "priority", self._priority)
+ p = getattr(self.callable, 'priority', self._priority)
cherrypy.serving.request.hooks.attach(self._point, self._wrapper,
priority=p, **conf)
@@ -253,11 +259,6 @@ class ErrorTool(Tool):
# Builtin tools #
-from cherrypy.lib import cptools, encoding, auth, static, jsontools
-from cherrypy.lib import sessions as _sessions, xmlrpcutil as _xmlrpc
-from cherrypy.lib import caching as _caching
-from cherrypy.lib import auth_basic, auth_digest
-
class SessionTool(Tool):
@@ -295,9 +296,9 @@ class SessionTool(Tool):
conf = self._merged_args()
- p = conf.pop("priority", None)
+ p = conf.pop('priority', None)
if p is None:
- p = getattr(self.callable, "priority", self._priority)
+ p = getattr(self.callable, 'priority', self._priority)
hooks.attach(self._point, self.callable, priority=p, **conf)
@@ -321,9 +322,12 @@ class SessionTool(Tool):
sess.regenerate()
# Grab cookie-relevant tool args
- conf = dict([(k, v) for k, v in self._merged_args().items()
- if k in ('path', 'path_header', 'name', 'timeout',
- 'domain', 'secure')])
+ relevant = 'path', 'path_header', 'name', 'timeout', 'domain', 'secure'
+ conf = dict(
+ (k, v)
+ for k, v in self._merged_args().items()
+ if k in relevant
+ )
_sessions.set_response_cookie(**conf)
@@ -365,6 +369,7 @@ class XMLRPCController(object):
# would be if someone actually disabled the default_toolbox. Meh.
_cp_config = {'tools.xmlrpc.on': True}
+ @expose
def default(self, *vpath, **params):
rpcparams, rpcmethod = _xmlrpc.process_body()
@@ -372,7 +377,7 @@ class XMLRPCController(object):
for attr in str(rpcmethod).split('.'):
subhandler = getattr(subhandler, attr, None)
- if subhandler and getattr(subhandler, "exposed", False):
+ if subhandler and getattr(subhandler, 'exposed', False):
body = subhandler(*(vpath + rpcparams), **params)
else:
@@ -382,20 +387,15 @@ class XMLRPCController(object):
# cherrypy.lib.xmlrpcutil.on_error
raise Exception('method "%s" is not supported' % attr)
- conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {})
+ conf = cherrypy.serving.request.toolmaps['tools'].get('xmlrpc', {})
_xmlrpc.respond(body,
conf.get('encoding', 'utf-8'),
conf.get('allow_none', 0))
return cherrypy.serving.response.body
- default.exposed = True
class SessionAuthTool(HandlerTool):
-
- def _setargs(self):
- for name in dir(cptools.SessionAuth):
- if not name.startswith("__"):
- setattr(self, name, None)
+ pass
class CachingTool(Tool):
@@ -410,14 +410,14 @@ class CachingTool(Tool):
if request.cacheable:
# Note the devious technique here of adding hooks on the fly
request.hooks.attach('before_finalize', _caching.tee_output,
- priority=90)
- _wrapper.priority = 20
+ priority=100)
+ _wrapper.priority = 90
def _setup(self):
"""Hook caching into cherrypy.request."""
conf = self._merged_args()
- p = conf.pop("priority", None)
+ p = conf.pop('priority', None)
cherrypy.serving.request.hooks.attach('before_handler', self._wrapper,
priority=p, **conf)
@@ -446,7 +446,7 @@ class Toolbox(object):
cherrypy.serving.request.toolmaps[self.namespace] = map = {}
def populate(k, v):
- toolname, arg = k.split(".", 1)
+ toolname, arg = k.split('.', 1)
bucket = map.setdefault(toolname, {})
bucket[arg] = v
return populate
@@ -456,15 +456,27 @@ class Toolbox(object):
map = cherrypy.serving.request.toolmaps.get(self.namespace)
if map:
for name, settings in map.items():
- if settings.get("on", False):
+ if settings.get('on', False):
tool = getattr(self, name)
tool._setup()
+ def register(self, point, **kwargs):
+ """
+ Return a decorator which registers the function
+ at the given hook point.
+ """
+ def decorator(func):
+ attr_name = kwargs.get('name', func.__name__)
+ tool = Tool(point, func, **kwargs)
+ setattr(self, attr_name, tool)
+ return func
+ return decorator
+
class DeprecatedTool(Tool):
_name = None
- warnmsg = "This Tool is deprecated."
+ warnmsg = 'This Tool is deprecated.'
def __init__(self, point, warnmsg=None):
self.point = point
@@ -482,7 +494,7 @@ class DeprecatedTool(Tool):
warnings.warn(self.warnmsg)
-default_toolbox = _d = Toolbox("tools")
+default_toolbox = _d = Toolbox('tools')
_d.session_auth = SessionAuthTool(cptools.session_auth)
_d.allow = Tool('on_start_resource', cptools.allow)
_d.proxy = Tool('before_request_body', cptools.proxy, priority=30)
@@ -504,14 +516,14 @@ _d.caching = CachingTool('before_handler', _caching.get, 'caching')
_d.expires = Tool('before_finalize', _caching.expires)
_d.tidy = DeprecatedTool(
'before_finalize',
- "The tidy tool has been removed from the standard distribution of "
- "CherryPy. The most recent version can be found at "
- "http://tools.cherrypy.org/browser.")
+ 'The tidy tool has been removed from the standard distribution of '
+ 'CherryPy. The most recent version can be found at '
+ 'http://tools.cherrypy.org/browser.')
_d.nsgmls = DeprecatedTool(
'before_finalize',
- "The nsgmls tool has been removed from the standard distribution of "
- "CherryPy. The most recent version can be found at "
- "http://tools.cherrypy.org/browser.")
+ 'The nsgmls tool has been removed from the standard distribution of '
+ 'CherryPy. The most recent version can be found at '
+ 'http://tools.cherrypy.org/browser.')
_d.ignore_headers = Tool('before_request_body', cptools.ignore_headers)
_d.referer = Tool('before_request_body', cptools.referer)
_d.basic_auth = Tool('on_start_resource', auth.basic_auth)
@@ -525,5 +537,6 @@ _d.json_in = Tool('before_request_body', jsontools.json_in, priority=30)
_d.json_out = Tool('before_handler', jsontools.json_out, priority=30)
_d.auth_basic = Tool('before_handler', auth_basic.basic_auth, priority=1)
_d.auth_digest = Tool('before_handler', auth_digest.digest_auth, priority=1)
+_d.params = Tool('before_handler', cptools.convert_params)
del _d, cptools, encoding, auth, static
diff --git a/cherrypy/_cptree.py b/cherrypy/_cptree.py
index a31b2793..22d826b4 100644
--- a/cherrypy/_cptree.py
+++ b/cherrypy/_cptree.py
@@ -2,14 +2,15 @@
import os
+import six
+
import cherrypy
-from cherrypy._cpcompat import ntou, py3k
+from cherrypy._cpcompat import ntou
from cherrypy import _cpconfig, _cplogging, _cprequest, _cpwsgi, tools
-from cherrypy.lib import httputil
+from cherrypy.lib import httputil, reprconf
class Application(object):
-
"""A CherryPy Application.
Servers and gateways should not instantiate Request objects directly.
@@ -30,7 +31,7 @@ class Application(object):
"""A dict of {path: pathconf} pairs, where 'pathconf' is itself a dict
of {key: value} pairs."""
- namespaces = _cpconfig.NamespaceSet()
+ namespaces = reprconf.NamespaceSet()
toolboxes = {'tools': cherrypy.tools}
log = None
@@ -44,22 +45,24 @@ class Application(object):
relative_urls = False
- def __init__(self, root, script_name="", config=None):
+ def __init__(self, root, script_name='', config=None):
+ """Initialize Application with given root."""
self.log = _cplogging.LogManager(id(self), cherrypy.log.logger_root)
self.root = root
self.script_name = script_name
self.wsgiapp = _cpwsgi.CPWSGIApp(self)
self.namespaces = self.namespaces.copy()
- self.namespaces["log"] = lambda k, v: setattr(self.log, k, v)
- self.namespaces["wsgi"] = self.wsgiapp.namespace_handler
+ self.namespaces['log'] = lambda k, v: setattr(self.log, k, v)
+ self.namespaces['wsgi'] = self.wsgiapp.namespace_handler
self.config = self.__class__.config.copy()
if config:
self.merge(config)
def __repr__(self):
- return "%s.%s(%r, %r)" % (self.__module__, self.__class__.__name__,
+ """Generate a representation of the Application instance."""
+ return '%s.%s(%r, %r)' % (self.__module__, self.__class__.__name__,
self.root, self.script_name)
script_name_doc = """The URI "mount point" for this app. A mount point
@@ -84,11 +87,11 @@ class Application(object):
# A `_script_name` with a value of None signals that the script name
# should be pulled from WSGI environ.
- return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip("/")
+ return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip('/')
def _set_script_name(self, value):
if value:
- value = value.rstrip("/")
+ value = value.rstrip('/')
self._script_name = value
script_name = property(fget=_get_script_name, fset=_set_script_name,
doc=script_name_doc)
@@ -98,22 +101,22 @@ class Application(object):
_cpconfig.merge(self.config, config)
# Handle namespaces specified in config.
- self.namespaces(self.config.get("/", {}))
+ self.namespaces(self.config.get('/', {}))
def find_config(self, path, key, default=None):
"""Return the most-specific value for key along path, or default."""
- trail = path or "/"
+ trail = path or '/'
while trail:
nodeconf = self.config.get(trail, {})
if key in nodeconf:
return nodeconf[key]
- lastslash = trail.rfind("/")
+ lastslash = trail.rfind('/')
if lastslash == -1:
break
- elif lastslash == 0 and trail != "/":
- trail = "/"
+ elif lastslash == 0 and trail != '/':
+ trail = '/'
else:
trail = trail[:lastslash]
@@ -142,17 +145,17 @@ class Application(object):
try:
req.close()
- except:
+ except Exception:
cherrypy.log(traceback=True, severity=40)
cherrypy.serving.clear()
def __call__(self, environ, start_response):
+ """Call a WSGI-callable."""
return self.wsgiapp(environ, start_response)
class Tree(object):
-
"""A registry of CherryPy applications, mounted at diverse points.
An instance of this class may also be used as a WSGI callable
@@ -168,9 +171,10 @@ class Tree(object):
WSGI callable if you happen to be using a WSGI server)."""
def __init__(self):
+ """Initialize registry Tree."""
self.apps = {}
- def mount(self, root, script_name="", config=None):
+ def mount(self, root, script_name='', config=None):
"""Mount a new app from a root object, script_name, and config.
root
@@ -195,29 +199,36 @@ class Tree(object):
if script_name is None:
raise TypeError(
"The 'script_name' argument may not be None. Application "
- "objects may, however, possess a script_name of None (in "
- "order to inpect the WSGI environ for SCRIPT_NAME upon each "
- "request). You cannot mount such Applications on this Tree; "
- "you must pass them to a WSGI server interface directly.")
+ 'objects may, however, possess a script_name of None (in '
+ 'order to inpect the WSGI environ for SCRIPT_NAME upon each '
+ 'request). You cannot mount such Applications on this Tree; '
+ 'you must pass them to a WSGI server interface directly.')
# Next line both 1) strips trailing slash and 2) maps "/" -> "".
- script_name = script_name.rstrip("/")
+ script_name = script_name.rstrip('/')
if isinstance(root, Application):
app = root
- if script_name != "" and script_name != app.script_name:
+ if script_name != '' and script_name != app.script_name:
raise ValueError(
- "Cannot specify a different script name and pass an "
- "Application instance to cherrypy.mount")
+ 'Cannot specify a different script name and pass an '
+ 'Application instance to cherrypy.mount')
script_name = app.script_name
else:
app = Application(root, script_name)
# If mounted at "", add favicon.ico
- if (script_name == "" and root is not None
- and not hasattr(root, "favicon_ico")):
- favicon = os.path.join(os.getcwd(), os.path.dirname(__file__),
- "favicon.ico")
+ needs_favicon = (
+ script_name == ''
+ and root is not None
+ and not hasattr(root, 'favicon_ico')
+ )
+ if needs_favicon:
+ favicon = os.path.join(
+ os.getcwd(),
+ os.path.dirname(__file__),
+ 'favicon.ico',
+ )
root.favicon_ico = tools.staticfile.handler(favicon)
if config:
@@ -227,10 +238,10 @@ class Tree(object):
return app
- def graft(self, wsgi_callable, script_name=""):
+ def graft(self, wsgi_callable, script_name=''):
"""Mount a wsgi callable at the given script_name."""
# Next line both 1) strips trailing slash and 2) maps "/" -> "".
- script_name = script_name.rstrip("/")
+ script_name = script_name.rstrip('/')
self.apps[script_name] = wsgi_callable
def script_name(self, path=None):
@@ -250,22 +261,23 @@ class Tree(object):
if path in self.apps:
return path
- if path == "":
+ if path == '':
return None
# Move one node up the tree and try again.
- path = path[:path.rfind("/")]
+ path = path[:path.rfind('/')]
def __call__(self, environ, start_response):
+ """Pre-initialize WSGI env and call WSGI-callable."""
# If you're calling this, then you're probably setting SCRIPT_NAME
# to '' (some WSGI servers always set SCRIPT_NAME to '').
# Try to look up the app using the full path.
env1x = environ
- if environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
+ if six.PY2 and environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
env1x = _cpwsgi.downgrade_wsgi_ux_to_1x(environ)
path = httputil.urljoin(env1x.get('SCRIPT_NAME', ''),
env1x.get('PATH_INFO', ''))
- sn = self.script_name(path or "/")
+ sn = self.script_name(path or '/')
if sn is None:
start_response('404 Not Found', [])
return []
@@ -274,26 +286,12 @@ class Tree(object):
# Correct the SCRIPT_NAME and PATH_INFO environ entries.
environ = environ.copy()
- if not py3k:
- if environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
- # Python 2/WSGI u.0: all strings MUST be of type unicode
- enc = environ[ntou('wsgi.url_encoding')]
- environ[ntou('SCRIPT_NAME')] = sn.decode(enc)
- environ[ntou('PATH_INFO')] = path[
- len(sn.rstrip("/")):].decode(enc)
- else:
- # Python 2/WSGI 1.x: all strings MUST be of type str
- environ['SCRIPT_NAME'] = sn
- environ['PATH_INFO'] = path[len(sn.rstrip("/")):]
+ if six.PY2 and environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
+ # Python 2/WSGI u.0: all strings MUST be of type unicode
+ enc = environ[ntou('wsgi.url_encoding')]
+ environ[ntou('SCRIPT_NAME')] = sn.decode(enc)
+ environ[ntou('PATH_INFO')] = path[len(sn.rstrip('/')):].decode(enc)
else:
- if environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
- # Python 3/WSGI u.0: all strings MUST be full unicode
- environ['SCRIPT_NAME'] = sn
- environ['PATH_INFO'] = path[len(sn.rstrip("/")):]
- else:
- # Python 3/WSGI 1.x: all strings MUST be ISO-8859-1 str
- environ['SCRIPT_NAME'] = sn.encode(
- 'utf-8').decode('ISO-8859-1')
- environ['PATH_INFO'] = path[
- len(sn.rstrip("/")):].encode('utf-8').decode('ISO-8859-1')
+ environ['SCRIPT_NAME'] = sn
+ environ['PATH_INFO'] = path[len(sn.rstrip('/')):]
return app(environ, start_response)
diff --git a/cherrypy/_cpwsgi.py b/cherrypy/_cpwsgi.py
index a8068fb0..a9c9083b 100644
--- a/cherrypy/_cpwsgi.py
+++ b/cherrypy/_cpwsgi.py
@@ -8,13 +8,17 @@ still be translatable to bytes via the Latin-1 encoding!"
"""
import sys as _sys
+import io
+
+import six
import cherrypy as _cherrypy
-from cherrypy._cpcompat import BytesIO, bytestr, ntob, ntou, py3k, unicodestr
+from cherrypy._cpcompat import ntob, ntou
from cherrypy import _cperror
from cherrypy.lib import httputil
from cherrypy.lib import is_closable_iterator
+
def downgrade_wsgi_ux_to_1x(environ):
"""Return a new environ dict for WSGI 1.x from the given WSGI u.x environ.
"""
@@ -24,7 +28,7 @@ def downgrade_wsgi_ux_to_1x(environ):
for k, v in list(environ.items()):
if k in [ntou('PATH_INFO'), ntou('SCRIPT_NAME'), ntou('QUERY_STRING')]:
v = v.encode(url_encoding)
- elif isinstance(v, unicodestr):
+ elif isinstance(v, six.text_type):
v = v.encode('ISO-8859-1')
env1x[k.encode('ISO-8859-1')] = v
@@ -43,10 +47,13 @@ class VirtualHost(object):
Domain2App = cherrypy.Application(root)
SecureApp = cherrypy.Application(Secure())
- vhost = cherrypy._cpwsgi.VirtualHost(RootApp,
- domains={'www.domain2.example': Domain2App,
- 'www.domain2.example:443': SecureApp,
- })
+ vhost = cherrypy._cpwsgi.VirtualHost(
+ RootApp,
+ domains={
+ 'www.domain2.example': Domain2App,
+ 'www.domain2.example:443': SecureApp,
+ },
+ )
cherrypy.tree.graft(vhost)
"""
@@ -75,7 +82,7 @@ class VirtualHost(object):
def __call__(self, environ, start_response):
domain = environ.get('HTTP_HOST', '')
if self.use_x_forwarded_host:
- domain = environ.get("HTTP_X_FORWARDED_HOST", domain)
+ domain = environ.get('HTTP_X_FORWARDED_HOST', domain)
nextapp = self.domains.get(domain)
if nextapp is None:
@@ -106,7 +113,7 @@ class InternalRedirector(object):
# Add the *previous* path_info + qs to redirections.
old_uri = sn + path
if qs:
- old_uri += "?" + qs
+ old_uri += '?' + qs
redirections.append(old_uri)
if not self.recursive:
@@ -114,18 +121,20 @@ class InternalRedirector(object):
# already
new_uri = sn + ir.path
if ir.query_string:
- new_uri += "?" + ir.query_string
+ new_uri += '?' + ir.query_string
if new_uri in redirections:
ir.request.close()
- raise RuntimeError("InternalRedirector visited the "
- "same URL twice: %r" % new_uri)
+ tmpl = (
+ 'InternalRedirector visited the same URL twice: %r'
+ )
+ raise RuntimeError(tmpl % new_uri)
# Munge the environment and try again.
- environ['REQUEST_METHOD'] = "GET"
+ environ['REQUEST_METHOD'] = 'GET'
environ['PATH_INFO'] = ir.path
environ['QUERY_STRING'] = ir.query_string
- environ['wsgi.input'] = BytesIO()
- environ['CONTENT_LENGTH'] = "0"
+ environ['wsgi.input'] = io.BytesIO()
+ environ['CONTENT_LENGTH'] = '0'
environ['cherrypy.previous_request'] = ir.request
@@ -157,19 +166,20 @@ class _TrappedResponse(object):
self.throws = throws
self.started_response = False
self.response = self.trap(
- self.nextapp, self.environ, self.start_response)
+ self.nextapp, self.environ, self.start_response,
+ )
self.iter_response = iter(self.response)
def __iter__(self):
self.started_response = True
return self
- if py3k:
- def __next__(self):
- return self.trap(next, self.iter_response)
- else:
- def next(self):
- return self.trap(self.iter_response.next)
+ def __next__(self):
+ return self.trap(next, self.iter_response)
+
+ # todo: https://pythonhosted.org/six/#six.Iterator
+ if six.PY2:
+ next = __next__
def close(self):
if hasattr(self.response, 'close'):
@@ -182,18 +192,19 @@ class _TrappedResponse(object):
raise
except StopIteration:
raise
- except:
+ except Exception:
tb = _cperror.format_exc()
- #print('trapped (started %s):' % self.started_response, tb)
_cherrypy.log(tb, severity=40)
if not _cherrypy.request.show_tracebacks:
- tb = ""
+ tb = ''
s, h, b = _cperror.bare_error(tb)
- if py3k:
+ if six.PY3:
# What fun.
s = s.decode('ISO-8859-1')
- h = [(k.decode('ISO-8859-1'), v.decode('ISO-8859-1'))
- for k, v in h]
+ h = [
+ (k.decode('ISO-8859-1'), v.decode('ISO-8859-1'))
+ for k, v in h
+ ]
if self.started_response:
# Empty our iterable (so future calls raise StopIteration)
self.iter_response = iter([])
@@ -202,7 +213,7 @@ class _TrappedResponse(object):
try:
self.start_response(s, h, _sys.exc_info())
- except:
+ except Exception:
# "The application must not trap any exceptions raised by
# start_response, if it called start_response with exc_info.
# Instead, it should allow such exceptions to propagate
@@ -212,7 +223,7 @@ class _TrappedResponse(object):
raise
if self.started_response:
- return ntob("").join(b)
+ return ntob('').join(b)
else:
return b
@@ -227,7 +238,7 @@ class AppResponse(object):
def __init__(self, environ, start_response, cpapp):
self.cpapp = cpapp
try:
- if not py3k:
+ if six.PY2:
if environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
environ = downgrade_wsgi_ux_to_1x(environ)
self.environ = environ
@@ -236,45 +247,47 @@ class AppResponse(object):
r = _cherrypy.serving.response
outstatus = r.output_status
- if not isinstance(outstatus, bytestr):
- raise TypeError("response.output_status is not a byte string.")
+ if not isinstance(outstatus, bytes):
+ raise TypeError('response.output_status is not a byte string.')
outheaders = []
for k, v in r.header_list:
- if not isinstance(k, bytestr):
- raise TypeError(
- "response.header_list key %r is not a byte string." %
- k)
- if not isinstance(v, bytestr):
- raise TypeError(
- "response.header_list value %r is not a byte string." %
- v)
+ if not isinstance(k, bytes):
+ tmpl = 'response.header_list key %r is not a byte string.'
+ raise TypeError(tmpl % k)
+ if not isinstance(v, bytes):
+ tmpl = (
+ 'response.header_list value %r is not a byte string.'
+ )
+ raise TypeError(tmpl % v)
outheaders.append((k, v))
- if py3k:
+ if six.PY3:
# According to PEP 3333, when using Python 3, the response
# status and headers must be bytes masquerading as unicode;
# that is, they must be of type "str" but are restricted to
# code points in the "latin-1" set.
outstatus = outstatus.decode('ISO-8859-1')
- outheaders = [(k.decode('ISO-8859-1'), v.decode('ISO-8859-1'))
- for k, v in outheaders]
+ outheaders = [
+ (k.decode('ISO-8859-1'), v.decode('ISO-8859-1'))
+ for k, v in outheaders
+ ]
self.iter_response = iter(r.body)
self.write = start_response(outstatus, outheaders)
- except:
+ except BaseException:
self.close()
raise
def __iter__(self):
return self
- if py3k:
- def __next__(self):
- return next(self.iter_response)
- else:
- def next(self):
- return self.iter_response.next()
+ def __next__(self):
+ return next(self.iter_response)
+
+ # todo: https://pythonhosted.org/six/#six.Iterator
+ if six.PY2:
+ next = __next__
def close(self):
"""Close and de-reference the current request and response. (Core)"""
@@ -296,14 +309,18 @@ class AppResponse(object):
"""Create a Request object using environ."""
env = self.environ.get
- local = httputil.Host('',
- int(env('SERVER_PORT', 80) or -1),
- env('SERVER_NAME', ''))
- remote = httputil.Host(env('REMOTE_ADDR', ''),
- int(env('REMOTE_PORT', -1) or -1),
- env('REMOTE_HOST', ''))
+ local = httputil.Host(
+ '',
+ int(env('SERVER_PORT', 80) or -1),
+ env('SERVER_NAME', ''),
+ )
+ remote = httputil.Host(
+ env('REMOTE_ADDR', ''),
+ int(env('REMOTE_PORT', -1) or -1),
+ env('REMOTE_HOST', ''),
+ )
scheme = env('wsgi.url_scheme')
- sproto = env('ACTUAL_SERVER_PROTOCOL', "HTTP/1.1")
+ sproto = env('ACTUAL_SERVER_PROTOCOL', 'HTTP/1.1')
request, resp = self.cpapp.get_serving(local, remote, scheme, sproto)
# LOGON_USER is served by IIS, and is the name of the
@@ -317,44 +334,54 @@ class AppResponse(object):
meth = self.environ['REQUEST_METHOD']
- path = httputil.urljoin(self.environ.get('SCRIPT_NAME', ''),
- self.environ.get('PATH_INFO', ''))
+ path = httputil.urljoin(
+ self.environ.get('SCRIPT_NAME', ''),
+ self.environ.get('PATH_INFO', ''),
+ )
qs = self.environ.get('QUERY_STRING', '')
- if py3k:
- # This isn't perfect; if the given PATH_INFO is in the
- # wrong encoding, it may fail to match the appropriate config
- # section URI. But meh.
- old_enc = self.environ.get('wsgi.url_encoding', 'ISO-8859-1')
- new_enc = self.cpapp.find_config(self.environ.get('PATH_INFO', ''),
- "request.uri_encoding", 'utf-8')
- if new_enc.lower() != old_enc.lower():
- # Even though the path and qs are unicode, the WSGI server
- # is required by PEP 3333 to coerce them to ISO-8859-1
- # masquerading as unicode. So we have to encode back to
- # bytes and then decode again using the "correct" encoding.
- try:
- u_path = path.encode(old_enc).decode(new_enc)
- u_qs = qs.encode(old_enc).decode(new_enc)
- except (UnicodeEncodeError, UnicodeDecodeError):
- # Just pass them through without transcoding and hope.
- pass
- else:
- # Only set transcoded values if they both succeed.
- path = u_path
- qs = u_qs
+ path, qs = self.recode_path_qs(path, qs) or (path, qs)
rproto = self.environ.get('SERVER_PROTOCOL')
headers = self.translate_headers(self.environ)
rfile = self.environ['wsgi.input']
request.run(meth, path, qs, rproto, headers, rfile)
- headerNames = {'HTTP_CGI_AUTHORIZATION': 'Authorization',
- 'CONTENT_LENGTH': 'Content-Length',
- 'CONTENT_TYPE': 'Content-Type',
- 'REMOTE_HOST': 'Remote-Host',
- 'REMOTE_ADDR': 'Remote-Addr',
- }
+ headerNames = {
+ 'HTTP_CGI_AUTHORIZATION': 'Authorization',
+ 'CONTENT_LENGTH': 'Content-Length',
+ 'CONTENT_TYPE': 'Content-Type',
+ 'REMOTE_HOST': 'Remote-Host',
+ 'REMOTE_ADDR': 'Remote-Addr',
+ }
+
+ def recode_path_qs(self, path, qs):
+ if not six.PY3:
+ return
+
+ # This isn't perfect; if the given PATH_INFO is in the
+ # wrong encoding, it may fail to match the appropriate config
+ # section URI. But meh.
+ old_enc = self.environ.get('wsgi.url_encoding', 'ISO-8859-1')
+ new_enc = self.cpapp.find_config(
+ self.environ.get('PATH_INFO', ''),
+ 'request.uri_encoding', 'utf-8',
+ )
+ if new_enc.lower() == old_enc.lower():
+ return
+
+ # Even though the path and qs are unicode, the WSGI server
+ # is required by PEP 3333 to coerce them to ISO-8859-1
+ # masquerading as unicode. So we have to encode back to
+ # bytes and then decode again using the "correct" encoding.
+ try:
+ return (
+ path.encode(old_enc).decode(new_enc),
+ qs.encode(old_enc).decode(new_enc),
+ )
+ except (UnicodeEncodeError, UnicodeDecodeError):
+ # Just pass them through without transcoding and hope.
+ pass
def translate_headers(self, environ):
"""Translate CGI-environ header names to HTTP header names."""
@@ -362,9 +389,9 @@ class AppResponse(object):
# We assume all incoming header keys are uppercase already.
if cgiName in self.headerNames:
yield self.headerNames[cgiName], environ[cgiName]
- elif cgiName[:5] == "HTTP_":
+ elif cgiName[:5] == 'HTTP_':
# Hackish attempt at recovering original header names.
- translatedHeader = cgiName[5:].replace("_", "-")
+ translatedHeader = cgiName[5:].replace('_', '-')
yield translatedHeader, environ[cgiName]
@@ -372,9 +399,10 @@ class CPWSGIApp(object):
"""A WSGI application object for a CherryPy Application."""
- pipeline = [('ExceptionTrapper', ExceptionTrapper),
- ('InternalRedirector', InternalRedirector),
- ]
+ pipeline = [
+ ('ExceptionTrapper', ExceptionTrapper),
+ ('InternalRedirector', InternalRedirector),
+ ]
"""A list of (name, wsgiapp) pairs. Each 'wsgiapp' MUST be a
constructor that takes an initial, positional 'nextapp' argument,
plus optional keyword arguments, and returns a WSGI application
@@ -424,16 +452,16 @@ class CPWSGIApp(object):
def namespace_handler(self, k, v):
"""Config handler for the 'wsgi' namespace."""
- if k == "pipeline":
+ if k == 'pipeline':
# Note this allows multiple 'wsgi.pipeline' config entries
# (but each entry will be processed in a 'random' order).
# It should also allow developers to set default middleware
# in code (passed to self.__init__) that deployers can add to
# (but not remove) via config.
self.pipeline.extend(v)
- elif k == "response_class":
+ elif k == 'response_class':
self.response_class = v
else:
- name, arg = k.split(".", 1)
+ name, arg = k.split('.', 1)
bucket = self.config.setdefault(name, {})
bucket[arg] = v
diff --git a/cherrypy/_cpwsgi_server.py b/cherrypy/_cpwsgi_server.py
index 874e2e9f..ac9d93f6 100644
--- a/cherrypy/_cpwsgi_server.py
+++ b/cherrypy/_cpwsgi_server.py
@@ -1,23 +1,55 @@
-"""WSGI server interface (see PEP 333). This adds some CP-specific bits to
-the framework-agnostic wsgiserver package.
+"""
+WSGI server interface (see PEP 333).
+
+This adds some CP-specific bits to the framework-agnostic cheroot package.
"""
import sys
+import cheroot.wsgi
+import cheroot.server
+
import cherrypy
-from cherrypy import wsgiserver
-class CPWSGIServer(wsgiserver.CherryPyWSGIServer):
+class CPWSGIHTTPRequest(cheroot.server.HTTPRequest):
+ """Wrapper for cheroot.server.HTTPRequest.
+
+ This is a layer, which preserves URI parsing mode like it which was
+ before Cheroot v5.8.0.
+ """
+
+ def __init__(self, server, conn):
+ """Initialize HTTP request container instance.
+
+ Args:
+ server (cheroot.server.HTTPServer):
+ web server object receiving this request
+ conn (cheroot.server.HTTPConnection):
+ HTTP connection object for this request
+ """
+ super(CPWSGIHTTPRequest, self).__init__(
+ server, conn, proxy_mode=True
+ )
+
- """Wrapper for wsgiserver.CherryPyWSGIServer.
+class CPWSGIServer(cheroot.wsgi.Server):
+ """Wrapper for cheroot.wsgi.Server.
- wsgiserver has been designed to not reference CherryPy in any way,
+ cheroot has been designed to not reference CherryPy in any way,
so that it can be used in other frameworks and applications. Therefore,
we wrap it here, so we can set our own mount points from cherrypy.tree
- and apply some attributes from config -> cherrypy.server -> wsgiserver.
+ and apply some attributes from config -> cherrypy.server -> wsgi.Server.
"""
+ fmt = 'CherryPy/{cherrypy.__version__} {cheroot.wsgi.Server.version}'
+ version = fmt.format(**globals())
+
def __init__(self, server_adapter=cherrypy.server):
+ """Initialize CPWSGIServer instance.
+
+ Args:
+ server_adapter (cherrypy._cpserver.Server): ...
+ """
self.server_adapter = server_adapter
self.max_request_header_size = (
self.server_adapter.max_request_header_size or 0
@@ -31,17 +63,20 @@ class CPWSGIServer(wsgiserver.CherryPyWSGIServer):
None)
self.wsgi_version = self.server_adapter.wsgi_version
- s = wsgiserver.CherryPyWSGIServer
- s.__init__(self, server_adapter.bind_addr, cherrypy.tree,
- self.server_adapter.thread_pool,
- server_name,
- max=self.server_adapter.thread_pool_max,
- request_queue_size=self.server_adapter.socket_queue_size,
- timeout=self.server_adapter.socket_timeout,
- shutdown_timeout=self.server_adapter.shutdown_timeout,
- accepted_queue_size=self.server_adapter.accepted_queue_size,
- accepted_queue_timeout=self.server_adapter.accepted_queue_timeout,
- )
+
+ super(CPWSGIServer, self).__init__(
+ server_adapter.bind_addr, cherrypy.tree,
+ self.server_adapter.thread_pool,
+ server_name,
+ max=self.server_adapter.thread_pool_max,
+ request_queue_size=self.server_adapter.socket_queue_size,
+ timeout=self.server_adapter.socket_timeout,
+ shutdown_timeout=self.server_adapter.shutdown_timeout,
+ accepted_queue_size=self.server_adapter.accepted_queue_size,
+ accepted_queue_timeout=self.server_adapter.accepted_queue_timeout,
+ )
+ self.ConnectionClass.RequestHandlerClass = CPWSGIHTTPRequest
+
self.protocol = self.server_adapter.protocol_version
self.nodelay = self.server_adapter.nodelay
@@ -50,21 +85,24 @@ class CPWSGIServer(wsgiserver.CherryPyWSGIServer):
else:
ssl_module = self.server_adapter.ssl_module or 'pyopenssl'
if self.server_adapter.ssl_context:
- adapter_class = wsgiserver.get_ssl_adapter_class(ssl_module)
+ adapter_class = cheroot.server.get_ssl_adapter_class(ssl_module)
self.ssl_adapter = adapter_class(
self.server_adapter.ssl_certificate,
self.server_adapter.ssl_private_key,
- self.server_adapter.ssl_certificate_chain)
+ self.server_adapter.ssl_certificate_chain,
+ self.server_adapter.ssl_ciphers)
self.ssl_adapter.context = self.server_adapter.ssl_context
elif self.server_adapter.ssl_certificate:
- adapter_class = wsgiserver.get_ssl_adapter_class(ssl_module)
+ adapter_class = cheroot.server.get_ssl_adapter_class(ssl_module)
self.ssl_adapter = adapter_class(
self.server_adapter.ssl_certificate,
self.server_adapter.ssl_private_key,
- self.server_adapter.ssl_certificate_chain)
+ self.server_adapter.ssl_certificate_chain,
+ self.server_adapter.ssl_ciphers)
self.stats['Enabled'] = getattr(
self.server_adapter, 'statistics', False)
- def error_log(self, msg="", level=20, traceback=False):
+ def error_log(self, msg='', level=20, traceback=False):
+ """Write given message to the error log."""
cherrypy.engine.log(msg, level, traceback)
diff --git a/cherrypy/_helper.py b/cherrypy/_helper.py
new file mode 100644
index 00000000..a0ab68fe
--- /dev/null
+++ b/cherrypy/_helper.py
@@ -0,0 +1,341 @@
+"""Helper functions for CP apps."""
+
+import six
+from six.moves import urllib
+
+from cherrypy._cpcompat import text_or_bytes
+
+import cherrypy
+
+
+def expose(func=None, alias=None):
+ """Expose the function or class.
+
+ Optionally provide an alias or set of aliases.
+ """
+ def expose_(func):
+ func.exposed = True
+ if alias is not None:
+ if isinstance(alias, text_or_bytes):
+ parents[alias.replace('.', '_')] = func
+ else:
+ for a in alias:
+ parents[a.replace('.', '_')] = func
+ return func
+
+ import sys
+ import types
+ decoratable_types = types.FunctionType, types.MethodType, type,
+ if six.PY2:
+ # Old-style classes are type types.ClassType.
+ decoratable_types += types.ClassType,
+ if isinstance(func, decoratable_types):
+ if alias is None:
+ # @expose
+ func.exposed = True
+ return func
+ else:
+ # func = expose(func, alias)
+ parents = sys._getframe(1).f_locals
+ return expose_(func)
+ elif func is None:
+ if alias is None:
+ # @expose()
+ parents = sys._getframe(1).f_locals
+ return expose_
+ else:
+ # @expose(alias="alias") or
+ # @expose(alias=["alias1", "alias2"])
+ parents = sys._getframe(1).f_locals
+ return expose_
+ else:
+ # @expose("alias") or
+ # @expose(["alias1", "alias2"])
+ parents = sys._getframe(1).f_locals
+ alias = func
+ return expose_
+
+
+def popargs(*args, **kwargs):
+ """A decorator for _cp_dispatch.
+
+ (cherrypy.dispatch.Dispatcher.dispatch_method_name)
+
+ Optional keyword argument: handler=(Object or Function)
+
+ Provides a _cp_dispatch function that pops off path segments into
+ cherrypy.request.params under the names specified. The dispatch
+ is then forwarded on to the next vpath element.
+
+ Note that any existing (and exposed) member function of the class that
+ popargs is applied to will override that value of the argument. For
+ instance, if you have a method named "list" on the class decorated with
+ popargs, then accessing "/list" will call that function instead of popping
+ it off as the requested parameter. This restriction applies to all
+ _cp_dispatch functions. The only way around this restriction is to create
+ a "blank class" whose only function is to provide _cp_dispatch.
+
+ If there are path elements after the arguments, or more arguments
+ are requested than are available in the vpath, then the 'handler'
+ keyword argument specifies the next object to handle the parameterized
+ request. If handler is not specified or is None, then self is used.
+ If handler is a function rather than an instance, then that function
+ will be called with the args specified and the return value from that
+ function used as the next object INSTEAD of adding the parameters to
+ cherrypy.request.args.
+
+ This decorator may be used in one of two ways:
+
+ As a class decorator:
+ @cherrypy.popargs('year', 'month', 'day')
+ class Blog:
+ def index(self, year=None, month=None, day=None):
+ #Process the parameters here; any url like
+ #/, /2009, /2009/12, or /2009/12/31
+ #will fill in the appropriate parameters.
+
+ def create(self):
+ #This link will still be available at /create. Defined functions
+ #take precedence over arguments.
+
+ Or as a member of a class:
+ class Blog:
+ _cp_dispatch = cherrypy.popargs('year', 'month', 'day')
+ #...
+
+ The handler argument may be used to mix arguments with built in functions.
+ For instance, the following setup allows different activities at the
+ day, month, and year level:
+
+ class DayHandler:
+ def index(self, year, month, day):
+ #Do something with this day; probably list entries
+
+ def delete(self, year, month, day):
+ #Delete all entries for this day
+
+ @cherrypy.popargs('day', handler=DayHandler())
+ class MonthHandler:
+ def index(self, year, month):
+ #Do something with this month; probably list entries
+
+ def delete(self, year, month):
+ #Delete all entries for this month
+
+ @cherrypy.popargs('month', handler=MonthHandler())
+ class YearHandler:
+ def index(self, year):
+ #Do something with this year
+
+ #...
+
+ @cherrypy.popargs('year', handler=YearHandler())
+ class Root:
+ def index(self):
+ #...
+
+ """
+ # Since keyword arg comes after *args, we have to process it ourselves
+ # for lower versions of python.
+
+ handler = None
+ handler_call = False
+ for k, v in kwargs.items():
+ if k == 'handler':
+ handler = v
+ else:
+ tm = "cherrypy.popargs() got an unexpected keyword argument '{0}'"
+ raise TypeError(tm.format(k))
+
+ import inspect
+
+ if handler is not None \
+ and (hasattr(handler, '__call__') or inspect.isclass(handler)):
+ handler_call = True
+
+ def decorated(cls_or_self=None, vpath=None):
+ if inspect.isclass(cls_or_self):
+ # cherrypy.popargs is a class decorator
+ cls = cls_or_self
+ name = cherrypy.dispatch.Dispatcher.dispatch_method_name
+ setattr(cls, name, decorated)
+ return cls
+
+ # We're in the actual function
+ self = cls_or_self
+ parms = {}
+ for arg in args:
+ if not vpath:
+ break
+ parms[arg] = vpath.pop(0)
+
+ if handler is not None:
+ if handler_call:
+ return handler(**parms)
+ else:
+ cherrypy.request.params.update(parms)
+ return handler
+
+ cherrypy.request.params.update(parms)
+
+ # If we are the ultimate handler, then to prevent our _cp_dispatch
+ # from being called again, we will resolve remaining elements through
+ # getattr() directly.
+ if vpath:
+ return getattr(self, vpath.pop(0), None)
+ else:
+ return self
+
+ return decorated
+
+
+def url(path='', qs='', script_name=None, base=None, relative=None):
+ """Create an absolute URL for the given path.
+
+ If 'path' starts with a slash ('/'), this will return
+ (base + script_name + path + qs).
+ If it does not start with a slash, this returns
+ (base + script_name [+ request.path_info] + path + qs).
+
+ If script_name is None, cherrypy.request will be used
+ to find a script_name, if available.
+
+ If base is None, cherrypy.request.base will be used (if available).
+ Note that you can use cherrypy.tools.proxy to change this.
+
+ Finally, note that this function can be used to obtain an absolute URL
+ for the current request path (minus the querystring) by passing no args.
+ If you call url(qs=cherrypy.request.query_string), you should get the
+ original browser URL (assuming no internal redirections).
+
+ If relative is None or not provided, request.app.relative_urls will
+ be used (if available, else False). If False, the output will be an
+ absolute URL (including the scheme, host, vhost, and script_name).
+ If True, the output will instead be a URL that is relative to the
+ current request path, perhaps including '..' atoms. If relative is
+ the string 'server', the output will instead be a URL that is
+ relative to the server root; i.e., it will start with a slash.
+ """
+ if isinstance(qs, (tuple, list, dict)):
+ qs = urllib.parse.urlencode(qs)
+ if qs:
+ qs = '?' + qs
+
+ if cherrypy.request.app:
+ if not path.startswith('/'):
+ # Append/remove trailing slash from path_info as needed
+ # (this is to support mistyped URL's without redirecting;
+ # if you want to redirect, use tools.trailing_slash).
+ pi = cherrypy.request.path_info
+ if cherrypy.request.is_index is True:
+ if not pi.endswith('/'):
+ pi = pi + '/'
+ elif cherrypy.request.is_index is False:
+ if pi.endswith('/') and pi != '/':
+ pi = pi[:-1]
+
+ if path == '':
+ path = pi
+ else:
+ path = urllib.parse.urljoin(pi, path)
+
+ if script_name is None:
+ script_name = cherrypy.request.script_name
+ if base is None:
+ base = cherrypy.request.base
+
+ newurl = base + script_name + normalize_path(path) + qs
+ else:
+ # No request.app (we're being called outside a request).
+ # We'll have to guess the base from server.* attributes.
+ # This will produce very different results from the above
+ # if you're using vhosts or tools.proxy.
+ if base is None:
+ base = cherrypy.server.base()
+
+ path = (script_name or '') + path
+ newurl = base + normalize_path(path) + qs
+
+ # At this point, we should have a fully-qualified absolute URL.
+
+ if relative is None:
+ relative = getattr(cherrypy.request.app, 'relative_urls', False)
+
+ # See http://www.ietf.org/rfc/rfc2396.txt
+ if relative == 'server':
+ # "A relative reference beginning with a single slash character is
+ # termed an absolute-path reference, as defined by <abs_path>..."
+ # This is also sometimes called "server-relative".
+ newurl = '/' + '/'.join(newurl.split('/', 3)[3:])
+ elif relative:
+ # "A relative reference that does not begin with a scheme name
+ # or a slash character is termed a relative-path reference."
+ old = url(relative=False).split('/')[:-1]
+ new = newurl.split('/')
+ while old and new:
+ a, b = old[0], new[0]
+ if a != b:
+ break
+ old.pop(0)
+ new.pop(0)
+ new = (['..'] * len(old)) + new
+ newurl = '/'.join(new)
+
+ return newurl
+
+
+def normalize_path(path):
+ """Resolve given path from relative into absolute form."""
+ if './' not in path:
+ return path
+
+ # Normalize the URL by removing ./ and ../
+ atoms = []
+ for atom in path.split('/'):
+ if atom == '.':
+ pass
+ elif atom == '..':
+ # Don't pop from empty list
+ # (i.e. ignore redundant '..')
+ if atoms:
+ atoms.pop()
+ elif atom:
+ atoms.append(atom)
+
+ newpath = '/'.join(atoms)
+ # Preserve leading '/'
+ if path.startswith('/'):
+ newpath = '/' + newpath
+
+ return newpath
+
+
+####
+# Inlined from jaraco.classes 1.4.3
+# Ref #1673
+class _ClassPropertyDescriptor(object):
+ """Descript for read-only class-based property.
+
+ Turns a classmethod-decorated func into a read-only property of that class
+ type (means the value cannot be set).
+ """
+
+ def __init__(self, fget, fset=None):
+ """Instantiated by ``_helper.classproperty``."""
+ self.fget = fget
+ self.fset = fset
+
+ def __get__(self, obj, klass=None):
+ """Return property value."""
+ if klass is None:
+ klass = type(obj)
+ return self.fget.__get__(obj, klass)()
+
+
+def classproperty(func):
+ """Decorator like classmethod to implement a static class property."""
+ if not isinstance(func, (classmethod, staticmethod)):
+ func = classmethod(func)
+
+ return _ClassPropertyDescriptor(func)
+####
diff --git a/cherrypy/cherryd b/cherrypy/cherryd
deleted file mode 100755
index 5d271c39..00000000
--- a/cherrypy/cherryd
+++ /dev/null
@@ -1,6 +0,0 @@
-#! /usr/bin/env python
-
-import cherrypy.daemon
-
-if __name__ == '__main__':
- cherrypy.daemon.run()
diff --git a/cherrypy/daemon.py b/cherrypy/daemon.py
index 395a2e68..74488c06 100755
--- a/cherrypy/daemon.py
+++ b/cherrypy/daemon.py
@@ -13,7 +13,7 @@ def start(configfiles=None, daemonize=False, environment=None,
"""Subscribe all engine plugins and start the engine."""
sys.path = [''] + sys.path
for i in imports or []:
- exec("import %s" % i)
+ exec('import %s' % i)
for c in configfiles or []:
cherrypy.config.update(c)
@@ -37,18 +37,18 @@ def start(configfiles=None, daemonize=False, environment=None,
if pidfile:
plugins.PIDFile(engine, pidfile).subscribe()
- if hasattr(engine, "signal_handler"):
+ if hasattr(engine, 'signal_handler'):
engine.signal_handler.subscribe()
- if hasattr(engine, "console_control_handler"):
+ if hasattr(engine, 'console_control_handler'):
engine.console_control_handler.subscribe()
if (fastcgi and (scgi or cgi)) or (scgi and cgi):
- cherrypy.log.error("You may only specify one of the cgi, fastcgi, and "
- "scgi options.", 'ENGINE')
+ cherrypy.log.error('You may only specify one of the cgi, fastcgi, and '
+ 'scgi options.', 'ENGINE')
sys.exit(1)
elif fastcgi or scgi or cgi:
# Turn off autoreload when using *cgi.
- cherrypy.config.update({'engine.autoreload_on': False})
+ cherrypy.config.update({'engine.autoreload.on': False})
# Turn off the default HTTP server (which is subscribed by default).
cherrypy.server.unsubscribe()
@@ -65,7 +65,7 @@ def start(configfiles=None, daemonize=False, environment=None,
# Always start the engine; this will start all other services
try:
engine.start()
- except:
+ except Exception:
# Assume the error has been logged already via bus.log.
sys.exit(1)
else:
@@ -73,28 +73,29 @@ def start(configfiles=None, daemonize=False, environment=None,
def run():
+ """Run cherryd CLI."""
from optparse import OptionParser
p = OptionParser()
- p.add_option('-c', '--config', action="append", dest='config',
- help="specify config file(s)")
- p.add_option('-d', action="store_true", dest='daemonize',
- help="run the server as a daemon")
+ p.add_option('-c', '--config', action='append', dest='config',
+ help='specify config file(s)')
+ p.add_option('-d', action='store_true', dest='daemonize',
+ help='run the server as a daemon')
p.add_option('-e', '--environment', dest='environment', default=None,
- help="apply the given config environment")
- p.add_option('-f', action="store_true", dest='fastcgi',
- help="start a fastcgi server instead of the default HTTP "
- "server")
- p.add_option('-s', action="store_true", dest='scgi',
- help="start a scgi server instead of the default HTTP server")
- p.add_option('-x', action="store_true", dest='cgi',
- help="start a cgi server instead of the default HTTP server")
- p.add_option('-i', '--import', action="append", dest='imports',
- help="specify modules to import")
+ help='apply the given config environment')
+ p.add_option('-f', action='store_true', dest='fastcgi',
+ help='start a fastcgi server instead of the default HTTP '
+ 'server')
+ p.add_option('-s', action='store_true', dest='scgi',
+ help='start a scgi server instead of the default HTTP server')
+ p.add_option('-x', action='store_true', dest='cgi',
+ help='start a cgi server instead of the default HTTP server')
+ p.add_option('-i', '--import', action='append', dest='imports',
+ help='specify modules to import')
p.add_option('-p', '--pidfile', dest='pidfile', default=None,
- help="store the process id in the given file")
- p.add_option('-P', '--Path', action="append", dest='Path',
- help="add the given paths to sys.path")
+ help='store the process id in the given file')
+ p.add_option('-P', '--Path', action='append', dest='Path',
+ help='add the given paths to sys.path')
options, args = p.parse_args()
if options.Path:
diff --git a/cherrypy/lib/__init__.py b/cherrypy/lib/__init__.py
index a75a53da..f815f76a 100644
--- a/cherrypy/lib/__init__.py
+++ b/cherrypy/lib/__init__.py
@@ -1,12 +1,14 @@
-"""CherryPy Library"""
+"""CherryPy Library."""
-# Deprecated in CherryPy 3.2 -- remove in CherryPy 3.3
-from cherrypy.lib.reprconf import unrepr, modules, attributes
def is_iterator(obj):
- '''Returns a boolean indicating if the object provided implements
- the iterator protocol (i.e. like a generator). This will return
- false for objects which iterable, but not iterators themselves.'''
+ """Detect if the object provided implements the iterator protocol.
+
+ (i.e. like a generator).
+
+ This will return False for objects which are iterable,
+ but not iterators themselves.
+ """
from types import GeneratorType
if isinstance(obj, GeneratorType):
return True
@@ -16,22 +18,23 @@ def is_iterator(obj):
# Types which implement the protocol must return themselves when
# invoking 'iter' upon them.
return iter(obj) is obj
-
+
+
def is_closable_iterator(obj):
-
+ """Detect if the given object is both closable and iterator."""
# Not an iterator.
if not is_iterator(obj):
return False
-
+
# A generator - the easiest thing to deal with.
import inspect
if inspect.isgenerator(obj):
return True
-
+
# A custom iterator. Look for a close method...
if not (hasattr(obj, 'close') and callable(obj.close)):
return False
-
+
# ... which doesn't require any arguments.
try:
inspect.getcallargs(obj.close)
@@ -40,18 +43,24 @@ def is_closable_iterator(obj):
else:
return True
+
class file_generator(object):
+ """Yield the given input (a file object) in chunks (default 64k).
- """Yield the given input (a file object) in chunks (default 64k). (Core)"""
+ (Core)
+ """
def __init__(self, input, chunkSize=65536):
+ """Initialize file_generator with file ``input`` for chunked access."""
self.input = input
self.chunkSize = chunkSize
def __iter__(self):
+ """Return iterator."""
return self
def __next__(self):
+ """Return next chunk of file."""
chunk = self.input.read(self.chunkSize)
if chunk:
return chunk
@@ -63,8 +72,10 @@ class file_generator(object):
def file_generator_limited(fileobj, count, chunk_size=65536):
- """Yield the given file object in chunks, stopping after `count`
- bytes has been emitted. Default chunk size is 64kB. (Core)
+ """Yield the given file object in chunks.
+
+ Stopps after `count` bytes has been emitted.
+ Default chunk size is 64kB. (Core)
"""
remaining = count
while remaining > 0:
@@ -77,9 +88,9 @@ def file_generator_limited(fileobj, count, chunk_size=65536):
def set_vary_header(response, header_name):
- "Add a Vary header to a response"
- varies = response.headers.get("Vary", "")
- varies = [x.strip() for x in varies.split(",") if x.strip()]
+ """Add a Vary header to a response."""
+ varies = response.headers.get('Vary', '')
+ varies = [x.strip() for x in varies.split(',') if x.strip()]
if header_name not in varies:
varies.append(header_name)
- response.headers['Vary'] = ", ".join(varies)
+ response.headers['Vary'] = ', '.join(varies)
diff --git a/cherrypy/lib/auth.py b/cherrypy/lib/auth.py
index 71591aaa..34ad6886 100644
--- a/cherrypy/lib/auth.py
+++ b/cherrypy/lib/auth.py
@@ -22,25 +22,25 @@ def check_auth(users, encrypt=None, realm=None):
if not isinstance(users, dict):
raise ValueError(
- "Authentication users must be a dictionary")
+ 'Authentication users must be a dictionary')
# fetch the user password
- password = users.get(ah["username"], None)
+ password = users.get(ah['username'], None)
except TypeError:
# returns a password (encrypted or clear text)
- password = users(ah["username"])
+ password = users(ah['username'])
else:
if not isinstance(users, dict):
- raise ValueError("Authentication users must be a dictionary")
+ raise ValueError('Authentication users must be a dictionary')
# fetch the user password
- password = users.get(ah["username"], None)
+ password = users.get(ah['username'], None)
# validate the authorization by re-computing it here
# and compare it with what the user-agent provided
if httpauth.checkResponse(ah, password, method=request.method,
encrypt=encrypt, realm=realm):
- request.login = ah["username"]
+ request.login = ah['username']
return True
request.login = False
@@ -72,7 +72,7 @@ def basic_auth(realm, users, encrypt=None, debug=False):
'www-authenticate'] = httpauth.basicAuth(realm)
raise cherrypy.HTTPError(
- 401, "You are not authorized to access that resource")
+ 401, 'You are not authorized to access that resource')
def digest_auth(realm, users, debug=False):
@@ -94,4 +94,4 @@ def digest_auth(realm, users, debug=False):
'www-authenticate'] = httpauth.digestAuth(realm)
raise cherrypy.HTTPError(
- 401, "You are not authorized to access that resource")
+ 401, 'You are not authorized to access that resource')
diff --git a/cherrypy/lib/auth_basic.py b/cherrypy/lib/auth_basic.py
index 5ba16f7f..44eb9b14 100644
--- a/cherrypy/lib/auth_basic.py
+++ b/cherrypy/lib/auth_basic.py
@@ -2,6 +2,12 @@
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab:fileencoding=utf-8
+import binascii
+
+import cherrypy
+from cherrypy._cpcompat import base64_decode
+
+
__doc__ = """This module provides a CherryPy 3.x tool which implements
the server-side of HTTP Basic Access Authentication, as described in
:rfc:`2617`.
@@ -22,10 +28,6 @@ as the credentials store::
__author__ = 'visteya'
__date__ = 'April 2009'
-import binascii
-from cherrypy._cpcompat import base64_decode
-import cherrypy
-
def checkpassword_dict(user_password_dict):
"""Returns a checkpassword function which checks credentials
@@ -70,7 +72,9 @@ def basic_auth(realm, checkpassword, debug=False):
auth_header = request.headers.get('authorization')
if auth_header is not None:
- try:
+ # split() error, base64.decodestring() error
+ msg = 'Bad Request'
+ with cherrypy.HTTPError.handle((ValueError, binascii.Error), 400, msg):
scheme, params = auth_header.split(' ', 1)
if scheme.lower() == 'basic':
username, password = base64_decode(params).split(':', 1)
@@ -79,12 +83,9 @@ def basic_auth(realm, checkpassword, debug=False):
cherrypy.log('Auth succeeded', 'TOOLS.AUTH_BASIC')
request.login = username
return # successful authentication
- # split() error, base64.decodestring() error
- except (ValueError, binascii.Error):
- raise cherrypy.HTTPError(400, 'Bad Request')
# Respond with 401 status and a WWW-Authenticate header
cherrypy.serving.response.headers[
'www-authenticate'] = 'Basic realm="%s"' % realm
raise cherrypy.HTTPError(
- 401, "You are not authorized to access that resource")
+ 401, 'You are not authorized to access that resource')
diff --git a/cherrypy/lib/auth_digest.py b/cherrypy/lib/auth_digest.py
index e833ff77..b604bf6d 100644
--- a/cherrypy/lib/auth_digest.py
+++ b/cherrypy/lib/auth_digest.py
@@ -2,6 +2,15 @@
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab:fileencoding=utf-8
+import time
+from hashlib import md5
+
+from six.moves.urllib.request import parse_http_list, parse_keqv_list
+
+import cherrypy
+from cherrypy._cpcompat import ntob
+
+
__doc__ = """An implementation of the server-side of HTTP Digest Access
Authentication, which is described in :rfc:`2617`.
@@ -22,13 +31,9 @@ __author__ = 'visteya'
__date__ = 'April 2009'
-import time
-from hashlib import md5
-from cherrypy._cpcompat import parse_http_list, parse_keqv_list
+def md5_hex(s):
+ return md5(ntob(s)).hexdigest()
-import cherrypy
-from cherrypy._cpcompat import ntob
-md5_hex = lambda s: md5(ntob(s)).hexdigest()
qop_auth = 'auth'
qop_auth_int = 'auth-int'
@@ -142,7 +147,7 @@ class HttpDigestAuthorization (object):
def __init__(self, auth_header, http_method, debug=False):
self.http_method = http_method
self.debug = debug
- scheme, params = auth_header.split(" ", 1)
+ scheme, params = auth_header.split(' ', 1)
self.scheme = scheme.lower()
if self.scheme != 'digest':
raise ValueError('Authorization scheme is not "Digest"')
@@ -180,7 +185,7 @@ class HttpDigestAuthorization (object):
)
if not has_reqd:
raise ValueError(
- self.errmsg("Not all required parameters are present."))
+ self.errmsg('Not all required parameters are present.'))
if self.qop:
if self.qop not in valid_qops:
@@ -188,13 +193,13 @@ class HttpDigestAuthorization (object):
self.errmsg("Unsupported value for qop: '%s'" % self.qop))
if not (self.cnonce and self.nc):
raise ValueError(
- self.errmsg("If qop is sent then "
- "cnonce and nc MUST be present"))
+ self.errmsg('If qop is sent then '
+ 'cnonce and nc MUST be present'))
else:
if self.cnonce or self.nc:
raise ValueError(
- self.errmsg("If qop is not sent, "
- "neither cnonce nor nc can be present"))
+ self.errmsg('If qop is not sent, '
+ 'neither cnonce nor nc can be present'))
def __str__(self):
return 'authorization : %s' % self.auth_header
@@ -239,7 +244,7 @@ class HttpDigestAuthorization (object):
except ValueError: # int() error
pass
if self.debug:
- TRACE("nonce is stale")
+ TRACE('nonce is stale')
return True
def HA2(self, entity_body=''):
@@ -251,14 +256,14 @@ class HttpDigestAuthorization (object):
#
# If the "qop" value is "auth-int", then A2 is:
# A2 = method ":" digest-uri-value ":" H(entity-body)
- if self.qop is None or self.qop == "auth":
+ if self.qop is None or self.qop == 'auth':
a2 = '%s:%s' % (self.http_method, self.uri)
- elif self.qop == "auth-int":
- a2 = "%s:%s:%s" % (self.http_method, self.uri, H(entity_body))
+ elif self.qop == 'auth-int':
+ a2 = '%s:%s:%s' % (self.http_method, self.uri, H(entity_body))
else:
# in theory, this should never happen, since I validate qop in
# __init__()
- raise ValueError(self.errmsg("Unrecognized value for qop!"))
+ raise ValueError(self.errmsg('Unrecognized value for qop!'))
return H(a2)
def request_digest(self, ha1, entity_body=''):
@@ -279,10 +284,10 @@ class HttpDigestAuthorization (object):
ha2 = self.HA2(entity_body)
# Request-Digest -- RFC 2617 3.2.2.1
if self.qop:
- req = "%s:%s:%s:%s:%s" % (
+ req = '%s:%s:%s:%s:%s' % (
self.nonce, self.nc, self.cnonce, self.qop, ha2)
else:
- req = "%s:%s" % (self.nonce, ha2)
+ req = '%s:%s' % (self.nonce, ha2)
# RFC 2617 3.2.2.2
#
@@ -351,12 +356,10 @@ def digest_auth(realm, get_ha1, key, debug=False):
auth_header = request.headers.get('authorization')
nonce_is_stale = False
if auth_header is not None:
- try:
+ msg = 'The Authorization header could not be parsed.'
+ with cherrypy.HTTPError.handle(ValueError, 400, msg):
auth = HttpDigestAuthorization(
auth_header, request.method, debug=debug)
- except ValueError:
- raise cherrypy.HTTPError(
- 400, "The Authorization header could not be parsed.")
if debug:
TRACE(str(auth))
@@ -370,7 +373,7 @@ def digest_auth(realm, get_ha1, key, debug=False):
digest = auth.request_digest(ha1, entity_body=request.body)
if digest == auth.response: # authenticated
if debug:
- TRACE("digest matches auth.response")
+ TRACE('digest matches auth.response')
# Now check if nonce is stale.
# The choice of ten minutes' lifetime for nonce is somewhat
# arbitrary
@@ -378,7 +381,7 @@ def digest_auth(realm, get_ha1, key, debug=False):
if not nonce_is_stale:
request.login = auth.username
if debug:
- TRACE("authentication of %s successful" %
+ TRACE('authentication of %s successful' %
auth.username)
return
@@ -388,4 +391,4 @@ def digest_auth(realm, get_ha1, key, debug=False):
TRACE(header)
cherrypy.serving.response.headers['WWW-Authenticate'] = header
raise cherrypy.HTTPError(
- 401, "You are not authorized to access that resource")
+ 401, 'You are not authorized to access that resource')
diff --git a/cherrypy/lib/caching.py b/cherrypy/lib/caching.py
index 375d5f0e..c4449d85 100644
--- a/cherrypy/lib/caching.py
+++ b/cherrypy/lib/caching.py
@@ -37,9 +37,11 @@ import sys
import threading
import time
+import six
+
import cherrypy
from cherrypy.lib import cptools, httputil
-from cherrypy._cpcompat import copyitems, ntob, set_daemon, sorted, Event
+from cherrypy._cpcompat import ntob, Event
class Cache(object):
@@ -170,7 +172,7 @@ class MemoryCache(Cache):
# Run self.expire_cache in a separate daemon thread.
t = threading.Thread(target=self.expire_cache, name='expire_cache')
self.expiration_thread = t
- set_daemon(t, True)
+ t.daemon = True
t.start()
def clear(self):
@@ -197,7 +199,8 @@ class MemoryCache(Cache):
now = time.time()
# Must make a copy of expirations so it doesn't change size
# during iteration
- for expiration_time, objects in copyitems(self.expirations):
+ items = list(six.iteritems(self.expirations))
+ for expiration_time, objects in items:
if expiration_time <= now:
for obj_size, uri, sel_header_values in objects:
try:
@@ -265,7 +268,7 @@ class MemoryCache(Cache):
self.store.pop(uri, None)
-def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs):
+def get(invalid_methods=('POST', 'PUT', 'DELETE'), debug=False, **kwargs):
"""Try to obtain cached output. If fresh enough, raise HTTPError(304).
If POST, PUT, or DELETE:
@@ -291,9 +294,9 @@ def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs):
request = cherrypy.serving.request
response = cherrypy.serving.response
- if not hasattr(cherrypy, "_cache"):
+ if not hasattr(cherrypy, '_cache'):
# Make a process-wide Cache object.
- cherrypy._cache = kwargs.pop("cache_class", MemoryCache)()
+ cherrypy._cache = kwargs.pop('cache_class', MemoryCache)()
# Take all remaining kwargs and set them on the Cache object.
for k, v in kwargs.items():
@@ -328,7 +331,7 @@ def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs):
if directive == 'max-age':
if len(atoms) != 1 or not atoms[0].isdigit():
raise cherrypy.HTTPError(
- 400, "Invalid Cache-Control header")
+ 400, 'Invalid Cache-Control header')
max_age = int(atoms[0])
break
elif directive == 'no-cache':
@@ -359,7 +362,7 @@ def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs):
dict.__setitem__(rh, k, dict.__getitem__(h, k))
# Add the required Age header
- response.headers["Age"] = str(age)
+ response.headers['Age'] = str(age)
try:
# Note that validate_since depends on a Last-Modified header;
@@ -457,14 +460,14 @@ def expires(secs=0, force=False, debug=False):
secs = (86400 * secs.days) + secs.seconds
if secs == 0:
- if force or ("Pragma" not in headers):
- headers["Pragma"] = "no-cache"
+ if force or ('Pragma' not in headers):
+ headers['Pragma'] = 'no-cache'
if cherrypy.serving.request.protocol >= (1, 1):
- if force or "Cache-Control" not in headers:
- headers["Cache-Control"] = "no-cache, must-revalidate"
+ if force or 'Cache-Control' not in headers:
+ headers['Cache-Control'] = 'no-cache, must-revalidate'
# Set an explicit Expires date in the past.
expiry = httputil.HTTPDate(1169942400.0)
else:
expiry = httputil.HTTPDate(response.time + secs)
- if force or "Expires" not in headers:
- headers["Expires"] = expiry
+ if force or 'Expires' not in headers:
+ headers['Expires'] = expiry
diff --git a/cherrypy/lib/covercp.py b/cherrypy/lib/covercp.py
index a74ec342..0bafca13 100644
--- a/cherrypy/lib/covercp.py
+++ b/cherrypy/lib/covercp.py
@@ -23,10 +23,15 @@ it will call ``serve()`` for you.
import re
import sys
import cgi
-from cherrypy._cpcompat import quote_plus
import os
import os.path
-localFile = os.path.join(os.path.dirname(__file__), "coverage.cache")
+
+from six.moves import urllib
+
+import cherrypy
+
+
+localFile = os.path.join(os.path.dirname(__file__), 'coverage.cache')
the_coverage = None
try:
@@ -42,8 +47,8 @@ except ImportError:
import warnings
warnings.warn(
- "No code coverage will be performed; "
- "coverage.py could not be imported.")
+ 'No code coverage will be performed; '
+ 'coverage.py could not be imported.')
def start():
pass
@@ -193,7 +198,7 @@ def _percent(statements, missing):
return 0
-def _show_branch(root, base, path, pct=0, showpct=False, exclude="",
+def _show_branch(root, base, path, pct=0, showpct=False, exclude='',
coverage=the_coverage):
# Show the directory name and any of our children
@@ -204,11 +209,11 @@ def _show_branch(root, base, path, pct=0, showpct=False, exclude="",
if newpath.lower().startswith(base):
relpath = newpath[len(base):]
- yield "| " * relpath.count(os.sep)
+ yield '| ' * relpath.count(os.sep)
yield (
"<a class='directory' "
"href='menu?base=%s&exclude=%s'>%s</a>\n" %
- (newpath, quote_plus(exclude), name)
+ (newpath, urllib.parse.quote_plus(exclude), name)
)
for chunk in _show_branch(
@@ -225,22 +230,22 @@ def _show_branch(root, base, path, pct=0, showpct=False, exclude="",
for name in files:
newpath = os.path.join(path, name)
- pc_str = ""
+ pc_str = ''
if showpct:
try:
_, statements, _, missing, _ = coverage.analysis2(newpath)
- except:
+ except Exception:
# Yes, we really want to pass on all errors.
pass
else:
pc = _percent(statements, missing)
- pc_str = ("%3d%% " % pc).replace(' ', '&nbsp;')
+ pc_str = ('%3d%% ' % pc).replace(' ', '&nbsp;')
if pc < float(pct) or pc == -1:
pc_str = "<span class='fail'>%s</span>" % pc_str
else:
pc_str = "<span class='pass'>%s</span>" % pc_str
- yield TEMPLATE_ITEM % ("| " * (relpath.count(os.sep) + 1),
+ yield TEMPLATE_ITEM % ('| ' * (relpath.count(os.sep) + 1),
pc_str, newpath, name)
@@ -260,8 +265,8 @@ def _graft(path, tree):
break
atoms.append(tail)
atoms.append(p)
- if p != "/":
- atoms.append("/")
+ if p != '/':
+ atoms.append('/')
atoms.reverse()
for node in atoms:
@@ -286,15 +291,15 @@ class CoverStats(object):
if root is None:
# Guess initial depth. Files outside this path will not be
# reachable from the web interface.
- import cherrypy
root = os.path.dirname(cherrypy.__file__)
self.root = root
+ @cherrypy.expose
def index(self):
return TEMPLATE_FRAMESET % self.root.lower()
- index.exposed = True
- def menu(self, base="/", pct="50", showpct="",
+ @cherrypy.expose
+ def menu(self, base='/', pct='50', showpct='',
exclude=r'python\d\.\d|test|tut\d|tutorial'):
# The coverage module uses all-lower-case names.
@@ -305,37 +310,36 @@ class CoverStats(object):
# Start by showing links for parent paths
yield "<div id='crumbs'>"
- path = ""
+ path = ''
atoms = base.split(os.sep)
atoms.pop()
for atom in atoms:
path += atom + os.sep
yield ("<a href='menu?base=%s&exclude=%s'>%s</a> %s"
- % (path, quote_plus(exclude), atom, os.sep))
- yield "</div>"
+ % (path, urllib.parse.quote_plus(exclude), atom, os.sep))
+ yield '</div>'
yield "<div id='tree'>"
# Then display the tree
tree = get_tree(base, exclude, self.coverage)
if not tree:
- yield "<p>No modules covered.</p>"
+ yield '<p>No modules covered.</p>'
else:
- for chunk in _show_branch(tree, base, "/", pct,
+ for chunk in _show_branch(tree, base, '/', pct,
showpct == 'checked', exclude,
coverage=self.coverage):
yield chunk
- yield "</div>"
- yield "</body></html>"
- menu.exposed = True
+ yield '</div>'
+ yield '</body></html>'
def annotated_file(self, filename, statements, excluded, missing):
source = open(filename, 'r')
buffer = []
for lineno, line in enumerate(source.readlines()):
lineno += 1
- line = line.strip("\n\r")
+ line = line.strip('\n\r')
empty_the_buffer = True
if lineno in excluded:
template = TEMPLATE_LOC_EXCLUDED
@@ -352,6 +356,7 @@ class CoverStats(object):
buffer = []
yield template % (lineno, cgi.escape(line))
+ @cherrypy.expose
def report(self, name):
filename, statements, excluded, missing, _ = self.coverage.analysis2(
name)
@@ -366,22 +371,21 @@ class CoverStats(object):
yield '</table>'
yield '</body>'
yield '</html>'
- report.exposed = True
def serve(path=localFile, port=8080, root=None):
if coverage is None:
- raise ImportError("The coverage module could not be imported.")
+ raise ImportError('The coverage module could not be imported.')
from coverage import coverage
cov = coverage(data_file=path)
cov.load()
- import cherrypy
cherrypy.config.update({'server.socket_port': int(port),
'server.thread_pool': 10,
- 'environment': "production",
+ 'environment': 'production',
})
cherrypy.quickstart(CoverStats(cov, root))
-if __name__ == "__main__":
+
+if __name__ == '__main__':
serve(*tuple(sys.argv[1:]))
diff --git a/cherrypy/lib/cpstats.py b/cherrypy/lib/cpstats.py
index 4aeabd7d..ae9f7475 100644
--- a/cherrypy/lib/cpstats.py
+++ b/cherrypy/lib/cpstats.py
@@ -187,9 +187,19 @@ To format statistics reports::
"""
+import logging
+import os
+import sys
+import threading
+import time
+
+import six
+
+import cherrypy
+from cherrypy._cpcompat import json
+
# ------------------------------- Statistics -------------------------------- #
-import logging
if not hasattr(logging, 'statistics'):
logging.statistics = {}
@@ -210,12 +220,6 @@ def extrapolate_statistics(scope):
# -------------------- CherryPy Applications Statistics --------------------- #
-import sys
-import threading
-import time
-
-import cherrypy
-
appstats = logging.statistics.setdefault('CherryPy Applications', {})
appstats.update({
'Enabled': True,
@@ -246,7 +250,9 @@ appstats.update({
'Requests': {},
})
-proc_time = lambda s: time.time() - s['Start Time']
+
+def proc_time(s):
+ return time.time() - s['Start Time']
class ByteCountWrapper(object):
@@ -292,7 +298,8 @@ class ByteCountWrapper(object):
return data
-average_uriset_time = lambda s: s['Count'] and (s['Sum'] / s['Count']) or 0
+def average_uriset_time(s):
+ return s['Count'] and (s['Sum'] / s['Count']) or 0
def _get_threading_ident():
@@ -300,6 +307,7 @@ def _get_threading_ident():
return threading.get_ident()
return threading._get_ident()
+
class StatsTool(cherrypy.Tool):
"""Record various information about the current request."""
@@ -390,28 +398,22 @@ class StatsTool(cherrypy.Tool):
sq.pop(0)
-import cherrypy
cherrypy.tools.cpstats = StatsTool()
# ---------------------- CherryPy Statistics Reporting ---------------------- #
-import os
thisdir = os.path.abspath(os.path.dirname(__file__))
-try:
- import json
-except ImportError:
- try:
- import simplejson as json
- except ImportError:
- json = None
+missing = object()
-missing = object()
+def locale_date(v):
+ return time.strftime('%c', time.gmtime(v))
+
-locale_date = lambda v: time.strftime('%c', time.gmtime(v))
-iso_format = lambda v: time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(v))
+def iso_format(v):
+ return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(v))
def pause_resume(ns):
@@ -475,6 +477,7 @@ class StatsPage(object):
},
}
+ @cherrypy.expose
def index(self):
# Transform the raw data into pretty output for HTML
yield """
@@ -578,7 +581,6 @@ table.stats2 th {
</body>
</html>
"""
- index.exposed = True
def get_namespaces(self):
"""Yield (title, scalars, collections) for each namespace."""
@@ -611,12 +613,7 @@ table.stats2 th {
"""Return ([headers], [rows]) for the given collection."""
# E.g., the 'Requests' dict.
headers = []
- try:
- # python2
- vals = v.itervalues()
- except AttributeError:
- # python3
- vals = v.values()
+ vals = six.itervalues(v)
for record in vals:
for k3 in record:
format = formatting.get(k3, missing)
@@ -678,22 +675,22 @@ table.stats2 th {
return headers, subrows
if json is not None:
+ @cherrypy.expose
def data(self):
s = extrapolate_statistics(logging.statistics)
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps(s, sort_keys=True, indent=4)
- data.exposed = True
+ @cherrypy.expose
def pause(self, namespace):
logging.statistics.get(namespace, {})['Enabled'] = False
raise cherrypy.HTTPRedirect('./')
- pause.exposed = True
pause.cp_config = {'tools.allow.on': True,
'tools.allow.methods': ['POST']}
+ @cherrypy.expose
def resume(self, namespace):
logging.statistics.get(namespace, {})['Enabled'] = True
raise cherrypy.HTTPRedirect('./')
- resume.exposed = True
resume.cp_config = {'tools.allow.on': True,
'tools.allow.methods': ['POST']}
diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py
index 9be571ba..b757bfe8 100644
--- a/cherrypy/lib/cptools.py
+++ b/cherrypy/lib/cptools.py
@@ -4,8 +4,11 @@ import logging
import re
from hashlib import md5
+import six
+from six.moves import urllib
+
import cherrypy
-from cherrypy._cpcompat import basestring, unicodestr
+from cherrypy._cpcompat import text_or_bytes
from cherrypy.lib import httputil as _httputil
from cherrypy.lib import is_iterator
@@ -31,7 +34,7 @@ def validate_etags(autotags=False, debug=False):
response = cherrypy.serving.response
# Guard against being run twice.
- if hasattr(response, "ETag"):
+ if hasattr(response, 'ETag'):
return
status, reason, msg = _httputil.valid_status(response.status)
@@ -70,24 +73,24 @@ def validate_etags(autotags=False, debug=False):
if debug:
cherrypy.log('If-Match conditions: %s' % repr(conditions),
'TOOLS.ETAGS')
- if conditions and not (conditions == ["*"] or etag in conditions):
- raise cherrypy.HTTPError(412, "If-Match failed: ETag %r did "
- "not match %r" % (etag, conditions))
+ if conditions and not (conditions == ['*'] or etag in conditions):
+ raise cherrypy.HTTPError(412, 'If-Match failed: ETag %r did '
+ 'not match %r' % (etag, conditions))
conditions = request.headers.elements('If-None-Match') or []
conditions = [str(x) for x in conditions]
if debug:
cherrypy.log('If-None-Match conditions: %s' % repr(conditions),
'TOOLS.ETAGS')
- if conditions == ["*"] or etag in conditions:
+ if conditions == ['*'] or etag in conditions:
if debug:
cherrypy.log('request.method: %s' %
request.method, 'TOOLS.ETAGS')
- if request.method in ("GET", "HEAD"):
+ if request.method in ('GET', 'HEAD'):
raise cherrypy.HTTPRedirect([], 304)
else:
- raise cherrypy.HTTPError(412, "If-None-Match failed: ETag %r "
- "matched %r" % (etag, conditions))
+ raise cherrypy.HTTPError(412, 'If-None-Match failed: ETag %r '
+ 'matched %r' % (etag, conditions))
def validate_since():
@@ -111,7 +114,7 @@ def validate_since():
since = request.headers.get('If-Modified-Since')
if since and since == lastmod:
if (status >= 200 and status <= 299) or status == 304:
- if request.method in ("GET", "HEAD"):
+ if request.method in ('GET', 'HEAD'):
raise cherrypy.HTTPRedirect([], 304)
else:
raise cherrypy.HTTPError(412)
@@ -184,7 +187,7 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For',
# This is for lighttpd/pound/Mongrel's 'X-Forwarded-Proto: https'
scheme = s
if not scheme:
- scheme = request.base[:request.base.find("://")]
+ scheme = request.base[:request.base.find('://')]
if local:
lbase = request.headers.get(local, None)
@@ -193,14 +196,12 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For',
if lbase is not None:
base = lbase.split(',')[0]
if not base:
- base = request.headers.get('Host', '127.0.0.1')
- port = request.local.port
- if port != 80:
- base += ':%s' % port
+ default = urllib.parse.urlparse(request.base).netloc
+ base = request.headers.get('Host', default)
- if base.find("://") == -1:
+ if base.find('://') == -1:
# add http:// or https:// if needed
- base = scheme + "://" + base
+ base = scheme + '://' + base
request.base = base
@@ -210,7 +211,7 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For',
cherrypy.log('Testing remote %r:%r' % (remote, xff), 'TOOLS.PROXY')
if xff:
if remote == 'X-Forwarded-For':
- #Bug #1268
+ # Bug #1268
xff = xff.split(',')[0].strip()
request.remote.ip = xff
@@ -238,6 +239,8 @@ def response_headers(headers=None, debug=False):
'TOOLS.RESPONSE_HEADERS')
for name, value in (headers or []):
cherrypy.serving.response.headers[name] = value
+
+
response_headers.failsafe = True
@@ -283,7 +286,7 @@ class SessionAuth(object):
"""Assert that the user is logged in."""
- session_key = "username"
+ session_key = 'username'
debug = False
def check_username_and_password(self, username, password):
@@ -304,7 +307,7 @@ class SessionAuth(object):
def login_screen(self, from_page='..', username='', error_msg='',
**kwargs):
- return (unicodestr("""<html><body>
+ return (six.text_type("""<html><body>
Message: %(error_msg)s
<form method="post" action="do_login">
Login: <input type="text" name="username" value="%(username)s" size="10" />
@@ -315,7 +318,7 @@ Message: %(error_msg)s
<br />
<input type="submit" />
</form>
-</body></html>""") % vars()).encode("utf-8")
+</body></html>""") % vars()).encode('utf-8')
def do_login(self, username, password, from_page='..', **kwargs):
"""Login. May raise redirect, or return True if request handled."""
@@ -324,15 +327,15 @@ Message: %(error_msg)s
if error_msg:
body = self.login_screen(from_page, username, error_msg)
response.body = body
- if "Content-Length" in response.headers:
+ if 'Content-Length' in response.headers:
# Delete Content-Length header so finalize() recalcs it.
- del response.headers["Content-Length"]
+ del response.headers['Content-Length']
return True
else:
cherrypy.serving.request.login = username
cherrypy.session[self.session_key] = username
self.on_login(username)
- raise cherrypy.HTTPRedirect(from_page or "/")
+ raise cherrypy.HTTPRedirect(from_page or '/')
def do_logout(self, from_page='..', **kwargs):
"""Logout. May raise redirect, or return True if request handled."""
@@ -362,9 +365,9 @@ Message: %(error_msg)s
locals(),
)
response.body = self.login_screen(url)
- if "Content-Length" in response.headers:
+ if 'Content-Length' in response.headers:
# Delete Content-Length header so finalize() recalcs it.
- del response.headers["Content-Length"]
+ del response.headers['Content-Length']
return True
self._debug_message('Setting request.login to %(username)r', locals())
request.login = username
@@ -386,14 +389,14 @@ Message: %(error_msg)s
return True
elif path.endswith('do_login'):
if request.method != 'POST':
- response.headers['Allow'] = "POST"
+ response.headers['Allow'] = 'POST'
self._debug_message('do_login requires POST')
raise cherrypy.HTTPError(405)
self._debug_message('routing %(path)r to do_login', locals())
return self.do_login(**request.params)
elif path.endswith('do_logout'):
if request.method != 'POST':
- response.headers['Allow'] = "POST"
+ response.headers['Allow'] = 'POST'
raise cherrypy.HTTPError(405)
self._debug_message('routing %(path)r to do_logout', locals())
return self.do_logout(**request.params)
@@ -407,24 +410,28 @@ def session_auth(**kwargs):
for k, v in kwargs.items():
setattr(sa, k, v)
return sa.run()
-session_auth.__doc__ = """Session authentication hook.
-Any attribute of the SessionAuth class may be overridden via a keyword arg
-to this function:
-""" + "\n".join(["%s: %s" % (k, type(getattr(SessionAuth, k)).__name__)
- for k in dir(SessionAuth) if not k.startswith("__")])
+session_auth.__doc__ = (
+ """Session authentication hook.
+
+ Any attribute of the SessionAuth class may be overridden via a keyword arg
+ to this function:
+
+ """ + '\n'.join(['%s: %s' % (k, type(getattr(SessionAuth, k)).__name__)
+ for k in dir(SessionAuth) if not k.startswith('__')])
+)
def log_traceback(severity=logging.ERROR, debug=False):
"""Write the last error's traceback to the cherrypy error log."""
- cherrypy.log("", "HTTP", severity=severity, traceback=True)
+ cherrypy.log('', 'HTTP', severity=severity, traceback=True)
def log_request_headers(debug=False):
"""Write request headers to the cherrypy error log."""
- h = [" %s: %s" % (k, v) for k, v in cherrypy.serving.request.header_list]
- cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), "HTTP")
+ h = [' %s: %s' % (k, v) for k, v in cherrypy.serving.request.header_list]
+ cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), 'HTTP')
def log_hooks(debug=False):
@@ -440,13 +447,13 @@ def log_hooks(debug=False):
points.append(k)
for k in points:
- msg.append(" %s:" % k)
+ msg.append(' %s:' % k)
v = request.hooks.get(k, [])
v.sort()
for h in v:
- msg.append(" %r" % h)
+ msg.append(' %r' % h)
cherrypy.log('\nRequest Hooks for ' + cherrypy.url() +
- ':\n' + '\n'.join(msg), "HTTP")
+ ':\n' + '\n'.join(msg), 'HTTP')
def redirect(url='', internal=True, debug=False):
@@ -531,7 +538,7 @@ def accept(media=None, debug=False):
"""
if not media:
return
- if isinstance(media, basestring):
+ if isinstance(media, text_or_bytes):
media = [media]
request = cherrypy.serving.request
@@ -547,12 +554,12 @@ def accept(media=None, debug=False):
# Note that 'ranges' is sorted in order of preference
for element in ranges:
if element.qvalue > 0:
- if element.value == "*/*":
+ if element.value == '*/*':
# Matches any type or subtype
if debug:
cherrypy.log('Match due to */*', 'TOOLS.ACCEPT')
return media[0]
- elif element.value.endswith("/*"):
+ elif element.value.endswith('/*'):
# Matches any subtype
mtype = element.value[:-1] # Keep the slash
for m in media:
@@ -572,36 +579,23 @@ def accept(media=None, debug=False):
# No suitable media-range found.
ah = request.headers.get('Accept')
if ah is None:
- msg = "Your client did not send an Accept header."
+ msg = 'Your client did not send an Accept header.'
else:
- msg = "Your client sent this Accept header: %s." % ah
- msg += (" But this resource only emits these media types: %s." %
- ", ".join(media))
+ msg = 'Your client sent this Accept header: %s.' % ah
+ msg += (' But this resource only emits these media types: %s.' %
+ ', '.join(media))
raise cherrypy.HTTPError(406, msg)
class MonitoredHeaderMap(_httputil.HeaderMap):
- def __init__(self):
- self.accessed_headers = set()
-
- def __getitem__(self, key):
+ def transform_key(self, key):
self.accessed_headers.add(key)
- return _httputil.HeaderMap.__getitem__(self, key)
+ return super(MonitoredHeaderMap, self).transform_key(key)
- def __contains__(self, key):
- self.accessed_headers.add(key)
- return _httputil.HeaderMap.__contains__(self, key)
-
- def get(self, key, default=None):
- self.accessed_headers.add(key)
- return _httputil.HeaderMap.get(self, key, default=default)
-
- if hasattr({}, 'has_key'):
- # Python 2
- def has_key(self, key):
- self.accessed_headers.add(key)
- return _httputil.HeaderMap.has_key(self, key)
+ def __init__(self):
+ self.accessed_headers = set()
+ super(MonitoredHeaderMap, self).__init__()
def autovary(ignore=None, debug=False):
@@ -628,3 +622,19 @@ def autovary(ignore=None, debug=False):
v.sort()
resp_h['Vary'] = ', '.join(v)
request.hooks.attach('before_finalize', set_response_header, 95)
+
+
+def convert_params(exception=ValueError, error=400):
+ """Convert request params based on function annotations, with error handling.
+
+ exception
+ Exception class to catch.
+
+ status
+ The HTTP error code to return to the client on failure.
+ """
+ request = cherrypy.serving.request
+ types = request.handler.callable.__annotations__
+ with cherrypy.HTTPError.handle(exception, error):
+ for key in set(types).intersection(request.params):
+ request.params[key] = types[key](request.params[key])
diff --git a/cherrypy/lib/encoding.py b/cherrypy/lib/encoding.py
index fb688f8d..72e58f9c 100644
--- a/cherrypy/lib/encoding.py
+++ b/cherrypy/lib/encoding.py
@@ -1,8 +1,11 @@
import struct
import time
+import io
+
+import six
import cherrypy
-from cherrypy._cpcompat import basestring, BytesIO, ntob, unicodestr
+from cherrypy._cpcompat import text_or_bytes, ntob
from cherrypy.lib import file_generator
from cherrypy.lib import is_closable_iterator
from cherrypy.lib import set_vary_header
@@ -34,6 +37,7 @@ def decode(encoding=None, default_encoding='utf-8'):
default_encoding = [default_encoding]
body.attempt_charsets = body.attempt_charsets + default_encoding
+
class UTF8StreamEncoder:
def __init__(self, iterator):
self._iterator = iterator
@@ -46,7 +50,7 @@ class UTF8StreamEncoder:
def __next__(self):
res = next(self._iterator)
- if isinstance(res, unicodestr):
+ if isinstance(res, six.text_type):
res = res.encode('utf-8')
return res
@@ -63,7 +67,7 @@ class UTF8StreamEncoder:
class ResponseEncoder:
default_encoding = 'utf-8'
- failmsg = "Response body could not be encoded with %r."
+ failmsg = 'Response body could not be encoded with %r.'
encoding = None
errors = 'strict'
text_only = True
@@ -95,7 +99,7 @@ class ResponseEncoder:
def encoder(body):
for chunk in body:
- if isinstance(chunk, unicodestr):
+ if isinstance(chunk, six.text_type):
chunk = chunk.encode(encoding, self.errors)
yield chunk
self.body = encoder(self.body)
@@ -108,7 +112,7 @@ class ResponseEncoder:
self.attempted_charsets.add(encoding)
body = []
for chunk in self.body:
- if isinstance(chunk, unicodestr):
+ if isinstance(chunk, six.text_type):
try:
chunk = chunk.encode(encoding, self.errors)
except (LookupError, UnicodeError):
@@ -128,7 +132,7 @@ class ResponseEncoder:
encoder = self.encode_stream
else:
encoder = self.encode_string
- if "Content-Length" in response.headers:
+ if 'Content-Length' in response.headers:
# Delete Content-Length header so finalize() recalcs it.
# Encoded strings may be of different lengths from their
# unicode equivalents, and even from each other. For example:
@@ -139,7 +143,7 @@ class ResponseEncoder:
# 6
# >>> len(t.encode("utf7"))
# 8
- del response.headers["Content-Length"]
+ del response.headers['Content-Length']
# Parse the Accept-Charset request header, and try to provide one
# of the requested charsets (in order of user preference).
@@ -154,7 +158,7 @@ class ResponseEncoder:
if self.debug:
cherrypy.log('Specified encoding %r' %
encoding, 'TOOLS.ENCODE')
- if (not charsets) or "*" in charsets or encoding in charsets:
+ if (not charsets) or '*' in charsets or encoding in charsets:
if self.debug:
cherrypy.log('Attempting encoding %r' %
encoding, 'TOOLS.ENCODE')
@@ -174,7 +178,7 @@ class ResponseEncoder:
else:
for element in encs:
if element.qvalue > 0:
- if element.value == "*":
+ if element.value == '*':
# Matches any charset. Try our default.
if self.debug:
cherrypy.log('Attempting default encoding due '
@@ -189,7 +193,7 @@ class ResponseEncoder:
if encoder(encoding):
return encoding
- if "*" not in charsets:
+ if '*' not in charsets:
# If no "*" is present in an Accept-Charset field, then all
# character sets not explicitly mentioned get a quality
# value of 0, except for ISO-8859-1, which gets a quality
@@ -205,18 +209,18 @@ class ResponseEncoder:
# No suitable encoding found.
ac = request.headers.get('Accept-Charset')
if ac is None:
- msg = "Your client did not send an Accept-Charset header."
+ msg = 'Your client did not send an Accept-Charset header.'
else:
- msg = "Your client sent this Accept-Charset header: %s." % ac
- _charsets = ", ".join(sorted(self.attempted_charsets))
- msg += " We tried these charsets: %s." % (_charsets,)
+ msg = 'Your client sent this Accept-Charset header: %s.' % ac
+ _charsets = ', '.join(sorted(self.attempted_charsets))
+ msg += ' We tried these charsets: %s.' % (_charsets,)
raise cherrypy.HTTPError(406, msg)
def __call__(self, *args, **kwargs):
response = cherrypy.serving.response
self.body = self.oldhandler(*args, **kwargs)
- if isinstance(self.body, basestring):
+ if isinstance(self.body, text_or_bytes):
# strings get wrapped in a list because iterating over a single
# item list is much faster than iterating over every character
# in a long string.
@@ -230,14 +234,14 @@ class ResponseEncoder:
elif self.body is None:
self.body = []
- ct = response.headers.elements("Content-Type")
+ ct = response.headers.elements('Content-Type')
if self.debug:
cherrypy.log('Content-Type: %r' % [str(h)
for h in ct], 'TOOLS.ENCODE')
if ct and self.add_charset:
ct = ct[0]
if self.text_only:
- if ct.value.lower().startswith("text/"):
+ if ct.value.lower().startswith('text/'):
if self.debug:
cherrypy.log(
'Content-Type %s starts with "text/"' % ct,
@@ -261,7 +265,7 @@ class ResponseEncoder:
if self.debug:
cherrypy.log('Setting Content-Type %s' % ct,
'TOOLS.ENCODE')
- response.headers["Content-Type"] = str(ct)
+ response.headers['Content-Type'] = str(ct)
return self.body
@@ -277,11 +281,11 @@ def compress(body, compress_level):
yield ntob('\x08') # CM: compression method
yield ntob('\x00') # FLG: none set
# MTIME: 4 bytes
- yield struct.pack("<L", int(time.time()) & int('FFFFFFFF', 16))
+ yield struct.pack('<L', int(time.time()) & int('FFFFFFFF', 16))
yield ntob('\x02') # XFL: max compression, slowest algo
yield ntob('\xff') # OS: unknown
- crc = zlib.crc32(ntob(""))
+ crc = zlib.crc32(ntob(''))
size = 0
zobj = zlib.compressobj(compress_level,
zlib.DEFLATED, -zlib.MAX_WBITS,
@@ -293,15 +297,15 @@ def compress(body, compress_level):
yield zobj.flush()
# CRC32: 4 bytes
- yield struct.pack("<L", crc & int('FFFFFFFF', 16))
+ yield struct.pack('<L', crc & int('FFFFFFFF', 16))
# ISIZE: 4 bytes
- yield struct.pack("<L", size & int('FFFFFFFF', 16))
+ yield struct.pack('<L', size & int('FFFFFFFF', 16))
def decompress(body):
import gzip
- zbuf = BytesIO()
+ zbuf = io.BytesIO()
zbuf.write(body)
zbuf.seek(0)
zfile = gzip.GzipFile(mode='rb', fileobj=zbuf)
@@ -318,9 +322,9 @@ def gzip(compress_level=5, mime_types=['text/html', 'text/plain'],
values in the mime_types arg before calling this function.
The provided list of mime-types must be of one of the following form:
- * type/subtype
- * type/*
- * type/*+subtype
+ * `type/subtype`
+ * `type/*`
+ * `type/*+subtype`
No compression is performed if any of the following hold:
* The client sends no Accept-Encoding request header
@@ -332,7 +336,7 @@ def gzip(compress_level=5, mime_types=['text/html', 'text/plain'],
request = cherrypy.serving.request
response = cherrypy.serving.response
- set_vary_header(response, "Accept-Encoding")
+ set_vary_header(response, 'Accept-Encoding')
if not response.body:
# Response body is empty (might be a 304 for instance)
@@ -342,7 +346,7 @@ def gzip(compress_level=5, mime_types=['text/html', 'text/plain'],
# If returning cached content (which should already have been gzipped),
# don't re-zip.
- if getattr(request, "cached", False):
+ if getattr(request, 'cached', False):
if debug:
cherrypy.log('Not gzipping cached response', context='TOOLS.GZIP')
return
@@ -410,12 +414,12 @@ def gzip(compress_level=5, mime_types=['text/html', 'text/plain'],
# Return a generator that compresses the page
response.headers['Content-Encoding'] = 'gzip'
response.body = compress(response.body, compress_level)
- if "Content-Length" in response.headers:
+ if 'Content-Length' in response.headers:
# Delete Content-Length header so finalize() recalcs it.
- del response.headers["Content-Length"]
+ del response.headers['Content-Length']
return
if debug:
cherrypy.log('No acceptable encoding found.', context='GZIP')
- cherrypy.HTTPError(406, "identity, gzip").set_response()
+ cherrypy.HTTPError(406, 'identity, gzip').set_response()
diff --git a/cherrypy/lib/gctools.py b/cherrypy/lib/gctools.py
index 4b616c59..26746d78 100644
--- a/cherrypy/lib/gctools.py
+++ b/cherrypy/lib/gctools.py
@@ -1,6 +1,5 @@
import gc
import inspect
-import os
import sys
import time
@@ -36,7 +35,7 @@ class ReferrerTree(object):
refs = gc.get_referrers(obj)
self.ignore.append(refs)
if len(refs) > self.maxparents:
- return [("[%s referrers]" % len(refs), [])]
+ return [('[%s referrers]' % len(refs), [])]
try:
ascendcode = self.ascend.__code__
@@ -72,20 +71,20 @@ class ReferrerTree(object):
return self.peek(repr(obj))
if isinstance(obj, dict):
- return "{" + ", ".join(["%s: %s" % (self._format(k, descend=False),
+ return '{' + ', '.join(['%s: %s' % (self._format(k, descend=False),
self._format(v, descend=False))
- for k, v in obj.items()]) + "}"
+ for k, v in obj.items()]) + '}'
elif isinstance(obj, list):
- return "[" + ", ".join([self._format(item, descend=False)
- for item in obj]) + "]"
+ return '[' + ', '.join([self._format(item, descend=False)
+ for item in obj]) + ']'
elif isinstance(obj, tuple):
- return "(" + ", ".join([self._format(item, descend=False)
- for item in obj]) + ")"
+ return '(' + ', '.join([self._format(item, descend=False)
+ for item in obj]) + ')'
r = self.peek(repr(obj))
if isinstance(obj, (str, int, float)):
return r
- return "%s: %s" % (type(obj), r)
+ return '%s: %s' % (type(obj), r)
def format(self, tree):
"""Return a list of string reprs from a nested list of referrers."""
@@ -93,7 +92,7 @@ class ReferrerTree(object):
def ascend(branch, depth=1):
for parent, grandparents in branch:
- output.append((" " * depth) + self._format(parent))
+ output.append((' ' * depth) + self._format(parent))
if grandparents:
ascend(grandparents, depth + 1)
ascend(tree)
@@ -114,20 +113,22 @@ class RequestCounter(SimplePlugin):
def after_request(self):
self.count -= 1
+
+
request_counter = RequestCounter(cherrypy.engine)
request_counter.subscribe()
def get_context(obj):
if isinstance(obj, _cprequest.Request):
- return "path=%s;stage=%s" % (obj.path_info, obj.stage)
+ return 'path=%s;stage=%s' % (obj.path_info, obj.stage)
elif isinstance(obj, _cprequest.Response):
- return "status=%s" % obj.status
+ return 'status=%s' % obj.status
elif isinstance(obj, _cpwsgi.AppResponse):
- return "PATH_INFO=%s" % obj.environ.get('PATH_INFO', '')
- elif hasattr(obj, "tb_lineno"):
- return "tb_lineno=%s" % obj.tb_lineno
- return ""
+ return 'PATH_INFO=%s' % obj.environ.get('PATH_INFO', '')
+ elif hasattr(obj, 'tb_lineno'):
+ return 'tb_lineno=%s' % obj.tb_lineno
+ return ''
class GCRoot(object):
@@ -136,26 +137,27 @@ class GCRoot(object):
classes = [
(_cprequest.Request, 2, 2,
- "Should be 1 in this request thread and 1 in the main thread."),
+ 'Should be 1 in this request thread and 1 in the main thread.'),
(_cprequest.Response, 2, 2,
- "Should be 1 in this request thread and 1 in the main thread."),
+ 'Should be 1 in this request thread and 1 in the main thread.'),
(_cpwsgi.AppResponse, 1, 1,
- "Should be 1 in this request thread only."),
+ 'Should be 1 in this request thread only.'),
]
+ @cherrypy.expose
def index(self):
- return "Hello, world!"
- index.exposed = True
+ return 'Hello, world!'
+ @cherrypy.expose
def stats(self):
- output = ["Statistics:"]
+ output = ['Statistics:']
for trial in range(10):
if request_counter.count > 0:
break
time.sleep(0.5)
else:
- output.append("\nNot all requests closed properly.")
+ output.append('\nNot all requests closed properly.')
# gc_collect isn't perfectly synchronous, because it may
# break reference cycles that then take time to fully
@@ -173,11 +175,11 @@ class GCRoot(object):
for x in gc.garbage:
trash[type(x)] = trash.get(type(x), 0) + 1
if trash:
- output.insert(0, "\n%s unreachable objects:" % unreachable)
+ output.insert(0, '\n%s unreachable objects:' % unreachable)
trash = [(v, k) for k, v in trash.items()]
trash.sort()
for pair in trash:
- output.append(" " + repr(pair))
+ output.append(' ' + repr(pair))
# Check declared classes to verify uncollected instances.
# These don't have to be part of a cycle; they can be
@@ -193,25 +195,24 @@ class GCRoot(object):
if lenobj < minobj or lenobj > maxobj:
if minobj == maxobj:
output.append(
- "\nExpected %s %r references, got %s." %
+ '\nExpected %s %r references, got %s.' %
(minobj, cls, lenobj))
else:
output.append(
- "\nExpected %s to %s %r references, got %s." %
+ '\nExpected %s to %s %r references, got %s.' %
(minobj, maxobj, cls, lenobj))
for obj in objs:
if objgraph is not None:
ig = [id(objs), id(inspect.currentframe())]
- fname = "graph_%s_%s.png" % (cls.__name__, id(obj))
+ fname = 'graph_%s_%s.png' % (cls.__name__, id(obj))
objgraph.show_backrefs(
obj, extra_ignore=ig, max_depth=4, too_many=20,
filename=fname, extra_info=get_context)
- output.append("\nReferrers for %s (refcount=%s):" %
+ output.append('\nReferrers for %s (refcount=%s):' %
(repr(obj), sys.getrefcount(obj)))
t = ReferrerTree(ignore=[objs], maxdepth=3)
tree = t.ascend(obj)
output.extend(t.format(tree))
- return "\n".join(output)
- stats.exposed = True
+ return '\n'.join(output)
diff --git a/cherrypy/lib/http.py b/cherrypy/lib/http.py
deleted file mode 100644
index 12043ad1..00000000
--- a/cherrypy/lib/http.py
+++ /dev/null
@@ -1,6 +0,0 @@
-import warnings
-warnings.warn('cherrypy.lib.http has been deprecated and will be removed '
- 'in CherryPy 3.3 use cherrypy.lib.httputil instead.',
- DeprecationWarning)
-
-from cherrypy.lib.httputil import *
diff --git a/cherrypy/lib/httpauth.py b/cherrypy/lib/httpauth.py
index 6d519907..7e9fb035 100644
--- a/cherrypy/lib/httpauth.py
+++ b/cherrypy/lib/httpauth.py
@@ -20,8 +20,19 @@ Usage:
SUPPORTED_ALGORITHM - list of supported 'Digest' algorithms
SUPPORTED_QOP - list of supported 'Digest' 'qop'.
"""
+
+import time
+from hashlib import md5
+
+from six.moves.urllib.request import parse_http_list, parse_keqv_list
+
+from cherrypy._cpcompat import (
+ base64_decode, ntob,
+)
+
+
__version__ = 1, 0, 1
-__author__ = "Tiago Cogumbreiro <cogumbreiro@users.sf.net>"
+__author__ = 'Tiago Cogumbreiro <cogumbreiro@users.sf.net>'
__credits__ = """
Peter van Kampen for its recipe which implement most of Digest
authentication:
@@ -56,21 +67,16 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
-__all__ = ("digestAuth", "basicAuth", "doAuth", "checkResponse",
- "parseAuthorization", "SUPPORTED_ALGORITHM", "md5SessionKey",
- "calculateNonce", "SUPPORTED_QOP")
+__all__ = ('digestAuth', 'basicAuth', 'doAuth', 'checkResponse',
+ 'parseAuthorization', 'SUPPORTED_ALGORITHM', 'md5SessionKey',
+ 'calculateNonce', 'SUPPORTED_QOP')
##########################################################################
-import time
-from hashlib import md5
-from cherrypy._cpcompat import base64_decode, ntob
-from cherrypy._cpcompat import parse_http_list, parse_keqv_list
-
-MD5 = "MD5"
-MD5_SESS = "MD5-sess"
-AUTH = "auth"
-AUTH_INT = "auth-int"
+MD5 = 'MD5'
+MD5_SESS = 'MD5-sess'
+AUTH = 'auth'
+AUTH_INT = 'auth-int'
SUPPORTED_ALGORITHM = (MD5, MD5_SESS)
SUPPORTED_QOP = (AUTH, AUTH_INT)
@@ -95,10 +101,10 @@ def calculateNonce(realm, algorithm=MD5):
try:
encoder = DIGEST_AUTH_ENCODERS[algorithm]
except KeyError:
- raise NotImplementedError("The chosen algorithm (%s) does not have "
- "an implementation yet" % algorithm)
+ raise NotImplementedError('The chosen algorithm (%s) does not have '
+ 'an implementation yet' % algorithm)
- return encoder("%d:%s" % (time.time(), realm))
+ return encoder('%d:%s' % (time.time(), realm))
def digestAuth(realm, algorithm=MD5, nonce=None, qop=AUTH):
@@ -129,7 +135,7 @@ def doAuth(realm):
This should be set in the HTTP header under the key 'WWW-Authenticate'."""
- return digestAuth(realm) + " " + basicAuth(realm)
+ return digestAuth(realm) + ' ' + basicAuth(realm)
##########################################################################
@@ -143,31 +149,30 @@ def _parseDigestAuthorization(auth_params):
# Now validate the params
# Check for required parameters
- required = ["username", "realm", "nonce", "uri", "response"]
+ required = ['username', 'realm', 'nonce', 'uri', 'response']
for k in required:
if k not in params:
return None
# If qop is sent then cnonce and nc MUST be present
- if "qop" in params and not ("cnonce" in params
- and "nc" in params):
+ if 'qop' in params and not ('cnonce' in params and 'nc' in params):
return None
# If qop is not sent, neither cnonce nor nc can be present
- if ("cnonce" in params or "nc" in params) and \
- "qop" not in params:
+ if ('cnonce' in params or 'nc' in params) and 'qop' not in params:
return None
return params
def _parseBasicAuthorization(auth_params):
- username, password = base64_decode(auth_params).split(":", 1)
- return {"username": username, "password": password}
+ username, password = base64_decode(auth_params).split(':', 1)
+ return {'username': username, 'password': password}
+
AUTH_SCHEMES = {
- "basic": _parseBasicAuthorization,
- "digest": _parseDigestAuthorization,
+ 'basic': _parseBasicAuthorization,
+ 'digest': _parseDigestAuthorization,
}
@@ -176,9 +181,7 @@ def parseAuthorization(credentials):
the HTTP header to a map itself. If the parsing fails 'None' is returned.
"""
- global AUTH_SCHEMES
-
- auth_scheme, auth_params = credentials.split(" ", 1)
+ auth_scheme, auth_params = credentials.split(' ', 1)
auth_scheme = auth_scheme.lower()
parser = AUTH_SCHEMES[auth_scheme]
@@ -187,8 +190,8 @@ def parseAuthorization(credentials):
if params is None:
return
- assert "auth_scheme" not in params
- params["auth_scheme"] = auth_scheme
+ assert 'auth_scheme' not in params
+ params['auth_scheme'] = auth_scheme
return params
@@ -214,50 +217,50 @@ def md5SessionKey(params, password):
specification.
"""
- keys = ("username", "realm", "nonce", "cnonce")
+ keys = ('username', 'realm', 'nonce', 'cnonce')
params_copy = {}
for key in keys:
params_copy[key] = params[key]
- params_copy["algorithm"] = MD5_SESS
+ params_copy['algorithm'] = MD5_SESS
return _A1(params_copy, password)
def _A1(params, password):
- algorithm = params.get("algorithm", MD5)
+ algorithm = params.get('algorithm', MD5)
H = DIGEST_AUTH_ENCODERS[algorithm]
if algorithm == MD5:
# If the "algorithm" directive's value is "MD5" or is
# unspecified, then A1 is:
# A1 = unq(username-value) ":" unq(realm-value) ":" passwd
- return "%s:%s:%s" % (params["username"], params["realm"], password)
+ return '%s:%s:%s' % (params['username'], params['realm'], password)
elif algorithm == MD5_SESS:
# This is A1 if qop is set
# A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
# ":" unq(nonce-value) ":" unq(cnonce-value)
- h_a1 = H("%s:%s:%s" % (params["username"], params["realm"], password))
- return "%s:%s:%s" % (h_a1, params["nonce"], params["cnonce"])
+ h_a1 = H('%s:%s:%s' % (params['username'], params['realm'], password))
+ return '%s:%s:%s' % (h_a1, params['nonce'], params['cnonce'])
def _A2(params, method, kwargs):
# If the "qop" directive's value is "auth" or is unspecified, then A2 is:
# A2 = Method ":" digest-uri-value
- qop = params.get("qop", "auth")
- if qop == "auth":
- return method + ":" + params["uri"]
- elif qop == "auth-int":
+ qop = params.get('qop', 'auth')
+ if qop == 'auth':
+ return method + ':' + params['uri']
+ elif qop == 'auth-int':
# If the "qop" value is "auth-int", then A2 is:
# A2 = Method ":" digest-uri-value ":" H(entity-body)
- entity_body = kwargs.get("entity_body", "")
- H = kwargs["H"]
+ entity_body = kwargs.get('entity_body', '')
+ H = kwargs['H']
- return "%s:%s:%s" % (
+ return '%s:%s:%s' % (
method,
- params["uri"],
+ params['uri'],
H(entity_body)
)
@@ -265,19 +268,21 @@ def _A2(params, method, kwargs):
raise NotImplementedError("The 'qop' method is unknown: %s" % qop)
-def _computeDigestResponse(auth_map, password, method="GET", A1=None,
+def _computeDigestResponse(auth_map, password, method='GET', A1=None,
**kwargs):
"""
Generates a response respecting the algorithm defined in RFC 2617
"""
params = auth_map
- algorithm = params.get("algorithm", MD5)
+ algorithm = params.get('algorithm', MD5)
H = DIGEST_AUTH_ENCODERS[algorithm]
- KD = lambda secret, data: H(secret + ":" + data)
- qop = params.get("qop", None)
+ def KD(secret, data):
+ return H(secret + ':' + data)
+
+ qop = params.get('qop', None)
H_A2 = H(_A2(params, method, kwargs))
@@ -286,7 +291,7 @@ def _computeDigestResponse(auth_map, password, method="GET", A1=None,
else:
H_A1 = H(_A1(params, password))
- if qop in ("auth", "auth-int"):
+ if qop in ('auth', 'auth-int'):
# If the "qop" value is "auth" or "auth-int":
# request-digest = <"> < KD ( H(A1), unq(nonce-value)
# ":" nc-value
@@ -294,11 +299,11 @@ def _computeDigestResponse(auth_map, password, method="GET", A1=None,
# ":" unq(qop-value)
# ":" H(A2)
# ) <">
- request = "%s:%s:%s:%s:%s" % (
- params["nonce"],
- params["nc"],
- params["cnonce"],
- params["qop"],
+ request = '%s:%s:%s:%s:%s' % (
+ params['nonce'],
+ params['nc'],
+ params['cnonce'],
+ params['qop'],
H_A2,
)
elif qop is None:
@@ -306,12 +311,12 @@ def _computeDigestResponse(auth_map, password, method="GET", A1=None,
# for compatibility with RFC 2069):
# request-digest =
# <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
- request = "%s:%s" % (params["nonce"], H_A2)
+ request = '%s:%s' % (params['nonce'], H_A2)
return KD(H_A1, request)
-def _checkDigestResponse(auth_map, password, method="GET", A1=None, **kwargs):
+def _checkDigestResponse(auth_map, password, method='GET', A1=None, **kwargs):
"""This function is used to verify the response given by the client when
he tries to authenticate.
Optional arguments:
@@ -329,29 +334,31 @@ def _checkDigestResponse(auth_map, password, method="GET", A1=None, **kwargs):
response = _computeDigestResponse(
auth_map, password, method, A1, **kwargs)
- return response == auth_map["response"]
+ return response == auth_map['response']
def _checkBasicResponse(auth_map, password, method='GET', encrypt=None,
**kwargs):
# Note that the Basic response doesn't provide the realm value so we cannot
# test it
- pass_through = lambda password, username=None: password
+ def pass_through(password, username=None):
+ return password
encrypt = encrypt or pass_through
try:
- candidate = encrypt(auth_map["password"], auth_map["username"])
+ candidate = encrypt(auth_map['password'], auth_map['username'])
except TypeError:
# if encrypt only takes one parameter, it's the password
- candidate = encrypt(auth_map["password"])
+ candidate = encrypt(auth_map['password'])
return candidate == password
+
AUTH_RESPONSES = {
- "basic": _checkBasicResponse,
- "digest": _checkDigestResponse,
+ 'basic': _checkBasicResponse,
+ 'digest': _checkDigestResponse,
}
-def checkResponse(auth_map, password, method="GET", encrypt=None, **kwargs):
+def checkResponse(auth_map, password, method='GET', encrypt=None, **kwargs):
"""'checkResponse' compares the auth_map with the password and optionally
other arguments that each implementation might need.
@@ -368,6 +375,6 @@ def checkResponse(auth_map, password, method="GET", encrypt=None, **kwargs):
The 'A1' argument is only used in MD5_SESS algorithm based responses.
Check md5SessionKey() for more info.
"""
- checker = AUTH_RESPONSES[auth_map["auth_scheme"]]
+ checker = AUTH_RESPONSES[auth_map['auth_scheme']]
return checker(auth_map, password, method=method, encrypt=encrypt,
**kwargs)
diff --git a/cherrypy/lib/httputil.py b/cherrypy/lib/httputil.py
index f249e6dd..aa3dd6d4 100644
--- a/cherrypy/lib/httputil.py
+++ b/cherrypy/lib/httputil.py
@@ -7,10 +7,21 @@ FuManChu will personally hang you up by your thumbs and submit you
to a public caning.
"""
+import functools
+import email.utils
+import re
from binascii import b2a_base64
-from cherrypy._cpcompat import BaseHTTPRequestHandler, HTTPDate, ntob, ntou
-from cherrypy._cpcompat import basestring, bytestr, iteritems, nativestr
-from cherrypy._cpcompat import reversed, sorted, unicodestr, unquote_qs
+from cgi import parse_header
+from email.header import decode_header
+
+import six
+from six.moves import range, builtins
+from six.moves.BaseHTTPServer import BaseHTTPRequestHandler
+
+from cherrypy._cpcompat import ntob, ntou
+from cherrypy._cpcompat import text_or_bytes
+from cherrypy._cpcompat import unquote_qs
+
response_codes = BaseHTTPRequestHandler.responses.copy()
# From https://github.com/cherrypy/cherrypy/issues/361
@@ -22,34 +33,34 @@ response_codes[503] = ('Service Unavailable',
'request due to a temporary overloading or '
'maintenance of the server.')
-import re
-import urllib
+
+HTTPDate = functools.partial(email.utils.formatdate, usegmt=True)
def urljoin(*atoms):
- """Return the given path \*atoms, joined into a single URL.
+ r"""Return the given path \*atoms, joined into a single URL.
This will correctly join a SCRIPT_NAME and PATH_INFO into the
original URL, even if either atom is blank.
"""
- url = "/".join([x for x in atoms if x])
- while "//" in url:
- url = url.replace("//", "/")
+ url = '/'.join([x for x in atoms if x])
+ while '//' in url:
+ url = url.replace('//', '/')
# Special-case the final url of "", and return "/" instead.
- return url or "/"
+ return url or '/'
def urljoin_bytes(*atoms):
- """Return the given path *atoms, joined into a single URL.
+ """Return the given path `*atoms`, joined into a single URL.
This will correctly join a SCRIPT_NAME and PATH_INFO into the
original URL, even if either atom is blank.
"""
- url = ntob("/").join([x for x in atoms if x])
- while ntob("//") in url:
- url = url.replace(ntob("//"), ntob("/"))
+ url = ntob('/').join([x for x in atoms if x])
+ while ntob('//') in url:
+ url = url.replace(ntob('//'), ntob('/'))
# Special-case the final url of "", and return "/" instead.
- return url or ntob("/")
+ return url or ntob('/')
def protocol_from_http(protocol_str):
@@ -72,9 +83,9 @@ def get_ranges(headervalue, content_length):
return None
result = []
- bytesunit, byteranges = headervalue.split("=", 1)
- for brange in byteranges.split(","):
- start, stop = [x.strip() for x in brange.split("-", 1)]
+ bytesunit, byteranges = headervalue.split('=', 1)
+ for brange in byteranges.split(','):
+ start, stop = [x.strip() for x in brange.split('-', 1)]
if start:
if not stop:
stop = content_length - 1
@@ -108,9 +119,9 @@ def get_ranges(headervalue, content_length):
# If the entity is shorter than the specified suffix-length,
# the entire entity-body is used.
if int(stop) > content_length:
- result.append((0, content_length))
+ result.append((0, content_length))
else:
- result.append((content_length - int(stop), content_length))
+ result.append((content_length - int(stop), content_length))
return result
@@ -126,14 +137,14 @@ class HeaderElement(object):
self.params = params
def __cmp__(self, other):
- return cmp(self.value, other.value)
+ return builtins.cmp(self.value, other.value)
def __lt__(self, other):
return self.value < other.value
def __str__(self):
- p = [";%s=%s" % (k, v) for k, v in iteritems(self.params)]
- return str("%s%s" % (self.value, "".join(p)))
+ p = [';%s=%s' % (k, v) for k, v in six.iteritems(self.params)]
+ return str('%s%s' % (self.value, ''.join(p)))
def __bytes__(self):
return ntob(self.__str__())
@@ -141,32 +152,17 @@ class HeaderElement(object):
def __unicode__(self):
return ntou(self.__str__())
+ @staticmethod
def parse(elementstr):
"""Transform 'token;key=val' to ('token', {'key': 'val'})."""
- # Split the element into a value and parameters. The 'value' may
- # be of the form, "token=token", but we don't split that here.
- atoms = [x.strip() for x in elementstr.split(";") if x.strip()]
- if not atoms:
- initial_value = ''
- else:
- initial_value = atoms.pop(0).strip()
- params = {}
- for atom in atoms:
- atom = [x.strip() for x in atom.split("=", 1) if x.strip()]
- key = atom.pop(0)
- if atom:
- val = atom[0]
- else:
- val = ""
- params[key] = val
+ initial_value, params = parse_header(elementstr)
return initial_value, params
- parse = staticmethod(parse)
+ @classmethod
def from_str(cls, elementstr):
"""Construct an instance from a string of the form 'token;key=val'."""
ival, params = cls.parse(elementstr)
return cls(ival, params)
- from_str = classmethod(from_str)
q_separator = re.compile(r'; *q *=')
@@ -183,6 +179,7 @@ class AcceptElement(HeaderElement):
have been the other way around, but it's too late to fix now.
"""
+ @classmethod
def from_str(cls, elementstr):
qvalue = None
# The first "q" parameter (if any) separates the initial
@@ -196,21 +193,21 @@ class AcceptElement(HeaderElement):
media_type, params = cls.parse(media_range)
if qvalue is not None:
- params["q"] = qvalue
+ params['q'] = qvalue
return cls(media_type, params)
- from_str = classmethod(from_str)
+ @property
def qvalue(self):
- val = self.params.get("q", "1")
+ 'The qvalue, or priority, of this value.'
+ val = self.params.get('q', '1')
if isinstance(val, HeaderElement):
val = val.value
return float(val)
- qvalue = property(qvalue, doc="The qvalue, or priority, of this value.")
def __cmp__(self, other):
- diff = cmp(self.qvalue, other.qvalue)
+ diff = builtins.cmp(self.qvalue, other.qvalue)
if diff == 0:
- diff = cmp(str(self), str(other))
+ diff = builtins.cmp(str(self), str(other))
return diff
def __lt__(self, other):
@@ -219,7 +216,10 @@ class AcceptElement(HeaderElement):
else:
return self.qvalue < other.qvalue
+
RE_HEADER_SPLIT = re.compile(',(?=(?:[^"]*"[^"]*")*[^"]*$)')
+
+
def header_elements(fieldname, fieldvalue):
"""Return a sorted HeaderElement list from a comma-separated header string.
"""
@@ -228,7 +228,7 @@ def header_elements(fieldname, fieldvalue):
result = []
for element in RE_HEADER_SPLIT.split(fieldvalue):
- if fieldname.startswith("Accept") or fieldname == 'TE':
+ if fieldname.startswith('Accept') or fieldname == 'TE':
hv = AcceptElement.from_str(element)
else:
hv = HeaderElement.from_str(element)
@@ -238,14 +238,14 @@ def header_elements(fieldname, fieldvalue):
def decode_TEXT(value):
- r"""Decode :rfc:`2047` TEXT (e.g. "=?utf-8?q?f=C3=BCr?=" -> "f\xfcr")."""
- try:
- # Python 3
- from email.header import decode_header
- except ImportError:
- from email.Header import decode_header
+ r"""
+ Decode :rfc:`2047` TEXT
+
+ >>> decode_TEXT("=?utf-8?q?f=C3=BCr?=") == b'f\xfcr'.decode('latin-1')
+ True
+ """
atoms = decode_header(value)
- decodedvalue = ""
+ decodedvalue = ''
for atom, charset in atoms:
if charset is not None:
atom = atom.decode(charset)
@@ -253,41 +253,51 @@ def decode_TEXT(value):
return decodedvalue
+def decode_TEXT_maybe(value):
+ """
+ Decode the text but only if '=?' appears in it.
+ """
+ return decode_TEXT(value) if '=?' in value else value
+
+
def valid_status(status):
"""Return legal HTTP status Code, Reason-phrase and Message.
- The status arg must be an int, or a str that begins with an int.
+ The status arg must be an int, a str that begins with an int
+ or the constant from ``http.client`` stdlib module.
+
+ If status has no reason-phrase is supplied, a default reason-
+ phrase will be provided.
- If status is an int, or a str and no reason-phrase is supplied,
- a default reason-phrase will be provided.
+ >>> from six.moves import http_client
+ >>> from six.moves.BaseHTTPServer import BaseHTTPRequestHandler
+ >>> valid_status(http_client.ACCEPTED) == (
+ ... int(http_client.ACCEPTED),
+ ... ) + BaseHTTPRequestHandler.responses[http_client.ACCEPTED]
+ True
"""
if not status:
status = 200
- status = str(status)
- parts = status.split(" ", 1)
- if len(parts) == 1:
- # No reason supplied.
- code, = parts
- reason = None
- else:
- code, reason = parts
- reason = reason.strip()
+ code, reason = status, None
+ if isinstance(status, six.string_types):
+ code, _, reason = status.partition(' ')
+ reason = reason.strip() or None
try:
code = int(code)
- except ValueError:
- raise ValueError("Illegal response status from server "
- "(%s is non-numeric)." % repr(code))
+ except (TypeError, ValueError):
+ raise ValueError('Illegal response status from server '
+ '(%s is non-numeric).' % repr(code))
if code < 100 or code > 599:
- raise ValueError("Illegal response status from server "
- "(%s is out of range)." % repr(code))
+ raise ValueError('Illegal response status from server '
+ '(%s is out of range).' % repr(code))
if code not in response_codes:
# code is unknown but not illegal
- default_reason, message = "", ""
+ default_reason, message = '', ''
else:
default_reason, message = response_codes[code]
@@ -328,7 +338,7 @@ def _parse_qs(qs, keep_blank_values=0, strict_parsing=0, encoding='utf-8'):
nv = name_value.split('=', 1)
if len(nv) != 2:
if strict_parsing:
- raise ValueError("bad query field: %r" % (name_value,))
+ raise ValueError('bad query field: %r' % (name_value,))
# Handle case of a control-name with no equal sign
if keep_blank_values:
nv.append('')
@@ -346,7 +356,7 @@ def _parse_qs(qs, keep_blank_values=0, strict_parsing=0, encoding='utf-8'):
return d
-image_map_pattern = re.compile(r"[0-9]+,[0-9]+")
+image_map_pattern = re.compile(r'[0-9]+,[0-9]+')
def parse_query_string(query_string, keep_blank_values=True, encoding='utf-8'):
@@ -359,60 +369,84 @@ def parse_query_string(query_string, keep_blank_values=True, encoding='utf-8'):
if image_map_pattern.match(query_string):
# Server-side image map. Map the coords to 'x' and 'y'
# (like CGI::Request does).
- pm = query_string.split(",")
+ pm = query_string.split(',')
pm = {'x': int(pm[0]), 'y': int(pm[1])}
else:
pm = _parse_qs(query_string, keep_blank_values, encoding=encoding)
return pm
-class CaseInsensitiveDict(dict):
-
- """A case-insensitive dict subclass.
-
- Each key is changed on entry to str(key).title().
+####
+# Inlined from jaraco.collections 1.5.2
+# Ref #1673
+class KeyTransformingDict(dict):
"""
+ A dict subclass that transforms the keys before they're used.
+ Subclasses may override the default transform_key to customize behavior.
+ """
+ @staticmethod
+ def transform_key(key):
+ return key
+
+ def __init__(self, *args, **kargs):
+ super(KeyTransformingDict, self).__init__()
+ # build a dictionary using the default constructs
+ d = dict(*args, **kargs)
+ # build this dictionary using transformed keys.
+ for item in d.items():
+ self.__setitem__(*item)
+
+ def __setitem__(self, key, val):
+ key = self.transform_key(key)
+ super(KeyTransformingDict, self).__setitem__(key, val)
def __getitem__(self, key):
- return dict.__getitem__(self, str(key).title())
+ key = self.transform_key(key)
+ return super(KeyTransformingDict, self).__getitem__(key)
- def __setitem__(self, key, value):
- dict.__setitem__(self, str(key).title(), value)
+ def __contains__(self, key):
+ key = self.transform_key(key)
+ return super(KeyTransformingDict, self).__contains__(key)
def __delitem__(self, key):
- dict.__delitem__(self, str(key).title())
+ key = self.transform_key(key)
+ return super(KeyTransformingDict, self).__delitem__(key)
- def __contains__(self, key):
- return dict.__contains__(self, str(key).title())
+ def get(self, key, *args, **kwargs):
+ key = self.transform_key(key)
+ return super(KeyTransformingDict, self).get(key, *args, **kwargs)
+
+ def setdefault(self, key, *args, **kwargs):
+ key = self.transform_key(key)
+ return super(KeyTransformingDict, self).setdefault(
+ key, *args, **kwargs)
- def get(self, key, default=None):
- return dict.get(self, str(key).title(), default)
+ def pop(self, key, *args, **kwargs):
+ key = self.transform_key(key)
+ return super(KeyTransformingDict, self).pop(key, *args, **kwargs)
- if hasattr({}, 'has_key'):
- def has_key(self, key):
- return str(key).title() in self
+ def matching_key_for(self, key):
+ """
+ Given a key, return the actual key stored in self that matches.
+ Raise KeyError if the key isn't found.
+ """
+ try:
+ return next(e_key for e_key in self.keys() if e_key == key)
+ except StopIteration:
+ raise KeyError(key)
+####
- def update(self, E):
- for k in E.keys():
- self[str(k).title()] = E[k]
- def fromkeys(cls, seq, value=None):
- newdict = cls()
- for k in seq:
- newdict[str(k).title()] = value
- return newdict
- fromkeys = classmethod(fromkeys)
+class CaseInsensitiveDict(KeyTransformingDict):
- def setdefault(self, key, x=None):
- key = str(key).title()
- try:
- return self[key]
- except KeyError:
- self[key] = x
- return x
+ """A case-insensitive dict subclass.
+
+ Each key is changed on entry to str(key).title().
+ """
- def pop(self, key, default):
- return dict.pop(self, str(key).title(), default)
+ @staticmethod
+ def transform_key(key):
+ return str(key).title()
# TEXT = <any OCTET except CTLs, but including LWS>
@@ -420,10 +454,10 @@ class CaseInsensitiveDict(dict):
# A CRLF is allowed in the definition of TEXT only as part of a header
# field continuation. It is expected that the folding LWS will be
# replaced with a single SP before interpretation of the TEXT value."
-if nativestr == bytestr:
- header_translate_table = ''.join([chr(i) for i in xrange(256)])
+if str == bytes:
+ header_translate_table = ''.join([chr(i) for i in range(256)])
header_translate_deletechars = ''.join(
- [chr(i) for i in xrange(32)]) + chr(127)
+ [chr(i) for i in range(32)]) + chr(127)
else:
header_translate_table = None
header_translate_deletechars = bytes(range(32)) + bytes([127])
@@ -440,7 +474,7 @@ class HeaderMap(CaseInsensitiveDict):
"""
protocol = (1, 1)
- encodings = ["ISO-8859-1"]
+ encodings = ['ISO-8859-1']
# Someday, when http-bis is done, this will probably get dropped
# since few servers, clients, or intermediaries do it. But until then,
@@ -463,19 +497,20 @@ class HeaderMap(CaseInsensitiveDict):
"""Transform self into a list of (name, value) tuples."""
return list(self.encode_header_items(self.items()))
+ @classmethod
def encode_header_items(cls, header_items):
"""
Prepare the sequence of name, value tuples into a form suitable for
transmitting on the wire for HTTP.
"""
for k, v in header_items:
- if isinstance(k, unicodestr):
+ if isinstance(k, six.text_type):
k = cls.encode(k)
- if not isinstance(v, basestring):
+ if not isinstance(v, text_or_bytes):
v = str(v)
- if isinstance(v, unicodestr):
+ if isinstance(v, six.text_type):
v = cls.encode(v)
# See header_translate_* constants above.
@@ -486,8 +521,8 @@ class HeaderMap(CaseInsensitiveDict):
header_translate_deletechars)
yield (k, v)
- encode_header_items = classmethod(encode_header_items)
+ @classmethod
def encode(cls, v):
"""Return the given header name or value, encoded for HTTP output."""
for enc in cls.encodings:
@@ -505,10 +540,9 @@ class HeaderMap(CaseInsensitiveDict):
v = b2a_base64(v.encode('utf-8'))
return (ntob('=?utf-8?b?') + v.strip(ntob('\n')) + ntob('?='))
- raise ValueError("Could not encode header part %r using "
- "any of the encodings %r." %
+ raise ValueError('Could not encode header part %r using '
+ 'any of the encodings %r.' %
(v, cls.encodings))
- encode = classmethod(encode)
class Host(object):
@@ -521,9 +555,9 @@ class Host(object):
"""
- ip = "0.0.0.0"
+ ip = '0.0.0.0'
port = 80
- name = "unknown.tld"
+ name = 'unknown.tld'
def __init__(self, ip, port, name=None):
self.ip = ip
@@ -533,4 +567,4 @@ class Host(object):
self.name = name
def __repr__(self):
- return "httputil.Host(%r, %r, %r)" % (self.ip, self.port, self.name)
+ return 'httputil.Host(%r, %r, %r)' % (self.ip, self.port, self.name)
diff --git a/cherrypy/lib/jsontools.py b/cherrypy/lib/jsontools.py
index 90b3ff8a..48683097 100644
--- a/cherrypy/lib/jsontools.py
+++ b/cherrypy/lib/jsontools.py
@@ -1,17 +1,15 @@
import cherrypy
-from cherrypy._cpcompat import basestring, ntou, json_encode, json_decode
+from cherrypy._cpcompat import text_or_bytes, ntou, json_encode, json_decode
def json_processor(entity):
"""Read application/json data into request.json."""
- if not entity.headers.get(ntou("Content-Length"), ntou("")):
+ if not entity.headers.get(ntou('Content-Length'), ntou('')):
raise cherrypy.HTTPError(411)
body = entity.fp.read()
- try:
+ with cherrypy.HTTPError.handle(ValueError, 400, 'Invalid JSON document'):
cherrypy.serving.request.json = json_decode(body.decode('utf-8'))
- except ValueError:
- raise cherrypy.HTTPError(400, 'Invalid JSON document')
def json_in(content_type=[ntou('application/json'), ntou('text/javascript')],
@@ -36,12 +34,9 @@ def json_in(content_type=[ntou('application/json'), ntou('text/javascript')],
request header, or it will raise "411 Length Required". If for any
other reason the request entity cannot be deserialized from JSON,
it will raise "400 Bad Request: Invalid JSON document".
-
- You must be using Python 2.6 or greater, or have the 'simplejson'
- package importable; otherwise, ValueError is raised during processing.
"""
request = cherrypy.serving.request
- if isinstance(content_type, basestring):
+ if isinstance(content_type, text_or_bytes):
content_type = [content_type]
if force:
@@ -74,9 +69,6 @@ def json_out(content_type='application/json', debug=False,
Provide your own handler to use a custom encoder. For example
cherrypy.config['tools.json_out.handler'] = <function>, or
@json_out(handler=function).
-
- You must be using Python 2.6 or greater, or have the 'simplejson'
- package importable; otherwise, ValueError is raised during processing.
"""
request = cherrypy.serving.request
# request.handler may be set to None by e.g. the caching tool
diff --git a/cherrypy/lib/lockfile.py b/cherrypy/lib/lockfile.py
index b9d8e027..e1fe0b8c 100644
--- a/cherrypy/lib/lockfile.py
+++ b/cherrypy/lib/lockfile.py
@@ -1,147 +1,143 @@
-"""
-Platform-independent file locking. Inspired by and modeled after zc.lockfile.
-"""
-
-import os
-
-try:
- import msvcrt
-except ImportError:
- pass
-
-try:
- import fcntl
-except ImportError:
- pass
-
-
-class LockError(Exception):
-
- "Could not obtain a lock"
-
- msg = "Unable to lock %r"
-
- def __init__(self, path):
- super(LockError, self).__init__(self.msg % path)
-
-
-class UnlockError(LockError):
-
- "Could not release a lock"
-
- msg = "Unable to unlock %r"
-
-
-# first, a default, naive locking implementation
-class LockFile(object):
-
- """
- A default, naive locking implementation. Always fails if the file
- already exists.
- """
-
- def __init__(self, path):
- self.path = path
- try:
- fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
- except OSError:
- raise LockError(self.path)
- os.close(fd)
-
- def release(self):
- os.remove(self.path)
-
- def remove(self):
- pass
-
-
-class SystemLockFile(object):
-
- """
- An abstract base class for platform-specific locking.
- """
-
- def __init__(self, path):
- self.path = path
-
- try:
- # Open lockfile for writing without truncation:
- self.fp = open(path, 'r+')
- except IOError:
- # If the file doesn't exist, IOError is raised; Use a+ instead.
- # Note that there may be a race here. Multiple processes
- # could fail on the r+ open and open the file a+, but only
- # one will get the the lock and write a pid.
- self.fp = open(path, 'a+')
-
- try:
- self._lock_file()
- except:
- self.fp.seek(1)
- self.fp.close()
- del self.fp
- raise
-
- self.fp.write(" %s\n" % os.getpid())
- self.fp.truncate()
- self.fp.flush()
-
- def release(self):
- if not hasattr(self, 'fp'):
- return
- self._unlock_file()
- self.fp.close()
- del self.fp
-
- def remove(self):
- """
- Attempt to remove the file
- """
- try:
- os.remove(self.path)
- except:
- pass
-
- #@abc.abstract_method
- # def _lock_file(self):
- # """Attempt to obtain the lock on self.fp. Raise LockError if not
- # acquired."""
-
- def _unlock_file(self):
- """Attempt to obtain the lock on self.fp. Raise UnlockError if not
- released."""
-
-
-class WindowsLockFile(SystemLockFile):
-
- def _lock_file(self):
- # Lock just the first byte
- try:
- msvcrt.locking(self.fp.fileno(), msvcrt.LK_NBLCK, 1)
- except IOError:
- raise LockError(self.fp.name)
-
- def _unlock_file(self):
- try:
- self.fp.seek(0)
- msvcrt.locking(self.fp.fileno(), msvcrt.LK_UNLCK, 1)
- except IOError:
- raise UnlockError(self.fp.name)
-
-if 'msvcrt' in globals():
- LockFile = WindowsLockFile
-
-
-class UnixLockFile(SystemLockFile):
-
- def _lock_file(self):
- flags = fcntl.LOCK_EX | fcntl.LOCK_NB
- try:
- fcntl.flock(self.fp.fileno(), flags)
- except IOError:
- raise LockError(self.fp.name)
-
- # no need to implement _unlock_file, it will be unlocked on close()
-
-if 'fcntl' in globals():
- LockFile = UnixLockFile
+"""
+Platform-independent file locking. Inspired by and modeled after zc.lockfile.
+"""
+
+import os
+
+try:
+ import msvcrt
+except ImportError:
+ pass
+
+try:
+ import fcntl
+except ImportError:
+ pass
+
+
+class LockError(Exception):
+
+ 'Could not obtain a lock'
+
+ msg = 'Unable to lock %r'
+
+ def __init__(self, path):
+ super(LockError, self).__init__(self.msg % path)
+
+
+class UnlockError(LockError):
+
+ 'Could not release a lock'
+
+ msg = 'Unable to unlock %r'
+
+
+# first, a default, naive locking implementation
+class NaiveLockFile(object):
+
+ """
+ A default, naive locking implementation. Always fails if the file
+ already exists.
+ """
+
+ def __init__(self, path):
+ self.path = path
+ try:
+ fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
+ except OSError:
+ raise LockError(self.path)
+ os.close(fd)
+
+ def release(self):
+ os.remove(self.path)
+
+ def remove(self):
+ pass
+
+
+class SystemLockFile(object):
+
+ """
+ An abstract base class for platform-specific locking.
+ """
+
+ def __init__(self, path):
+ self.path = path
+
+ try:
+ # Open lockfile for writing without truncation:
+ self.fp = open(path, 'r+')
+ except IOError:
+ # If the file doesn't exist, IOError is raised; Use a+ instead.
+ # Note that there may be a race here. Multiple processes
+ # could fail on the r+ open and open the file a+, but only
+ # one will get the the lock and write a pid.
+ self.fp = open(path, 'a+')
+
+ try:
+ self._lock_file()
+ except Exception:
+ self.fp.seek(1)
+ self.fp.close()
+ del self.fp
+ raise
+
+ self.fp.write(' %s\n' % os.getpid())
+ self.fp.truncate()
+ self.fp.flush()
+
+ def release(self):
+ if not hasattr(self, 'fp'):
+ return
+ self._unlock_file()
+ self.fp.close()
+ del self.fp
+
+ def remove(self):
+ """
+ Attempt to remove the file
+ """
+ try:
+ os.remove(self.path)
+ except Exception:
+ pass
+
+ def _unlock_file(self):
+ """Attempt to obtain the lock on self.fp. Raise UnlockError if not
+ released."""
+
+
+class WindowsLockFile(SystemLockFile):
+
+ def _lock_file(self):
+ # Lock just the first byte
+ try:
+ msvcrt.locking(self.fp.fileno(), msvcrt.LK_NBLCK, 1)
+ except IOError:
+ raise LockError(self.fp.name)
+
+ def _unlock_file(self):
+ try:
+ self.fp.seek(0)
+ msvcrt.locking(self.fp.fileno(), msvcrt.LK_UNLCK, 1)
+ except IOError:
+ raise UnlockError(self.fp.name)
+
+
+class UnixLockFile(SystemLockFile):
+
+ def _lock_file(self):
+ flags = fcntl.LOCK_EX | fcntl.LOCK_NB
+ try:
+ fcntl.flock(self.fp.fileno(), flags)
+ except IOError:
+ raise LockError(self.fp.name)
+
+ # no need to implement _unlock_file, it will be unlocked on close()
+
+
+LockFile = (
+ UnixLockFile if 'fcntl' in globals() else
+ WindowsLockFile if 'msvcrt' in globals() else
+ NaiveLockFile
+)
diff --git a/cherrypy/lib/locking.py b/cherrypy/lib/locking.py
index 72dda9b3..317fb58c 100644
--- a/cherrypy/lib/locking.py
+++ b/cherrypy/lib/locking.py
@@ -11,7 +11,7 @@ class Timer(object):
A simple timer that will indicate when an expiration time has passed.
"""
def __init__(self, expiration):
- "Create a timer that expires at `expiration` (UTC datetime)"
+ 'Create a timer that expires at `expiration` (UTC datetime)'
self.expiration = expiration
@classmethod
@@ -26,7 +26,7 @@ class Timer(object):
class LockTimeout(Exception):
- "An exception when a lock could not be acquired before a timeout period"
+ 'An exception when a lock could not be acquired before a timeout period'
class LockChecker(object):
@@ -43,5 +43,5 @@ class LockChecker(object):
def expired(self):
if self.timer.expired():
raise LockTimeout(
- "Timeout acquiring lock for %(session_id)s" % vars(self))
+ 'Timeout acquiring lock for %(session_id)s' % vars(self))
return False
diff --git a/cherrypy/lib/profiler.py b/cherrypy/lib/profiler.py
index a3477454..fccf2eb8 100644
--- a/cherrypy/lib/profiler.py
+++ b/cherrypy/lib/profiler.py
@@ -10,9 +10,9 @@ You can profile any of your pages as follows::
class Root:
p = profiler.Profiler("/path/to/profile/dir")
+ @cherrypy.expose
def index(self):
self.p.run(self._index)
- index.exposed = True
def _index(self):
return "Hello, world!"
@@ -33,29 +33,36 @@ module from the command line, it will call ``serve()`` for you.
"""
+import io
+import os
+import os.path
+import sys
+import warnings
+
+import cherrypy
-def new_func_strip_path(func_name):
- """Make profiler output more readable by adding `__init__` modules' parents
- """
- filename, line, name = func_name
- if filename.endswith("__init__.py"):
- return os.path.basename(filename[:-12]) + filename[-12:], line, name
- return os.path.basename(filename), line, name
try:
import profile
import pstats
+
+ def new_func_strip_path(func_name):
+ """Make profiler output more readable by adding `__init__` modules' parents
+ """
+ filename, line, name = func_name
+ if filename.endswith('__init__.py'):
+ return (
+ os.path.basename(filename[:-12]) + filename[-12:],
+ line,
+ name,
+ )
+ return os.path.basename(filename), line, name
+
pstats.func_strip_path = new_func_strip_path
except ImportError:
profile = None
pstats = None
-import os
-import os.path
-import sys
-import warnings
-
-from cherrypy._cpcompat import StringIO
_count = 0
@@ -64,7 +71,7 @@ class Profiler(object):
def __init__(self, path=None):
if not path:
- path = os.path.join(os.path.dirname(__file__), "profile")
+ path = os.path.join(os.path.dirname(__file__), 'profile')
self.path = path
if not os.path.exists(path):
os.makedirs(path)
@@ -73,7 +80,7 @@ class Profiler(object):
"""Dump profile data into self.path."""
global _count
c = _count = _count + 1
- path = os.path.join(self.path, "cp_%04d.prof" % c)
+ path = os.path.join(self.path, 'cp_%04d.prof' % c)
prof = profile.Profile()
result = prof.runcall(func, *args, **params)
prof.dump_stats(path)
@@ -83,12 +90,12 @@ class Profiler(object):
""":rtype: list of available profiles.
"""
return [f for f in os.listdir(self.path)
- if f.startswith("cp_") and f.endswith(".prof")]
+ if f.startswith('cp_') and f.endswith('.prof')]
def stats(self, filename, sortby='cumulative'):
""":rtype stats(index): output of print_stats() for the given profile.
"""
- sio = StringIO()
+ sio = io.StringIO()
if sys.version_info >= (2, 5):
s = pstats.Stats(os.path.join(self.path, filename), stream=sio)
s.strip_dirs()
@@ -110,6 +117,7 @@ class Profiler(object):
sio.close()
return response
+ @cherrypy.expose
def index(self):
return """<html>
<head><title>CherryPy profile data</title></head>
@@ -119,23 +127,21 @@ class Profiler(object):
</frameset>
</html>
"""
- index.exposed = True
+ @cherrypy.expose
def menu(self):
- yield "<h2>Profiling runs</h2>"
- yield "<p>Click on one of the runs below to see profiling data.</p>"
+ yield '<h2>Profiling runs</h2>'
+ yield '<p>Click on one of the runs below to see profiling data.</p>'
runs = self.statfiles()
runs.sort()
for i in runs:
yield "<a href='report?filename=%s' target='main'>%s</a><br />" % (
i, i)
- menu.exposed = True
+ @cherrypy.expose
def report(self, filename):
- import cherrypy
cherrypy.response.headers['Content-Type'] = 'text/plain'
return self.stats(filename)
- report.exposed = True
class ProfileAggregator(Profiler):
@@ -147,7 +153,7 @@ class ProfileAggregator(Profiler):
self.profiler = profile.Profile()
def run(self, func, *args, **params):
- path = os.path.join(self.path, "cp_%04d.prof" % self.count)
+ path = os.path.join(self.path, 'cp_%04d.prof' % self.count)
result = self.profiler.runcall(func, *args, **params)
self.profiler.dump_stats(path)
return result
@@ -172,11 +178,11 @@ class make_app:
"""
if profile is None or pstats is None:
- msg = ("Your installation of Python does not have a profile "
+ msg = ('Your installation of Python does not have a profile '
"module. If you're on Debian, try "
- "`sudo apt-get install python-profiler`. "
- "See http://www.cherrypy.org/wiki/ProfilingOnDebian "
- "for details.")
+ '`sudo apt-get install python-profiler`. '
+ 'See http://www.cherrypy.org/wiki/ProfilingOnDebian '
+ 'for details.')
warnings.warn(msg)
self.nextapp = nextapp
@@ -197,20 +203,19 @@ class make_app:
def serve(path=None, port=8080):
if profile is None or pstats is None:
- msg = ("Your installation of Python does not have a profile module. "
+ msg = ('Your installation of Python does not have a profile module. '
"If you're on Debian, try "
- "`sudo apt-get install python-profiler`. "
- "See http://www.cherrypy.org/wiki/ProfilingOnDebian "
- "for details.")
+ '`sudo apt-get install python-profiler`. '
+ 'See http://www.cherrypy.org/wiki/ProfilingOnDebian '
+ 'for details.')
warnings.warn(msg)
- import cherrypy
cherrypy.config.update({'server.socket_port': int(port),
'server.thread_pool': 10,
- 'environment': "production",
+ 'environment': 'production',
})
cherrypy.quickstart(Profiler(path))
-if __name__ == "__main__":
+if __name__ == '__main__':
serve(*tuple(sys.argv[1:]))
diff --git a/cherrypy/lib/reprconf.py b/cherrypy/lib/reprconf.py
index 8af1f777..208a7a4e 100644
--- a/cherrypy/lib/reprconf.py
+++ b/cherrypy/lib/reprconf.py
@@ -18,6 +18,8 @@ by adding a named handler to Config.namespaces. The name can be any string,
and the handler must be either a callable or a context manager.
"""
+from cherrypy._cpcompat import text_or_bytes
+
try:
# Python 3.0+
from configparser import ConfigParser
@@ -25,29 +27,19 @@ except ImportError:
from ConfigParser import ConfigParser
try:
- set
+ text_or_bytes
except NameError:
- from sets import Set as set
-
-try:
- basestring
-except NameError:
- basestring = str
-
-try:
- # Python 3
- import builtins
-except ImportError:
- # Python 2
- import __builtin__ as builtins
+ text_or_bytes = str
import operator as _operator
import sys
+from six.moves import builtins
+
def as_dict(config):
"""Return a dict from 'config' whether it is a dict, file, or filename."""
- if isinstance(config, basestring):
+ if isinstance(config, text_or_bytes):
config = Parser().dict_from_file(config)
elif hasattr(config, 'read'):
config = Parser().dict_from_file(config)
@@ -83,19 +75,19 @@ class NamespaceSet(dict):
# Separate the given config into namespaces
ns_confs = {}
for k in config:
- if "." in k:
- ns, name = k.split(".", 1)
+ if '.' in k:
+ ns, name = k.split('.', 1)
bucket = ns_confs.setdefault(ns, {})
bucket[name] = config[k]
# I chose __enter__ and __exit__ so someday this could be
# rewritten using Python 2.5's 'with' statement:
- # for ns, handler in self.iteritems():
+ # for ns, handler in six.iteritems(self):
# with handler as callable:
- # for k, v in ns_confs.get(ns, {}).iteritems():
+ # for k, v in six.iteritems(ns_confs.get(ns, {})):
# callable(k, v)
for ns, handler in self.items():
- exit = getattr(handler, "__exit__", None)
+ exit = getattr(handler, '__exit__', None)
if exit:
callable = handler.__enter__()
no_exc = True
@@ -103,7 +95,7 @@ class NamespaceSet(dict):
try:
for k, v in ns_confs.get(ns, {}).items():
callable(k, v)
- except:
+ except Exception:
# The exceptional case is handled here
no_exc = False
if exit is None:
@@ -120,7 +112,7 @@ class NamespaceSet(dict):
handler(k, v)
def __repr__(self):
- return "%s.%s(%s)" % (self.__module__, self.__class__.__name__,
+ return '%s.%s(%s)' % (self.__module__, self.__class__.__name__,
dict.__repr__(self))
def __copy__(self):
@@ -155,7 +147,7 @@ class Config(dict):
def update(self, config):
"""Update self from a dict, file or filename."""
- if isinstance(config, basestring):
+ if isinstance(config, text_or_bytes):
# Filename
config = Parser().dict_from_file(config)
elif hasattr(config, 'read'):
@@ -192,7 +184,7 @@ class Parser(ConfigParser):
return optionstr
def read(self, filenames):
- if isinstance(filenames, basestring):
+ if isinstance(filenames, text_or_bytes):
filenames = [filenames]
for filename in filenames:
# try:
@@ -218,8 +210,8 @@ class Parser(ConfigParser):
value = unrepr(value)
except Exception:
x = sys.exc_info()[1]
- msg = ("Config error in section: %r, option: %r, "
- "value: %r. Config values must be valid Python." %
+ msg = ('Config error in section: %r, option: %r, '
+ 'value: %r. Config values must be valid Python.' %
(section, option, value))
raise ValueError(msg, x.__class__.__name__, x.args)
result[section][option] = value
@@ -241,7 +233,7 @@ class _Builder2:
def build(self, o):
m = getattr(self, 'build_' + o.__class__.__name__, None)
if m is None:
- raise TypeError("unrepr does not recognize %s" %
+ raise TypeError('unrepr does not recognize %s' %
repr(o.__class__.__name__))
return m(o)
@@ -254,7 +246,7 @@ class _Builder2:
# e.g. IronPython 1.0.
return eval(s)
- p = compiler.parse("__tempvalue__ = " + s)
+ p = compiler.parse('__tempvalue__ = ' + s)
return p.getChildren()[1].getChildren()[0].getChildren()[1]
def build_Subscript(self, o):
@@ -279,7 +271,7 @@ class _Builder2:
if class_name == 'Keyword':
kwargs.update(self.build(child))
# Everything else becomes args
- else :
+ else:
args.append(self.build(child))
return callee(*args, **kwargs)
@@ -327,7 +319,7 @@ class _Builder2:
except AttributeError:
pass
- raise TypeError("unrepr could not resolve the name %s" % repr(name))
+ raise TypeError('unrepr could not resolve the name %s' % repr(name))
def build_Add(self, o):
left, right = map(self.build, o.getChildren())
@@ -356,7 +348,7 @@ class _Builder3:
def build(self, o):
m = getattr(self, 'build_' + o.__class__.__name__, None)
if m is None:
- raise TypeError("unrepr does not recognize %s" %
+ raise TypeError('unrepr does not recognize %s' %
repr(o.__class__.__name__))
return m(o)
@@ -369,7 +361,7 @@ class _Builder3:
# e.g. IronPython 1.0.
return eval(s)
- p = ast.parse("__tempvalue__ = " + s)
+ p = ast.parse('__tempvalue__ = ' + s)
return p.body[0].value
def build_Subscript(self, o):
@@ -394,16 +386,16 @@ class _Builder3:
args.append(self.build(a))
kwargs = {}
for kw in o.keywords:
- if kw.arg is None: # double asterix `**`
+ if kw.arg is None: # double asterix `**`
rst = self.build(kw.value)
if not isinstance(rst, dict):
- raise TypeError("Invalid argument for call."
- "Must be a mapping object.")
+ raise TypeError('Invalid argument for call.'
+ 'Must be a mapping object.')
# give preference to the keys set directly from arg=value
for k, v in rst.items():
if k not in kwargs:
kwargs[k] = v
- else: # defined on the call as: arg=value
+ else: # defined on the call as: arg=value
kwargs[kw.arg] = self.build(kw.value)
return callee(*args, **kwargs)
@@ -427,7 +419,7 @@ class _Builder3:
kwargs = {}
else:
kwargs = self.build(o.kwargs)
- if o.keywords is not None: # direct a=b keywords
+ if o.keywords is not None: # direct a=b keywords
for kw in o.keywords:
# preference because is a direct keyword against **kwargs
kwargs[kw.arg] = self.build(kw.value)
@@ -471,7 +463,7 @@ class _Builder3:
except AttributeError:
pass
- raise TypeError("unrepr could not resolve the name %s" % repr(name))
+ raise TypeError('unrepr could not resolve the name %s' % repr(name))
def build_NameConstant(self, o):
return o.value
@@ -523,7 +515,7 @@ def attributes(full_attribute_name):
"""Load a module and retrieve an attribute of that module."""
# Parse out the path, module, and attribute
- last_dot = full_attribute_name.rfind(".")
+ last_dot = full_attribute_name.rfind('.')
attr_name = full_attribute_name[last_dot + 1:]
mod_path = full_attribute_name[:last_dot]
diff --git a/cherrypy/lib/sessions.py b/cherrypy/lib/sessions.py
index e9605cb8..c8ad7952 100644
--- a/cherrypy/lib/sessions.py
+++ b/cherrypy/lib/sessions.py
@@ -4,13 +4,13 @@ You need to edit your config file to use sessions. Here's an example::
[/]
tools.sessions.on = True
- tools.sessions.storage_type = "file"
+ tools.sessions.storage_class = cherrypy.lib.sessions.FileSession
tools.sessions.storage_path = "/home/site/sessions"
tools.sessions.timeout = 60
This sets the session to be stored in files in the directory
/home/site/sessions, and the session timeout to 60 minutes. If you omit
-``storage_type`` the sessions will be saved in RAM.
+``storage_class``, the sessions will be saved in RAM.
``tools.sessions.on`` is the only required line for working sessions,
the rest are optional.
@@ -57,6 +57,17 @@ However, CherryPy "recognizes" a session id by looking up the saved session
data for that id. Therefore, if you never save any session data,
**you will get a new session id for every request**.
+A side effect of CherryPy overwriting unrecognised session ids is that if you
+have multiple, separate CherryPy applications running on a single domain (e.g.
+on different ports), each app will overwrite the other's session id because by
+default they use the same cookie name (``"session_id"``) but do not recognise
+each others sessions. It is therefore a good idea to use a different name for
+each, for example::
+
+ [/]
+ ...
+ tools.sessions.name = "my_app_session_id"
+
================
Sharing Sessions
================
@@ -94,10 +105,12 @@ import datetime
import os
import time
import threading
-import types
+import binascii
+
+import six
+from six.moves import cPickle as pickle
import cherrypy
-from cherrypy._cpcompat import copyitems, pickle, random20, unicodestr
from cherrypy.lib import httputil
from cherrypy.lib import lockfile
from cherrypy.lib import locking
@@ -122,10 +135,10 @@ class Session(object):
self._id = value
for o in self.id_observers:
o(value)
- id = property(_get_id, _set_id, doc="The current session ID.")
+ id = property(_get_id, _set_id, doc='The current session ID.')
timeout = 60
- "Number of minutes after which to delete session data."
+ 'Number of minutes after which to delete session data.'
locked = False
"""
@@ -138,16 +151,16 @@ class Session(object):
automatically on the first attempt to access session data."""
clean_thread = None
- "Class-level Monitor which calls self.clean_up."
+ 'Class-level Monitor which calls self.clean_up.'
clean_freq = 5
- "The poll rate for expired session cleanup in minutes."
+ 'The poll rate for expired session cleanup in minutes.'
originalid = None
- "The session id passed by the client. May be missing or unsafe."
+ 'The session id passed by the client. May be missing or unsafe.'
missing = False
- "True if the session requested by the client did not exist."
+ 'True if the session requested by the client did not exist.'
regenerated = False
"""
@@ -155,7 +168,7 @@ class Session(object):
internal calls to regenerate the session id."""
debug = False
- "If True, log debug information."
+ 'If True, log debug information.'
# --------------------- Session management methods --------------------- #
@@ -236,7 +249,7 @@ class Session(object):
def generate_id(self):
"""Return a new session id."""
- return random20()
+ return binascii.hexlify(os.urandom(20)).decode('ascii')
def save(self):
"""Save session data."""
@@ -335,13 +348,6 @@ class Session(object):
self.load()
return key in self._data
- if hasattr({}, 'has_key'):
- def has_key(self, key):
- """D.has_key(k) -> True if D has a key k, else False."""
- if not self.loaded:
- self.load()
- return key in self._data
-
def get(self, key, default=None):
"""D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None."""
if not self.loaded:
@@ -395,7 +401,7 @@ class RamSession(Session):
"""Clean up expired sessions."""
now = self.now()
- for _id, (data, expiration_time) in copyitems(self.cache):
+ for _id, (data, expiration_time) in list(six.iteritems(self.cache)):
if expiration_time <= now:
try:
del self.cache[_id]
@@ -410,7 +416,11 @@ class RamSession(Session):
# added to remove obsolete lock objects
for _id in list(self.locks):
- if _id not in self.cache and self.locks[_id].acquire(blocking=False):
+ locked = (
+ _id not in self.cache
+ and self.locks[_id].acquire(blocking=False)
+ )
+ if locked:
lock = self.locks.pop(_id)
lock.release()
@@ -471,9 +481,11 @@ class FileSession(Session):
if isinstance(self.lock_timeout, (int, float)):
self.lock_timeout = datetime.timedelta(seconds=self.lock_timeout)
if not isinstance(self.lock_timeout, (datetime.timedelta, type(None))):
- raise ValueError("Lock timeout must be numeric seconds or "
- "a timedelta instance.")
+ raise ValueError(
+ 'Lock timeout must be numeric seconds or a timedelta instance.'
+ )
+ @classmethod
def setup(cls, **kwargs):
"""Set up the storage system for file-based sessions.
@@ -485,12 +497,11 @@ class FileSession(Session):
for k, v in kwargs.items():
setattr(cls, k, v)
- setup = classmethod(setup)
def _get_file_path(self):
f = os.path.join(self.storage_path, self.SESSION_PREFIX + self.id)
if not os.path.abspath(f).startswith(self.storage_path):
- raise cherrypy.HTTPError(400, "Invalid session id in cookie.")
+ raise cherrypy.HTTPError(400, 'Invalid session id in cookie.')
return f
def _exists(self):
@@ -498,12 +509,12 @@ class FileSession(Session):
return os.path.exists(path)
def _load(self, path=None):
- assert self.locked, ("The session load without being locked. "
+ assert self.locked, ('The session load without being locked. '
"Check your tools' priority levels.")
if path is None:
path = self._get_file_path()
try:
- f = open(path, "rb")
+ f = open(path, 'rb')
try:
return pickle.load(f)
finally:
@@ -511,21 +522,21 @@ class FileSession(Session):
except (IOError, EOFError):
e = sys.exc_info()[1]
if self.debug:
- cherrypy.log("Error loading the session pickle: %s" %
+ cherrypy.log('Error loading the session pickle: %s' %
e, 'TOOLS.SESSIONS')
return None
def _save(self, expiration_time):
- assert self.locked, ("The session was saved without being locked. "
+ assert self.locked, ('The session was saved without being locked. '
"Check your tools' priority levels.")
- f = open(self._get_file_path(), "wb")
+ f = open(self._get_file_path(), 'wb')
try:
pickle.dump((self._data, expiration_time), f, self.pickle_protocol)
finally:
f.close()
def _delete(self):
- assert self.locked, ("The session deletion without being locked. "
+ assert self.locked, ('The session deletion without being locked. '
"Check your tools' priority levels.")
try:
os.unlink(self._get_file_path())
@@ -560,8 +571,11 @@ class FileSession(Session):
now = self.now()
# Iterate over all session files in self.storage_path
for fname in os.listdir(self.storage_path):
- if (fname.startswith(self.SESSION_PREFIX)
- and not fname.endswith(self.LOCK_SUFFIX)):
+ have_session = (
+ fname.startswith(self.SESSION_PREFIX)
+ and not fname.endswith(self.LOCK_SUFFIX)
+ )
+ if have_session:
# We have a session file: lock and load it and check
# if it's expired. If it fails, nevermind.
path = os.path.join(self.storage_path, fname)
@@ -587,95 +601,8 @@ class FileSession(Session):
def __len__(self):
"""Return the number of active sessions."""
return len([fname for fname in os.listdir(self.storage_path)
- if (fname.startswith(self.SESSION_PREFIX)
- and not fname.endswith(self.LOCK_SUFFIX))])
-
-
-class PostgresqlSession(Session):
-
- """ Implementation of the PostgreSQL backend for sessions. It assumes
- a table like this::
-
- create table session (
- id varchar(40),
- data text,
- expiration_time timestamp
- )
-
- You must provide your own get_db function.
- """
-
- pickle_protocol = pickle.HIGHEST_PROTOCOL
-
- def __init__(self, id=None, **kwargs):
- Session.__init__(self, id, **kwargs)
- self.cursor = self.db.cursor()
-
- def setup(cls, **kwargs):
- """Set up the storage system for Postgres-based sessions.
-
- This should only be called once per process; this will be done
- automatically when using sessions.init (as the built-in Tool does).
- """
- for k, v in kwargs.items():
- setattr(cls, k, v)
-
- self.db = self.get_db()
- setup = classmethod(setup)
-
- def __del__(self):
- if self.cursor:
- self.cursor.close()
- self.db.commit()
-
- def _exists(self):
- # Select session data from table
- self.cursor.execute('select data, expiration_time from session '
- 'where id=%s', (self.id,))
- rows = self.cursor.fetchall()
- return bool(rows)
-
- def _load(self):
- # Select session data from table
- self.cursor.execute('select data, expiration_time from session '
- 'where id=%s', (self.id,))
- rows = self.cursor.fetchall()
- if not rows:
- return None
-
- pickled_data, expiration_time = rows[0]
- data = pickle.loads(pickled_data)
- return data, expiration_time
-
- def _save(self, expiration_time):
- pickled_data = pickle.dumps(self._data, self.pickle_protocol)
- self.cursor.execute('update session set data = %s, '
- 'expiration_time = %s where id = %s',
- (pickled_data, expiration_time, self.id))
-
- def _delete(self):
- self.cursor.execute('delete from session where id=%s', (self.id,))
-
- def acquire_lock(self):
- """Acquire an exclusive lock on the currently-loaded session data."""
- # We use the "for update" clause to lock the row
- self.locked = True
- self.cursor.execute('select id from session where id=%s for update',
- (self.id,))
- if self.debug:
- cherrypy.log('Lock acquired.', 'TOOLS.SESSIONS')
-
- def release_lock(self):
- """Release the lock on the currently-loaded session data."""
- # We just close the cursor and that will remove the lock
- # introduced by the "for update" clause
- self.cursor.close()
- self.locked = False
-
- def clean_up(self):
- """Clean up expired sessions."""
- self.cursor.execute('delete from session where expiration_time < %s',
- (self.now(),))
+ if (fname.startswith(self.SESSION_PREFIX) and
+ not fname.endswith(self.LOCK_SUFFIX))])
class MemcachedSession(Session):
@@ -684,11 +611,12 @@ class MemcachedSession(Session):
# Wrap all .get and .set operations in a single lock.
mc_lock = threading.RLock()
- # This is a seperate set of locks per session id.
+ # This is a separate set of locks per session id.
locks = {}
servers = ['127.0.0.1:11211']
+ @classmethod
def setup(cls, **kwargs):
"""Set up the storage system for memcached-based sessions.
@@ -700,21 +628,6 @@ class MemcachedSession(Session):
import memcache
cls.cache = memcache.Client(cls.servers)
- setup = classmethod(setup)
-
- def _get_id(self):
- return self._id
-
- def _set_id(self, value):
- # This encode() call is where we differ from the superclass.
- # Memcache keys MUST be byte strings, not unicode.
- if isinstance(value, unicodestr):
- value = value.encode('utf-8')
-
- self._id = value
- for o in self.id_observers:
- o(value)
- id = property(_get_id, _set_id, doc="The current session ID.")
def _exists(self):
self.mc_lock.acquire()
@@ -737,7 +650,7 @@ class MemcachedSession(Session):
try:
if not self.cache.set(self.id, (self._data, expiration_time), td):
raise AssertionError(
- "Session data for id %r not set." % self.id)
+ 'Session data for id %r not set.' % self.id)
finally:
self.mc_lock.release()
@@ -766,13 +679,13 @@ class MemcachedSession(Session):
def save():
"""Save any changed session data."""
- if not hasattr(cherrypy.serving, "session"):
+ if not hasattr(cherrypy.serving, 'session'):
return
request = cherrypy.serving.request
response = cherrypy.serving.response
# Guard against running twice
- if hasattr(request, "_sessionsaved"):
+ if hasattr(request, '_sessionsaved'):
return
request._sessionsaved = True
@@ -786,28 +699,39 @@ def save():
if is_iterator(response.body):
response.collapse_body()
cherrypy.session.save()
+
+
save.failsafe = True
def close():
"""Close the session object for this request."""
- sess = getattr(cherrypy.serving, "session", None)
- if getattr(sess, "locked", False):
+ sess = getattr(cherrypy.serving, 'session', None)
+ if getattr(sess, 'locked', False):
# If the session is still locked we release the lock
sess.release_lock()
if sess.debug:
cherrypy.log('Lock released on close.', 'TOOLS.SESSIONS')
+
+
close.failsafe = True
close.priority = 90
-def init(storage_type='ram', path=None, path_header=None, name='session_id',
+def init(storage_type=None, path=None, path_header=None, name='session_id',
timeout=60, domain=None, secure=False, clean_freq=5,
- persistent=True, httponly=False, debug=False, **kwargs):
+ persistent=True, httponly=False, debug=False,
+ # Py27 compat
+ # *, storage_class=RamSession,
+ **kwargs):
"""Initialize session object (using cookies).
+ storage_class
+ The Session subclass to use. Defaults to RamSession.
+
storage_type
- One of 'ram', 'file', 'postgresql', 'memcached'. This will be
+ (deprecated)
+ One of 'ram', 'file', memcached'. This will be
used to look up the corresponding class in cherrypy.lib.sessions
globals. For example, 'file' will use the FileSession class.
@@ -851,10 +775,13 @@ def init(storage_type='ram', path=None, path_header=None, name='session_id',
you're using for more information.
"""
+ # Py27 compat
+ storage_class = kwargs.pop('storage_class', RamSession)
+
request = cherrypy.serving.request
# Guard against running twice
- if hasattr(request, "_session_init_flag"):
+ if hasattr(request, '_session_init_flag'):
return
request._session_init_flag = True
@@ -866,11 +793,18 @@ def init(storage_type='ram', path=None, path_header=None, name='session_id',
cherrypy.log('ID obtained from request.cookie: %r' % id,
'TOOLS.SESSIONS')
- # Find the storage class and call setup (first time only).
- storage_class = storage_type.title() + 'Session'
- storage_class = globals()[storage_class]
- if not hasattr(cherrypy, "session"):
- if hasattr(storage_class, "setup"):
+ first_time = not hasattr(cherrypy, 'session')
+
+ if storage_type:
+ if first_time:
+ msg = 'storage_type is deprecated. Supply storage_class instead'
+ cherrypy.log(msg)
+ storage_class = storage_type.title() + 'Session'
+ storage_class = globals()[storage_class]
+
+ # call setup first time only
+ if first_time:
+ if hasattr(storage_class, 'setup'):
storage_class.setup(**kwargs)
# Create and attach a new Session instance to cherrypy.serving.
@@ -887,7 +821,7 @@ def init(storage_type='ram', path=None, path_header=None, name='session_id',
sess.id_observers.append(update_cookie)
# Create cherrypy.session which will proxy to cherrypy.serving.session
- if not hasattr(cherrypy, "session"):
+ if not hasattr(cherrypy, 'session'):
cherrypy.session = cherrypy._ThreadLocalProxy('session')
if persistent:
@@ -941,24 +875,30 @@ def set_response_cookie(path=None, path_header=None, name='session_id',
'/'
)
- # We'd like to use the "max-age" param as indicated in
- # http://www.faqs.org/rfcs/rfc2109.html but IE doesn't
- # save it to disk and the session is lost if people close
- # the browser. So we have to use the old "expires" ... sigh ...
-## cookie[name]['max-age'] = timeout * 60
if timeout:
- e = time.time() + (timeout * 60)
- cookie[name]['expires'] = httputil.HTTPDate(e)
+ cookie[name]['max-age'] = timeout * 60
+ _add_MSIE_max_age_workaround(cookie[name], timeout)
if domain is not None:
cookie[name]['domain'] = domain
if secure:
cookie[name]['secure'] = 1
if httponly:
if not cookie[name].isReservedKey('httponly'):
- raise ValueError("The httponly cookie token is not supported.")
+ raise ValueError('The httponly cookie token is not supported.')
cookie[name]['httponly'] = 1
+def _add_MSIE_max_age_workaround(cookie, timeout):
+ """
+ We'd like to use the "max-age" param as indicated in
+ http://www.faqs.org/rfcs/rfc2109.html but IE doesn't
+ save it to disk and the session is lost if people close
+ the browser. So we have to use the old "expires" ... sigh ...
+ """
+ expires = time.time() + timeout * 60
+ cookie['expires'] = httputil.HTTPDate(expires)
+
+
def expire():
"""Expire the current session cookie."""
name = cherrypy.serving.request.config.get(
@@ -966,3 +906,4 @@ def expire():
one_year = 60 * 60 * 24 * 365
e = time.time() - one_year
cherrypy.serving.response.cookie[name]['expires'] = httputil.HTTPDate(e)
+ cherrypy.serving.response.cookie[name].pop('max-age', None)
diff --git a/cherrypy/lib/static.py b/cherrypy/lib/static.py
index 6a78fc13..ed6467a0 100644
--- a/cherrypy/lib/static.py
+++ b/cherrypy/lib/static.py
@@ -1,23 +1,32 @@
+"""Module with helpers for serving static files."""
+
import os
+import platform
import re
import stat
import mimetypes
-try:
- from io import UnsupportedOperation
-except ImportError:
- UnsupportedOperation = object()
+from email.generator import _make_boundary as make_boundary
+from io import UnsupportedOperation
+
+from six.moves import urllib
import cherrypy
-from cherrypy._cpcompat import ntob, unquote
+from cherrypy._cpcompat import ntob
from cherrypy.lib import cptools, httputil, file_generator_limited
-mimetypes.init()
-mimetypes.types_map['.dwg'] = 'image/x-dwg'
-mimetypes.types_map['.ico'] = 'image/x-icon'
-mimetypes.types_map['.bz2'] = 'application/x-bzip2'
-mimetypes.types_map['.gz'] = 'application/x-gzip'
+def _setup_mimetypes():
+ """Pre-initialize global mimetype map."""
+ if not mimetypes.inited:
+ mimetypes.init()
+ mimetypes.types_map['.dwg'] = 'image/x-dwg'
+ mimetypes.types_map['.ico'] = 'image/x-icon'
+ mimetypes.types_map['.bz2'] = 'application/x-bzip2'
+ mimetypes.types_map['.gz'] = 'application/x-gzip'
+
+
+_setup_mimetypes()
def serve_file(path, content_type=None, disposition=None, name=None,
@@ -33,7 +42,6 @@ def serve_file(path, content_type=None, disposition=None, name=None,
to the basename of path. If disposition is None, no Content-Disposition
header will be written.
"""
-
response = cherrypy.serving.response
# If path is relative, users should fix it by making path absolute.
@@ -71,7 +79,7 @@ def serve_file(path, content_type=None, disposition=None, name=None,
if content_type is None:
# Set content-type based on filename extension
- ext = ""
+ ext = ''
i = path.rfind('.')
if i != -1:
ext = path[i:].lower()
@@ -86,7 +94,7 @@ def serve_file(path, content_type=None, disposition=None, name=None,
if name is None:
name = os.path.basename(path)
cd = '%s; filename="%s"' % (disposition, name)
- response.headers["Content-Disposition"] = cd
+ response.headers['Content-Disposition'] = cd
if debug:
cherrypy.log('Content-Disposition: %r' % cd, 'TOOLS.STATIC')
@@ -115,7 +123,6 @@ def serve_fileobj(fileobj, content_type=None, disposition=None, name=None,
serve_fileobj(), expecting that the data would be served starting from that
position.
"""
-
response = cherrypy.serving.response
try:
@@ -144,7 +151,7 @@ def serve_fileobj(fileobj, content_type=None, disposition=None, name=None,
cd = disposition
else:
cd = '%s; filename="%s"' % (disposition, name)
- response.headers["Content-Disposition"] = cd
+ response.headers['Content-Disposition'] = cd
if debug:
cherrypy.log('Content-Disposition: %r' % cd, 'TOOLS.STATIC')
@@ -158,12 +165,12 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False):
# HTTP/1.0 didn't have Range/Accept-Ranges headers, or the 206 code
request = cherrypy.serving.request
if request.protocol >= (1, 1):
- response.headers["Accept-Ranges"] = "bytes"
+ response.headers['Accept-Ranges'] = 'bytes'
r = httputil.get_ranges(request.headers.get('Range'), content_length)
if r == []:
- response.headers['Content-Range'] = "bytes */%s" % content_length
- message = ("Invalid Range (first-byte-pos greater than "
- "Content-Length)")
+ response.headers['Content-Range'] = 'bytes */%s' % content_length
+ message = ('Invalid Range (first-byte-pos greater than '
+ 'Content-Length)')
if debug:
cherrypy.log(message, 'TOOLS.STATIC')
raise cherrypy.HTTPError(416, message)
@@ -179,31 +186,25 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False):
cherrypy.log(
'Single part; start: %r, stop: %r' % (start, stop),
'TOOLS.STATIC')
- response.status = "206 Partial Content"
+ response.status = '206 Partial Content'
response.headers['Content-Range'] = (
- "bytes %s-%s/%s" % (start, stop - 1, content_length))
+ 'bytes %s-%s/%s' % (start, stop - 1, content_length))
response.headers['Content-Length'] = r_len
fileobj.seek(start)
response.body = file_generator_limited(fileobj, r_len)
else:
# Return a multipart/byteranges response.
- response.status = "206 Partial Content"
- try:
- # Python 3
- from email.generator import _make_boundary as make_boundary
- except ImportError:
- # Python 2
- from mimetools import choose_boundary as make_boundary
+ response.status = '206 Partial Content'
boundary = make_boundary()
- ct = "multipart/byteranges; boundary=%s" % boundary
+ ct = 'multipart/byteranges; boundary=%s' % boundary
response.headers['Content-Type'] = ct
- if "Content-Length" in response.headers:
+ if 'Content-Length' in response.headers:
# Delete Content-Length header so finalize() recalcs it.
- del response.headers["Content-Length"]
+ del response.headers['Content-Length']
def file_ranges():
# Apache compatibility:
- yield ntob("\r\n")
+ yield ntob('\r\n')
for start, stop in r:
if debug:
@@ -211,23 +212,23 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False):
'Multipart; start: %r, stop: %r' % (
start, stop),
'TOOLS.STATIC')
- yield ntob("--" + boundary, 'ascii')
- yield ntob("\r\nContent-type: %s" % content_type,
+ yield ntob('--' + boundary, 'ascii')
+ yield ntob('\r\nContent-type: %s' % content_type,
'ascii')
yield ntob(
- "\r\nContent-range: bytes %s-%s/%s\r\n\r\n" % (
+ '\r\nContent-range: bytes %s-%s/%s\r\n\r\n' % (
start, stop - 1, content_length),
'ascii')
fileobj.seek(start)
gen = file_generator_limited(fileobj, stop - start)
for chunk in gen:
yield chunk
- yield ntob("\r\n")
+ yield ntob('\r\n')
# Final boundary
- yield ntob("--" + boundary + "--", 'ascii')
+ yield ntob('--' + boundary + '--', 'ascii')
# Apache compatibility:
- yield ntob("\r\n")
+ yield ntob('\r\n')
response.body = file_ranges()
return response.body
else:
@@ -244,7 +245,7 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False):
def serve_download(path, name=None):
"""Serve 'path' as an application/x-download attachment."""
# This is such a common idiom I felt it deserved its own wrapper.
- return serve_file(path, "application/x-download", "attachment", name)
+ return serve_file(path, 'application/x-download', 'attachment', name)
def _attempt(filename, content_types, debug=False):
@@ -268,7 +269,7 @@ def _attempt(filename, content_types, debug=False):
return False
-def staticdir(section, dir, root="", match="", content_types=None, index="",
+def staticdir(section, dir, root='', match='', content_types=None, index='',
debug=False):
"""Serve a static resource from the given (root +) dir.
@@ -306,7 +307,7 @@ def staticdir(section, dir, root="", match="", content_types=None, index="",
# If dir is relative, make absolute using "root".
if not os.path.isabs(dir):
if not root:
- msg = "Static dir requires an absolute dir (or root)."
+ msg = 'Static dir requires an absolute dir (or root).'
if debug:
cherrypy.log(msg, 'TOOLS.STATICDIR')
raise ValueError(msg)
@@ -315,10 +316,18 @@ def staticdir(section, dir, root="", match="", content_types=None, index="",
# Determine where we are in the object tree relative to 'section'
# (where the static tool was defined).
if section == 'global':
- section = "/"
- section = section.rstrip(r"\/")
+ section = '/'
+ section = section.rstrip(r'\/')
branch = request.path_info[len(section) + 1:]
- branch = unquote(branch.lstrip(r"\/"))
+ branch = urllib.parse.unquote(branch.lstrip(r'\/'))
+
+ # Requesting a file in sub-dir of the staticdir results
+ # in mixing of delimiter styles, e.g. C:\static\js/script.js.
+ # Windows accepts this form except not when the path is
+ # supplied in extended-path notation, e.g. \\?\C:\static\js/script.js.
+ # http://bit.ly/1vdioCX
+ if platform.system() == 'Windows':
+ branch = branch.replace('/', '\\')
# If branch is "", filename will end in a slash
filename = os.path.join(dir, branch)
@@ -338,11 +347,11 @@ def staticdir(section, dir, root="", match="", content_types=None, index="",
if index:
handled = _attempt(os.path.join(filename, index), content_types)
if handled:
- request.is_index = filename[-1] in (r"\/")
+ request.is_index = filename[-1] in (r'\/')
return handled
-def staticfile(filename, root=None, match="", content_types=None, debug=False):
+def staticfile(filename, root=None, match='', content_types=None, debug=False):
"""Serve a static resource from the given (root +) filename.
match
diff --git a/cherrypy/lib/xmlrpcutil.py b/cherrypy/lib/xmlrpcutil.py
index 9fc9564f..ddaac86a 100644
--- a/cherrypy/lib/xmlrpcutil.py
+++ b/cherrypy/lib/xmlrpcutil.py
@@ -1,21 +1,19 @@
+"""XML-RPC tool helpers."""
import sys
+from six.moves.xmlrpc_client import (
+ loads as xmlrpc_loads, dumps as xmlrpc_dumps,
+ Fault as XMLRPCFault
+)
+
import cherrypy
from cherrypy._cpcompat import ntob
-def get_xmlrpclib():
- try:
- import xmlrpc.client as x
- except ImportError:
- import xmlrpclib as x
- return x
-
-
def process_body():
"""Return (params, method) from request body."""
try:
- return get_xmlrpclib().loads(cherrypy.request.body.read())
+ return xmlrpc_loads(cherrypy.request.body.read())
except Exception:
return ('ERROR PARAMS', ), 'ERRORMETHOD'
@@ -31,9 +29,10 @@ def patched_path(path):
def _set_response(body):
+ """Set up HTTP status, headers and body within CherryPy."""
# The XML-RPC spec (http://www.xmlrpc.com/spec) says:
# "Unless there's a lower-level error, always return 200 OK."
- # Since Python's xmlrpclib interprets a non-200 response
+ # Since Python's xmlrpc_client interprets a non-200 response
# as a "Protocol Error", we'll just return 200 every time.
response = cherrypy.response
response.status = '200 OK'
@@ -43,15 +42,20 @@ def _set_response(body):
def respond(body, encoding='utf-8', allow_none=0):
- xmlrpclib = get_xmlrpclib()
- if not isinstance(body, xmlrpclib.Fault):
+ """Construct HTTP response body."""
+ if not isinstance(body, XMLRPCFault):
body = (body,)
- _set_response(xmlrpclib.dumps(body, methodresponse=1,
- encoding=encoding,
- allow_none=allow_none))
+
+ _set_response(
+ xmlrpc_dumps(
+ body, methodresponse=1,
+ encoding=encoding,
+ allow_none=allow_none
+ )
+ )
def on_error(*args, **kwargs):
+ """Construct HTTP response body for an error response."""
body = str(sys.exc_info()[1])
- xmlrpclib = get_xmlrpclib()
- _set_response(xmlrpclib.dumps(xmlrpclib.Fault(1, body)))
+ _set_response(xmlrpc_dumps(XMLRPCFault(1, body)))
diff --git a/cherrypy/process/__init__.py b/cherrypy/process/__init__.py
index f15b1237..f242d226 100644
--- a/cherrypy/process/__init__.py
+++ b/cherrypy/process/__init__.py
@@ -10,5 +10,8 @@ use with the bus. Some use tool-specific channels; see the documentation
for each class.
"""
-from cherrypy.process.wspbus import bus
-from cherrypy.process import plugins, servers
+from .wspbus import bus
+from . import plugins, servers
+
+
+__all__ = ('bus', 'plugins', 'servers')
diff --git a/cherrypy/process/plugins.py b/cherrypy/process/plugins.py
index 0ec585c0..4f34c390 100644
--- a/cherrypy/process/plugins.py
+++ b/cherrypy/process/plugins.py
@@ -7,8 +7,10 @@ import sys
import time
import threading
-from cherrypy._cpcompat import basestring, get_daemon, get_thread_ident
-from cherrypy._cpcompat import ntob, Timer, SetDaemonProperty
+from six.moves import _thread
+
+from cherrypy._cpcompat import text_or_bytes
+from cherrypy._cpcompat import ntob, Timer
# _module__file__base is used by Autoreload to make
# absolute any filenames retrieved from sys.modules which are not
@@ -104,15 +106,14 @@ class SignalHandler(object):
if sys.platform[:4] == 'java':
del self.handlers['SIGUSR1']
self.handlers['SIGUSR2'] = self.bus.graceful
- self.bus.log("SIGUSR1 cannot be set on the JVM platform. "
- "Using SIGUSR2 instead.")
+ self.bus.log('SIGUSR1 cannot be set on the JVM platform. '
+ 'Using SIGUSR2 instead.')
self.handlers['SIGINT'] = self._jython_SIGINT_handler
self._previous_handlers = {}
# used to determine is the process is a daemon in `self._is_daemonized`
self._original_pid = os.getpid()
-
def _jython_SIGINT_handler(self, signum=None, frame=None):
# See http://bugs.jython.org/issue1313
self.bus.log('Keyboard Interrupt: shutting down bus')
@@ -131,12 +132,10 @@ class SignalHandler(object):
is executing inside other process like in a CI tool
(Buildbot, Jenkins).
"""
- if (self._original_pid != os.getpid() and
- not os.isatty(sys.stdin.fileno())):
- return True
- else:
- return False
-
+ return (
+ self._original_pid != os.getpid() and
+ not os.isatty(sys.stdin.fileno())
+ )
def subscribe(self):
"""Subscribe self.handlers to signals."""
@@ -152,19 +151,19 @@ class SignalHandler(object):
signame = self.signals[signum]
if handler is None:
- self.bus.log("Restoring %s handler to SIG_DFL." % signame)
+ self.bus.log('Restoring %s handler to SIG_DFL.' % signame)
handler = _signal.SIG_DFL
else:
- self.bus.log("Restoring %s handler %r." % (signame, handler))
+ self.bus.log('Restoring %s handler %r.' % (signame, handler))
try:
our_handler = _signal.signal(signum, handler)
if our_handler is None:
- self.bus.log("Restored old %s handler %r, but our "
- "handler was not registered." %
+ self.bus.log('Restored old %s handler %r, but our '
+ 'handler was not registered.' %
(signame, handler), level=30)
except ValueError:
- self.bus.log("Unable to restore %s handler %r." %
+ self.bus.log('Unable to restore %s handler %r.' %
(signame, handler), level=40, traceback=True)
def set_handler(self, signal, listener=None):
@@ -176,39 +175,39 @@ class SignalHandler(object):
If the given signal name or number is not available on the current
platform, ValueError is raised.
"""
- if isinstance(signal, basestring):
+ if isinstance(signal, text_or_bytes):
signum = getattr(_signal, signal, None)
if signum is None:
- raise ValueError("No such signal: %r" % signal)
+ raise ValueError('No such signal: %r' % signal)
signame = signal
else:
try:
signame = self.signals[signal]
except KeyError:
- raise ValueError("No such signal: %r" % signal)
+ raise ValueError('No such signal: %r' % signal)
signum = signal
prev = _signal.signal(signum, self._handle_signal)
self._previous_handlers[signum] = prev
if listener is not None:
- self.bus.log("Listening for %s." % signame)
+ self.bus.log('Listening for %s.' % signame)
self.bus.subscribe(signame, listener)
def _handle_signal(self, signum=None, frame=None):
"""Python signal handler (self.set_handler subscribes it for you)."""
signame = self.signals[signum]
- self.bus.log("Caught signal %s." % signame)
+ self.bus.log('Caught signal %s.' % signame)
self.bus.publish(signame)
def handle_SIGHUP(self):
"""Restart if daemonized, else exit."""
if self._is_daemonized():
- self.bus.log("SIGHUP caught while daemonized. Restarting.")
+ self.bus.log('SIGHUP caught while daemonized. Restarting.')
self.bus.restart()
else:
# not daemonized (may be foreground or background)
- self.bus.log("SIGHUP caught but not daemonized. Exiting.")
+ self.bus.log('SIGHUP caught but not daemonized. Exiting.')
self.bus.exit()
@@ -223,7 +222,8 @@ class DropPrivileges(SimplePlugin):
"""Drop privileges. uid/gid arguments not available on Windows.
- Special thanks to `Gavin Baker <http://antonym.org/2005/12/dropping-privileges-in-python.html>`_
+ Special thanks to `Gavin Baker
+ <http://antonym.org/2005/12/dropping-privileges-in-python.html>`_
"""
def __init__(self, bus, umask=None, uid=None, gid=None):
@@ -239,14 +239,14 @@ class DropPrivileges(SimplePlugin):
def _set_uid(self, val):
if val is not None:
if pwd is None:
- self.bus.log("pwd module not available; ignoring uid.",
+ self.bus.log('pwd module not available; ignoring uid.',
level=30)
val = None
- elif isinstance(val, basestring):
+ elif isinstance(val, text_or_bytes):
val = pwd.getpwnam(val)[2]
self._uid = val
uid = property(_get_uid, _set_uid,
- doc="The uid under which to run. Availability: Unix.")
+ doc='The uid under which to run. Availability: Unix.')
def _get_gid(self):
return self._gid
@@ -254,14 +254,14 @@ class DropPrivileges(SimplePlugin):
def _set_gid(self, val):
if val is not None:
if grp is None:
- self.bus.log("grp module not available; ignoring gid.",
+ self.bus.log('grp module not available; ignoring gid.',
level=30)
val = None
- elif isinstance(val, basestring):
+ elif isinstance(val, text_or_bytes):
val = grp.getgrnam(val)[2]
self._gid = val
gid = property(_get_gid, _set_gid,
- doc="The gid under which to run. Availability: Unix.")
+ doc='The gid under which to run. Availability: Unix.')
def _get_umask(self):
return self._umask
@@ -271,7 +271,7 @@ class DropPrivileges(SimplePlugin):
try:
os.umask
except AttributeError:
- self.bus.log("umask function not available; ignoring umask.",
+ self.bus.log('umask function not available; ignoring umask.',
level=30)
val = None
self._umask = val
@@ -347,7 +347,7 @@ class Daemonizer(SimplePlugin):
process still return proper exit codes. Therefore, if you use this
plugin to daemonize, don't use the return code as an accurate indicator
of whether the process fully started. In fact, that return code only
- indicates if the process succesfully finished the first fork.
+ indicates if the process successfully finished the first fork.
"""
def __init__(self, bus, stdin='/dev/null', stdout='/dev/null',
@@ -372,6 +372,15 @@ class Daemonizer(SimplePlugin):
'Daemonizing now may cause strange failures.' %
threading.enumerate(), level=30)
+ self.daemonize(self.stdin, self.stdout, self.stderr, self.bus.log)
+
+ self.finalized = True
+ start.priority = 65
+
+ @staticmethod
+ def daemonize(
+ stdin='/dev/null', stdout='/dev/null', stderr='/dev/null',
+ logger=lambda msg: None):
# See http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
# (or http://www.faqs.org/faqs/unix-faq/programmer/faq/ section 1.7)
# and http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
@@ -380,41 +389,29 @@ class Daemonizer(SimplePlugin):
sys.stdout.flush()
sys.stderr.flush()
- # Do first fork.
- try:
- pid = os.fork()
- if pid == 0:
- # This is the child process. Continue.
- pass
- else:
- # This is the first parent. Exit, now that we've forked.
- self.bus.log('Forking once.')
- os._exit(0)
- except OSError:
- # Python raises OSError rather than returning negative numbers.
- exc = sys.exc_info()[1]
- sys.exit("%s: fork #1 failed: (%d) %s\n"
- % (sys.argv[0], exc.errno, exc.strerror))
-
- os.setsid()
-
- # Do second fork
- try:
- pid = os.fork()
- if pid > 0:
- self.bus.log('Forking twice.')
- os._exit(0) # Exit second parent
- except OSError:
- exc = sys.exc_info()[1]
- sys.exit("%s: fork #2 failed: (%d) %s\n"
- % (sys.argv[0], exc.errno, exc.strerror))
-
- os.chdir("/")
+ error_tmpl = (
+ '{sys.argv[0]}: fork #{n} failed: ({exc.errno}) {exc.strerror}\n'
+ )
+
+ for fork in range(2):
+ msg = ['Forking once.', 'Forking twice.'][fork]
+ try:
+ pid = os.fork()
+ if pid > 0:
+ # This is the parent; exit.
+ logger(msg)
+ os._exit(0)
+ except OSError as exc:
+ # Python raises OSError rather than returning negative numbers.
+ sys.exit(error_tmpl.format(sys=sys, exc=exc, n=fork + 1))
+ if fork == 0:
+ os.setsid()
+
os.umask(0)
- si = open(self.stdin, "r")
- so = open(self.stdout, "a+")
- se = open(self.stderr, "a+")
+ si = open(stdin, 'r')
+ so = open(stdout, 'a+')
+ se = open(stderr, 'a+')
# os.dup2(fd, fd2) will close fd2 if necessary,
# so we don't explicitly close stdin/out/err.
@@ -423,9 +420,7 @@ class Daemonizer(SimplePlugin):
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
- self.bus.log('Daemonized to PID: %s' % os.getpid())
- self.finalized = True
- start.priority = 65
+ logger('Daemonized to PID: %s' % os.getpid())
class PIDFile(SimplePlugin):
@@ -442,7 +437,7 @@ class PIDFile(SimplePlugin):
if self.finalized:
self.bus.log('PID %r already written to %r.' % (pid, self.pidfile))
else:
- open(self.pidfile, "wb").write(ntob("%s\n" % pid, 'utf8'))
+ open(self.pidfile, 'wb').write(ntob('%s\n' % pid, 'utf8'))
self.bus.log('PID %r written to %r.' % (pid, self.pidfile))
self.finalized = True
start.priority = 70
@@ -453,7 +448,7 @@ class PIDFile(SimplePlugin):
self.bus.log('PID file removed: %r.' % self.pidfile)
except (KeyboardInterrupt, SystemExit):
raise
- except:
+ except Exception:
pass
@@ -481,13 +476,13 @@ class PerpetualTimer(Timer):
except Exception:
if self.bus:
self.bus.log(
- "Error in perpetual timer thread function %r." %
+ 'Error in perpetual timer thread function %r.' %
self.function, level=40, traceback=True)
# Quit on first error to avoid massive logs.
raise
-class BackgroundTask(SetDaemonProperty, threading.Thread):
+class BackgroundTask(threading.Thread):
"""A subclass of threading.Thread whose run() method repeats.
@@ -499,7 +494,7 @@ class BackgroundTask(SetDaemonProperty, threading.Thread):
"""
def __init__(self, interval, function, args=[], kwargs={}, bus=None):
- threading.Thread.__init__(self)
+ super(BackgroundTask, self).__init__()
self.interval = interval
self.function = function
self.args = args
@@ -523,7 +518,7 @@ class BackgroundTask(SetDaemonProperty, threading.Thread):
self.function(*self.args, **self.kwargs)
except Exception:
if self.bus:
- self.bus.log("Error in background task thread function %r."
+ self.bus.log('Error in background task thread function %r.'
% self.function, level=40, traceback=True)
# Quit on first error to avoid massive logs.
raise
@@ -560,24 +555,24 @@ class Monitor(SimplePlugin):
bus=self.bus)
self.thread.setName(threadname)
self.thread.start()
- self.bus.log("Started monitor thread %r." % threadname)
+ self.bus.log('Started monitor thread %r.' % threadname)
else:
- self.bus.log("Monitor thread %r already started." % threadname)
+ self.bus.log('Monitor thread %r already started.' % threadname)
start.priority = 70
def stop(self):
"""Stop our callback's background task thread."""
if self.thread is None:
- self.bus.log("No thread running for %s." %
+ self.bus.log('No thread running for %s.' %
self.name or self.__class__.__name__)
else:
if self.thread is not threading.currentThread():
name = self.thread.getName()
self.thread.cancel()
- if not get_daemon(self.thread):
- self.bus.log("Joining %r" % name)
+ if not self.thread.daemon:
+ self.bus.log('Joining %r' % name)
self.thread.join()
- self.bus.log("Stopped thread %r." % name)
+ self.bus.log('Stopped thread %r.' % name)
self.thread = None
def graceful(self):
@@ -674,10 +669,10 @@ class Autoreloader(Monitor):
else:
if mtime is None or mtime > oldtime:
# The file has been deleted or modified.
- self.bus.log("Restarting because %s changed." %
+ self.bus.log('Restarting because %s changed.' %
filename)
self.thread.cancel()
- self.bus.log("Stopped thread %r." %
+ self.bus.log('Stopped thread %r.' %
self.thread.getName())
self.bus.restart()
return
@@ -717,7 +712,7 @@ class ThreadManager(SimplePlugin):
If the current thread has already been seen, any 'start_thread'
listeners will not be run again.
"""
- thread_ident = get_thread_ident()
+ thread_ident = _thread.get_ident()
if thread_ident not in self.threads:
# We can't just use get_ident as the thread ID
# because some platforms reuse thread ID's.
@@ -727,7 +722,7 @@ class ThreadManager(SimplePlugin):
def release_thread(self):
"""Release the current thread and run 'stop_thread' listeners."""
- thread_ident = get_thread_ident()
+ thread_ident = _thread.get_ident()
i = self.threads.pop(thread_ident, None)
if i is not None:
self.bus.publish('stop_thread', i)
diff --git a/cherrypy/process/servers.py b/cherrypy/process/servers.py
index 91ebf604..dcb34de6 100644
--- a/cherrypy/process/servers.py
+++ b/cherrypy/process/servers.py
@@ -1,4 +1,4 @@
-"""
+r"""
Starting in CherryPy 3.1, cherrypy.server is implemented as an
:ref:`Engine Plugin<plugins>`. It's an instance of
:class:`cherrypy._cpserver.Server`, which is a subclass of
@@ -12,10 +12,14 @@ If you need to start more than one HTTP server (to serve on multiple ports, or
protocols, etc.), you can manually register each one and then start them all
with engine.start::
- s1 = ServerAdapter(cherrypy.engine, MyWSGIServer(host='0.0.0.0', port=80))
- s2 = ServerAdapter(cherrypy.engine,
- another.HTTPServer(host='127.0.0.1',
- SSL=True))
+ s1 = ServerAdapter(
+ cherrypy.engine,
+ MyWSGIServer(host='0.0.0.0', port=80)
+ )
+ s2 = ServerAdapter(
+ cherrypy.engine,
+ another.HTTPServer(host='127.0.0.1', SSL=True)
+ )
s1.subscribe()
s2.subscribe()
cherrypy.engine.start()
@@ -58,10 +62,10 @@ hello.py::
import cherrypy
class HelloWorld:
- \"""Sample request handler class.\"""
+ '''Sample request handler class.'''
+ @cherrypy.expose
def index(self):
return "Hello world!"
- index.exposed = True
cherrypy.tree.mount(HelloWorld())
# CherryPy autoreload must be disabled for the flup server to work
@@ -113,9 +117,18 @@ Please see `Lighttpd FastCGI Docs
an explanation of the possible configuration options.
"""
+import os
import sys
import time
import warnings
+import contextlib
+
+import portend
+
+
+class Timeouts:
+ occupied = 5
+ free = 1
class ServerAdapter(object):
@@ -150,49 +163,56 @@ class ServerAdapter(object):
def start(self):
"""Start the HTTP server."""
- if self.bind_addr is None:
- on_what = "unknown interface (dynamic?)"
- elif isinstance(self.bind_addr, tuple):
- on_what = self._get_base()
- else:
- on_what = "socket file: %s" % self.bind_addr
-
if self.running:
- self.bus.log("Already serving on %s" % on_what)
+ self.bus.log('Already serving on %s' % self.description)
return
self.interrupt = None
if not self.httpserver:
- raise ValueError("No HTTP server has been created.")
+ raise ValueError('No HTTP server has been created.')
- # Start the httpserver in a new thread.
- if isinstance(self.bind_addr, tuple):
- wait_for_free_port(*self.bind_addr)
+ if not os.environ.get('LISTEN_PID', None):
+ # Start the httpserver in a new thread.
+ if isinstance(self.bind_addr, tuple):
+ portend.free(*self.bind_addr, timeout=Timeouts.free)
import threading
t = threading.Thread(target=self._start_http_thread)
- t.setName("HTTPServer " + t.getName())
+ t.setName('HTTPServer ' + t.getName())
t.start()
self.wait()
self.running = True
- self.bus.log("Serving on %s" % on_what)
+ self.bus.log('Serving on %s' % self.description)
start.priority = 75
+ @property
+ def description(self):
+ """
+ A description about where this server is bound.
+ """
+ if self.bind_addr is None:
+ on_what = 'unknown interface (dynamic?)'
+ elif isinstance(self.bind_addr, tuple):
+ on_what = self._get_base()
+ else:
+ on_what = 'socket file: %s' % self.bind_addr
+ return on_what
+
def _get_base(self):
if not self.httpserver:
return ''
- host, port = self.bind_addr
+ host, port = self.bound_addr
if getattr(self.httpserver, 'ssl_adapter', None):
- scheme = "https"
+ scheme = 'https'
if port != 443:
- host += ":%s" % port
+ host += ':%s' % port
else:
- scheme = "http"
+ scheme = 'http'
if port != 80:
- host += ":%s" % port
+ host += ':%s' % port
- return "%s://%s" % (scheme, host)
+ return '%s://%s' % (scheme, host)
def _start_http_thread(self):
"""HTTP servers MUST be running in new threads, so that the
@@ -204,32 +224,52 @@ class ServerAdapter(object):
try:
self.httpserver.start()
except KeyboardInterrupt:
- self.bus.log("<Ctrl-C> hit: shutting down HTTP server")
+ self.bus.log('<Ctrl-C> hit: shutting down HTTP server')
self.interrupt = sys.exc_info()[1]
self.bus.exit()
except SystemExit:
- self.bus.log("SystemExit raised: shutting down HTTP server")
+ self.bus.log('SystemExit raised: shutting down HTTP server')
self.interrupt = sys.exc_info()[1]
self.bus.exit()
raise
- except:
+ except Exception:
self.interrupt = sys.exc_info()[1]
- self.bus.log("Error in HTTP server: shutting down",
+ self.bus.log('Error in HTTP server: shutting down',
traceback=True, level=40)
self.bus.exit()
raise
def wait(self):
"""Wait until the HTTP server is ready to receive requests."""
- while not getattr(self.httpserver, "ready", False):
+ while not getattr(self.httpserver, 'ready', False):
if self.interrupt:
raise self.interrupt
time.sleep(.1)
- # Wait for port to be occupied
- if isinstance(self.bind_addr, tuple):
- host, port = self.bind_addr
- wait_for_occupied_port(host, port)
+ # bypass check when LISTEN_PID is set
+ if os.environ.get('LISTEN_PID', None):
+ return
+
+ # bypass check when running via socket-activation
+ # (for socket-activation the port will be managed by systemd)
+ if not isinstance(self.bind_addr, tuple):
+ return
+
+ # wait for port to be occupied
+ with _safe_wait(*self.bound_addr):
+ portend.occupied(*self.bound_addr, timeout=Timeouts.occupied)
+
+ @property
+ def bound_addr(self):
+ """
+ The bind address, or if it's an ephemeral port and the
+ socket has been bound, return the actual port bound.
+ """
+ host, port = self.bind_addr
+ if port == 0 and self.httpserver.socket:
+ # Bound to ephemeral port. Get the actual port allocated.
+ port = self.httpserver.socket.getsockname()[1]
+ return host, port
def stop(self):
"""Stop the HTTP server."""
@@ -238,11 +278,11 @@ class ServerAdapter(object):
self.httpserver.stop()
# Wait for the socket to be truly freed.
if isinstance(self.bind_addr, tuple):
- wait_for_free_port(*self.bind_addr)
+ portend.free(*self.bound_addr, timeout=Timeouts.free)
self.running = False
- self.bus.log("HTTP Server %s shut down" % self.httpserver)
+ self.bus.log('HTTP Server %s shut down' % self.httpserver)
else:
- self.bus.log("HTTP Server %s already shut down" % self.httpserver)
+ self.bus.log('HTTP Server %s already shut down' % self.httpserver)
stop.priority = 25
def restart(self):
@@ -359,107 +399,18 @@ class FlupSCGIServer(object):
self.scgiserver._threadPool.maxSpare = 0
-def client_host(server_host):
- """Return the host on which a client can connect to the given listener."""
- if server_host == '0.0.0.0':
- # 0.0.0.0 is INADDR_ANY, which should answer on localhost.
- return '127.0.0.1'
- if server_host in ('::', '::0', '::0.0.0.0'):
- # :: is IN6ADDR_ANY, which should answer on localhost.
- # ::0 and ::0.0.0.0 are non-canonical but common
- # ways to write IN6ADDR_ANY.
- return '::1'
- return server_host
-
-
-def check_port(host, port, timeout=1.0):
- """Raise an error if the given port is not free on the given host."""
- if not host:
- raise ValueError("Host values of '' or None are not allowed.")
- host = client_host(host)
- port = int(port)
-
- import socket
-
- # AF_INET or AF_INET6 socket
- # Get the correct address family for our host (allows IPv6 addresses)
+@contextlib.contextmanager
+def _safe_wait(host, port):
+ """
+ On systems where a loopback interface is not available and the
+ server is bound to all interfaces, it's difficult to determine
+ whether the server is in fact occupying the port. In this case,
+ just issue a warning and move on. See issue #1100.
+ """
try:
- info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
- socket.SOCK_STREAM)
- except socket.gaierror:
- if ':' in host:
- info = [(
- socket.AF_INET6, socket.SOCK_STREAM, 0, "", (host, port, 0, 0)
- )]
- else:
- info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", (host, port))]
-
- for res in info:
- af, socktype, proto, canonname, sa = res
- s = None
- try:
- s = socket.socket(af, socktype, proto)
- # See http://groups.google.com/group/cherrypy-users/
- # browse_frm/thread/bbfe5eb39c904fe0
- s.settimeout(timeout)
- s.connect((host, port))
- s.close()
- except socket.error:
- if s:
- s.close()
- else:
- raise IOError("Port %s is in use on %s; perhaps the previous "
- "httpserver did not shut down properly." %
- (repr(port), repr(host)))
-
-
-# Feel free to increase these defaults on slow systems:
-free_port_timeout = 0.1
-occupied_port_timeout = 1.0
-
-
-def wait_for_free_port(host, port, timeout=None):
- """Wait for the specified port to become free (drop requests)."""
- if not host:
- raise ValueError("Host values of '' or None are not allowed.")
- if timeout is None:
- timeout = free_port_timeout
-
- for trial in range(50):
- try:
- # we are expecting a free port, so reduce the timeout
- check_port(host, port, timeout=timeout)
- except IOError:
- # Give the old server thread time to free the port.
- time.sleep(timeout)
- else:
- return
-
- raise IOError("Port %r not free on %r" % (port, host))
-
-
-def wait_for_occupied_port(host, port, timeout=None):
- """Wait for the specified port to become active (receive requests)."""
- if not host:
- raise ValueError("Host values of '' or None are not allowed.")
- if timeout is None:
- timeout = occupied_port_timeout
-
- for trial in range(50):
- try:
- check_port(host, port, timeout=timeout)
- except IOError:
- # port is occupied
- return
- else:
- time.sleep(timeout)
-
- if host == client_host(host):
- raise IOError("Port %r not bound on %r" % (port, host))
-
- # On systems where a loopback interface is not available and the
- # server is bound to all interfaces, it's difficult to determine
- # whether the server is in fact occupying the port. In this case,
- # just issue a warning and move on. See issue #1100.
- msg = "Unable to verify that the server is bound on %r" % port
- warnings.warn(msg)
+ yield
+ except portend.Timeout:
+ if host == portend.client_host(host):
+ raise
+ msg = 'Unable to verify that the server is bound on %r' % port
+ warnings.warn(msg)
diff --git a/cherrypy/process/win32.py b/cherrypy/process/win32.py
index 4afd3f14..a57595ca 100644
--- a/cherrypy/process/win32.py
+++ b/cherrypy/process/win32.py
@@ -85,7 +85,7 @@ class Win32Bus(wspbus.Bus):
return self.events[state]
except KeyError:
event = win32event.CreateEvent(None, 0, 0,
- "WSPBus %s Event (pid=%r)" %
+ 'WSPBus %s Event (pid=%r)' %
(state.name, os.getpid()))
self.events[state] = event
return event
@@ -135,7 +135,8 @@ class _ControlCodes(dict):
for key, val in self.items():
if val is obj:
return key
- raise ValueError("The given object could not be found: %r" % obj)
+ raise ValueError('The given object could not be found: %r' % obj)
+
control_codes = _ControlCodes({'graceful': 138})
@@ -153,14 +154,14 @@ class PyWebService(win32serviceutil.ServiceFramework):
"""Python Web Service."""
- _svc_name_ = "Python Web Service"
- _svc_display_name_ = "Python Web Service"
+ _svc_name_ = 'Python Web Service'
+ _svc_display_name_ = 'Python Web Service'
_svc_deps_ = None # sequence of service names on which this depends
- _exe_name_ = "pywebsvc"
+ _exe_name_ = 'pywebsvc'
_exe_args_ = None # Default to no arguments
# Only exists on Windows 2000 or later, ignored on windows NT
- _svc_description_ = "Python Web Service"
+ _svc_description_ = 'Python Web Service'
def SvcDoRun(self):
from cherrypy import process
@@ -173,6 +174,7 @@ class PyWebService(win32serviceutil.ServiceFramework):
process.bus.exit()
def SvcOther(self, control):
+ from cherrypy import process
process.bus.publish(control_codes.key_for(control))
diff --git a/cherrypy/process/wspbus.py b/cherrypy/process/wspbus.py
index 9c9a2739..2fe4159b 100644
--- a/cherrypy/process/wspbus.py
+++ b/cherrypy/process/wspbus.py
@@ -1,4 +1,4 @@
-"""An implementation of the Web Site Process Bus.
+r"""An implementation of the Web Site Process Bus.
This module is completely standalone, depending only on the stdlib.
@@ -61,12 +61,28 @@ the new state.::
"""
import atexit
+
+try:
+ import ctypes
+except ImportError:
+ """Google AppEngine is shipped without ctypes
+
+ :seealso: http://stackoverflow.com/a/6523777/70170
+ """
+ ctypes = None
+
+import operator
import os
import sys
import threading
import time
import traceback as _traceback
import warnings
+import subprocess
+import functools
+
+import six
+
# Here I save the value of os.getcwd(), which, if I am imported early enough,
# will be the directory from which the startup script was run. This is needed
@@ -78,15 +94,13 @@ _startup_cwd = os.getcwd()
class ChannelFailures(Exception):
+ """Exception raised during errors on Bus.publish()."""
- """Exception raised when errors occur in a listener during Bus.publish().
- """
delimiter = '\n'
def __init__(self, *args, **kwargs):
- # Don't use 'super' here; Exceptions are old-style in Py2.4
- # See https://github.com/cherrypy/cherrypy/issues/959
- Exception.__init__(self, *args, **kwargs)
+ """Initialize ChannelFailures errors wrapper."""
+ super(ChannelFailures, self).__init__(*args, **kwargs)
self._exceptions = list()
def handle_exception(self):
@@ -98,12 +112,14 @@ class ChannelFailures(Exception):
return self._exceptions[:]
def __str__(self):
+ """Render the list of errors, which happened in channel."""
exception_strings = map(repr, self.get_instances())
return self.delimiter.join(exception_strings)
__repr__ = __str__
def __bool__(self):
+ """Determine whether any error happened in channel."""
return bool(self._exceptions)
__nonzero__ = __bool__
@@ -116,12 +132,14 @@ class _StateEnum(object):
name = None
def __repr__(self):
- return "states.%s" % self.name
+ return 'states.%s' % self.name
def __setattr__(self, key, value):
if isinstance(value, self.State):
value.name = key
object.__setattr__(self, key, value)
+
+
states = _StateEnum()
states.STOPPED = states.State()
states.STARTING = states.State()
@@ -142,7 +160,6 @@ else:
class Bus(object):
-
"""Process state-machine and messenger for HTTP site deployment.
All listeners for a given channel are guaranteed to be called even
@@ -158,18 +175,31 @@ class Bus(object):
max_cloexec_files = max_files
def __init__(self):
+ """Initialize pub/sub bus."""
self.execv = False
self.state = states.STOPPED
+ channels = 'start', 'stop', 'exit', 'graceful', 'log', 'main'
self.listeners = dict(
- [(channel, set()) for channel
- in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])
+ (channel, set())
+ for channel in channels
+ )
self._priorities = {}
- def subscribe(self, channel, callback, priority=None):
- """Add the given callback at the given channel (if not present)."""
- if channel not in self.listeners:
- self.listeners[channel] = set()
- self.listeners[channel].add(callback)
+ def subscribe(self, channel, callback=None, priority=None):
+ """Add the given callback at the given channel (if not present).
+
+ If callback is None, return a partial suitable for decorating
+ the callback.
+ """
+ if callback is None:
+ return functools.partial(
+ self.subscribe,
+ channel,
+ priority=priority,
+ )
+
+ ch_listeners = self.listeners.setdefault(channel, set())
+ ch_listeners.add(callback)
if priority is None:
priority = getattr(callback, 'priority', 50)
@@ -190,14 +220,11 @@ class Bus(object):
exc = ChannelFailures()
output = []
- items = [(self._priorities[(channel, listener)], listener)
- for listener in self.listeners[channel]]
- try:
- items.sort(key=lambda item: item[0])
- except TypeError:
- # Python 2.3 had no 'key' arg, but that doesn't matter
- # since it could sort dissimilar types just fine.
- items.sort()
+ raw_items = (
+ (self._priorities[(channel, listener)], listener)
+ for listener in self.listeners[channel]
+ )
+ items = sorted(raw_items, key=operator.itemgetter(0))
for priority, listener in items:
try:
output.append(listener(*args, **kwargs))
@@ -209,13 +236,13 @@ class Bus(object):
if exc and e.code == 0:
e.code = 1
raise
- except:
+ except Exception:
exc.handle_exception()
if channel == 'log':
# Assume any further messages to 'log' will fail.
pass
else:
- self.log("Error in %r listener %r" % (channel, listener),
+ self.log('Error in %r listener %r' % (channel, listener),
level=40, traceback=True)
if exc:
raise exc
@@ -225,10 +252,10 @@ class Bus(object):
"""An atexit handler which asserts the Bus is not running."""
if self.state != states.EXITING:
warnings.warn(
- "The main thread is exiting, but the Bus is in the %r state; "
- "shutting it down automatically now. You must either call "
- "bus.block() after start(), or call bus.exit() before the "
- "main thread exits." % self.state, RuntimeWarning)
+ 'The main thread is exiting, but the Bus is in the %r state; '
+ 'shutting it down automatically now. You must either call '
+ 'bus.block() after start(), or call bus.exit() before the '
+ 'main thread exits.' % self.state, RuntimeWarning)
self.exit()
def start(self):
@@ -243,13 +270,13 @@ class Bus(object):
self.log('Bus STARTED')
except (KeyboardInterrupt, SystemExit):
raise
- except:
- self.log("Shutting down due to error in start listener:",
+ except Exception:
+ self.log('Shutting down due to error in start listener:',
level=40, traceback=True)
e_info = sys.exc_info()[1]
try:
self.exit()
- except:
+ except Exception:
# Any stop/exit errors will be logged inside publish().
pass
# Re-raise the original error
@@ -258,6 +285,7 @@ class Bus(object):
def exit(self):
"""Stop all services and prepare to exit the process."""
exitstate = self.state
+ EX_SOFTWARE = 70
try:
self.stop()
@@ -267,19 +295,19 @@ class Bus(object):
# This isn't strictly necessary, but it's better than seeing
# "Waiting for child threads to terminate..." and then nothing.
self.log('Bus EXITED')
- except:
+ except Exception:
# This method is often called asynchronously (whether thread,
# signal handler, console handler, or atexit handler), so we
# can't just let exceptions propagate out unhandled.
# Assume it's been logged and just die.
- os._exit(70) # EX_SOFTWARE
+ os._exit(EX_SOFTWARE)
if exitstate == states.STARTING:
# exit() was called before start() finished, possibly due to
# Ctrl-C because a start listener got stuck. In this case,
# we could get stuck in a loop where Ctrl-C never exits the
# process, so we just call os.exit here.
- os._exit(70) # EX_SOFTWARE
+ os._exit(EX_SOFTWARE)
def restart(self):
"""Restart the process (may close connections).
@@ -321,7 +349,7 @@ class Bus(object):
# It's also good to let them all shut down before allowing
# the main thread to call atexit handlers.
# See https://github.com/cherrypy/cherrypy/issues/751.
- self.log("Waiting for child threads to terminate...")
+ self.log('Waiting for child threads to terminate...')
for t in threading.enumerate():
# Validate the we're not trying to join the MainThread
# that will cause a deadlock and the case exist when
@@ -329,18 +357,13 @@ class Bus(object):
# that another thread executes cherrypy.engine.exit()
if (
t != threading.currentThread() and
- t.isAlive() and
- not isinstance(t, threading._MainThread)
+ not isinstance(t, threading._MainThread) and
+ # Note that any dummy (external) threads are
+ # always daemonic.
+ not t.daemon
):
- # Note that any dummy (external) threads are always daemonic.
- if hasattr(threading.Thread, "daemon"):
- # Python 2.6+
- d = t.daemon
- else:
- d = t.isDaemon()
- if not d:
- self.log("Waiting for thread %s." % t.getName())
- t.join()
+ self.log('Waiting for thread %s.' % t.getName())
+ t.join()
if self.execv:
self._do_execv()
@@ -376,14 +399,20 @@ class Bus(object):
This must be called from the main thread, because certain platforms
(OS X) don't allow execv to be called in a child thread very well.
"""
- args = sys.argv[:]
+ try:
+ args = self._get_true_argv()
+ except NotImplementedError:
+ """It's probably win32 or GAE"""
+ args = [sys.executable] + self._get_interpreter_argv() + sys.argv
+
self.log('Re-spawning %s' % ' '.join(args))
+ self._extend_pythonpath(os.environ)
+
if sys.platform[:4] == 'java':
from _systemrestart import SystemRestart
raise SystemRestart
else:
- args.insert(0, sys.executable)
if sys.platform == 'win32':
args = ['"%s"' % arg for arg in args]
@@ -392,6 +421,134 @@ class Bus(object):
self._set_cloexec()
os.execv(sys.executable, args)
+ @staticmethod
+ def _get_interpreter_argv():
+ """Retrieve current Python interpreter's arguments.
+
+ Returns empty tuple in case of frozen mode, uses built-in arguments
+ reproduction function otherwise.
+
+ Frozen mode is possible for the app has been packaged into a binary
+ executable using py2exe. In this case the interpreter's arguments are
+ already built-in into that executable.
+
+ :seealso: https://github.com/cherrypy/cherrypy/issues/1526
+ Ref: https://pythonhosted.org/PyInstaller/runtime-information.html
+ """
+ return ([]
+ if getattr(sys, 'frozen', False)
+ else subprocess._args_from_interpreter_flags())
+
+ @staticmethod
+ def _get_true_argv():
+ """Retrieve all real arguments of the python interpreter.
+
+ ...even those not listed in ``sys.argv``
+
+ :seealso: http://stackoverflow.com/a/28338254/595220
+ :seealso: http://stackoverflow.com/a/6683222/595220
+ :seealso: http://stackoverflow.com/a/28414807/595220
+ """
+ try:
+ char_p = ctypes.c_char_p if six.PY2 else ctypes.c_wchar_p
+
+ argv = ctypes.POINTER(char_p)()
+ argc = ctypes.c_int()
+
+ ctypes.pythonapi.Py_GetArgcArgv(
+ ctypes.byref(argc),
+ ctypes.byref(argv),
+ )
+
+ _argv = argv[:argc.value]
+
+ # The code below is trying to correctly handle special cases.
+ # `-c`'s argument interpreted by Python itself becomes `-c` as
+ # well. Same applies to `-m`. This snippet is trying to survive
+ # at least the case with `-m`
+ # Ref: https://github.com/cherrypy/cherrypy/issues/1545
+ # Ref: python/cpython@418baf9
+ argv_len, is_command, is_module = len(_argv), False, False
+
+ try:
+ m_ind = _argv.index('-m')
+ if m_ind < argv_len - 1 and _argv[m_ind + 1] in ('-c', '-m'):
+ """
+ In some older Python versions `-m`'s argument may be
+ substituted with `-c`, not `-m`
+ """
+ is_module = True
+ except (IndexError, ValueError):
+ m_ind = None
+
+ try:
+ c_ind = _argv.index('-c')
+ if m_ind < argv_len - 1 and _argv[c_ind + 1] == '-c':
+ is_command = True
+ except (IndexError, ValueError):
+ c_ind = None
+
+ if is_module:
+ """It's containing `-m -m` sequence of arguments"""
+ if is_command and c_ind < m_ind:
+ """There's `-c -c` before `-m`"""
+ raise RuntimeError(
+ "Cannot reconstruct command from '-c'. Ref: "
+ 'https://github.com/cherrypy/cherrypy/issues/1545')
+ # Survive module argument here
+ original_module = sys.argv[0]
+ if not os.access(original_module, os.R_OK):
+ """There's no such module exist"""
+ raise AttributeError(
+ "{} doesn't seem to be a module "
+ 'accessible by current user'.format(original_module))
+ del _argv[m_ind:m_ind + 2] # remove `-m -m`
+ # ... and substitute it with the original module path:
+ _argv.insert(m_ind, original_module)
+ elif is_command:
+ """It's containing just `-c -c` sequence of arguments"""
+ raise RuntimeError(
+ "Cannot reconstruct command from '-c'. "
+ 'Ref: https://github.com/cherrypy/cherrypy/issues/1545')
+ except AttributeError:
+ """It looks Py_GetArgcArgv is completely absent in some environments
+
+ It is known, that there's no Py_GetArgcArgv in MS Windows and
+ ``ctypes`` module is completely absent in Google AppEngine
+
+ :seealso: https://github.com/cherrypy/cherrypy/issues/1506
+ :seealso: https://github.com/cherrypy/cherrypy/issues/1512
+ :ref: http://bit.ly/2gK6bXK
+ """
+ raise NotImplementedError
+ else:
+ return _argv
+
+ @staticmethod
+ def _extend_pythonpath(env):
+ """Prepend current working dir to PATH environment variable if needed.
+
+ If sys.path[0] is an empty string, the interpreter was likely
+ invoked with -m and the effective path is about to change on
+ re-exec. Add the current directory to $PYTHONPATH to ensure
+ that the new process sees the same path.
+
+ This issue cannot be addressed in the general case because
+ Python cannot reliably reconstruct the
+ original command line (http://bugs.python.org/issue14208).
+
+ (This idea filched from tornado.autoreload)
+ """
+ path_prefix = '.' + os.pathsep
+ existing_path = env.get('PYTHONPATH', '')
+ needs_patch = (
+ sys.path[0] == '' and
+ not existing_path.startswith(path_prefix)
+ )
+
+ if needs_patch:
+ env['PYTHONPATH'] = path_prefix + existing_path
+
def _set_cloexec(self):
"""Set the CLOEXEC flag on all open files (except stdin/out/err).
@@ -437,10 +594,11 @@ class Bus(object):
return t
- def log(self, msg="", level=20, traceback=False):
+ def log(self, msg='', level=20, traceback=False):
"""Log the given message. Append the last traceback if requested."""
if traceback:
- msg += "\n" + "".join(_traceback.format_exception(*sys.exc_info()))
+ msg += '\n' + ''.join(_traceback.format_exception(*sys.exc_info()))
self.publish('log', msg, level)
+
bus = Bus()
diff --git a/cherrypy/scaffold/__init__.py b/cherrypy/scaffold/__init__.py
index 50de34bb..bcddba2d 100644
--- a/cherrypy/scaffold/__init__.py
+++ b/cherrypy/scaffold/__init__.py
@@ -8,7 +8,7 @@ then tweak as desired.
Even before any tweaking, this should serve a few demonstration pages.
Change to this directory and run:
- ../cherryd -c site.conf
+ cherryd -c site.conf
"""
@@ -19,36 +19,38 @@ import os
local_dir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+@cherrypy.config(**{'tools.log_tracebacks.on': True})
class Root:
+ """Declaration of the CherryPy app URI structure."""
- _cp_config = {'tools.log_tracebacks.on': True,
- }
-
+ @cherrypy.expose
def index(self):
+ """Render HTML-template at the root path of the web-app."""
return """<html>
<body>Try some <a href='%s?a=7'>other</a> path,
or a <a href='%s?n=14'>default</a> path.<br />
Or, just look at the pretty picture:<br />
<img src='%s' />
-</body></html>""" % (url("other"), url("else"),
- url("files/made_with_cherrypy_small.png"))
- index.exposed = True
+</body></html>""" % (url('other'), url('else'),
+ url('files/made_with_cherrypy_small.png'))
+ @cherrypy.expose
def default(self, *args, **kwargs):
- return "args: %s kwargs: %s" % (args, kwargs)
- default.exposed = True
+ """Render catch-all args and kwargs."""
+ return 'args: %s kwargs: %s' % (args, kwargs)
+ @cherrypy.expose
def other(self, a=2, b='bananas', c=None):
+ """Render number of fruits based on third argument."""
cherrypy.response.headers['Content-Type'] = 'text/plain'
if c is None:
- return "Have %d %s." % (int(a), b)
+ return 'Have %d %s.' % (int(a), b)
else:
- return "Have %d %s, %s." % (int(a), b, c)
- other.exposed = True
+ return 'Have %d %s, %s.' % (int(a), b, c)
- files = cherrypy.tools.staticdir.handler(
- section="/files",
- dir=os.path.join(local_dir, "static"),
+ files = tools.staticdir.handler(
+ section='/files',
+ dir=os.path.join(local_dir, 'static'),
# Ignore .php files, etc.
match=r'\.(css|gif|html?|ico|jpe?g|js|png|swf|xml)$',
)
@@ -57,5 +59,5 @@ Or, just look at the pretty picture:<br />
root = Root()
# Uncomment the following to use your own favicon instead of CP's default.
-#favicon_path = os.path.join(local_dir, "favicon.ico")
-#root.favicon_ico = tools.staticfile.handler(filename=favicon_path)
+# favicon_path = os.path.join(local_dir, "favicon.ico")
+# root.favicon_ico = tools.staticfile.handler(filename=favicon_path)
diff --git a/cherrypy/scaffold/apache-fcgi.conf b/cherrypy/scaffold/apache-fcgi.conf
index 922398ea..6e4f144c 100644
--- a/cherrypy/scaffold/apache-fcgi.conf
+++ b/cherrypy/scaffold/apache-fcgi.conf
@@ -19,4 +19,4 @@ RewriteRule ^(.*)$ /fastcgi.pyc [L]
# If filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.
# The filename does not have to exist in the local filesystem. URIs that Apache resolves to this
# filename will be handled by this external FastCGI application.
-FastCgiExternalServer "C:/fastcgi.pyc" -host 127.0.0.1:8088 \ No newline at end of file
+FastCgiExternalServer "C:/fastcgi.pyc" -host 127.0.0.1:8088
diff --git a/cherrypy/scaffold/example.conf b/cherrypy/scaffold/example.conf
index 93a6e53c..63250fe3 100644
--- a/cherrypy/scaffold/example.conf
+++ b/cherrypy/scaffold/example.conf
@@ -1,3 +1,3 @@
[/]
log.error_file: "error.log"
-log.access_file: "access.log" \ No newline at end of file
+log.access_file: "access.log"
diff --git a/cherrypy/scaffold/static/made_with_cherrypy_small.png b/cherrypy/scaffold/static/made_with_cherrypy_small.png
index c3aafeed..724f9d72 100644
--- a/cherrypy/scaffold/static/made_with_cherrypy_small.png
+++ b/cherrypy/scaffold/static/made_with_cherrypy_small.png
Binary files differ
diff --git a/cherrypy/test/__init__.py b/cherrypy/test/__init__.py
index 0927c170..068382be 100644
--- a/cherrypy/test/__init__.py
+++ b/cherrypy/test/__init__.py
@@ -1,11 +1,5 @@
-"""Regression test suite for CherryPy.
-
-Run 'nosetests -s test/' to exercise all tests.
-
-The '-s' flag instructs nose to output stdout messages, wihch is crucial to
-the 'interactive' mode of webtest.py. If you run these tests without the '-s'
-flag, don't be surprised if the test seems to hang: it's waiting for your
-interactive input.
+"""
+Regression test suite for CherryPy.
"""
import os
diff --git a/cherrypy/test/_test_decorators.py b/cherrypy/test/_test_decorators.py
index 666ea6d9..f6b3e1b1 100644
--- a/cherrypy/test/_test_decorators.py
+++ b/cherrypy/test/_test_decorators.py
@@ -1,5 +1,6 @@
"""Test module for the @-decorator syntax, which is version-specific"""
+import cherrypy
from cherrypy import expose, tools
from cherrypy._cpcompat import ntob
@@ -8,32 +9,32 @@ class ExposeExamples(object):
@expose
def no_call(self):
- return "Mr E. R. Bradshaw"
+ return 'Mr E. R. Bradshaw'
@expose()
def call_empty(self):
- return "Mrs. B.J. Smegma"
+ return 'Mrs. B.J. Smegma'
- @expose("call_alias")
+ @expose('call_alias')
def nesbitt(self):
- return "Mr Nesbitt"
+ return 'Mr Nesbitt'
- @expose(["alias1", "alias2"])
+ @expose(['alias1', 'alias2'])
def andrews(self):
- return "Mr Ken Andrews"
+ return 'Mr Ken Andrews'
- @expose(alias="alias3")
+ @expose(alias='alias3')
def watson(self):
- return "Mr. and Mrs. Watson"
+ return 'Mr. and Mrs. Watson'
class ToolExamples(object):
@expose
+ # This is here to demonstrate that using the config decorator
+ # does not overwrite other config attributes added by the Tool
+ # decorator (in this case response_headers).
+ @cherrypy.config(**{'response.stream': True})
@tools.response_headers(headers=[('Content-Type', 'application/data')])
def blah(self):
- yield ntob("blah")
- # This is here to demonstrate that _cp_config = {...} overwrites
- # the _cp_config attribute added by the Tool decorator. You have
- # to write _cp_config[k] = v or _cp_config.update(...) instead.
- blah._cp_config['response.stream'] = True
+ yield ntob('blah')
diff --git a/cherrypy/test/_test_states_demo.py b/cherrypy/test/_test_states_demo.py
index f90f14f9..a49407ba 100644
--- a/cherrypy/test/_test_states_demo.py
+++ b/cherrypy/test/_test_states_demo.py
@@ -1,29 +1,31 @@
import os
import sys
import time
-starttime = time.time()
import cherrypy
+starttime = time.time()
+
class Root:
+ @cherrypy.expose
def index(self):
- return "Hello World"
- index.exposed = True
+ return 'Hello World'
+ @cherrypy.expose
def mtimes(self):
- return repr(cherrypy.engine.publish("Autoreloader", "mtimes"))
- mtimes.exposed = True
+ return repr(cherrypy.engine.publish('Autoreloader', 'mtimes'))
+ @cherrypy.expose
def pid(self):
return str(os.getpid())
- pid.exposed = True
+ @cherrypy.expose
def start(self):
return repr(starttime)
- start.exposed = True
+ @cherrypy.expose
def exit(self):
# This handler might be called before the engine is STARTED if an
# HTTP worker thread handles it before the HTTP server returns
@@ -31,13 +33,13 @@ class Root:
# by waiting for the Bus to be STARTED.
cherrypy.engine.wait(state=cherrypy.engine.states.STARTED)
cherrypy.engine.exit()
- exit.exposed = True
+@cherrypy.engine.subscribe('start', priority=100)
def unsub_sig():
- cherrypy.log("unsubsig: %s" % cherrypy.config.get('unsubsig', False))
+ cherrypy.log('unsubsig: %s' % cherrypy.config.get('unsubsig', False))
if cherrypy.config.get('unsubsig', False):
- cherrypy.log("Unsubscribing the default cherrypy signal handler")
+ cherrypy.log('Unsubscribing the default cherrypy signal handler')
cherrypy.engine.signal_handler.unsubscribe()
try:
from signal import signal, SIGTERM
@@ -45,24 +47,23 @@ def unsub_sig():
pass
else:
def old_term_handler(signum=None, frame=None):
- cherrypy.log("I am an old SIGTERM handler.")
+ cherrypy.log('I am an old SIGTERM handler.')
sys.exit(0)
- cherrypy.log("Subscribing the new one.")
+ cherrypy.log('Subscribing the new one.')
signal(SIGTERM, old_term_handler)
-cherrypy.engine.subscribe('start', unsub_sig, priority=100)
+@cherrypy.engine.subscribe('start', priority=6)
def starterror():
if cherrypy.config.get('starterror', False):
- zerodiv = 1 / 0
-cherrypy.engine.subscribe('start', starterror, priority=6)
+ 1 / 0
+@cherrypy.engine.subscribe('start', priority=6)
def log_test_case_name():
if cherrypy.config.get('test_case_name', False):
- cherrypy.log("STARTED FROM: %s" %
+ cherrypy.log('STARTED FROM: %s' %
cherrypy.config.get('test_case_name'))
-cherrypy.engine.subscribe('start', log_test_case_name, priority=6)
cherrypy.tree.mount(Root(), '/', {'/': {}})
diff --git a/cherrypy/test/benchmark.py b/cherrypy/test/benchmark.py
index cb3ce9f6..5bfcf699 100644
--- a/cherrypy/test/benchmark.py
+++ b/cherrypy/test/benchmark.py
@@ -23,12 +23,9 @@
import getopt
import os
-curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
-
import re
import sys
import time
-import traceback
import cherrypy
from cherrypy._cpcompat import ntob
@@ -36,13 +33,15 @@ from cherrypy import _cperror, _cpmodpy
from cherrypy.lib import httputil
-AB_PATH = ""
-APACHE_PATH = "apache"
-SCRIPT_NAME = "/cpbench/users/rdelon/apps/blog"
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+
+AB_PATH = ''
+APACHE_PATH = 'apache'
+SCRIPT_NAME = '/cpbench/users/rdelon/apps/blog'
__all__ = ['ABSession', 'Root', 'print_report',
'run_standard_benchmarks', 'safe_threads',
- 'size_report', 'startup', 'thread_report',
+ 'size_report', 'thread_report',
]
size_cache = {}
@@ -50,6 +49,7 @@ size_cache = {}
class Root:
+ @cherrypy.expose
def index(self):
return """<html>
<head>
@@ -65,18 +65,17 @@ class Root:
</ul>
</body>
</html>"""
- index.exposed = True
+ @cherrypy.expose
def hello(self):
- return "Hello, world\r\n"
- hello.exposed = True
+ return 'Hello, world\r\n'
+ @cherrypy.expose
def sizer(self, size):
resp = size_cache.get(size, None)
if resp is None:
- size_cache[size] = resp = "X" * int(size)
+ size_cache[size] = resp = 'X' * int(size)
return resp
- sizer.exposed = True
cherrypy.config.update({
@@ -86,7 +85,7 @@ cherrypy.config.update({
'server.socket_port': 54583,
'server.max_request_header_size': 0,
'server.max_request_body_size': 0,
- 'engine.deadlock_poll_freq': 0,
+ 'engine.timeout_monitor.frequency': 0,
})
# Cheat mode on ;)
@@ -108,20 +107,20 @@ class NullRequest:
"""A null HTTP request class, returning 200 and an empty body."""
- def __init__(self, local, remote, scheme="http"):
+ def __init__(self, local, remote, scheme='http'):
pass
def close(self):
pass
def run(self, method, path, query_string, protocol, headers, rfile):
- cherrypy.response.status = "200 OK"
- cherrypy.response.header_list = [("Content-Type", 'text/html'),
- ("Server", "Null CherryPy"),
- ("Date", httputil.HTTPDate()),
- ("Content-Length", "0"),
+ cherrypy.response.status = '200 OK'
+ cherrypy.response.header_list = [('Content-Type', 'text/html'),
+ ('Server', 'Null CherryPy'),
+ ('Date', httputil.HTTPDate()),
+ ('Content-Length', '0'),
]
- cherrypy.response.body = [""]
+ cherrypy.response.body = ['']
return cherrypy.response
@@ -203,7 +202,7 @@ Finished 1000 requests
ntob(r'^Transfer rate:\s*([0-9.]+)'))
]
- def __init__(self, path=SCRIPT_NAME + "/hello", requests=1000,
+ def __init__(self, path=SCRIPT_NAME + '/hello', requests=1000,
concurrency=10):
self.path = path
self.requests = requests
@@ -216,14 +215,14 @@ Finished 1000 requests
# Don't use "localhost".
# Cf
# http://mail.python.org/pipermail/python-win32/2008-March/007050.html
- return ("-k -n %s -c %s http://127.0.0.1:%s%s" %
+ return ('-k -n %s -c %s http://127.0.0.1:%s%s' %
(self.requests, self.concurrency, port, self.path))
def run(self):
# Parse output of ab, setting attributes on self
try:
- self.output = _cpmodpy.read_process(AB_PATH or "ab", self.args())
- except:
+ self.output = _cpmodpy.read_process(AB_PATH or 'ab', self.args())
+ except Exception:
print(_cperror.format_exc())
raise
@@ -237,12 +236,12 @@ Finished 1000 requests
safe_threads = (25, 50, 100, 200, 400)
-if sys.platform in ("win32",):
+if sys.platform in ('win32',):
# For some reason, ab crashes with > 50 threads on my Win2k laptop.
safe_threads = (10, 20, 30, 40, 50)
-def thread_report(path=SCRIPT_NAME + "/hello", concurrency=safe_threads):
+def thread_report(path=SCRIPT_NAME + '/hello', concurrency=safe_threads):
sess = ABSession(path)
attrs, names, patterns = list(zip(*sess.parse_patterns))
avg = dict.fromkeys(attrs, 0.0)
@@ -265,7 +264,7 @@ def thread_report(path=SCRIPT_NAME + "/hello", concurrency=safe_threads):
yield row
# Add a row of averages.
- yield ["Average"] + [str(avg[attr] / len(concurrency)) for attr in attrs]
+ yield ['Average'] + [str(avg[attr] / len(concurrency)) for attr in attrs]
def size_report(sizes=(10, 100, 1000, 10000, 100000, 100000000),
@@ -274,33 +273,33 @@ def size_report(sizes=(10, 100, 1000, 10000, 100000, 100000000),
attrs, names, patterns = list(zip(*sess.parse_patterns))
yield ('bytes',) + names
for sz in sizes:
- sess.path = "%s/sizer?size=%s" % (SCRIPT_NAME, sz)
+ sess.path = '%s/sizer?size=%s' % (SCRIPT_NAME, sz)
sess.run()
yield [sz] + [getattr(sess, attr) for attr in attrs]
def print_report(rows):
for row in rows:
- print("")
- for i, val in enumerate(row):
- sys.stdout.write(str(val).rjust(10) + " | ")
- print("")
+ print('')
+ for val in row:
+ sys.stdout.write(str(val).rjust(10) + ' | ')
+ print('')
def run_standard_benchmarks():
- print("")
- print("Client Thread Report (1000 requests, 14 byte response body, "
- "%s server threads):" % cherrypy.server.thread_pool)
+ print('')
+ print('Client Thread Report (1000 requests, 14 byte response body, '
+ '%s server threads):' % cherrypy.server.thread_pool)
print_report(thread_report())
- print("")
- print("Client Thread Report (1000 requests, 14 bytes via staticdir, "
- "%s server threads):" % cherrypy.server.thread_pool)
- print_report(thread_report("%s/static/index.html" % SCRIPT_NAME))
+ print('')
+ print('Client Thread Report (1000 requests, 14 bytes via staticdir, '
+ '%s server threads):' % cherrypy.server.thread_pool)
+ print_report(thread_report('%s/static/index.html' % SCRIPT_NAME))
- print("")
- print("Size Report (1000 requests, 50 client threads, "
- "%s server threads):" % cherrypy.server.thread_pool)
+ print('')
+ print('Size Report (1000 requests, 50 client threads, '
+ '%s server threads):' % cherrypy.server.thread_pool)
print_report(size_report())
@@ -311,10 +310,10 @@ def startup_modpython(req=None):
"""
if cherrypy.engine.state == cherrypy._cpengine.STOPPED:
if req:
- if "nullreq" in req.get_options():
+ if 'nullreq' in req.get_options():
cherrypy.engine.request_class = NullRequest
cherrypy.engine.response_class = NullResponse
- ab_opt = req.get_options().get("ab", "")
+ ab_opt = req.get_options().get('ab', '')
if ab_opt:
global AB_PATH
AB_PATH = ab_opt
@@ -325,27 +324,27 @@ def startup_modpython(req=None):
def run_modpython(use_wsgi=False):
- print("Starting mod_python...")
+ print('Starting mod_python...')
pyopts = []
# Pass the null and ab=path options through Apache
- if "--null" in opts:
- pyopts.append(("nullreq", ""))
+ if '--null' in opts:
+ pyopts.append(('nullreq', ''))
- if "--ab" in opts:
- pyopts.append(("ab", opts["--ab"]))
+ if '--ab' in opts:
+ pyopts.append(('ab', opts['--ab']))
s = _cpmodpy.ModPythonServer
if use_wsgi:
- pyopts.append(("wsgi.application", "cherrypy::tree"))
+ pyopts.append(('wsgi.application', 'cherrypy::tree'))
pyopts.append(
- ("wsgi.startup", "cherrypy.test.benchmark::startup_modpython"))
- handler = "modpython_gateway::handler"
+ ('wsgi.startup', 'cherrypy.test.benchmark::startup_modpython'))
+ handler = 'modpython_gateway::handler'
s = s(port=54583, opts=pyopts,
apache_path=APACHE_PATH, handler=handler)
else:
pyopts.append(
- ("cherrypy.setup", "cherrypy.test.benchmark::startup_modpython"))
+ ('cherrypy.setup', 'cherrypy.test.benchmark::startup_modpython'))
s = s(port=54583, opts=pyopts, apache_path=APACHE_PATH)
try:
@@ -359,45 +358,45 @@ if __name__ == '__main__':
longopts = ['cpmodpy', 'modpython', 'null', 'notests',
'help', 'ab=', 'apache=']
try:
- switches, args = getopt.getopt(sys.argv[1:], "", longopts)
+ switches, args = getopt.getopt(sys.argv[1:], '', longopts)
opts = dict(switches)
except getopt.GetoptError:
print(__doc__)
sys.exit(2)
- if "--help" in opts:
+ if '--help' in opts:
print(__doc__)
sys.exit(0)
- if "--ab" in opts:
+ if '--ab' in opts:
AB_PATH = opts['--ab']
- if "--notests" in opts:
+ if '--notests' in opts:
# Return without stopping the server, so that the pages
# can be tested from a standard web browser.
def run():
port = cherrypy.server.socket_port
- print("You may now open http://127.0.0.1:%s%s/" %
+ print('You may now open http://127.0.0.1:%s%s/' %
(port, SCRIPT_NAME))
- if "--null" in opts:
- print("Using null Request object")
+ if '--null' in opts:
+ print('Using null Request object')
else:
def run():
end = time.time() - start
- print("Started in %s seconds" % end)
- if "--null" in opts:
- print("\nUsing null Request object")
+ print('Started in %s seconds' % end)
+ if '--null' in opts:
+ print('\nUsing null Request object')
try:
try:
run_standard_benchmarks()
- except:
+ except Exception:
print(_cperror.format_exc())
raise
finally:
cherrypy.engine.exit()
- print("Starting CherryPy app server...")
+ print('Starting CherryPy app server...')
class NullWriter(object):
@@ -409,12 +408,12 @@ if __name__ == '__main__':
start = time.time()
- if "--cpmodpy" in opts:
+ if '--cpmodpy' in opts:
run_modpython()
- elif "--modpython" in opts:
+ elif '--modpython' in opts:
run_modpython(use_wsgi=True)
else:
- if "--null" in opts:
+ if '--null' in opts:
cherrypy.server.request_class = NullRequest
cherrypy.server.response_class = NullResponse
diff --git a/cherrypy/test/checkerdemo.py b/cherrypy/test/checkerdemo.py
index 68fb222b..3438bd0c 100644
--- a/cherrypy/test/checkerdemo.py
+++ b/cherrypy/test/checkerdemo.py
@@ -13,6 +13,7 @@ thisdir = os.path.dirname(os.path.abspath(__file__))
class Root:
pass
+
if __name__ == '__main__':
conf = {'/base': {'tools.staticdir.root': thisdir,
# Obsolete key.
diff --git a/cherrypy/test/helper.py b/cherrypy/test/helper.py
index adc225df..bdf74f86 100644
--- a/cherrypy/test/helper.py
+++ b/cherrypy/test/helper.py
@@ -1,63 +1,30 @@
"""A library of helper functions for the CherryPy test suite."""
import datetime
+import io
import logging
-log = logging.getLogger(__name__)
import os
-thisdir = os.path.abspath(os.path.dirname(__file__))
-serverpem = os.path.join(os.getcwd(), thisdir, 'test.pem')
-import unittest
-
import re
+import subprocess
import sys
import time
+import unittest
import warnings
+import portend
+import pytest
+import six
+
+from cheroot.test import webtest
+
import cherrypy
-from cherrypy._cpcompat import basestring, copyitems, HTTPSConnection, ntob
+from cherrypy._cpcompat import text_or_bytes, HTTPSConnection, ntob
from cherrypy.lib import httputil
from cherrypy.lib import gctools
-from cherrypy.lib.reprconf import unrepr
-from cherrypy.test import webtest
-
-# Use subprocess module from Python 2.7 on Python 2.3-2.6
-if sys.version_info < (2, 7):
- import cherrypy._cpcompat_subprocess as subprocess
-else:
- import subprocess
-
-import nose
-
-_testconfig = None
-
-def get_tst_config(overconf={}):
- global _testconfig
- if _testconfig is None:
- conf = {
- 'scheme': 'http',
- 'protocol': "HTTP/1.1",
- 'port': 54583,
- 'host': '127.0.0.1',
- 'validate': False,
- 'conquer': False,
- 'server': 'wsgi',
- }
- try:
- import testconfig
- _conf = testconfig.config.get('supervisor', None)
- if _conf is not None:
- for k, v in _conf.items():
- if isinstance(v, basestring):
- _conf[k] = unrepr(v)
- conf.update(_conf)
- except ImportError:
- pass
- _testconfig = conf
- conf = _testconfig.copy()
- conf.update(overconf)
-
- return conf
+log = logging.getLogger(__name__)
+thisdir = os.path.abspath(os.path.dirname(__file__))
+serverpem = os.path.join(os.getcwd(), thisdir, 'test.pem')
class Supervisor(object):
@@ -71,7 +38,8 @@ class Supervisor(object):
setattr(self, k, v)
-log_to_stderr = lambda msg, level: sys.stderr.write(msg + os.linesep)
+def log_to_stderr(msg, level):
+ return sys.stderr.write(msg + os.linesep)
class LocalSupervisor(Supervisor):
@@ -98,11 +66,10 @@ class LocalSupervisor(Supervisor):
# place that i've found so far that I KNOW is early enough to set this.
cherrypy.config.update({'log.screen': False})
engine = cherrypy.engine
- if hasattr(engine, "signal_handler"):
+ if hasattr(engine, 'signal_handler'):
engine.signal_handler.subscribe()
- if hasattr(engine, "console_control_handler"):
+ if hasattr(engine, 'console_control_handler'):
engine.console_control_handler.subscribe()
- #engine.subscribe('log', log_to_stderr)
def start(self, modulename=None):
"""Load and start the HTTP server."""
@@ -126,7 +93,8 @@ class LocalSupervisor(Supervisor):
cherrypy.engine.exit()
- for name, server in copyitems(getattr(cherrypy, 'servers', {})):
+ servers_copy = list(six.iteritems(getattr(cherrypy, 'servers', {})))
+ for name, server in servers_copy:
server.unsubscribe()
del cherrypy.servers[name]
@@ -135,24 +103,24 @@ class NativeServerSupervisor(LocalSupervisor):
"""Server supervisor for the builtin HTTP server."""
- httpserver_class = "cherrypy._cpnative_server.CPHTTPServer"
+ httpserver_class = 'cherrypy._cpnative_server.CPHTTPServer'
using_apache = False
using_wsgi = False
def __str__(self):
- return "Builtin HTTP Server on %s:%s" % (self.host, self.port)
+ return 'Builtin HTTP Server on %s:%s' % (self.host, self.port)
class LocalWSGISupervisor(LocalSupervisor):
"""Server supervisor for the builtin WSGI server."""
- httpserver_class = "cherrypy._cpwsgi_server.CPWSGIServer"
+ httpserver_class = 'cherrypy._cpwsgi_server.CPWSGIServer'
using_apache = False
using_wsgi = True
def __str__(self):
- return "Builtin WSGI Server on %s:%s" % (self.host, self.port)
+ return 'Builtin WSGI Server on %s:%s' % (self.host, self.port)
def sync_apps(self):
"""Hook a new WSGI app into the origin server."""
@@ -163,21 +131,12 @@ class LocalWSGISupervisor(LocalSupervisor):
if app is None:
app = cherrypy.tree
- if self.conquer:
- try:
- import wsgiconq
- except ImportError:
- warnings.warn(
- "Error importing wsgiconq. pyconquer will not run.")
- else:
- app = wsgiconq.WSGILogger(app, c_calls=True)
-
if self.validate:
try:
from wsgiref import validate
except ImportError:
warnings.warn(
- "Error importing wsgiref. The validator will not run.")
+ 'Error importing wsgiref. The validator will not run.')
else:
# wraps the app in the validator
app = validate.validator(app)
@@ -222,8 +181,8 @@ def get_wsgi_u_supervisor(**options):
class CPWebCase(webtest.WebCase):
- script_name = ""
- scheme = "http"
+ script_name = ''
+ scheme = 'http'
available_servers = {'wsgi': LocalWSGISupervisor,
'wsgi_u': get_wsgi_u_supervisor,
@@ -234,18 +193,19 @@ class CPWebCase(webtest.WebCase):
'modfcgid': get_modfcgid_supervisor,
'modfastcgi': get_modfastcgi_supervisor,
}
- default_server = "wsgi"
+ default_server = 'wsgi'
+ @classmethod
def _setup_server(cls, supervisor, conf):
v = sys.version.split()[0]
- log.info("Python version used to run this test script: %s" % v)
- log.info("CherryPy version: %s" % cherrypy.__version__)
- if supervisor.scheme == "https":
- ssl = " (ssl)"
+ log.info('Python version used to run this test script: %s' % v)
+ log.info('CherryPy version: %s' % cherrypy.__version__)
+ if supervisor.scheme == 'https':
+ ssl = ' (ssl)'
else:
- ssl = ""
- log.info("HTTP server version: %s%s" % (supervisor.protocol, ssl))
- log.info("PID: %s" % os.getpid())
+ ssl = ''
+ log.info('HTTP server version: %s%s' % (supervisor.protocol, ssl))
+ log.info('PID: %s' % os.getpid())
cherrypy.server.using_apache = supervisor.using_apache
cherrypy.server.using_wsgi = supervisor.using_wsgi
@@ -253,7 +213,7 @@ class CPWebCase(webtest.WebCase):
if sys.platform[:4] == 'java':
cherrypy.config.update({'server.nodelay': False})
- if isinstance(conf, basestring):
+ if isinstance(conf, text_or_bytes):
parser = cherrypy.lib.reprconf.Parser()
conf = parser.dict_from_file(conf).get('global', {})
else:
@@ -262,10 +222,10 @@ class CPWebCase(webtest.WebCase):
baseconf.update({'server.socket_host': supervisor.host,
'server.socket_port': supervisor.port,
'server.protocol_version': supervisor.protocol,
- 'environment': "test_suite",
+ 'environment': 'test_suite',
})
- if supervisor.scheme == "https":
- #baseconf['server.ssl_module'] = 'builtin'
+ if supervisor.scheme == 'https':
+ # baseconf['server.ssl_module'] = 'builtin'
baseconf['server.ssl_certificate'] = serverpem
baseconf['server.ssl_private_key'] = serverpem
@@ -275,15 +235,22 @@ class CPWebCase(webtest.WebCase):
# exactly like each test module does, because a relative import
# would stick a second instance of webtest in sys.modules,
# and we wouldn't be able to globally override the port anymore.
- if supervisor.scheme == "https":
+ if supervisor.scheme == 'https':
webtest.WebCase.HTTP_CONN = HTTPSConnection
return baseconf
- _setup_server = classmethod(_setup_server)
+ @classmethod
def setup_class(cls):
''
# Creates a server
- conf = get_tst_config()
+ conf = {
+ 'scheme': 'http',
+ 'protocol': 'HTTP/1.1',
+ 'port': 54583,
+ 'host': '127.0.0.1',
+ 'validate': False,
+ 'server': 'wsgi',
+ }
supervisor_factory = cls.available_servers.get(
conf.get('server', 'wsgi'))
if supervisor_factory is None:
@@ -309,38 +276,42 @@ class CPWebCase(webtest.WebCase):
supervisor.start(cls.__module__)
cls.supervisor = supervisor
- setup_class = classmethod(setup_class)
+ @classmethod
def teardown_class(cls):
''
if hasattr(cls, 'setup_server'):
cls.supervisor.stop()
- teardown_class = classmethod(teardown_class)
do_gc_test = False
def test_gc(self):
- if self.do_gc_test:
- self.getPage("/gc/stats")
- self.assertBody("Statistics:")
+ if not self.do_gc_test:
+ return
+
+ self.getPage('/gc/stats')
+ try:
+ self.assertBody('Statistics:')
+ except Exception:
+ 'Failures occur intermittently. See #1420'
def prefix(self):
- return self.script_name.rstrip("/")
+ return self.script_name.rstrip('/')
def base(self):
- if ((self.scheme == "http" and self.PORT == 80) or
- (self.scheme == "https" and self.PORT == 443)):
- port = ""
+ if ((self.scheme == 'http' and self.PORT == 80) or
+ (self.scheme == 'https' and self.PORT == 443)):
+ port = ''
else:
- port = ":%s" % self.PORT
+ port = ':%s' % self.PORT
- return "%s://%s%s%s" % (self.scheme, self.HOST, port,
- self.script_name.rstrip("/"))
+ return '%s://%s%s%s' % (self.scheme, self.HOST, port,
+ self.script_name.rstrip('/'))
def exit(self):
sys.exit()
- def getPage(self, url, headers=None, method="GET", body=None,
+ def getPage(self, url, headers=None, method='GET', body=None,
protocol=None, raise_subcls=None):
"""Open the url. Return status, headers, body.
@@ -355,7 +326,7 @@ class CPWebCase(webtest.WebCase):
protocol, raise_subcls)
def skip(self, msg='skipped '):
- raise nose.SkipTest(msg)
+ pytest.skip(msg)
def assertErrorPage(self, status, message=None, pattern=''):
"""Compare the response body with a built in error page.
@@ -419,6 +390,8 @@ def _test_method_sorter(_, x, y):
if x < y:
return -1
return 0
+
+
unittest.TestLoader.sortTestMethodsUsing = _test_method_sorter
@@ -457,7 +430,7 @@ log.access_file: r'%(access_log)s'
self.host = socket_host or cherrypy.server.socket_host
self.port = socket_port or cherrypy.server.socket_port
- def write_conf(self, extra=""):
+ def write_conf(self, extra=''):
if self.ssl:
serverpem = os.path.join(thisdir, 'test.pem')
ssl = """
@@ -465,7 +438,7 @@ server.ssl_certificate: r'%s'
server.ssl_private_key: r'%s'
""" % (serverpem, serverpem)
else:
- ssl = ""
+ ssl = ''
conf = self.config_template % {
'host': self.host,
@@ -475,19 +448,37 @@ server.ssl_private_key: r'%s'
'ssl': ssl,
'extra': extra,
}
- f = open(self.config_file, 'wb')
- f.write(ntob(conf, 'utf-8'))
- f.close()
+ with io.open(self.config_file, 'w', encoding='utf-8') as f:
+ f.write(six.text_type(conf))
def start(self, imports=None):
"""Start cherryd in a subprocess."""
- cherrypy._cpserver.wait_for_free_port(self.host, self.port)
+ portend.free(self.host, self.port, timeout=1)
args = [
- os.path.join(thisdir, '..', 'cherryd'),
+ '-m',
+ 'cherrypy',
'-c', self.config_file,
'-p', self.pid_file,
]
+ r"""
+ Command for running cherryd server with autoreload enabled
+
+ Using
+
+ ```
+ ['-c',
+ "__requires__ = 'CherryPy'; \
+ import pkg_resources, re, sys; \
+ sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]); \
+ sys.exit(\
+ pkg_resources.load_entry_point(\
+ 'CherryPy', 'console_scripts', 'cherryd')())"]
+ ```
+
+ doesn't work as it's impossible to reconstruct the `-c`'s contents.
+ Ref: https://github.com/cherrypy/cherrypy/issues/1545
+ """
if not isinstance(imports, (list, tuple)):
imports = [imports]
@@ -512,7 +503,7 @@ server.ssl_private_key: r'%s'
if self.wait:
self.exit_code = self._proc.wait()
else:
- cherrypy._cpserver.wait_for_occupied_port(self.host, self.port)
+ portend.occupied(self.host, self.port, timeout=5)
# Give the engine a wee bit more time to finish STARTING
if self.daemonize:
diff --git a/cherrypy/test/logtest.py b/cherrypy/test/logtest.py
index cc59499a..b51a0e32 100644
--- a/cherrypy/test/logtest.py
+++ b/cherrypy/test/logtest.py
@@ -2,9 +2,11 @@
import sys
import time
+from uuid import UUID
-import cherrypy
-from cherrypy._cpcompat import basestring, ntob, unicodestr
+import six
+
+from cherrypy._cpcompat import text_or_bytes, ntob
try:
@@ -45,47 +47,47 @@ class LogCase(object):
logfile = None
lastmarker = None
- markerPrefix = ntob("test suite marker: ")
+ markerPrefix = ntob('test suite marker: ')
def _handleLogError(self, msg, data, marker, pattern):
- print("")
- print(" ERROR: %s" % msg)
+ print('')
+ print(' ERROR: %s' % msg)
if not self.interactive:
raise self.failureException(msg)
- p = (" Show: "
- "[L]og [M]arker [P]attern; "
- "[I]gnore, [R]aise, or sys.e[X]it >> ")
+ p = (' Show: '
+ '[L]og [M]arker [P]attern; '
+ '[I]gnore, [R]aise, or sys.e[X]it >> ')
sys.stdout.write(p + ' ')
# ARGH
sys.stdout.flush()
while True:
i = getchar().upper()
- if i not in "MPLIRX":
+ if i not in 'MPLIRX':
continue
print(i.upper()) # Also prints new line
- if i == "L":
+ if i == 'L':
for x, line in enumerate(data):
if (x + 1) % self.console_height == 0:
# The \r and comma should make the next line overwrite
- sys.stdout.write("<-- More -->\r ")
+ sys.stdout.write('<-- More -->\r ')
m = getchar().lower()
# Erase our "More" prompt
- sys.stdout.write(" \r ")
- if m == "q":
+ sys.stdout.write(' \r ')
+ if m == 'q':
break
print(line.rstrip())
- elif i == "M":
+ elif i == 'M':
print(repr(marker or self.lastmarker))
- elif i == "P":
+ elif i == 'P':
print(repr(pattern))
- elif i == "I":
+ elif i == 'I':
# return without raising the normal exception
return
- elif i == "R":
+ elif i == 'R':
raise self.failureException(msg)
- elif i == "X":
+ elif i == 'X':
self.exit()
sys.stdout.write(p + ' ')
@@ -94,7 +96,7 @@ class LogCase(object):
def emptyLog(self):
"""Overwrite self.logfile with 0 bytes."""
- open(self.logfile, 'wb').write("")
+ open(self.logfile, 'wb').write('')
def markLog(self, key=None):
"""Insert a marker line into the log and set self.lastmarker."""
@@ -103,7 +105,7 @@ class LogCase(object):
self.lastmarker = key
open(self.logfile, 'ab+').write(
- ntob("%s%s\n" % (self.markerPrefix, key), "utf-8"))
+ ntob('%s%s\n' % (self.markerPrefix, key), 'utf-8'))
def _read_marked_region(self, marker=None):
"""Return lines from self.logfile in the marked region.
@@ -119,13 +121,13 @@ class LogCase(object):
if marker is None:
return open(logfile, 'rb').readlines()
- if isinstance(marker, unicodestr):
+ if isinstance(marker, six.text_type):
marker = marker.encode('utf-8')
data = []
in_region = False
for line in open(logfile, 'rb'):
if in_region:
- if (line.startswith(self.markerPrefix) and not marker in line):
+ if line.startswith(self.markerPrefix) and marker not in line:
break
else:
data.append(line)
@@ -144,7 +146,7 @@ class LogCase(object):
for logline in data:
if line in logline:
return
- msg = "%r not found in log" % line
+ msg = '%r not found in log' % line
self._handleLogError(msg, data, marker, line)
def assertNotInLog(self, line, marker=None):
@@ -157,9 +159,36 @@ class LogCase(object):
data = self._read_marked_region(marker)
for logline in data:
if line in logline:
- msg = "%r found in log" % line
+ msg = '%r found in log' % line
self._handleLogError(msg, data, marker, line)
+ def assertValidUUIDv4(self, marker=None):
+ """Fail if the given UUIDv4 is not valid.
+
+ The log will be searched from the given marker to the next marker.
+ If marker is None, self.lastmarker is used. If the log hasn't
+ been marked (using self.markLog), the entire log will be searched.
+ """
+ data = self._read_marked_region(marker)
+ data = [
+ chunk.decode('utf-8').rstrip('\n').rstrip('\r')
+ for chunk in data
+ ]
+ for log_chunk in data:
+ try:
+ uuid_log = data[-1]
+ uuid_obj = UUID(uuid_log, version=4)
+ except (TypeError, ValueError):
+ pass # it might be in other chunk
+ else:
+ if str(uuid_obj) == uuid_log:
+ return
+ msg = '%r is not a valid UUIDv4' % uuid_log
+ self._handleLogError(msg, data, marker, log_chunk)
+
+ msg = 'UUIDv4 not found in log'
+ self._handleLogError(msg, data, marker, log_chunk)
+
def assertLog(self, sliceargs, lines, marker=None):
"""Fail if log.readlines()[sliceargs] is not contained in 'lines'.
@@ -172,13 +201,13 @@ class LogCase(object):
# Single arg. Use __getitem__ and allow lines to be str or list.
if isinstance(lines, (tuple, list)):
lines = lines[0]
- if isinstance(lines, unicodestr):
+ if isinstance(lines, six.text_type):
lines = lines.encode('utf-8')
if lines not in data[sliceargs]:
- msg = "%r not found on log line %r" % (lines, sliceargs)
+ msg = '%r not found on log line %r' % (lines, sliceargs)
self._handleLogError(
msg,
- [data[sliceargs], "--EXTRA CONTEXT--"] + data[
+ [data[sliceargs], '--EXTRA CONTEXT--'] + data[
sliceargs + 1:sliceargs + 6],
marker,
lines)
@@ -186,14 +215,14 @@ class LogCase(object):
# Multiple args. Use __getslice__ and require lines to be list.
if isinstance(lines, tuple):
lines = list(lines)
- elif isinstance(lines, basestring):
+ elif isinstance(lines, text_or_bytes):
raise TypeError("The 'lines' arg must be a list when "
"'sliceargs' is a tuple.")
start, stop = sliceargs
for line, logline in zip(lines, data[start:stop]):
- if isinstance(line, unicodestr):
+ if isinstance(line, six.text_type):
line = line.encode('utf-8')
if line not in logline:
- msg = "%r not found in log" % line
+ msg = '%r not found in log' % line
self._handleLogError(msg, data[start:stop], marker, line)
diff --git a/cherrypy/test/modfastcgi.py b/cherrypy/test/modfastcgi.py
index 53645474..79ec3d18 100644
--- a/cherrypy/test/modfastcgi.py
+++ b/cherrypy/test/modfastcgi.py
@@ -34,21 +34,20 @@ KNOWN BUGS
"""
import os
-curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import re
-import sys
-import time
import cherrypy
-from cherrypy.process import plugins, servers
+from cherrypy.process import servers
from cherrypy.test import helper
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+
-def read_process(cmd, args=""):
- pipein, pipeout = os.popen4("%s %s" % (cmd, args))
+def read_process(cmd, args=''):
+ pipein, pipeout = os.popen4('%s %s' % (cmd, args))
try:
firstline = pipeout.readline()
- if (re.search(r"(not recognized|No such file|not found)", firstline,
+ if (re.search(r'(not recognized|No such file|not found)', firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
@@ -57,8 +56,8 @@ def read_process(cmd, args=""):
return output
-APACHE_PATH = "apache2ctl"
-CONF_PATH = "fastcgi.conf"
+APACHE_PATH = 'apache2ctl'
+CONF_PATH = 'fastcgi.conf'
conf_fastcgi = """
# Apache2 server conf file for testing CherryPy with mod_fastcgi.
@@ -88,13 +87,13 @@ def erase_script_name(environ, start_response):
class ModFCGISupervisor(helper.LocalWSGISupervisor):
- httpserver_class = "cherrypy.process.servers.FlupFCGIServer"
+ httpserver_class = 'cherrypy.process.servers.FlupFCGIServer'
using_apache = True
using_wsgi = True
template = conf_fastcgi
def __str__(self):
- return "FCGI Server on %s:%s" % (self.host, self.port)
+ return 'FCGI Server on %s:%s' % (self.host, self.port)
def start(self, modulename):
cherrypy.server.httpserver = servers.FlupFCGIServer(
@@ -123,13 +122,13 @@ class ModFCGISupervisor(helper.LocalWSGISupervisor):
finally:
f.close()
- result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf)
+ result = read_process(APACHE_PATH, '-k start -f %s' % fcgiconf)
if result:
print(result)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
- read_process(APACHE_PATH, "-k stop")
+ read_process(APACHE_PATH, '-k stop')
helper.LocalWSGISupervisor.stop(self)
def sync_apps(self):
diff --git a/cherrypy/test/modfcgid.py b/cherrypy/test/modfcgid.py
index 6f8a3584..d101bd67 100644
--- a/cherrypy/test/modfcgid.py
+++ b/cherrypy/test/modfcgid.py
@@ -34,22 +34,21 @@ KNOWN BUGS
"""
import os
-curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import re
-import sys
-import time
import cherrypy
from cherrypy._cpcompat import ntob
-from cherrypy.process import plugins, servers
+from cherrypy.process import servers
from cherrypy.test import helper
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+
-def read_process(cmd, args=""):
- pipein, pipeout = os.popen4("%s %s" % (cmd, args))
+def read_process(cmd, args=''):
+ pipein, pipeout = os.popen4('%s %s' % (cmd, args))
try:
firstline = pipeout.readline()
- if (re.search(r"(not recognized|No such file|not found)", firstline,
+ if (re.search(r'(not recognized|No such file|not found)', firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
@@ -58,8 +57,8 @@ def read_process(cmd, args=""):
return output
-APACHE_PATH = "httpd"
-CONF_PATH = "fcgi.conf"
+APACHE_PATH = 'httpd'
+CONF_PATH = 'fcgi.conf'
conf_fcgid = """
# Apache2 server conf file for testing CherryPy with mod_fcgid.
@@ -85,7 +84,7 @@ class ModFCGISupervisor(helper.LocalSupervisor):
template = conf_fcgid
def __str__(self):
- return "FCGI Server on %s:%s" % (self.host, self.port)
+ return 'FCGI Server on %s:%s' % (self.host, self.port)
def start(self, modulename):
cherrypy.server.httpserver = servers.FlupFCGIServer(
@@ -112,13 +111,13 @@ class ModFCGISupervisor(helper.LocalSupervisor):
finally:
f.close()
- result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf)
+ result = read_process(APACHE_PATH, '-k start -f %s' % fcgiconf)
if result:
print(result)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
- read_process(APACHE_PATH, "-k stop")
+ read_process(APACHE_PATH, '-k stop')
helper.LocalServer.stop(self)
def sync_apps(self):
diff --git a/cherrypy/test/modpy.py b/cherrypy/test/modpy.py
index 829628b7..7c288d2c 100644
--- a/cherrypy/test/modpy.py
+++ b/cherrypy/test/modpy.py
@@ -35,18 +35,19 @@ KNOWN BUGS
"""
import os
-curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import re
-import time
+import cherrypy
from cherrypy.test import helper
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+
-def read_process(cmd, args=""):
- pipein, pipeout = os.popen4("%s %s" % (cmd, args))
+def read_process(cmd, args=''):
+ pipein, pipeout = os.popen4('%s %s' % (cmd, args))
try:
firstline = pipeout.readline()
- if (re.search(r"(not recognized|No such file|not found)", firstline,
+ if (re.search(r'(not recognized|No such file|not found)', firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
@@ -55,8 +56,8 @@ def read_process(cmd, args=""):
return output
-APACHE_PATH = "httpd"
-CONF_PATH = "test_mp.conf"
+APACHE_PATH = 'httpd'
+CONF_PATH = 'test_mp.conf'
conf_modpython_gateway = """
# Apache2 server conf file for testing CherryPy with modpython_gateway.
@@ -99,7 +100,7 @@ class ModPythonSupervisor(helper.Supervisor):
template = None
def __str__(self):
- return "ModPython Server on %s:%s" % (self.host, self.port)
+ return 'ModPython Server on %s:%s' % (self.host, self.port)
def start(self, modulename):
mpconf = CONF_PATH
@@ -114,13 +115,13 @@ class ModPythonSupervisor(helper.Supervisor):
finally:
f.close()
- result = read_process(APACHE_PATH, "-k start -f %s" % mpconf)
+ result = read_process(APACHE_PATH, '-k start -f %s' % mpconf)
if result:
print(result)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
- read_process(APACHE_PATH, "-k stop")
+ read_process(APACHE_PATH, '-k stop')
loaded = False
@@ -132,11 +133,10 @@ def wsgisetup(req):
loaded = True
options = req.get_options()
- import cherrypy
cherrypy.config.update({
- "log.error_file": os.path.join(curdir, "test.log"),
- "environment": "test_suite",
- "server.socket_host": options['socket_host'],
+ 'log.error_file': os.path.join(curdir, 'test.log'),
+ 'environment': 'test_suite',
+ 'server.socket_host': options['socket_host'],
})
modname = options['testmod']
@@ -155,11 +155,10 @@ def cpmodpysetup(req):
loaded = True
options = req.get_options()
- import cherrypy
cherrypy.config.update({
- "log.error_file": os.path.join(curdir, "test.log"),
- "environment": "test_suite",
- "server.socket_host": options['socket_host'],
+ 'log.error_file': os.path.join(curdir, 'test.log'),
+ 'environment': 'test_suite',
+ 'server.socket_host': options['socket_host'],
})
from mod_python import apache
return apache.OK
diff --git a/cherrypy/test/modwsgi.py b/cherrypy/test/modwsgi.py
index 043fb6e8..f558e223 100644
--- a/cherrypy/test/modwsgi.py
+++ b/cherrypy/test/modwsgi.py
@@ -33,20 +33,25 @@ KNOWN BUGS
"""
import os
-curdir = os.path.abspath(os.path.dirname(__file__))
import re
import sys
import time
+import portend
+
+from cheroot.test import webtest
+
import cherrypy
-from cherrypy.test import helper, webtest
+from cherrypy.test import helper
+
+curdir = os.path.abspath(os.path.dirname(__file__))
-def read_process(cmd, args=""):
- pipein, pipeout = os.popen4("%s %s" % (cmd, args))
+def read_process(cmd, args=''):
+ pipein, pipeout = os.popen4('%s %s' % (cmd, args))
try:
firstline = pipeout.readline()
- if (re.search(r"(not recognized|No such file|not found)", firstline,
+ if (re.search(r'(not recognized|No such file|not found)', firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
@@ -56,11 +61,11 @@ def read_process(cmd, args=""):
if sys.platform == 'win32':
- APACHE_PATH = "httpd"
+ APACHE_PATH = 'httpd'
else:
- APACHE_PATH = "apache"
+ APACHE_PATH = 'apache'
-CONF_PATH = "test_mw.conf"
+CONF_PATH = 'test_mw.conf'
conf_modwsgi = r"""
# Apache2 server conf file for testing CherryPy with modpython_gateway.
@@ -85,7 +90,7 @@ LoadModule env_module modules/mod_env.so
WSGIScriptAlias / "%(curdir)s/modwsgi.py"
SetEnv testmod %(testmod)s
-"""
+""" # noqa E501
class ModWSGISupervisor(helper.Supervisor):
@@ -97,7 +102,7 @@ class ModWSGISupervisor(helper.Supervisor):
template = conf_modwsgi
def __str__(self):
- return "ModWSGI Server on %s:%s" % (self.host, self.port)
+ return 'ModWSGI Server on %s:%s' % (self.host, self.port)
def start(self, modulename):
mpconf = CONF_PATH
@@ -113,38 +118,37 @@ class ModWSGISupervisor(helper.Supervisor):
finally:
f.close()
- result = read_process(APACHE_PATH, "-k start -f %s" % mpconf)
+ result = read_process(APACHE_PATH, '-k start -f %s' % mpconf)
if result:
print(result)
# Make a request so mod_wsgi starts up our app.
# If we don't, concurrent initial requests will 404.
- cherrypy._cpserver.wait_for_occupied_port("127.0.0.1", self.port)
+ portend.occupied('127.0.0.1', self.port, timeout=5)
webtest.openURL('/ihopetheresnodefault', port=self.port)
time.sleep(1)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
- read_process(APACHE_PATH, "-k stop")
+ read_process(APACHE_PATH, '-k stop')
loaded = False
def application(environ, start_response):
- import cherrypy
global loaded
if not loaded:
loaded = True
- modname = "cherrypy.test." + environ['testmod']
+ modname = 'cherrypy.test.' + environ['testmod']
mod = __import__(modname, globals(), locals(), [''])
mod.setup_server()
cherrypy.config.update({
- "log.error_file": os.path.join(curdir, "test.error.log"),
- "log.access_file": os.path.join(curdir, "test.access.log"),
- "environment": "test_suite",
- "engine.SIGHUP": None,
- "engine.SIGTERM": None,
+ 'log.error_file': os.path.join(curdir, 'test.error.log'),
+ 'log.access_file': os.path.join(curdir, 'test.access.log'),
+ 'environment': 'test_suite',
+ 'engine.SIGHUP': None,
+ 'engine.SIGTERM': None,
})
return cherrypy.tree(environ, start_response)
diff --git a/cherrypy/test/sessiondemo.py b/cherrypy/test/sessiondemo.py
index f76b130a..8226c1b9 100755
--- a/cherrypy/test/sessiondemo.py
+++ b/cherrypy/test/sessiondemo.py
@@ -4,9 +4,11 @@
import calendar
from datetime import datetime
import sys
+
+import six
+
import cherrypy
from cherrypy.lib import sessions
-from cherrypy._cpcompat import copyitems
page = """
@@ -93,7 +95,7 @@ function init() {
<tr><th>Python Version:</th><td>%(pyversion)s</td></tr>
</table>
</body></html>
-"""
+""" # noqa E501
class Root(object):
@@ -121,9 +123,9 @@ class Root(object):
'changemsg': '<br>'.join(changemsg),
'respcookie': cherrypy.response.cookie.output(),
'reqcookie': cherrypy.request.cookie.output(),
- 'sessiondata': copyitems(cherrypy.session),
+ 'sessiondata': list(six.iteritems(cherrypy.session)),
'servertime': (
- datetime.utcnow().strftime("%Y/%m/%d %H:%M") + " UTC"
+ datetime.utcnow().strftime('%Y/%m/%d %H:%M') + ' UTC'
),
'serverunixtime': calendar.timegm(datetime.utcnow().timetuple()),
'cpversion': cherrypy.__version__,
@@ -131,27 +133,28 @@ class Root(object):
'expires': expires,
}
+ @cherrypy.expose
def index(self):
# Must modify data or the session will not be saved.
cherrypy.session['color'] = 'green'
return self.page()
- index.exposed = True
+ @cherrypy.expose
def expire(self):
sessions.expire()
return self.page()
- expire.exposed = True
+ @cherrypy.expose
def regen(self):
cherrypy.session.regenerate()
# Must modify data or the session will not be saved.
cherrypy.session['color'] = 'yellow'
return self.page()
- regen.exposed = True
+
if __name__ == '__main__':
cherrypy.config.update({
- #'environment': 'production',
+ # 'environment': 'production',
'log.screen': True,
'tools.sessions.on': True,
})
diff --git a/cherrypy/test/static/dirback.jpg b/cherrypy/test/static/dirback.jpg
index 530e6d6a..80403dc2 100644
--- a/cherrypy/test/static/dirback.jpg
+++ b/cherrypy/test/static/dirback.jpg
Binary files differ
diff --git a/cherrypy/test/test_auth_basic.py b/cherrypy/test/test_auth_basic.py
index d03b1321..48582ec2 100644
--- a/cherrypy/test/test_auth_basic.py
+++ b/cherrypy/test/test_auth_basic.py
@@ -12,26 +12,27 @@ from cherrypy.test import helper
class BasicAuthTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "This is public."
- index.exposed = True
+ return 'This is public.'
class BasicProtected:
+ @cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
- index.exposed = True
class BasicProtected2:
+ @cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
- index.exposed = True
userpassdict = {'xuser': 'xpassword'}
userhashdict = {'xuser': md5(ntob('xpassword')).hexdigest()}
@@ -58,16 +59,15 @@ class BasicAuthTest(helper.CPWebCase):
root.basic = BasicProtected()
root.basic2 = BasicProtected2()
cherrypy.tree.mount(root, config=conf)
- setup_server = staticmethod(setup_server)
def testPublic(self):
- self.getPage("/")
+ self.getPage('/')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
self.assertBody('This is public.')
def testBasic(self):
- self.getPage("/basic/")
+ self.getPage('/basic/')
self.assertStatus(401)
self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
@@ -81,7 +81,7 @@ class BasicAuthTest(helper.CPWebCase):
self.assertBody("Hello xuser, you've been authorized.")
def testBasic2(self):
- self.getPage("/basic2/")
+ self.getPage('/basic2/')
self.assertStatus(401)
self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
diff --git a/cherrypy/test/test_auth_digest.py b/cherrypy/test/test_auth_digest.py
index b46698d9..8f71a8dc 100644
--- a/cherrypy/test/test_auth_digest.py
+++ b/cherrypy/test/test_auth_digest.py
@@ -11,19 +11,20 @@ from cherrypy.test import helper
class DigestAuthTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "This is public."
- index.exposed = True
+ return 'This is public.'
class DigestProtected:
+ @cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
- index.exposed = True
def fetch_users():
return {'test': 'test'}
@@ -38,28 +39,27 @@ class DigestAuthTest(helper.CPWebCase):
root = Root()
root.digest = DigestProtected()
cherrypy.tree.mount(root, config=conf)
- setup_server = staticmethod(setup_server)
def testPublic(self):
- self.getPage("/")
+ self.getPage('/')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
self.assertBody('This is public.')
def testDigest(self):
- self.getPage("/digest/")
+ self.getPage('/digest/')
self.assertStatus(401)
value = None
for k, v in self.headers:
- if k.lower() == "www-authenticate":
- if v.startswith("Digest"):
+ if k.lower() == 'www-authenticate':
+ if v.startswith('Digest'):
value = v
break
if value is None:
self._handlewebError(
- "Digest authentification scheme was not found")
+ 'Digest authentification scheme was not found')
value = value[7:]
items = value.split(', ')
@@ -68,7 +68,7 @@ class DigestAuthTest(helper.CPWebCase):
key, value = item.split('=')
tokens[key.lower()] = value
- missing_msg = "%s is missing"
+ missing_msg = '%s is missing'
bad_value_msg = "'%s' was expecting '%s' but found '%s'"
nonce = None
if 'realm' not in tokens:
diff --git a/cherrypy/test/test_bus.py b/cherrypy/test/test_bus.py
index 6c927ffb..6026b47e 100644
--- a/cherrypy/test/test_bus.py
+++ b/cherrypy/test/test_bus.py
@@ -2,11 +2,10 @@ import threading
import time
import unittest
-from cherrypy._cpcompat import get_daemon
from cherrypy.process import wspbus
-msg = "Listener %d on channel %s: %s."
+msg = 'Listener %d on channel %s: %s.'
class PublishSubscribeTests(unittest.TestCase):
@@ -191,7 +190,7 @@ class BusMethodTests(unittest.TestCase):
# The wait method MUST wait for the given state(s).
if b.state not in states:
- self.fail("State %r not in %r" % (b.state, states))
+ self.fail('State %r not in %r' % (b.state, states))
def test_block(self):
b = wspbus.Bus()
@@ -205,7 +204,7 @@ class BusMethodTests(unittest.TestCase):
time.sleep(0.4)
threading.Thread(target=f).start()
threading.Thread(target=g).start()
- threads = [t for t in threading.enumerate() if not get_daemon(t)]
+ threads = [t for t in threading.enumerate() if not t.daemon]
self.assertEqual(len(threads), 3)
b.block()
@@ -214,7 +213,7 @@ class BusMethodTests(unittest.TestCase):
self.assertEqual(b.state, b.states.EXITING)
# The block method MUST wait for ALL non-main, non-daemon threads to
# finish.
- threads = [t for t in threading.enumerate() if not get_daemon(t)]
+ threads = [t for t in threading.enumerate() if not t.daemon]
self.assertEqual(len(threads), 1)
# The last message will mention an indeterminable thread name; ignore
# it
@@ -230,19 +229,19 @@ class BusMethodTests(unittest.TestCase):
events = []
def f(*args, **kwargs):
- events.append(("f", args, kwargs))
+ events.append(('f', args, kwargs))
def g():
- events.append("g")
- b.subscribe("start", g)
- b.start_with_callback(f, (1, 3, 5), {"foo": "bar"})
+ events.append('g')
+ b.subscribe('start', g)
+ b.start_with_callback(f, (1, 3, 5), {'foo': 'bar'})
# Give wait() time to run f()
time.sleep(0.2)
# The callback method MUST wait for the STARTED state.
self.assertEqual(b.state, b.states.STARTED)
# The callback method MUST run after all start methods.
- self.assertEqual(events, ["g", ("f", (1, 3, 5), {"foo": "bar"})])
+ self.assertEqual(events, ['g', ('f', (1, 3, 5), {'foo': 'bar'})])
finally:
b.exit()
@@ -253,7 +252,7 @@ class BusMethodTests(unittest.TestCase):
# Try a normal message.
expected = []
- for msg in ["O mah darlin'"] * 3 + ["Clementiiiiiiiine"]:
+ for msg in ["O mah darlin'"] * 3 + ['Clementiiiiiiiine']:
b.log(msg)
expected.append(msg)
self.assertLog(expected)
@@ -262,14 +261,14 @@ class BusMethodTests(unittest.TestCase):
try:
foo
except NameError:
- b.log("You are lost and gone forever", traceback=True)
+ b.log('You are lost and gone forever', traceback=True)
lastmsg = self._log_entries[-1]
- if "Traceback" not in lastmsg or "NameError" not in lastmsg:
- self.fail("Last log message %r did not contain "
- "the expected traceback." % lastmsg)
+ if 'Traceback' not in lastmsg or 'NameError' not in lastmsg:
+ self.fail('Last log message %r did not contain '
+ 'the expected traceback.' % lastmsg)
else:
- self.fail("NameError was not raised as expected.")
+ self.fail('NameError was not raised as expected.')
-if __name__ == "__main__":
+if __name__ == '__main__':
unittest.main()
diff --git a/cherrypy/test/test_caching.py b/cherrypy/test/test_caching.py
index be1950d6..4a459a3f 100644
--- a/cherrypy/test/test_caching.py
+++ b/cherrypy/test/test_caching.py
@@ -1,17 +1,23 @@
import datetime
-import gzip
from itertools import count
import os
-curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
-import sys
import threading
import time
-import urllib
+
+from six.moves import range
+from six.moves import urllib
+
+import pytest
import cherrypy
-from cherrypy._cpcompat import next, ntob, quote, xrange
+from cherrypy._cpcompat import ntob
from cherrypy.lib import httputil
+from cherrypy.test import helper
+
+
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+
gif_bytes = ntob(
'GIF89a\x01\x00\x01\x00\x82\x00\x01\x99"\x1e\x00\x00\x00\x00\x00'
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
@@ -19,39 +25,37 @@ gif_bytes = ntob(
)
-from cherrypy.test import helper
-
-
class CacheTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
+ @cherrypy.config(**{'tools.caching.on': True})
class Root:
- _cp_config = {'tools.caching.on': True}
-
def __init__(self):
self.counter = 0
self.control_counter = 0
self.longlock = threading.Lock()
+ @cherrypy.expose
def index(self):
self.counter += 1
- msg = "visit #%s" % self.counter
+ msg = 'visit #%s' % self.counter
return msg
- index.exposed = True
+ @cherrypy.expose
def control(self):
self.control_counter += 1
- return "visit #%s" % self.control_counter
- control.exposed = True
+ return 'visit #%s' % self.control_counter
+ @cherrypy.expose
def a_gif(self):
cherrypy.response.headers[
'Last-Modified'] = httputil.HTTPDate()
return gif_bytes
- a_gif.exposed = True
+ @cherrypy.expose
def long_process(self, seconds='1'):
try:
self.longlock.acquire()
@@ -59,284 +63,331 @@ class CacheTest(helper.CPWebCase):
finally:
self.longlock.release()
return 'success!'
- long_process.exposed = True
+ @cherrypy.expose
def clear_cache(self, path):
cherrypy._cache.store[cherrypy.request.base + path].clear()
- clear_cache.exposed = True
+ @cherrypy.config(**{
+ 'tools.caching.on': True,
+ 'tools.response_headers.on': True,
+ 'tools.response_headers.headers': [
+ ('Vary', 'Our-Varying-Header')
+ ],
+ })
class VaryHeaderCachingServer(object):
- _cp_config = {
- 'tools.caching.on': True,
- 'tools.response_headers.on': True,
- 'tools.response_headers.headers': [
- ('Vary', 'Our-Varying-Header')
- ],
- }
-
def __init__(self):
self.counter = count(1)
+ @cherrypy.expose
def index(self):
- return "visit #%s" % next(self.counter)
- index.exposed = True
-
+ return 'visit #%s' % next(self.counter)
+
+ @cherrypy.config(**{
+ 'tools.expires.on': True,
+ 'tools.expires.secs': 60,
+ 'tools.staticdir.on': True,
+ 'tools.staticdir.dir': 'static',
+ 'tools.staticdir.root': curdir,
+ })
class UnCached(object):
- _cp_config = {'tools.expires.on': True,
- 'tools.expires.secs': 60,
- 'tools.staticdir.on': True,
- 'tools.staticdir.dir': 'static',
- 'tools.staticdir.root': curdir,
- }
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.expires.secs': 0})
def force(self):
cherrypy.response.headers['Etag'] = 'bibbitybobbityboo'
self._cp_config['tools.expires.force'] = True
self._cp_config['tools.expires.secs'] = 0
- return "being forceful"
- force.exposed = True
- force._cp_config = {'tools.expires.secs': 0}
+ return 'being forceful'
+ @cherrypy.expose
def dynamic(self):
cherrypy.response.headers['Etag'] = 'bibbitybobbityboo'
cherrypy.response.headers['Cache-Control'] = 'private'
- return "D-d-d-dynamic!"
- dynamic.exposed = True
+ return 'D-d-d-dynamic!'
+ @cherrypy.expose
def cacheable(self):
cherrypy.response.headers['Etag'] = 'bibbitybobbityboo'
return "Hi, I'm cacheable."
- cacheable.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.expires.secs': 86400})
def specific(self):
cherrypy.response.headers[
'Etag'] = 'need_this_to_make_me_cacheable'
- return "I am being specific"
- specific.exposed = True
- specific._cp_config = {'tools.expires.secs': 86400}
+ return 'I am being specific'
class Foo(object):
pass
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.expires.secs': Foo()})
def wrongtype(self):
cherrypy.response.headers[
'Etag'] = 'need_this_to_make_me_cacheable'
- return "Woops"
- wrongtype.exposed = True
- wrongtype._cp_config = {'tools.expires.secs': Foo()}
+ return 'Woops'
+
+ @cherrypy.config(**{
+ 'tools.gzip.mime_types': ['text/*', 'image/*'],
+ 'tools.caching.on': True,
+ 'tools.staticdir.on': True,
+ 'tools.staticdir.dir': 'static',
+ 'tools.staticdir.root': curdir
+ })
+ class GzipStaticCache(object):
+ pass
cherrypy.tree.mount(Root())
- cherrypy.tree.mount(UnCached(), "/expires")
- cherrypy.tree.mount(VaryHeaderCachingServer(), "/varying_headers")
+ cherrypy.tree.mount(UnCached(), '/expires')
+ cherrypy.tree.mount(VaryHeaderCachingServer(), '/varying_headers')
+ cherrypy.tree.mount(GzipStaticCache(), '/gzip_static_cache')
cherrypy.config.update({'tools.gzip.on': True})
- setup_server = staticmethod(setup_server)
def testCaching(self):
elapsed = 0.0
for trial in range(10):
- self.getPage("/")
+ self.getPage('/')
# The response should be the same every time,
# except for the Age response header.
self.assertBody('visit #1')
if trial != 0:
- age = int(self.assertHeader("Age"))
+ age = int(self.assertHeader('Age'))
self.assert_(age >= elapsed)
elapsed = age
# POST, PUT, DELETE should not be cached.
- self.getPage("/", method="POST")
+ self.getPage('/', method='POST')
self.assertBody('visit #2')
# Because gzip is turned on, the Vary header should always Vary for
# content-encoding
self.assertHeader('Vary', 'Accept-Encoding')
# The previous request should have invalidated the cache,
# so this request will recalc the response.
- self.getPage("/", method="GET")
+ self.getPage('/', method='GET')
self.assertBody('visit #3')
# ...but this request should get the cached copy.
- self.getPage("/", method="GET")
+ self.getPage('/', method='GET')
self.assertBody('visit #3')
- self.getPage("/", method="DELETE")
+ self.getPage('/', method='DELETE')
self.assertBody('visit #4')
# The previous request should have invalidated the cache,
# so this request will recalc the response.
- self.getPage("/", method="GET", headers=[('Accept-Encoding', 'gzip')])
+ self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')])
self.assertHeader('Content-Encoding', 'gzip')
self.assertHeader('Vary')
self.assertEqual(
- cherrypy.lib.encoding.decompress(self.body), ntob("visit #5"))
+ cherrypy.lib.encoding.decompress(self.body), ntob('visit #5'))
# Now check that a second request gets the gzip header and gzipped body
# This also tests a bug in 3.0 to 3.0.2 whereby the cached, gzipped
# response body was being gzipped a second time.
- self.getPage("/", method="GET", headers=[('Accept-Encoding', 'gzip')])
+ self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')])
self.assertHeader('Content-Encoding', 'gzip')
self.assertEqual(
- cherrypy.lib.encoding.decompress(self.body), ntob("visit #5"))
+ cherrypy.lib.encoding.decompress(self.body), ntob('visit #5'))
# Now check that a third request that doesn't accept gzip
# skips the cache (because the 'Vary' header denies it).
- self.getPage("/", method="GET")
+ self.getPage('/', method='GET')
self.assertNoHeader('Content-Encoding')
self.assertBody('visit #6')
def testVaryHeader(self):
- self.getPage("/varying_headers/")
- self.assertStatus("200 OK")
+ self.getPage('/varying_headers/')
+ self.assertStatus('200 OK')
self.assertHeaderItemValue('Vary', 'Our-Varying-Header')
self.assertBody('visit #1')
# Now check that different 'Vary'-fields don't evict each other.
# This test creates 2 requests with different 'Our-Varying-Header'
# and then tests if the first one still exists.
- self.getPage("/varying_headers/",
+ self.getPage('/varying_headers/',
headers=[('Our-Varying-Header', 'request 2')])
- self.assertStatus("200 OK")
+ self.assertStatus('200 OK')
self.assertBody('visit #2')
- self.getPage("/varying_headers/",
+ self.getPage('/varying_headers/',
headers=[('Our-Varying-Header', 'request 2')])
- self.assertStatus("200 OK")
+ self.assertStatus('200 OK')
self.assertBody('visit #2')
- self.getPage("/varying_headers/")
- self.assertStatus("200 OK")
+ self.getPage('/varying_headers/')
+ self.assertStatus('200 OK')
self.assertBody('visit #1')
def testExpiresTool(self):
# test setting an expires header
- self.getPage("/expires/specific")
- self.assertStatus("200 OK")
- self.assertHeader("Expires")
+ self.getPage('/expires/specific')
+ self.assertStatus('200 OK')
+ self.assertHeader('Expires')
# test exceptions for bad time values
- self.getPage("/expires/wrongtype")
+ self.getPage('/expires/wrongtype')
self.assertStatus(500)
- self.assertInBody("TypeError")
+ self.assertInBody('TypeError')
# static content should not have "cache prevention" headers
- self.getPage("/expires/index.html")
- self.assertStatus("200 OK")
- self.assertNoHeader("Pragma")
- self.assertNoHeader("Cache-Control")
- self.assertHeader("Expires")
+ self.getPage('/expires/index.html')
+ self.assertStatus('200 OK')
+ self.assertNoHeader('Pragma')
+ self.assertNoHeader('Cache-Control')
+ self.assertHeader('Expires')
# dynamic content that sets indicators should not have
# "cache prevention" headers
- self.getPage("/expires/cacheable")
- self.assertStatus("200 OK")
- self.assertNoHeader("Pragma")
- self.assertNoHeader("Cache-Control")
- self.assertHeader("Expires")
+ self.getPage('/expires/cacheable')
+ self.assertStatus('200 OK')
+ self.assertNoHeader('Pragma')
+ self.assertNoHeader('Cache-Control')
+ self.assertHeader('Expires')
self.getPage('/expires/dynamic')
- self.assertBody("D-d-d-dynamic!")
+ self.assertBody('D-d-d-dynamic!')
# the Cache-Control header should be untouched
- self.assertHeader("Cache-Control", "private")
- self.assertHeader("Expires")
+ self.assertHeader('Cache-Control', 'private')
+ self.assertHeader('Expires')
# configure the tool to ignore indicators and replace existing headers
- self.getPage("/expires/force")
- self.assertStatus("200 OK")
+ self.getPage('/expires/force')
+ self.assertStatus('200 OK')
# This also gives us a chance to test 0 expiry with no other headers
- self.assertHeader("Pragma", "no-cache")
- if cherrypy.server.protocol_version == "HTTP/1.1":
- self.assertHeader("Cache-Control", "no-cache, must-revalidate")
- self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT")
+ self.assertHeader('Pragma', 'no-cache')
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
+ self.assertHeader('Cache-Control', 'no-cache, must-revalidate')
+ self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT')
# static content should now have "cache prevention" headers
- self.getPage("/expires/index.html")
- self.assertStatus("200 OK")
- self.assertHeader("Pragma", "no-cache")
- if cherrypy.server.protocol_version == "HTTP/1.1":
- self.assertHeader("Cache-Control", "no-cache, must-revalidate")
- self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT")
+ self.getPage('/expires/index.html')
+ self.assertStatus('200 OK')
+ self.assertHeader('Pragma', 'no-cache')
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
+ self.assertHeader('Cache-Control', 'no-cache, must-revalidate')
+ self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT')
# the cacheable handler should now have "cache prevention" headers
- self.getPage("/expires/cacheable")
- self.assertStatus("200 OK")
- self.assertHeader("Pragma", "no-cache")
- if cherrypy.server.protocol_version == "HTTP/1.1":
- self.assertHeader("Cache-Control", "no-cache, must-revalidate")
- self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT")
+ self.getPage('/expires/cacheable')
+ self.assertStatus('200 OK')
+ self.assertHeader('Pragma', 'no-cache')
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
+ self.assertHeader('Cache-Control', 'no-cache, must-revalidate')
+ self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT')
self.getPage('/expires/dynamic')
- self.assertBody("D-d-d-dynamic!")
+ self.assertBody('D-d-d-dynamic!')
# dynamic sets Cache-Control to private but it should be
# overwritten here ...
- self.assertHeader("Pragma", "no-cache")
- if cherrypy.server.protocol_version == "HTTP/1.1":
- self.assertHeader("Cache-Control", "no-cache, must-revalidate")
- self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT")
+ self.assertHeader('Pragma', 'no-cache')
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
+ self.assertHeader('Cache-Control', 'no-cache, must-revalidate')
+ self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT')
+
+ def _assert_resp_len_and_enc_for_gzip(self, uri):
+ """
+ Test that after querying gzipped content it's remains valid in
+ cache and available non-gzipped as well.
+ """
+ ACCEPT_GZIP_HEADERS = [('Accept-Encoding', 'gzip')]
+ content_len = None
+
+ for _ in range(3):
+ self.getPage(uri, method='GET', headers=ACCEPT_GZIP_HEADERS)
+
+ if content_len is not None:
+ # all requests should get the same length
+ self.assertHeader('Content-Length', content_len)
+ self.assertHeader('Content-Encoding', 'gzip')
+
+ content_len = dict(self.headers)['Content-Length']
+
+ # check that we can still get non-gzipped version
+ self.getPage(uri, method='GET')
+ self.assertNoHeader('Content-Encoding')
+ # non-gzipped version should have a different content length
+ self.assertNoHeaderItemValue('Content-Length', content_len)
+
+ def testGzipStaticCache(self):
+ """Test that cache and gzip tools play well together when both enabled.
+
+ Ref GitHub issue #1190.
+ """
+ GZIP_STATIC_CACHE_TMPL = '/gzip_static_cache/{}'
+ resource_files = ('index.html', 'dirback.jpg')
+
+ for f in resource_files:
+ uri = GZIP_STATIC_CACHE_TMPL.format(f)
+ self._assert_resp_len_and_enc_for_gzip(uri)
def testLastModified(self):
- self.getPage("/a.gif")
+ self.getPage('/a.gif')
self.assertStatus(200)
self.assertBody(gif_bytes)
- lm1 = self.assertHeader("Last-Modified")
+ lm1 = self.assertHeader('Last-Modified')
# this request should get the cached copy.
- self.getPage("/a.gif")
+ self.getPage('/a.gif')
self.assertStatus(200)
self.assertBody(gif_bytes)
- self.assertHeader("Age")
- lm2 = self.assertHeader("Last-Modified")
+ self.assertHeader('Age')
+ lm2 = self.assertHeader('Last-Modified')
self.assertEqual(lm1, lm2)
# this request should match the cached copy, but raise 304.
- self.getPage("/a.gif", [('If-Modified-Since', lm1)])
+ self.getPage('/a.gif', [('If-Modified-Since', lm1)])
self.assertStatus(304)
- self.assertNoHeader("Last-Modified")
- if not getattr(cherrypy.server, "using_apache", False):
- self.assertHeader("Age")
+ self.assertNoHeader('Last-Modified')
+ if not getattr(cherrypy.server, 'using_apache', False):
+ self.assertHeader('Age')
+ @pytest.mark.xfail(reason='#1536')
def test_antistampede(self):
SECONDS = 4
+ slow_url = '/long_process?seconds={SECONDS}'.format(**locals())
# We MUST make an initial synchronous request in order to create the
# AntiStampedeCache object, and populate its selecting_headers,
# before the actual stampede.
- self.getPage("/long_process?seconds=%d" % SECONDS)
+ self.getPage(slow_url)
self.assertBody('success!')
- self.getPage("/clear_cache?path=" +
- quote('/long_process?seconds=%d' % SECONDS, safe=''))
+ path = urllib.parse.quote(slow_url, safe='')
+ self.getPage('/clear_cache?path=' + path)
self.assertStatus(200)
start = datetime.datetime.now()
def run():
- self.getPage("/long_process?seconds=%d" % SECONDS)
+ self.getPage(slow_url)
# The response should be the same every time
self.assertBody('success!')
- ts = [threading.Thread(target=run) for i in xrange(100)]
+ ts = [threading.Thread(target=run) for i in range(100)]
for t in ts:
t.start()
for t in ts:
t.join()
- self.assertEqualDates(start, datetime.datetime.now(),
- # Allow a second (two, for slow hosts)
- # for our thread/TCP overhead etc.
- seconds=SECONDS + 2)
+ finish = datetime.datetime.now()
+ # Allow for overhead, two seconds for slow hosts
+ allowance = SECONDS + 2
+ self.assertEqualDates(start, finish, seconds=allowance)
def test_cache_control(self):
- self.getPage("/control")
+ self.getPage('/control')
self.assertBody('visit #1')
- self.getPage("/control")
+ self.getPage('/control')
self.assertBody('visit #1')
- self.getPage("/control", headers=[('Cache-Control', 'no-cache')])
+ self.getPage('/control', headers=[('Cache-Control', 'no-cache')])
self.assertBody('visit #2')
- self.getPage("/control")
+ self.getPage('/control')
self.assertBody('visit #2')
- self.getPage("/control", headers=[('Pragma', 'no-cache')])
+ self.getPage('/control', headers=[('Pragma', 'no-cache')])
self.assertBody('visit #3')
- self.getPage("/control")
+ self.getPage('/control')
self.assertBody('visit #3')
time.sleep(1)
- self.getPage("/control", headers=[('Cache-Control', 'max-age=0')])
+ self.getPage('/control', headers=[('Cache-Control', 'max-age=0')])
self.assertBody('visit #4')
- self.getPage("/control")
+ self.getPage('/control')
self.assertBody('visit #4')
diff --git a/cherrypy/test/test_compat.py b/cherrypy/test/test_compat.py
index 257a5e70..7a2420fa 100644
--- a/cherrypy/test/test_compat.py
+++ b/cherrypy/test/test_compat.py
@@ -1,38 +1,56 @@
+"""Test Python 2/3 compatibility module."""
+from __future__ import unicode_literals
+
import unittest
-import nose
+import pytest
+import six
from cherrypy import _cpcompat as compat
class StringTester(unittest.TestCase):
+ """Tests for string conversion."""
+
+ @pytest.mark.skipif(six.PY3, reason='Only useful on Python 2')
def test_ntob_native(self):
- if compat.py3k:
- raise nose.SkipTest("Only useful on Python 2")
- s = compat.ntob('fight')
- assert isinstance(s, str), 'ntob should return a bytestring when given a bytestring'
- self.assertEqual(s, 'fight')
+ s = compat.ntob(b'fight')
+ assert isinstance(s, str), (
+ 'ntob should return a bytestring when given a bytestring')
+ self.assertEqual(s, b'fight')
+ @pytest.mark.skipif(six.PY3, reason='Only useful on Python 2')
def test_ntob_non_native(self):
- """
- ntob should raise an Exception on unicode.
+ """ntob should raise an Exception on unicode.
+
(Python 2 only)
See #1132 for discussion.
"""
- if compat.py3k:
- raise nose.SkipTest("Only useful on Python 2")
- self.assertRaises(Exception, compat.ntob, unicode('fight'))
+ self.assertRaises(TypeError, compat.ntob, 'fight')
def test_always_bytes_unicode(self):
- s = compat.always_bytes(compat.unicodestr('fight'))
- assert isinstance(s, compat.nativestr), 'always_bytes should return a bytestring when given unicode'
+ s = compat.always_bytes('fight')
+ assert isinstance(s, str), (
+ 'always_bytes should return a bytestring when given unicode')
self.assertEqual(s, 'fight')
def test_always_bytes_already_bytes(self):
- nat = compat.nativestr('fight')
+ nat = str('fight')
s = compat.always_bytes(nat)
- assert s is nat, 'always_bytes should return its input when given a bytestring'
+ assert s is nat, (
+ 'always_bytes should return its input when given a bytestring')
def test_always_bytes_invalid_input(self):
- self.assertRaises(Exception, compat.always_bytes, ['not a string'])
+ self.assertRaises(TypeError, compat.always_bytes, ['not a string'])
+
+
+class EscapeTester(unittest.TestCase):
+ """Class to test escape_html function from _cpcompat."""
+
+ def test_escape_quote(self):
+ """test_escape_quote - Verify the output for &<>"' chars."""
+ self.assertEqual(
+ """xx&amp;&lt;&gt;"aa'""",
+ compat.escape_html("""xx&<>"aa'"""),
+ )
diff --git a/cherrypy/test/test_config.py b/cherrypy/test/test_config.py
index 0508f92c..70fe535b 100644
--- a/cherrypy/test/test_config.py
+++ b/cherrypy/test/test_config.py
@@ -1,78 +1,81 @@
"""Tests for the CherryPy configuration system."""
+import io
import os
import sys
import unittest
+import six
+
import cherrypy
import cherrypy._cpcompat as compat
+from cherrypy.test import helper
+
+
localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+def StringIOFromNative(x):
+ return io.StringIO(six.text_type(x))
+
+
def setup_server():
+ @cherrypy.config(foo='this', bar='that')
class Root:
- _cp_config = {'foo': 'this',
- 'bar': 'that'}
-
def __init__(self):
cherrypy.config.namespaces['db'] = self.db_namespace
def db_namespace(self, k, v):
- if k == "scheme":
+ if k == 'scheme':
self.db = v
- # @cherrypy.expose(alias=('global_', 'xyz'))
+ @cherrypy.expose(alias=('global_', 'xyz'))
def index(self, key):
- return cherrypy.request.config.get(key, "None")
- index = cherrypy.expose(index, alias=('global_', 'xyz'))
+ return cherrypy.request.config.get(key, 'None')
+ @cherrypy.expose
def repr(self, key):
return repr(cherrypy.request.config.get(key, None))
- repr.exposed = True
+ @cherrypy.expose
def dbscheme(self):
return self.db
- dbscheme.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{'request.body.attempt_charsets': ['utf-16']})
def plain(self, x):
return x
- plain.exposed = True
- plain._cp_config = {'request.body.attempt_charsets': ['utf-16']}
favicon_ico = cherrypy.tools.staticfile.handler(
filename=os.path.join(localDir, '../favicon.ico'))
+ @cherrypy.config(foo='this2', baz='that2')
class Foo:
- _cp_config = {'foo': 'this2',
- 'baz': 'that2'}
-
+ @cherrypy.expose
def index(self, key):
- return cherrypy.request.config.get(key, "None")
- index.exposed = True
+ return cherrypy.request.config.get(key, 'None')
nex = index
+ @cherrypy.expose
+ @cherrypy.config(**{'response.headers.X-silly': 'sillyval'})
def silly(self):
return 'Hello world'
- silly.exposed = True
- silly._cp_config = {'response.headers.X-silly': 'sillyval'}
# Test the expose and config decorators
- #@cherrypy.expose
- #@cherrypy.config(foo='this3', **{'bax': 'this4'})
+ @cherrypy.config(foo='this3', **{'bax': 'this4'})
+ @cherrypy.expose
def bar(self, key):
return repr(cherrypy.request.config.get(key, None))
- bar.exposed = True
- bar._cp_config = {'foo': 'this3', 'bax': 'this4'}
class Another:
+ @cherrypy.expose
def index(self, key):
- return str(cherrypy.request.config.get(key, "None"))
- index.exposed = True
+ return str(cherrypy.request.config.get(key, 'None'))
def raw_namespace(key, value):
if key == 'input.map':
@@ -95,21 +98,20 @@ def setup_server():
return value(handler())
cherrypy.request.handler = wrapper
+ @cherrypy.config(**{'raw.output': repr})
class Raw:
- _cp_config = {'raw.output': repr}
-
+ @cherrypy.expose
+ @cherrypy.config(**{'raw.input.map': {'num': int}})
def incr(self, num):
return num + 1
- incr.exposed = True
- incr._cp_config = {'raw.input.map': {'num': int}}
- if not compat.py3k:
+ if not six.PY3:
thing3 = "thing3: unicode('test', errors='ignore')"
else:
thing3 = ''
- ioconf = compat.StringIO("""
+ ioconf = StringIOFromNative("""
[/]
neg: -1234
filename: os.path.join(sys.prefix, "hello.py")
@@ -132,29 +134,27 @@ tools.staticfile.filename = %r
app = cherrypy.tree.mount(root, config=ioconf)
app.request_class.namespaces['raw'] = raw_namespace
- cherrypy.tree.mount(Another(), "/another")
+ cherrypy.tree.mount(Another(), '/another')
cherrypy.config.update({'luxuryyacht': 'throatwobblermangrove',
- 'db.scheme': r"sqlite///memory",
+ 'db.scheme': r'sqlite///memory',
})
# Client-side code #
-from cherrypy.test import helper
-
class ConfigTests(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def testConfig(self):
tests = [
- ('/', 'nex', 'None'),
- ('/', 'foo', 'this'),
- ('/', 'bar', 'that'),
- ('/xyz', 'foo', 'this'),
- ('/foo/', 'foo', 'this2'),
- ('/foo/', 'bar', 'that'),
- ('/foo/', 'bax', 'None'),
+ ('/', 'nex', 'None'),
+ ('/', 'foo', 'this'),
+ ('/', 'bar', 'that'),
+ ('/xyz', 'foo', 'this'),
+ ('/foo/', 'foo', 'this2'),
+ ('/foo/', 'bar', 'that'),
+ ('/foo/', 'bax', 'None'),
('/foo/bar', 'baz', "'that2'"),
('/foo/nex', 'baz', 'that2'),
# If 'foo' == 'this', then the mount point '/another' leaks into
@@ -162,7 +162,7 @@ class ConfigTests(helper.CPWebCase):
('/another/', 'foo', 'None'),
]
for path, key, expected in tests:
- self.getPage(path + "?key=" + key)
+ self.getPage(path + '?key=' + key)
self.assertBody(expected)
expectedconf = {
@@ -184,65 +184,65 @@ class ConfigTests(helper.CPWebCase):
'bax': 'this4',
}
for key, expected in expectedconf.items():
- self.getPage("/foo/bar?key=" + key)
+ self.getPage('/foo/bar?key=' + key)
self.assertBody(repr(expected))
def testUnrepr(self):
- self.getPage("/repr?key=neg")
- self.assertBody("-1234")
+ self.getPage('/repr?key=neg')
+ self.assertBody('-1234')
- self.getPage("/repr?key=filename")
- self.assertBody(repr(os.path.join(sys.prefix, "hello.py")))
+ self.getPage('/repr?key=filename')
+ self.assertBody(repr(os.path.join(sys.prefix, 'hello.py')))
- self.getPage("/repr?key=thing1")
+ self.getPage('/repr?key=thing1')
self.assertBody(repr(cherrypy.lib.httputil.response_codes[404]))
- if not getattr(cherrypy.server, "using_apache", False):
+ if not getattr(cherrypy.server, 'using_apache', False):
# The object ID's won't match up when using Apache, since the
# server and client are running in different processes.
- self.getPage("/repr?key=thing2")
+ self.getPage('/repr?key=thing2')
from cherrypy.tutorial import thing2
self.assertBody(repr(thing2))
- if not compat.py3k:
- self.getPage("/repr?key=thing3")
- self.assertBody(repr(unicode('test')))
+ if not six.PY3:
+ self.getPage('/repr?key=thing3')
+ self.assertBody(repr(six.text_type('test')))
- self.getPage("/repr?key=complex")
- self.assertBody("(3+2j)")
+ self.getPage('/repr?key=complex')
+ self.assertBody('(3+2j)')
- self.getPage("/repr?key=mul")
- self.assertBody("18")
+ self.getPage('/repr?key=mul')
+ self.assertBody('18')
- self.getPage("/repr?key=stradd")
- self.assertBody(repr("112233"))
+ self.getPage('/repr?key=stradd')
+ self.assertBody(repr('112233'))
def testRespNamespaces(self):
- self.getPage("/foo/silly")
+ self.getPage('/foo/silly')
self.assertHeader('X-silly', 'sillyval')
self.assertBody('Hello world')
def testCustomNamespaces(self):
- self.getPage("/raw/incr?num=12")
- self.assertBody("13")
+ self.getPage('/raw/incr?num=12')
+ self.assertBody('13')
- self.getPage("/dbscheme")
- self.assertBody(r"sqlite///memory")
+ self.getPage('/dbscheme')
+ self.assertBody(r'sqlite///memory')
def testHandlerToolConfigOverride(self):
# Assert that config overrides tool constructor args. Above, we set
# the favicon in the page handler to be '../favicon.ico',
# but then overrode it in config to be './static/dirback.jpg'.
- self.getPage("/favicon.ico")
- self.assertBody(open(os.path.join(localDir, "static/dirback.jpg"),
- "rb").read())
+ self.getPage('/favicon.ico')
+ self.assertBody(open(os.path.join(localDir, 'static/dirback.jpg'),
+ 'rb').read())
def test_request_body_namespace(self):
- self.getPage("/plain", method='POST', headers=[
+ self.getPage('/plain', method='POST', headers=[
('Content-Type', 'application/x-www-form-urlencoded'),
('Content-Length', '13')],
body=compat.ntob('\xff\xfex\x00=\xff\xfea\x00b\x00c\x00'))
- self.assertBody("abc")
+ self.assertBody('abc')
class VariableSubstitutionTests(unittest.TestCase):
@@ -263,25 +263,24 @@ class VariableSubstitutionTests(unittest.TestCase):
""")
- fp = compat.StringIO(conf)
+ fp = StringIOFromNative(conf)
cherrypy.config.update(fp)
- self.assertEqual(cherrypy.config["my"]["my.dir"], "/some/dir/my/dir")
- self.assertEqual(cherrypy.config["my"]
- ["my.dir2"], "/some/dir/my/dir/dir2")
+ self.assertEqual(cherrypy.config['my']['my.dir'], '/some/dir/my/dir')
+ self.assertEqual(cherrypy.config['my']
+ ['my.dir2'], '/some/dir/my/dir/dir2')
class CallablesInConfigTest(unittest.TestCase):
setup_server = staticmethod(setup_server)
-
def test_call_with_literal_dict(self):
from textwrap import dedent
conf = dedent("""
[my]
value = dict(**{'foo': 'bar'})
""")
- fp = compat.StringIO(conf)
+ fp = StringIOFromNative(conf)
cherrypy.config.update(fp)
self.assertEqual(cherrypy.config['my']['value'], {'foo': 'bar'})
@@ -292,12 +291,12 @@ class CallablesInConfigTest(unittest.TestCase):
value = dict(foo="buzz", **cherrypy._test_dict)
""")
test_dict = {
- "foo": "bar",
- "bar": "foo",
- "fizz": "buzz"
+ 'foo': 'bar',
+ 'bar': 'foo',
+ 'fizz': 'buzz'
}
cherrypy._test_dict = test_dict
- fp = compat.StringIO(conf)
+ fp = StringIOFromNative(conf)
cherrypy.config.update(fp)
test_dict['foo'] = 'buzz'
self.assertEqual(cherrypy.config['my']['value']['foo'], 'buzz')
diff --git a/cherrypy/test/test_config_server.py b/cherrypy/test/test_config_server.py
index f4f574de..7b183530 100644
--- a/cherrypy/test/test_config_server.py
+++ b/cherrypy/test/test_config_server.py
@@ -1,37 +1,36 @@
"""Tests for the CherryPy configuration system."""
import os
-import sys
-localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))
-import socket
-import time
import cherrypy
+from cherrypy.test import helper
-# Client-side code #
+localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))
-from cherrypy.test import helper
+
+# Client-side code #
class ServerConfigTests(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
return cherrypy.request.wsgi_environ['SERVER_PORT']
- index.exposed = True
+ @cherrypy.expose
def upload(self, file):
- return "Size: %s" % len(file.file.read())
- upload.exposed = True
+ return 'Size: %s' % len(file.file.read())
+ @cherrypy.expose
+ @cherrypy.config(**{'request.body.maxbytes': 100})
def tinyupload(self):
return cherrypy.request.body.read()
- tinyupload.exposed = True
- tinyupload._cp_config = {'request.body.maxbytes': 100}
cherrypy.tree.mount(Root())
@@ -50,54 +49,53 @@ class ServerConfigTests(helper.CPWebCase):
# Also test default server.instance = builtin server
'server.yetanother.socket_port': 9878,
})
- setup_server = staticmethod(setup_server)
PORT = 9876
def testBasicConfig(self):
- self.getPage("/")
+ self.getPage('/')
self.assertBody(str(self.PORT))
def testAdditionalServers(self):
if self.scheme == 'https':
- return self.skip("not available under ssl")
+ return self.skip('not available under ssl')
self.PORT = 9877
- self.getPage("/")
+ self.getPage('/')
self.assertBody(str(self.PORT))
self.PORT = 9878
- self.getPage("/")
+ self.getPage('/')
self.assertBody(str(self.PORT))
def testMaxRequestSizePerHandler(self):
- if getattr(cherrypy.server, "using_apache", False):
- return self.skip("skipped due to known Apache differences... ")
+ if getattr(cherrypy.server, 'using_apache', False):
+ return self.skip('skipped due to known Apache differences... ')
- self.getPage('/tinyupload', method="POST",
+ self.getPage('/tinyupload', method='POST',
headers=[('Content-Type', 'text/plain'),
('Content-Length', '100')],
- body="x" * 100)
+ body='x' * 100)
self.assertStatus(200)
- self.assertBody("x" * 100)
+ self.assertBody('x' * 100)
- self.getPage('/tinyupload', method="POST",
+ self.getPage('/tinyupload', method='POST',
headers=[('Content-Type', 'text/plain'),
('Content-Length', '101')],
- body="x" * 101)
+ body='x' * 101)
self.assertStatus(413)
def testMaxRequestSize(self):
- if getattr(cherrypy.server, "using_apache", False):
- return self.skip("skipped due to known Apache differences... ")
+ if getattr(cherrypy.server, 'using_apache', False):
+ return self.skip('skipped due to known Apache differences... ')
for size in (500, 5000, 50000):
- self.getPage("/", headers=[('From', "x" * 500)])
+ self.getPage('/', headers=[('From', 'x' * 500)])
self.assertStatus(413)
# Test for https://github.com/cherrypy/cherrypy/issues/421
# (Incorrect border condition in readline of SizeCheckWrapper).
# This hangs in rev 891 and earlier.
- lines256 = "x" * 248
- self.getPage("/",
+ lines256 = 'x' * 248
+ self.getPage('/',
headers=[('Host', '%s:%s' % (self.HOST, self.PORT)),
('From', lines256)])
@@ -115,14 +113,14 @@ class ServerConfigTests(helper.CPWebCase):
'%s',
'--x--'])
partlen = 200 - len(body)
- b = body % ("x" * partlen)
- h = [("Content-type", "multipart/form-data; boundary=x"),
- ("Content-Length", "%s" % len(b))]
- self.getPage('/upload', h, "POST", b)
+ b = body % ('x' * partlen)
+ h = [('Content-type', 'multipart/form-data; boundary=x'),
+ ('Content-Length', '%s' % len(b))]
+ self.getPage('/upload', h, 'POST', b)
self.assertBody('Size: %d' % partlen)
- b = body % ("x" * 200)
- h = [("Content-type", "multipart/form-data; boundary=x"),
- ("Content-Length", "%s" % len(b))]
- self.getPage('/upload', h, "POST", b)
+ b = body % ('x' * 200)
+ h = [('Content-type', 'multipart/form-data; boundary=x'),
+ ('Content-Length', '%s' % len(b))]
+ self.getPage('/upload', h, 'POST', b)
self.assertStatus(413)
diff --git a/cherrypy/test/test_conn.py b/cherrypy/test/test_conn.py
index 3e0cbc16..06676286 100644
--- a/cherrypy/test/test_conn.py
+++ b/cherrypy/test/test_conn.py
@@ -1,22 +1,21 @@
"""Tests for TCP connection handling, including proper and timely close."""
+import errno
import socket
import sys
import time
-import errno
+import six
+from six.moves import urllib
+from six.moves.http_client import BadStatusLine, HTTPConnection, NotConnected
+
+import pytest
+
+from cheroot.test import webtest
import cherrypy
-from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, NotConnected
-from cherrypy._cpcompat import (
- BadStatusLine,
- ntob,
- tonative,
- urlopen,
- unicodestr,
- py3k
-)
-from cherrypy.test import webtest
+from cherrypy._cpcompat import HTTPSConnection, ntob, tonative
+from cherrypy.test import helper
timeout = 1
@@ -30,21 +29,23 @@ def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
return pov
- index.exposed = True
page1 = index
page2 = index
page3 = index
+ @cherrypy.expose
def hello(self):
- return "Hello, world!"
- hello.exposed = True
+ return 'Hello, world!'
+ @cherrypy.expose
def timeout(self, t):
return str(cherrypy.server.httpserver.timeout)
- timeout.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{'response.stream': True})
def stream(self, set_cl=False):
if set_cl:
cherrypy.response.headers['Content-Length'] = 10
@@ -54,48 +55,46 @@ def setup_server():
yield str(x)
return content()
- stream.exposed = True
- stream._cp_config = {'response.stream': True}
+ @cherrypy.expose
def error(self, code=500):
raise cherrypy.HTTPError(code)
- error.exposed = True
+ @cherrypy.expose
def upload(self):
if not cherrypy.request.method == 'POST':
raise AssertionError("'POST' != request.method %r" %
cherrypy.request.method)
return "thanks for '%s'" % cherrypy.request.body.read()
- upload.exposed = True
+ @cherrypy.expose
def custom(self, response_code):
cherrypy.response.status = response_code
- return "Code = %s" % response_code
- custom.exposed = True
+ return 'Code = %s' % response_code
+ @cherrypy.expose
+ @cherrypy.config(**{'hooks.on_start_resource': raise500})
def err_before_read(self):
- return "ok"
- err_before_read.exposed = True
- err_before_read._cp_config = {'hooks.on_start_resource': raise500}
+ return 'ok'
+ @cherrypy.expose
def one_megabyte_of_a(self):
- return ["a" * 1024] * 1024
- one_megabyte_of_a.exposed = True
+ return ['a' * 1024] * 1024
+ @cherrypy.expose
+ # Turn off the encoding tool so it doens't collapse
+ # our response body and reclaculate the Content-Length.
+ @cherrypy.config(**{'tools.encode.on': False})
def custom_cl(self, body, cl):
cherrypy.response.headers['Content-Length'] = cl
if not isinstance(body, list):
body = [body]
newbody = []
for chunk in body:
- if isinstance(chunk, unicodestr):
+ if isinstance(chunk, six.text_type):
chunk = chunk.encode('ISO-8859-1')
newbody.append(chunk)
return newbody
- custom_cl.exposed = True
- # Turn off the encoding tool so it doens't collapse
- # our response body and reclaculate the Content-Length.
- custom_cl._cp_config = {'tools.encode.on': False}
cherrypy.tree.mount(Root())
cherrypy.config.update({
@@ -104,40 +103,37 @@ def setup_server():
})
-from cherrypy.test import helper
-
-
class ConnectionCloseTests(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def test_HTTP11(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
self.persistent = True
# Make the first request and assert there's no "Connection: close".
- self.getPage("/")
+ self.getPage('/')
self.assertStatus('200 OK')
self.assertBody(pov)
- self.assertNoHeader("Connection")
+ self.assertNoHeader('Connection')
# Make another request on the same connection.
- self.getPage("/page1")
+ self.getPage('/page1')
self.assertStatus('200 OK')
self.assertBody(pov)
- self.assertNoHeader("Connection")
+ self.assertNoHeader('Connection')
# Test client-side close.
- self.getPage("/page2", headers=[("Connection", "close")])
+ self.getPage('/page2', headers=[('Connection', 'close')])
self.assertStatus('200 OK')
self.assertBody(pov)
- self.assertHeader("Connection", "close")
+ self.assertHeader('Connection', 'close')
# Make another request on the same connection, which should error.
- self.assertRaises(NotConnected, self.getPage, "/")
+ self.assertRaises(NotConnected, self.getPage, '/')
def test_Streaming_no_len(self):
try:
@@ -158,25 +154,25 @@ class ConnectionCloseTests(helper.CPWebCase):
pass
def _streaming(self, set_cl):
- if cherrypy.server.protocol_version == "HTTP/1.1":
- self.PROTOCOL = "HTTP/1.1"
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
+ self.PROTOCOL = 'HTTP/1.1'
self.persistent = True
# Make the first request and assert there's no "Connection: close".
- self.getPage("/")
+ self.getPage('/')
self.assertStatus('200 OK')
self.assertBody(pov)
- self.assertNoHeader("Connection")
+ self.assertNoHeader('Connection')
# Make another, streamed request on the same connection.
if set_cl:
# When a Content-Length is provided, the content should stream
# without closing the connection.
- self.getPage("/stream?set_cl=Yes")
- self.assertHeader("Content-Length")
- self.assertNoHeader("Connection", "close")
- self.assertNoHeader("Transfer-Encoding")
+ self.getPage('/stream?set_cl=Yes')
+ self.assertHeader('Content-Length')
+ self.assertNoHeader('Connection', 'close')
+ self.assertNoHeader('Transfer-Encoding')
self.assertStatus('200 OK')
self.assertBody('0123456789')
@@ -184,97 +180,97 @@ class ConnectionCloseTests(helper.CPWebCase):
# When no Content-Length response header is provided,
# streamed output will either close the connection, or use
# chunked encoding, to determine transfer-length.
- self.getPage("/stream")
- self.assertNoHeader("Content-Length")
+ self.getPage('/stream')
+ self.assertNoHeader('Content-Length')
self.assertStatus('200 OK')
self.assertBody('0123456789')
chunked_response = False
for k, v in self.headers:
- if k.lower() == "transfer-encoding":
- if str(v) == "chunked":
+ if k.lower() == 'transfer-encoding':
+ if str(v) == 'chunked':
chunked_response = True
if chunked_response:
- self.assertNoHeader("Connection", "close")
+ self.assertNoHeader('Connection', 'close')
else:
- self.assertHeader("Connection", "close")
+ self.assertHeader('Connection', 'close')
# Make another request on the same connection, which should
# error.
- self.assertRaises(NotConnected, self.getPage, "/")
+ self.assertRaises(NotConnected, self.getPage, '/')
# Try HEAD. See
# https://github.com/cherrypy/cherrypy/issues/864.
- self.getPage("/stream", method='HEAD')
+ self.getPage('/stream', method='HEAD')
self.assertStatus('200 OK')
self.assertBody('')
- self.assertNoHeader("Transfer-Encoding")
+ self.assertNoHeader('Transfer-Encoding')
else:
- self.PROTOCOL = "HTTP/1.0"
+ self.PROTOCOL = 'HTTP/1.0'
self.persistent = True
# Make the first request and assert Keep-Alive.
- self.getPage("/", headers=[("Connection", "Keep-Alive")])
+ self.getPage('/', headers=[('Connection', 'Keep-Alive')])
self.assertStatus('200 OK')
self.assertBody(pov)
- self.assertHeader("Connection", "Keep-Alive")
+ self.assertHeader('Connection', 'Keep-Alive')
# Make another, streamed request on the same connection.
if set_cl:
# When a Content-Length is provided, the content should
# stream without closing the connection.
- self.getPage("/stream?set_cl=Yes",
- headers=[("Connection", "Keep-Alive")])
- self.assertHeader("Content-Length")
- self.assertHeader("Connection", "Keep-Alive")
- self.assertNoHeader("Transfer-Encoding")
+ self.getPage('/stream?set_cl=Yes',
+ headers=[('Connection', 'Keep-Alive')])
+ self.assertHeader('Content-Length')
+ self.assertHeader('Connection', 'Keep-Alive')
+ self.assertNoHeader('Transfer-Encoding')
self.assertStatus('200 OK')
self.assertBody('0123456789')
else:
# When a Content-Length is not provided,
# the server should close the connection.
- self.getPage("/stream", headers=[("Connection", "Keep-Alive")])
+ self.getPage('/stream', headers=[('Connection', 'Keep-Alive')])
self.assertStatus('200 OK')
self.assertBody('0123456789')
- self.assertNoHeader("Content-Length")
- self.assertNoHeader("Connection", "Keep-Alive")
- self.assertNoHeader("Transfer-Encoding")
+ self.assertNoHeader('Content-Length')
+ self.assertNoHeader('Connection', 'Keep-Alive')
+ self.assertNoHeader('Transfer-Encoding')
# Make another request on the same connection, which should
# error.
- self.assertRaises(NotConnected, self.getPage, "/")
+ self.assertRaises(NotConnected, self.getPage, '/')
def test_HTTP10_KeepAlive(self):
- self.PROTOCOL = "HTTP/1.0"
- if self.scheme == "https":
+ self.PROTOCOL = 'HTTP/1.0'
+ if self.scheme == 'https':
self.HTTP_CONN = HTTPSConnection
else:
self.HTTP_CONN = HTTPConnection
# Test a normal HTTP/1.0 request.
- self.getPage("/page2")
+ self.getPage('/page2')
self.assertStatus('200 OK')
self.assertBody(pov)
# Apache, for example, may emit a Connection header even for HTTP/1.0
-# self.assertNoHeader("Connection")
+ # self.assertNoHeader("Connection")
# Test a keep-alive HTTP/1.0 request.
self.persistent = True
- self.getPage("/page3", headers=[("Connection", "Keep-Alive")])
+ self.getPage('/page3', headers=[('Connection', 'Keep-Alive')])
self.assertStatus('200 OK')
self.assertBody(pov)
- self.assertHeader("Connection", "Keep-Alive")
+ self.assertHeader('Connection', 'Keep-Alive')
# Remove the keep-alive header again.
- self.getPage("/page3")
+ self.getPage('/page3')
self.assertStatus('200 OK')
self.assertBody(pov)
# Apache, for example, may emit a Connection header even for HTTP/1.0
-# self.assertNoHeader("Connection")
+ # self.assertNoHeader("Connection")
class PipelineTests(helper.CPWebCase):
@@ -283,10 +279,10 @@ class PipelineTests(helper.CPWebCase):
def test_HTTP11_Timeout(self):
# If we timeout without sending any data,
# the server will close the conn with a 408.
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Connect but send nothing.
self.persistent = True
@@ -298,7 +294,7 @@ class PipelineTests(helper.CPWebCase):
time.sleep(timeout * 2)
# The request should have returned 408 already.
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 408)
conn.close()
@@ -309,13 +305,13 @@ class PipelineTests(helper.CPWebCase):
conn.auto_open = False
conn.connect()
conn.send(ntob('GET /hello HTTP/1.1'))
- conn.send(("Host: %s" % self.HOST).encode('ascii'))
+ conn.send(('Host: %s' % self.HOST).encode('ascii'))
# Wait for our socket timeout
time.sleep(timeout * 2)
# The conn should have already sent 408.
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 408)
conn.close()
@@ -323,18 +319,18 @@ class PipelineTests(helper.CPWebCase):
def test_HTTP11_Timeout_after_request(self):
# If we timeout after at least one request has succeeded,
# the server will close the conn without 408.
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Make an initial request
self.persistent = True
conn = self.HTTP_CONN
- conn.putrequest("GET", "/timeout?t=%s" % timeout, skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/timeout?t=%s' % timeout, skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 200)
self.body = response.read()
@@ -342,33 +338,33 @@ class PipelineTests(helper.CPWebCase):
# Make a second request on the same socket
conn._output(ntob('GET /hello HTTP/1.1'))
- conn._output(ntob("Host: %s" % self.HOST, 'ascii'))
+ conn._output(ntob('Host: %s' % self.HOST, 'ascii'))
conn._send_output()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 200)
self.body = response.read()
- self.assertBody("Hello, world!")
+ self.assertBody('Hello, world!')
# Wait for our socket timeout
time.sleep(timeout * 2)
# Make another request on the same socket, which should error
conn._output(ntob('GET /hello HTTP/1.1'))
- conn._output(ntob("Host: %s" % self.HOST, 'ascii'))
+ conn._output(ntob('Host: %s' % self.HOST, 'ascii'))
conn._send_output()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
try:
response.begin()
- except:
+ except Exception:
if not isinstance(sys.exc_info()[1],
(socket.error, BadStatusLine)):
self.fail("Writing to timed out socket didn't fail"
- " as it should have: %s" % sys.exc_info()[1])
+ ' as it should have: %s' % sys.exc_info()[1])
else:
if response.status != 408:
self.fail("Writing to timed out socket didn't fail"
- " as it should have: %s" %
+ ' as it should have: %s' %
response.read())
conn.close()
@@ -376,10 +372,10 @@ class PipelineTests(helper.CPWebCase):
# Make another request on a new socket, which should work
self.persistent = True
conn = self.HTTP_CONN
- conn.putrequest("GET", "/", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 200)
self.body = response.read()
@@ -390,17 +386,17 @@ class PipelineTests(helper.CPWebCase):
conn.send(ntob('GET /hello HTTP/1.1'))
# Wait for our socket timeout
time.sleep(timeout * 2)
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
try:
response.begin()
- except:
+ except Exception:
if not isinstance(sys.exc_info()[1],
(socket.error, BadStatusLine)):
self.fail("Writing to timed out socket didn't fail"
- " as it should have: %s" % sys.exc_info()[1])
+ ' as it should have: %s' % sys.exc_info()[1])
else:
self.fail("Writing to timed out socket didn't fail"
- " as it should have: %s" %
+ ' as it should have: %s' %
response.read())
conn.close()
@@ -408,10 +404,10 @@ class PipelineTests(helper.CPWebCase):
# Retry the request on a new connection, which should work
self.persistent = True
conn = self.HTTP_CONN
- conn.putrequest("GET", "/", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 200)
self.body = response.read()
@@ -419,53 +415,53 @@ class PipelineTests(helper.CPWebCase):
conn.close()
def test_HTTP11_pipelining(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Test pipelining. httplib doesn't support this directly.
self.persistent = True
conn = self.HTTP_CONN
# Put request 1
- conn.putrequest("GET", "/hello", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/hello', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
for trial in range(5):
# Put next request
conn._output(ntob('GET /hello HTTP/1.1'))
- conn._output(ntob("Host: %s" % self.HOST, 'ascii'))
+ conn._output(ntob('Host: %s' % self.HOST, 'ascii'))
conn._send_output()
# Retrieve previous response
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
# there is a bug in python3 regarding the buffering of
# ``conn.sock``. Until that bug get's fixed we will
- # monkey patch the ``reponse`` instance.
+ # monkey patch the ``response`` instance.
# https://bugs.python.org/issue23377
- if py3k:
- response.fp = conn.sock.makefile("rb", 0)
+ if six.PY3:
+ response.fp = conn.sock.makefile('rb', 0)
response.begin()
body = response.read(13)
self.assertEqual(response.status, 200)
- self.assertEqual(body, ntob("Hello, world!"))
+ self.assertEqual(body, ntob('Hello, world!'))
# Retrieve final response
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
body = response.read()
self.assertEqual(response.status, 200)
- self.assertEqual(body, ntob("Hello, world!"))
+ self.assertEqual(body, ntob('Hello, world!'))
conn.close()
def test_100_Continue(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
self.persistent = True
conn = self.HTTP_CONN
@@ -474,13 +470,13 @@ class PipelineTests(helper.CPWebCase):
# Note that httplib's response.begin automatically ignores
# 100 Continue responses, so we must manually check for it.
try:
- conn.putrequest("POST", "/upload", skip_host=True)
- conn.putheader("Host", self.HOST)
- conn.putheader("Content-Type", "text/plain")
- conn.putheader("Content-Length", "4")
+ conn.putrequest('POST', '/upload', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Content-Type', 'text/plain')
+ conn.putheader('Content-Length', '4')
conn.endheaders()
conn.send(ntob("d'oh"))
- response = conn.response_class(conn.sock, method="POST")
+ response = conn.response_class(conn.sock, method='POST')
version, status, reason = response._read_status()
self.assertNotEqual(status, 100)
finally:
@@ -489,13 +485,13 @@ class PipelineTests(helper.CPWebCase):
# Now try a page with an Expect header...
try:
conn.connect()
- conn.putrequest("POST", "/upload", skip_host=True)
- conn.putheader("Host", self.HOST)
- conn.putheader("Content-Type", "text/plain")
- conn.putheader("Content-Length", "17")
- conn.putheader("Expect", "100-continue")
+ conn.putrequest('POST', '/upload', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Content-Type', 'text/plain')
+ conn.putheader('Content-Length', '17')
+ conn.putheader('Expect', '100-continue')
conn.endheaders()
- response = conn.response_class(conn.sock, method="POST")
+ response = conn.response_class(conn.sock, method='POST')
# ...assert and then skip the 100 response
version, status, reason = response._read_status()
@@ -504,13 +500,13 @@ class PipelineTests(helper.CPWebCase):
line = response.fp.readline().strip()
if line:
self.fail(
- "100 Continue should not output any headers. Got %r" %
+ '100 Continue should not output any headers. Got %r' %
line)
else:
break
# ...send the body
- body = ntob("I am a small file")
+ body = ntob('I am a small file')
conn.send(body)
# ...get the final response
@@ -526,12 +522,12 @@ class ConnectionTests(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def test_readall_or_close(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
- if self.scheme == "https":
+ if self.scheme == 'https':
self.HTTP_CONN = HTTPSConnection
else:
self.HTTP_CONN = HTTPConnection
@@ -545,13 +541,13 @@ class ConnectionTests(helper.CPWebCase):
conn = self.HTTP_CONN
# Get a POST page with an error
- conn.putrequest("POST", "/err_before_read", skip_host=True)
- conn.putheader("Host", self.HOST)
- conn.putheader("Content-Type", "text/plain")
- conn.putheader("Content-Length", "1000")
- conn.putheader("Expect", "100-continue")
+ conn.putrequest('POST', '/err_before_read', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Content-Type', 'text/plain')
+ conn.putheader('Content-Length', '1000')
+ conn.putheader('Expect', '100-continue')
conn.endheaders()
- response = conn.response_class(conn.sock, method="POST")
+ response = conn.response_class(conn.sock, method='POST')
# ...assert and then skip the 100 response
version, status, reason = response._read_status()
@@ -562,7 +558,7 @@ class ConnectionTests(helper.CPWebCase):
break
# ...send the body
- conn.send(ntob("x" * 1000))
+ conn.send(ntob('x' * 1000))
# ...get the final response
response.begin()
@@ -571,12 +567,12 @@ class ConnectionTests(helper.CPWebCase):
# Now try a working page with an Expect header...
conn._output(ntob('POST /upload HTTP/1.1'))
- conn._output(ntob("Host: %s" % self.HOST, 'ascii'))
- conn._output(ntob("Content-Type: text/plain"))
- conn._output(ntob("Content-Length: 17"))
- conn._output(ntob("Expect: 100-continue"))
+ conn._output(ntob('Host: %s' % self.HOST, 'ascii'))
+ conn._output(ntob('Content-Type: text/plain'))
+ conn._output(ntob('Content-Length: 17'))
+ conn._output(ntob('Expect: 100-continue'))
conn._send_output()
- response = conn.response_class(conn.sock, method="POST")
+ response = conn.response_class(conn.sock, method='POST')
# ...assert and then skip the 100 response
version, status, reason = response._read_status()
@@ -587,7 +583,7 @@ class ConnectionTests(helper.CPWebCase):
break
# ...send the body
- body = ntob("I am a small file")
+ body = ntob('I am a small file')
conn.send(body)
# ...get the final response
@@ -598,61 +594,61 @@ class ConnectionTests(helper.CPWebCase):
conn.close()
def test_No_Message_Body(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Set our HTTP_CONN to an instance so it persists between requests.
self.persistent = True
# Make the first request and assert there's no "Connection: close".
- self.getPage("/")
+ self.getPage('/')
self.assertStatus('200 OK')
self.assertBody(pov)
- self.assertNoHeader("Connection")
+ self.assertNoHeader('Connection')
# Make a 204 request on the same connection.
- self.getPage("/custom/204")
+ self.getPage('/custom/204')
self.assertStatus(204)
- self.assertNoHeader("Content-Length")
- self.assertBody("")
- self.assertNoHeader("Connection")
+ self.assertNoHeader('Content-Length')
+ self.assertBody('')
+ self.assertNoHeader('Connection')
# Make a 304 request on the same connection.
- self.getPage("/custom/304")
+ self.getPage('/custom/304')
self.assertStatus(304)
- self.assertNoHeader("Content-Length")
- self.assertBody("")
- self.assertNoHeader("Connection")
+ self.assertNoHeader('Content-Length')
+ self.assertBody('')
+ self.assertNoHeader('Connection')
def test_Chunked_Encoding(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
if (hasattr(self, 'harness') and
- "modpython" in self.harness.__class__.__name__.lower()):
+ 'modpython' in self.harness.__class__.__name__.lower()):
# mod_python forbids chunked encoding
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Set our HTTP_CONN to an instance so it persists between requests.
self.persistent = True
conn = self.HTTP_CONN
# Try a normal chunked request (with extensions)
- body = ntob("8;key=value\r\nxx\r\nxxxx\r\n5\r\nyyyyy\r\n0\r\n"
- "Content-Type: application/json\r\n"
- "\r\n")
- conn.putrequest("POST", "/upload", skip_host=True)
- conn.putheader("Host", self.HOST)
- conn.putheader("Transfer-Encoding", "chunked")
- conn.putheader("Trailer", "Content-Type")
+ body = ntob('8;key=value\r\nxx\r\nxxxx\r\n5\r\nyyyyy\r\n0\r\n'
+ 'Content-Type: application/json\r\n'
+ '\r\n')
+ conn.putrequest('POST', '/upload', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Transfer-Encoding', 'chunked')
+ conn.putheader('Trailer', 'Content-Type')
# Note that this is somewhat malformed:
# we shouldn't be sending Content-Length.
# RFC 2616 says the server should ignore it.
- conn.putheader("Content-Length", "3")
+ conn.putheader('Content-Length', '3')
conn.endheaders()
conn.send(body)
response = conn.getresponse()
@@ -662,13 +658,13 @@ class ConnectionTests(helper.CPWebCase):
# Try a chunked request that exceeds server.max_request_body_size.
# Note that the delimiters and trailer are included.
- body = ntob("3e3\r\n" + ("x" * 995) + "\r\n0\r\n\r\n")
- conn.putrequest("POST", "/upload", skip_host=True)
- conn.putheader("Host", self.HOST)
- conn.putheader("Transfer-Encoding", "chunked")
- conn.putheader("Content-Type", "text/plain")
+ body = ntob('3e3\r\n' + ('x' * 995) + '\r\n0\r\n\r\n')
+ conn.putrequest('POST', '/upload', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Transfer-Encoding', 'chunked')
+ conn.putheader('Content-Type', 'text/plain')
# Chunked requests don't need a content-length
-## conn.putheader("Content-Length", len(body))
+ # # conn.putheader("Content-Length", len(body))
conn.endheaders()
conn.send(body)
response = conn.getresponse()
@@ -681,16 +677,16 @@ class ConnectionTests(helper.CPWebCase):
# server.max_request_body_size. Assert error before body send.
self.persistent = True
conn = self.HTTP_CONN
- conn.putrequest("POST", "/upload", skip_host=True)
- conn.putheader("Host", self.HOST)
- conn.putheader("Content-Type", "text/plain")
- conn.putheader("Content-Length", "9999")
+ conn.putrequest('POST', '/upload', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Content-Type', 'text/plain')
+ conn.putheader('Content-Length', '9999')
conn.endheaders()
response = conn.getresponse()
self.status, self.headers, self.body = webtest.shb(response)
self.assertStatus(413)
- self.assertBody("The entity sent with the request exceeds "
- "the maximum allowed bytes.")
+ self.assertBody('The entity sent with the request exceeds '
+ 'the maximum allowed bytes.')
conn.close()
def test_Content_Length_out_preheaders(self):
@@ -698,16 +694,16 @@ class ConnectionTests(helper.CPWebCase):
# the actual bytes in the response body.
self.persistent = True
conn = self.HTTP_CONN
- conn.putrequest("GET", "/custom_cl?body=I+have+too+many+bytes&cl=5",
+ conn.putrequest('GET', '/custom_cl?body=I+have+too+many+bytes&cl=5',
skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
response = conn.getresponse()
self.status, self.headers, self.body = webtest.shb(response)
self.assertStatus(500)
self.assertBody(
- "The requested resource returned more bytes than the "
- "declared Content-Length.")
+ 'The requested resource returned more bytes than the '
+ 'declared Content-Length.')
conn.close()
def test_Content_Length_out_postheaders(self):
@@ -716,19 +712,24 @@ class ConnectionTests(helper.CPWebCase):
self.persistent = True
conn = self.HTTP_CONN
conn.putrequest(
- "GET", "/custom_cl?body=I+too&body=+have+too+many&cl=5",
+ 'GET', '/custom_cl?body=I+too&body=+have+too+many&cl=5',
skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
response = conn.getresponse()
self.status, self.headers, self.body = webtest.shb(response)
self.assertStatus(200)
- self.assertBody("I too")
+ self.assertBody('I too')
conn.close()
def test_598(self):
- remote_data_conn = urlopen('%s://%s:%s/one_megabyte_of_a/' %
- (self.scheme, self.HOST, self.PORT,))
+ tmpl = '{scheme}://{host}:{port}/one_megabyte_of_a/'
+ url = tmpl.format(
+ scheme=self.scheme,
+ host=self.HOST,
+ port=self.PORT,
+ )
+ remote_data_conn = urllib.request.urlopen(url)
buf = remote_data_conn.read(512)
time.sleep(timeout * 0.6)
remaining = (1024 * 1024) - 512
@@ -741,7 +742,7 @@ class ConnectionTests(helper.CPWebCase):
remaining -= len(data)
self.assertEqual(len(buf), 1024 * 1024)
- self.assertEqual(buf, ntob("a" * 1024 * 1024))
+ self.assertEqual(buf, ntob('a' * 1024 * 1024))
self.assertEqual(remaining, 0)
remote_data_conn.close()
@@ -749,12 +750,12 @@ class ConnectionTests(helper.CPWebCase):
def setup_upload_server():
class Root:
+ @cherrypy.expose
def upload(self):
if not cherrypy.request.method == 'POST':
raise AssertionError("'POST' != request.method %r" %
cherrypy.request.method)
return "thanks for '%s'" % tonative(cherrypy.request.body.read())
- upload.exposed = True
cherrypy.tree.mount(Root())
cherrypy.config.update({
@@ -764,24 +765,26 @@ def setup_upload_server():
'server.accepted_queue_timeout': 0.1,
})
+
reset_names = 'ECONNRESET', 'WSAECONNRESET'
socket_reset_errors = [
getattr(errno, name)
for name in reset_names
if hasattr(errno, name)
]
-"reset error numbers available on this platform"
+'reset error numbers available on this platform'
socket_reset_errors += [
# Python 3.5 raises an http.client.RemoteDisconnected
# with this message
- "Remote end closed connection without response",
+ 'Remote end closed connection without response',
]
class LimitedRequestQueueTests(helper.CPWebCase):
setup_server = staticmethod(setup_upload_server)
+ @pytest.mark.xfail(reason='#1535')
def test_queue_full(self):
conns = []
overflow_conn = None
@@ -791,14 +794,15 @@ class LimitedRequestQueueTests(helper.CPWebCase):
# all of wsgiserver's WorkerThreads and fill its Queue.
for i in range(15):
conn = self.HTTP_CONN(self.HOST, self.PORT)
- conn.putrequest("POST", "/upload", skip_host=True)
- conn.putheader("Host", self.HOST)
- conn.putheader("Content-Type", "text/plain")
- conn.putheader("Content-Length", "4")
+ conn.putrequest('POST', '/upload', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Content-Type', 'text/plain')
+ conn.putheader('Content-Length', '4')
conn.endheaders()
conns.append(conn)
- # Now try a 16th conn, which should be closed by the server immediately.
+ # Now try a 16th conn, which should be closed by the
+ # server immediately.
overflow_conn = self.HTTP_CONN(self.HOST, self.PORT)
# Manually connect since httplib won't let us set a timeout
for res in socket.getaddrinfo(self.HOST, self.PORT, 0,
@@ -809,19 +813,22 @@ class LimitedRequestQueueTests(helper.CPWebCase):
overflow_conn.sock.connect(sa)
break
- overflow_conn.putrequest("GET", "/", skip_host=True)
- overflow_conn.putheader("Host", self.HOST)
+ overflow_conn.putrequest('GET', '/', skip_host=True)
+ overflow_conn.putheader('Host', self.HOST)
overflow_conn.endheaders()
- response = overflow_conn.response_class(overflow_conn.sock, method="GET")
+ response = overflow_conn.response_class(
+ overflow_conn.sock,
+ method='GET',
+ )
try:
response.begin()
except socket.error as exc:
if exc.args[0] in socket_reset_errors:
- pass # Expected.
+ pass # Expected.
else:
tmpl = (
- "Overflow conn did not get RST. "
- "Got {exc.args!r} instead"
+ 'Overflow conn did not get RST. '
+ 'Got {exc.args!r} instead'
)
raise AssertionError(tmpl.format(**locals()))
except BadStatusLine:
@@ -829,11 +836,11 @@ class LimitedRequestQueueTests(helper.CPWebCase):
# RST correctly.
assert sys.platform == 'darwin'
else:
- raise AssertionError("Overflow conn did not get RST ")
+ raise AssertionError('Overflow conn did not get RST ')
finally:
for conn in conns:
- conn.send(ntob("done"))
- response = conn.response_class(conn.sock, method="POST")
+ conn.send(ntob('done'))
+ response = conn.response_class(conn.sock, method='POST')
response.begin()
self.body = response.read()
self.assertBody("thanks for 'done'")
@@ -842,6 +849,7 @@ class LimitedRequestQueueTests(helper.CPWebCase):
if overflow_conn:
overflow_conn.close()
+
class BadRequestTests(helper.CPWebCase):
setup_server = staticmethod(setup_server)
@@ -850,16 +858,16 @@ class BadRequestTests(helper.CPWebCase):
conn = self.HTTP_CONN
conn.send(ntob('GET /hello HTTP/1.1\n\n'))
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.body = response.read()
- self.assertBody("HTTP requires CRLF terminators")
+ self.assertBody('HTTP requires CRLF terminators')
conn.close()
conn.connect()
conn.send(ntob('GET /hello HTTP/1.1\r\n\n'))
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.body = response.read()
- self.assertBody("HTTP requires CRLF terminators")
+ self.assertBody('HTTP requires CRLF terminators')
conn.close()
diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py
index 16a0219d..ef5f5016 100644
--- a/cherrypy/test/test_core.py
+++ b/cherrypy/test/test_core.py
@@ -1,45 +1,50 @@
+# coding: utf-8
+
"""Basic tests for the CherryPy core: request handling."""
import os
-localDir = os.path.dirname(__file__)
import sys
import types
+import six
+
import cherrypy
-from cherrypy._cpcompat import IncompleteRead, itervalues, ntob
+from cherrypy._cpcompat import ntob, ntou
from cherrypy import _cptools, tools
from cherrypy.lib import httputil, static
+
from cherrypy.test._test_decorators import ExposeExamples
+from cherrypy.test import helper
-favicon_path = os.path.join(os.getcwd(), localDir, "../favicon.ico")
+localDir = os.path.dirname(__file__)
+favicon_path = os.path.join(os.getcwd(), localDir, '../favicon.ico')
# Client-side code #
-from cherrypy.test import helper
-
class CoreRequestHandlingTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "hello"
- index.exposed = True
+ return 'hello'
favicon_ico = tools.staticfile.handler(filename=favicon_path)
+ @cherrypy.expose
def defct(self, newct):
- newct = "text/%s" % newct
+ newct = 'text/%s' % newct
cherrypy.config.update({'tools.response_headers.on': True,
'tools.response_headers.headers':
[('Content-Type', newct)]})
- defct.exposed = True
+ @cherrypy.expose
def baseurl(self, path_info, relative=None):
return cherrypy.url(path_info, relative=bool(relative))
- baseurl.exposed = True
root = Root()
root.expose_dec = ExposeExamples()
@@ -52,16 +57,15 @@ class CoreRequestHandlingTest(helper.CPWebCase):
"""
def __init__(cls, name, bases, dct):
type.__init__(cls, name, bases, dct)
- for value in itervalues(dct):
+ for value in six.itervalues(dct):
if isinstance(value, types.FunctionType):
value.exposed = True
setattr(root, name.lower(), cls())
Test = TestType('Test', (object, ), {})
+ @cherrypy.config(**{'tools.trailing_slash.on': False})
class URL(Test):
- _cp_config = {'tools.trailing_slash.on': False}
-
def index(self, path_info, relative=None):
if relative != 'server':
relative = bool(relative)
@@ -72,6 +76,9 @@ class CoreRequestHandlingTest(helper.CPWebCase):
relative = bool(relative)
return cherrypy.url(path_info, relative=relative)
+ def qs(self, qs):
+ return cherrypy.url(qs=qs)
+
def log_status():
Status.statuses.append(cherrypy.response.status)
cherrypy.tools.log_status = cherrypy.Tool(
@@ -80,10 +87,10 @@ class CoreRequestHandlingTest(helper.CPWebCase):
class Status(Test):
def index(self):
- return "normal"
+ return 'normal'
def blank(self):
- cherrypy.response.status = ""
+ cherrypy.response.status = ''
# According to RFC 2616, new status codes are OK as long as they
# are between 100 and 599.
@@ -91,93 +98,101 @@ class CoreRequestHandlingTest(helper.CPWebCase):
# Here is an illegal code...
def illegal(self):
cherrypy.response.status = 781
- return "oops"
+ return 'oops'
# ...and here is an unknown but legal code.
def unknown(self):
- cherrypy.response.status = "431 My custom error"
- return "funky"
+ cherrypy.response.status = '431 My custom error'
+ return 'funky'
# Non-numeric code
def bad(self):
- cherrypy.response.status = "error"
- return "bad news"
+ cherrypy.response.status = 'error'
+ return 'bad news'
statuses = []
+ @cherrypy.config(**{'tools.log_status.on': True})
def on_end_resource_stage(self):
return repr(self.statuses)
- on_end_resource_stage._cp_config = {'tools.log_status.on': True}
class Redirect(Test):
+ @cherrypy.config(**{
+ 'tools.err_redirect.on': True,
+ 'tools.err_redirect.url': '/errpage',
+ 'tools.err_redirect.internal': False,
+ })
class Error:
- _cp_config = {"tools.err_redirect.on": True,
- "tools.err_redirect.url": "/errpage",
- "tools.err_redirect.internal": False,
- }
-
+ @cherrypy.expose
def index(self):
- raise NameError("redirect_test")
- index.exposed = True
+ raise NameError('redirect_test')
+
error = Error()
def index(self):
- return "child"
+ return 'child'
def custom(self, url, code):
raise cherrypy.HTTPRedirect(url, code)
+ @cherrypy.config(**{'tools.trailing_slash.extra': True})
def by_code(self, code):
- raise cherrypy.HTTPRedirect("somewhere%20else", code)
- by_code._cp_config = {'tools.trailing_slash.extra': True}
+ raise cherrypy.HTTPRedirect('somewhere%20else', code)
def nomodify(self):
- raise cherrypy.HTTPRedirect("", 304)
+ raise cherrypy.HTTPRedirect('', 304)
def proxy(self):
- raise cherrypy.HTTPRedirect("proxy", 305)
+ raise cherrypy.HTTPRedirect('proxy', 305)
def stringify(self):
- return str(cherrypy.HTTPRedirect("/"))
+ return str(cherrypy.HTTPRedirect('/'))
def fragment(self, frag):
- raise cherrypy.HTTPRedirect("/some/url#%s" % frag)
+ raise cherrypy.HTTPRedirect('/some/url#%s' % frag)
def url_with_quote(self):
raise cherrypy.HTTPRedirect("/some\"url/that'we/want")
+ def url_with_xss(self):
+ raise cherrypy.HTTPRedirect(
+ "/some<script>alert(1);</script>url/that'we/want")
+
+ def url_with_unicode(self):
+ raise cherrypy.HTTPRedirect(ntou('тест', 'utf-8'))
+
def login_redir():
- if not getattr(cherrypy.request, "login", None):
- raise cherrypy.InternalRedirect("/internalredirect/login")
+ if not getattr(cherrypy.request, 'login', None):
+ raise cherrypy.InternalRedirect('/internalredirect/login')
tools.login_redir = _cptools.Tool('before_handler', login_redir)
def redir_custom():
- raise cherrypy.InternalRedirect("/internalredirect/custom_err")
+ raise cherrypy.InternalRedirect('/internalredirect/custom_err')
class InternalRedirect(Test):
def index(self):
- raise cherrypy.InternalRedirect("/")
+ raise cherrypy.InternalRedirect('/')
+ @cherrypy.expose
+ @cherrypy.config(**{'hooks.before_error_response': redir_custom})
def choke(self):
return 3 / 0
- choke.exposed = True
- choke._cp_config = {'hooks.before_error_response': redir_custom}
def relative(self, a, b):
- raise cherrypy.InternalRedirect("cousin?t=6")
+ raise cherrypy.InternalRedirect('cousin?t=6')
def cousin(self, t):
assert cherrypy.request.prev.closed
return cherrypy.request.prev.query_string
def petshop(self, user_id):
- if user_id == "parrot":
+ if user_id == 'parrot':
# Trade it for a slug when redirecting
raise cherrypy.InternalRedirect(
'/image/getImagesByUser?user_id=slug')
- elif user_id == "terrier":
+ elif user_id == 'terrier':
# Trade it for a fish when redirecting
raise cherrypy.InternalRedirect(
'/image/getImagesByUser?user_id=fish')
@@ -190,41 +205,41 @@ class CoreRequestHandlingTest(helper.CPWebCase):
# this:
# @tools.login_redir()
def secure(self):
- return "Welcome!"
+ return 'Welcome!'
secure = tools.login_redir()(secure)
# Since calling the tool returns the same function you pass in,
# you could skip binding the return value, and just write:
# tools.login_redir()(secure)
def login(self):
- return "Please log in"
+ return 'Please log in'
def custom_err(self):
- return "Something went horribly wrong."
+ return 'Something went horribly wrong.'
+ @cherrypy.config(**{'hooks.before_request_body': redir_custom})
def early_ir(self, arg):
- return "whatever"
- early_ir._cp_config = {'hooks.before_request_body': redir_custom}
+ return 'whatever'
class Image(Test):
def getImagesByUser(self, user_id):
- return "0 images for %s" % user_id
+ return '0 images for %s' % user_id
class Flatten(Test):
def as_string(self):
- return "content"
+ return 'content'
def as_list(self):
- return ["con", "tent"]
+ return ['con', 'tent']
def as_yield(self):
- yield ntob("content")
+ yield ntob('content')
+ @cherrypy.config(**{'tools.flatten.on': True})
def as_dblyield(self):
yield self.as_yield()
- as_dblyield._cp_config = {'tools.flatten.on': True}
def as_refyield(self):
for chunk in self.as_yield():
@@ -238,7 +253,7 @@ class CoreRequestHandlingTest(helper.CPWebCase):
def slice_file(self):
path = os.path.join(os.getcwd(), os.path.dirname(__file__))
return static.serve_file(
- os.path.join(path, "static/index.html"))
+ os.path.join(path, 'static/index.html'))
class Cookies(Test):
@@ -253,8 +268,8 @@ class CoreRequestHandlingTest(helper.CPWebCase):
def append_headers(header_list, debug=False):
if debug:
cherrypy.log(
- "Extending response headers with %s" % repr(header_list),
- "TOOLS.APPEND_HEADERS")
+ 'Extending response headers with %s' % repr(header_list),
+ 'TOOLS.APPEND_HEADERS')
cherrypy.serving.response.header_list.extend(header_list)
cherrypy.tools.append_headers = cherrypy.Tool(
'on_end_resource', append_headers)
@@ -273,28 +288,27 @@ class CoreRequestHandlingTest(helper.CPWebCase):
'WWW-Authenticate'] = 'Negotiate,Basic realm="foo"'
cherrypy.tree.mount(root)
- setup_server = staticmethod(setup_server)
def testStatus(self):
- self.getPage("/status/")
+ self.getPage('/status/')
self.assertBody('normal')
self.assertStatus(200)
- self.getPage("/status/blank")
+ self.getPage('/status/blank')
self.assertBody('')
self.assertStatus(200)
- self.getPage("/status/illegal")
+ self.getPage('/status/illegal')
self.assertStatus(500)
- msg = "Illegal response status from server (781 is out of range)."
+ msg = 'Illegal response status from server (781 is out of range).'
self.assertErrorPage(500, msg)
if not getattr(cherrypy.server, 'using_apache', False):
- self.getPage("/status/unknown")
+ self.getPage('/status/unknown')
self.assertBody('funky')
self.assertStatus(431)
- self.getPage("/status/bad")
+ self.getPage('/status/bad')
self.assertStatus(500)
msg = "Illegal response status from server ('error' is non-numeric)."
self.assertErrorPage(500, msg)
@@ -303,33 +317,37 @@ class CoreRequestHandlingTest(helper.CPWebCase):
self.getPage('/status/on_end_resource_stage')
self.assertBody('[]')
self.getPage('/status/on_end_resource_stage')
- self.assertBody(repr(["200 OK"]))
+ self.assertBody(repr(['200 OK']))
def testSlashes(self):
# Test that requests for index methods without a trailing slash
# get redirected to the same URI path with a trailing slash.
# Make sure GET params are preserved.
- self.getPage("/redirect?id=3")
+ self.getPage('/redirect?id=3')
self.assertStatus(301)
- self.assertMatchesBody('<a href=([\'"])%s/redirect/[?]id=3\\1>'
- "%s/redirect/[?]id=3</a>" % (self.base(), self.base()))
+ self.assertMatchesBody(
+ '<a href=([\'"])%s/redirect/[?]id=3\\1>'
+ '%s/redirect/[?]id=3</a>' % (self.base(), self.base())
+ )
if self.prefix():
# Corner case: the "trailing slash" redirect could be tricky if
# we're using a virtual root and the URI is "/vroot" (no slash).
- self.getPage("")
+ self.getPage('')
self.assertStatus(301)
self.assertMatchesBody("<a href=(['\"])%s/\\1>%s/</a>" %
- (self.base(), self.base()))
+ (self.base(), self.base()))
# Test that requests for NON-index methods WITH a trailing slash
# get redirected to the same URI path WITHOUT a trailing slash.
# Make sure GET params are preserved.
- self.getPage("/redirect/by_code/?code=307")
+ self.getPage('/redirect/by_code/?code=307')
self.assertStatus(301)
- self.assertMatchesBody("<a href=(['\"])%s/redirect/by_code[?]code=307\\1>"
- "%s/redirect/by_code[?]code=307</a>"
- % (self.base(), self.base()))
+ self.assertMatchesBody(
+ "<a href=(['\"])%s/redirect/by_code[?]code=307\\1>"
+ '%s/redirect/by_code[?]code=307</a>'
+ % (self.base(), self.base())
+ )
# If the trailing_slash tool is off, CP should just continue
# as if the slashes were correct. But it needs some help
@@ -340,73 +358,73 @@ class CoreRequestHandlingTest(helper.CPWebCase):
self.assertBody('%s/url/page1' % self.base())
def testRedirect(self):
- self.getPage("/redirect/")
+ self.getPage('/redirect/')
self.assertBody('child')
self.assertStatus(200)
- self.getPage("/redirect/by_code?code=300")
+ self.getPage('/redirect/by_code?code=300')
self.assertMatchesBody(
r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>")
self.assertStatus(300)
- self.getPage("/redirect/by_code?code=301")
+ self.getPage('/redirect/by_code?code=301')
self.assertMatchesBody(
r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>")
self.assertStatus(301)
- self.getPage("/redirect/by_code?code=302")
+ self.getPage('/redirect/by_code?code=302')
self.assertMatchesBody(
r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>")
self.assertStatus(302)
- self.getPage("/redirect/by_code?code=303")
+ self.getPage('/redirect/by_code?code=303')
self.assertMatchesBody(
r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>")
self.assertStatus(303)
- self.getPage("/redirect/by_code?code=307")
+ self.getPage('/redirect/by_code?code=307')
self.assertMatchesBody(
r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>")
self.assertStatus(307)
- self.getPage("/redirect/nomodify")
+ self.getPage('/redirect/nomodify')
self.assertBody('')
self.assertStatus(304)
- self.getPage("/redirect/proxy")
+ self.getPage('/redirect/proxy')
self.assertBody('')
self.assertStatus(305)
# HTTPRedirect on error
- self.getPage("/redirect/error/")
+ self.getPage('/redirect/error/')
self.assertStatus(('302 Found', '303 See Other'))
self.assertInBody('/errpage')
# Make sure str(HTTPRedirect()) works.
- self.getPage("/redirect/stringify", protocol="HTTP/1.0")
+ self.getPage('/redirect/stringify', protocol='HTTP/1.0')
self.assertStatus(200)
self.assertBody("(['%s/'], 302)" % self.base())
- if cherrypy.server.protocol_version == "HTTP/1.1":
- self.getPage("/redirect/stringify", protocol="HTTP/1.1")
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
+ self.getPage('/redirect/stringify', protocol='HTTP/1.1')
self.assertStatus(200)
self.assertBody("(['%s/'], 303)" % self.base())
# check that #fragments are handled properly
# http://skrb.org/ietf/http_errata.html#location-fragments
- frag = "foo"
- self.getPage("/redirect/fragment/%s" % frag)
+ frag = 'foo'
+ self.getPage('/redirect/fragment/%s' % frag)
self.assertMatchesBody(
r"<a href=(['\"])(.*)\/some\/url\#%s\1>\2\/some\/url\#%s</a>" % (
frag, frag))
loc = self.assertHeader('Location')
- assert loc.endswith("#%s" % frag)
+ assert loc.endswith('#%s' % frag)
self.assertStatus(('302 Found', '303 See Other'))
# check injection protection
# See https://github.com/cherrypy/cherrypy/issues/1003
self.getPage(
- "/redirect/custom?"
- "code=303&url=/foobar/%0d%0aSet-Cookie:%20somecookie=someval")
+ '/redirect/custom?'
+ 'code=303&url=/foobar/%0d%0aSet-Cookie:%20somecookie=someval')
self.assertStatus(303)
loc = self.assertHeader('Location')
assert 'Set-Cookie' in loc
@@ -415,137 +433,161 @@ class CoreRequestHandlingTest(helper.CPWebCase):
def assertValidXHTML():
from xml.etree import ElementTree
try:
- ElementTree.fromstring('<html><body>%s</body></html>' % self.body)
- except ElementTree.ParseError as e:
- self._handlewebError('automatically generated redirect '
- 'did not generate well-formed html')
+ ElementTree.fromstring(
+ '<html><body>%s</body></html>' % self.body,
+ )
+ except ElementTree.ParseError:
+ self._handlewebError(
+ 'automatically generated redirect did not '
+ 'generate well-formed html',
+ )
# check redirects to URLs generated valid HTML - we check this
# by seeing if it appears as valid XHTML.
- self.getPage("/redirect/by_code?code=303")
+ self.getPage('/redirect/by_code?code=303')
self.assertStatus(303)
assertValidXHTML()
# do the same with a url containing quote characters.
- self.getPage("/redirect/url_with_quote")
+ self.getPage('/redirect/url_with_quote')
self.assertStatus(303)
assertValidXHTML()
+ def test_redirect_with_xss(self):
+ """A redirect to a URL with HTML injected should result
+ in page contents escaped."""
+ self.getPage('/redirect/url_with_xss')
+ self.assertStatus(303)
+ assert b'<script>' not in self.body
+ assert b'&lt;script&gt;' in self.body
+
+ def test_redirect_with_unicode(self):
+ """
+ A redirect to a URL with Unicode should return a Location
+ header containing that Unicode URL.
+ """
+ # test disabled due to #1440
+ return
+ self.getPage('/redirect/url_with_unicode')
+ self.assertStatus(303)
+ loc = self.assertHeader('Location')
+ assert ntou('тест', encoding='utf-8') in loc
+
def test_InternalRedirect(self):
# InternalRedirect
- self.getPage("/internalredirect/")
+ self.getPage('/internalredirect/')
self.assertBody('hello')
self.assertStatus(200)
# Test passthrough
self.getPage(
- "/internalredirect/petshop?user_id=Sir-not-appearing-in-this-film")
+ '/internalredirect/petshop?user_id=Sir-not-appearing-in-this-film')
self.assertBody('0 images for Sir-not-appearing-in-this-film')
self.assertStatus(200)
# Test args
- self.getPage("/internalredirect/petshop?user_id=parrot")
+ self.getPage('/internalredirect/petshop?user_id=parrot')
self.assertBody('0 images for slug')
self.assertStatus(200)
# Test POST
- self.getPage("/internalredirect/petshop", method="POST",
- body="user_id=terrier")
+ self.getPage('/internalredirect/petshop', method='POST',
+ body='user_id=terrier')
self.assertBody('0 images for fish')
self.assertStatus(200)
# Test ir before body read
- self.getPage("/internalredirect/early_ir", method="POST",
- body="arg=aha!")
- self.assertBody("Something went horribly wrong.")
+ self.getPage('/internalredirect/early_ir', method='POST',
+ body='arg=aha!')
+ self.assertBody('Something went horribly wrong.')
self.assertStatus(200)
- self.getPage("/internalredirect/secure")
+ self.getPage('/internalredirect/secure')
self.assertBody('Please log in')
self.assertStatus(200)
# Relative path in InternalRedirect.
# Also tests request.prev.
- self.getPage("/internalredirect/relative?a=3&b=5")
- self.assertBody("a=3&b=5")
+ self.getPage('/internalredirect/relative?a=3&b=5')
+ self.assertBody('a=3&b=5')
self.assertStatus(200)
# InternalRedirect on error
- self.getPage("/internalredirect/choke")
+ self.getPage('/internalredirect/choke')
self.assertStatus(200)
- self.assertBody("Something went horribly wrong.")
+ self.assertBody('Something went horribly wrong.')
def testFlatten(self):
- for url in ["/flatten/as_string", "/flatten/as_list",
- "/flatten/as_yield", "/flatten/as_dblyield",
- "/flatten/as_refyield"]:
+ for url in ['/flatten/as_string', '/flatten/as_list',
+ '/flatten/as_yield', '/flatten/as_dblyield',
+ '/flatten/as_refyield']:
self.getPage(url)
self.assertBody('content')
def testRanges(self):
- self.getPage("/ranges/get_ranges?bytes=3-6")
- self.assertBody("[(3, 7)]")
+ self.getPage('/ranges/get_ranges?bytes=3-6')
+ self.assertBody('[(3, 7)]')
# Test multiple ranges and a suffix-byte-range-spec, for good measure.
- self.getPage("/ranges/get_ranges?bytes=2-4,-1")
- self.assertBody("[(2, 5), (7, 8)]")
+ self.getPage('/ranges/get_ranges?bytes=2-4,-1')
+ self.assertBody('[(2, 5), (7, 8)]')
# Test a suffix-byte-range longer than the content
# length. Note that in this test, the content length
# is 8 bytes.
- self.getPage("/ranges/get_ranges?bytes=-100")
- self.assertBody("[(0, 8)]")
+ self.getPage('/ranges/get_ranges?bytes=-100')
+ self.assertBody('[(0, 8)]')
# Get a partial file.
- if cherrypy.server.protocol_version == "HTTP/1.1":
- self.getPage("/ranges/slice_file", [('Range', 'bytes=2-5')])
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
+ self.getPage('/ranges/slice_file', [('Range', 'bytes=2-5')])
self.assertStatus(206)
- self.assertHeader("Content-Type", "text/html;charset=utf-8")
- self.assertHeader("Content-Range", "bytes 2-5/14")
- self.assertBody("llo,")
+ self.assertHeader('Content-Type', 'text/html;charset=utf-8')
+ self.assertHeader('Content-Range', 'bytes 2-5/14')
+ self.assertBody('llo,')
# What happens with overlapping ranges (and out of order, too)?
- self.getPage("/ranges/slice_file", [('Range', 'bytes=4-6,2-5')])
+ self.getPage('/ranges/slice_file', [('Range', 'bytes=4-6,2-5')])
self.assertStatus(206)
- ct = self.assertHeader("Content-Type")
- expected_type = "multipart/byteranges; boundary="
+ ct = self.assertHeader('Content-Type')
+ expected_type = 'multipart/byteranges; boundary='
self.assert_(ct.startswith(expected_type))
boundary = ct[len(expected_type):]
- expected_body = ("\r\n--%s\r\n"
- "Content-type: text/html\r\n"
- "Content-range: bytes 4-6/14\r\n"
- "\r\n"
- "o, \r\n"
- "--%s\r\n"
- "Content-type: text/html\r\n"
- "Content-range: bytes 2-5/14\r\n"
- "\r\n"
- "llo,\r\n"
- "--%s--\r\n" % (boundary, boundary, boundary))
+ expected_body = ('\r\n--%s\r\n'
+ 'Content-type: text/html\r\n'
+ 'Content-range: bytes 4-6/14\r\n'
+ '\r\n'
+ 'o, \r\n'
+ '--%s\r\n'
+ 'Content-type: text/html\r\n'
+ 'Content-range: bytes 2-5/14\r\n'
+ '\r\n'
+ 'llo,\r\n'
+ '--%s--\r\n' % (boundary, boundary, boundary))
self.assertBody(expected_body)
- self.assertHeader("Content-Length")
+ self.assertHeader('Content-Length')
# Test "416 Requested Range Not Satisfiable"
- self.getPage("/ranges/slice_file", [('Range', 'bytes=2300-2900')])
+ self.getPage('/ranges/slice_file', [('Range', 'bytes=2300-2900')])
self.assertStatus(416)
# "When this status code is returned for a byte-range request,
# the response SHOULD include a Content-Range entity-header
# field specifying the current length of the selected resource"
- self.assertHeader("Content-Range", "bytes */14")
- elif cherrypy.server.protocol_version == "HTTP/1.0":
+ self.assertHeader('Content-Range', 'bytes */14')
+ elif cherrypy.server.protocol_version == 'HTTP/1.0':
# Test Range behavior with HTTP/1.0 request
- self.getPage("/ranges/slice_file", [('Range', 'bytes=2-5')])
+ self.getPage('/ranges/slice_file', [('Range', 'bytes=2-5')])
self.assertStatus(200)
- self.assertBody("Hello, world\r\n")
+ self.assertBody('Hello, world\r\n')
def testFavicon(self):
# favicon.ico is served by staticfile.
- icofilename = os.path.join(localDir, "../favicon.ico")
- icofile = open(icofilename, "rb")
+ icofilename = os.path.join(localDir, '../favicon.ico')
+ icofile = open(icofilename, 'rb')
data = icofile.read()
icofile.close()
- self.getPage("/favicon.ico")
+ self.getPage('/favicon.ico')
self.assertBody(data)
def skip_if_bad_cookies(self):
@@ -558,23 +600,23 @@ class CoreRequestHandlingTest(helper.CPWebCase):
if not _is_legal_key(','):
return
issue = 'http://bugs.python.org/issue26302'
- tmpl = "Broken cookies module ({issue})"
+ tmpl = 'Broken cookies module ({issue})'
self.skip(tmpl.format(**locals()))
def testCookies(self):
self.skip_if_bad_cookies()
- self.getPage("/cookies/single?name=First",
+ self.getPage('/cookies/single?name=First',
[('Cookie', 'First=Dinsdale;')])
self.assertHeader('Set-Cookie', 'First=Dinsdale')
- self.getPage("/cookies/multiple?names=First&names=Last",
+ self.getPage('/cookies/multiple?names=First&names=Last',
[('Cookie', 'First=Dinsdale; Last=Piranha;'),
])
self.assertHeader('Set-Cookie', 'First=Dinsdale')
self.assertHeader('Set-Cookie', 'Last=Piranha')
- self.getPage("/cookies/single?name=Something-With%2CComma",
+ self.getPage('/cookies/single?name=Something-With%2CComma',
[('Cookie', 'Something-With,Comma=some-value')])
self.assertStatus(400)
@@ -621,6 +663,8 @@ class CoreRequestHandlingTest(helper.CPWebCase):
self.assertBody('%s/url/other/page1' % self.base())
self.getPage('/url/?path_info=/other/./page1')
self.assertBody('%s/other/page1' % self.base())
+ self.getPage('/url/?path_info=/other/././././page1')
+ self.assertBody('%s/other/page1' % self.base())
# Double dots
self.getPage('/url/leaf?path_info=../page1')
@@ -629,6 +673,20 @@ class CoreRequestHandlingTest(helper.CPWebCase):
self.assertBody('%s/url/page1' % self.base())
self.getPage('/url/leaf?path_info=/other/../page1')
self.assertBody('%s/page1' % self.base())
+ self.getPage('/url/leaf?path_info=/other/../../../page1')
+ self.assertBody('%s/page1' % self.base())
+ self.getPage('/url/leaf?path_info=/other/../../../../../page1')
+ self.assertBody('%s/page1' % self.base())
+
+ # qs param is not normalized as a path
+ self.getPage('/url/qs?qs=/other')
+ self.assertBody('%s/url/qs?/other' % self.base())
+ self.getPage('/url/qs?qs=/other/../page1')
+ self.assertBody('%s/url/qs?/other/../page1' % self.base())
+ self.getPage('/url/qs?qs=../page1')
+ self.assertBody('%s/url/qs?../page1' % self.base())
+ self.getPage('/url/qs?qs=../../page1')
+ self.assertBody('%s/url/qs?../../page1' % self.base())
# Output relative to current path or script_name
self.getPage('/url/?path_info=page1&relative=True')
@@ -665,44 +723,45 @@ class CoreRequestHandlingTest(helper.CPWebCase):
def test_expose_decorator(self):
# Test @expose
- self.getPage("/expose_dec/no_call")
+ self.getPage('/expose_dec/no_call')
self.assertStatus(200)
- self.assertBody("Mr E. R. Bradshaw")
+ self.assertBody('Mr E. R. Bradshaw')
# Test @expose()
- self.getPage("/expose_dec/call_empty")
+ self.getPage('/expose_dec/call_empty')
self.assertStatus(200)
- self.assertBody("Mrs. B.J. Smegma")
+ self.assertBody('Mrs. B.J. Smegma')
# Test @expose("alias")
- self.getPage("/expose_dec/call_alias")
+ self.getPage('/expose_dec/call_alias')
self.assertStatus(200)
- self.assertBody("Mr Nesbitt")
+ self.assertBody('Mr Nesbitt')
# Does the original name work?
- self.getPage("/expose_dec/nesbitt")
+ self.getPage('/expose_dec/nesbitt')
self.assertStatus(200)
- self.assertBody("Mr Nesbitt")
+ self.assertBody('Mr Nesbitt')
# Test @expose(["alias1", "alias2"])
- self.getPage("/expose_dec/alias1")
+ self.getPage('/expose_dec/alias1')
self.assertStatus(200)
- self.assertBody("Mr Ken Andrews")
- self.getPage("/expose_dec/alias2")
+ self.assertBody('Mr Ken Andrews')
+ self.getPage('/expose_dec/alias2')
self.assertStatus(200)
- self.assertBody("Mr Ken Andrews")
+ self.assertBody('Mr Ken Andrews')
# Does the original name work?
- self.getPage("/expose_dec/andrews")
+ self.getPage('/expose_dec/andrews')
self.assertStatus(200)
- self.assertBody("Mr Ken Andrews")
+ self.assertBody('Mr Ken Andrews')
# Test @expose(alias="alias")
- self.getPage("/expose_dec/alias3")
+ self.getPage('/expose_dec/alias3')
self.assertStatus(200)
- self.assertBody("Mr. and Mrs. Watson")
+ self.assertBody('Mr. and Mrs. Watson')
class ErrorTests(helper.CPWebCase):
+ @staticmethod
def setup_server():
def break_header():
# Add a header after finalize that is invalid
@@ -712,20 +771,53 @@ class ErrorTests(helper.CPWebCase):
class Root:
+ @cherrypy.expose
def index(self):
- return "hello"
- index.exposed = True
+ return 'hello'
+ @cherrypy.config(**{'tools.break_header.on': True})
def start_response_error(self):
- return "salud!"
- start_response_error._cp_config = {'tools.break_header.on': True}
+ return 'salud!'
+
+ @cherrypy.expose
+ def stat(self, path):
+ with cherrypy.HTTPError.handle(OSError, 404):
+ os.stat(path)
+
root = Root()
cherrypy.tree.mount(root)
- setup_server = staticmethod(setup_server)
def test_start_response_error(self):
- self.getPage("/start_response_error")
+ self.getPage('/start_response_error')
self.assertStatus(500)
self.assertInBody(
- "TypeError: response.header_list key 2 is not a byte string.")
+ 'TypeError: response.header_list key 2 is not a byte string.')
+
+ def test_contextmanager(self):
+ self.getPage('/stat/missing')
+ self.assertStatus(404)
+ body_text = self.body.decode('utf-8')
+ assert (
+ 'No such file or directory' in body_text or
+ 'cannot find the file specified' in body_text
+ )
+
+
+class TestBinding:
+ def test_bind_ephemeral_port(self):
+ """
+ A server configured to bind to port 0 will bind to an ephemeral
+ port and indicate that port number on startup.
+ """
+ cherrypy.config.reset()
+ bind_ephemeral_conf = {
+ 'server.socket_port': 0,
+ }
+ cherrypy.config.update(bind_ephemeral_conf)
+ cherrypy.engine.start()
+ assert cherrypy.server.bound_addr != cherrypy.server.bind_addr
+ _host, port = cherrypy.server.bound_addr
+ assert port > 0
+ cherrypy.engine.stop()
+ assert cherrypy.server.bind_addr == cherrypy.server.bound_addr
diff --git a/cherrypy/test/test_dynamicobjectmapping.py b/cherrypy/test/test_dynamicobjectmapping.py
index a64e9925..725a3ce0 100644
--- a/cherrypy/test/test_dynamicobjectmapping.py
+++ b/cherrypy/test/test_dynamicobjectmapping.py
@@ -1,29 +1,29 @@
+import six
+
import cherrypy
-from cherrypy._cpcompat import sorted, unicodestr
-from cherrypy._cptree import Application
from cherrypy.test import helper
-script_names = ["", "/foo", "/users/fred/blog", "/corp/blog"]
+script_names = ['', '/foo', '/users/fred/blog', '/corp/blog']
def setup_server():
class SubSubRoot:
+ @cherrypy.expose
def index(self):
- return "SubSubRoot index"
- index.exposed = True
+ return 'SubSubRoot index'
+ @cherrypy.expose
def default(self, *args):
- return "SubSubRoot default"
- default.exposed = True
+ return 'SubSubRoot default'
+ @cherrypy.expose
def handler(self):
- return "SubSubRoot handler"
- handler.exposed = True
+ return 'SubSubRoot handler'
+ @cherrypy.expose
def dispatch(self):
- return "SubSubRoot dispatch"
- dispatch.exposed = True
+ return 'SubSubRoot dispatch'
subsubnodes = {
'1': SubSubRoot(),
@@ -32,17 +32,17 @@ def setup_server():
class SubRoot:
+ @cherrypy.expose
def index(self):
- return "SubRoot index"
- index.exposed = True
+ return 'SubRoot index'
+ @cherrypy.expose
def default(self, *args):
- return "SubRoot %s" % (args,)
- default.exposed = True
+ return 'SubRoot %s' % (args,)
+ @cherrypy.expose
def handler(self):
- return "SubRoot handler"
- handler.exposed = True
+ return 'SubRoot handler'
def _cp_dispatch(self, vpath):
return subsubnodes.get(vpath[0], None)
@@ -54,22 +54,22 @@ def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "index"
- index.exposed = True
+ return 'index'
+ @cherrypy.expose
def default(self, *args):
- return "default %s" % (args,)
- default.exposed = True
+ return 'default %s' % (args,)
+ @cherrypy.expose
def handler(self):
- return "handler"
- handler.exposed = True
+ return 'handler'
def _cp_dispatch(self, vpath):
return subnodes.get(vpath[0])
- #--------------------------------------------------------------------------
+ # -------------------------------------------------------------------------
# DynamicNodeAndMethodDispatcher example.
# This example exposes a fairly naive HTTP api
class User(object):
@@ -79,7 +79,7 @@ def setup_server():
self.name = name
def __unicode__(self):
- return unicode(self.name)
+ return six.text_type(self.name)
def __str__(self):
return str(self.name)
@@ -95,17 +95,17 @@ def setup_server():
user_lookup[id] = User(id, name)
return id
+ @cherrypy.expose
class UserContainerNode(object):
- exposed = True
def POST(self, name):
"""
Allow the creation of a new Object
"""
- return "POST %d" % make_user(name)
+ return 'POST %d' % make_user(name)
def GET(self):
- return unicodestr(sorted(user_lookup.keys()))
+ return six.text_type(sorted(user_lookup.keys()))
def dynamic_dispatch(self, vpath):
try:
@@ -114,8 +114,8 @@ def setup_server():
return None
return UserInstanceNode(id)
+ @cherrypy.expose
class UserInstanceNode(object):
- exposed = True
def __init__(self, id):
self.id = id
@@ -130,14 +130,14 @@ def setup_server():
"""
Return the appropriate representation of the instance.
"""
- return unicodestr(self.user)
+ return six.text_type(self.user)
def POST(self, name):
"""
Update the fields of the user instance.
"""
self.user.name = name
- return "POST %d" % self.user.id
+ return 'POST %d' % self.user.id
def PUT(self, name):
"""
@@ -147,10 +147,10 @@ def setup_server():
if self.user:
# Edit the current user
self.user.name = name
- return "PUT %d" % self.user.id
+ return 'PUT %d' % self.user.id
else:
# Make a new user with said attributes.
- return "PUT %d" % make_user(name, self.id)
+ return 'PUT %d' % make_user(name, self.id)
def DELETE(self):
"""
@@ -159,15 +159,15 @@ def setup_server():
id = self.user.id
del user_lookup[self.user.id]
del self.user
- return "DELETE %d" % id
+ return 'DELETE %d' % id
class ABHandler:
class CustomDispatch:
+ @cherrypy.expose
def index(self, a, b):
- return "custom"
- index.exposed = True
+ return 'custom'
def _cp_dispatch(self, vpath):
"""Make sure that if we don't pop anything from vpath,
@@ -175,16 +175,16 @@ def setup_server():
"""
return self.CustomDispatch()
+ @cherrypy.expose
def index(self, a, b=None):
body = ['a:' + str(a)]
if b is not None:
body.append(',b:' + str(b))
return ''.join(body)
- index.exposed = True
+ @cherrypy.expose
def delete(self, a, b):
return 'deleting ' + str(a) + ' and ' + str(b)
- delete.exposed = True
class IndexOnly:
@@ -196,21 +196,21 @@ def setup_server():
vpath.pop()
return self
+ @cherrypy.expose
def index(self):
- return "IndexOnly index"
- index.exposed = True
+ return 'IndexOnly index'
class DecoratedPopArgs:
"""Test _cp_dispatch with @cherrypy.popargs."""
+ @cherrypy.expose
def index(self):
- return "no params"
- index.exposed = True
+ return 'no params'
+ @cherrypy.expose
def hi(self):
return "hi was not interpreted as 'a' param"
- hi.exposed = True
DecoratedPopArgs = cherrypy.popargs(
'a', 'b', handler=ABHandler())(DecoratedPopArgs)
@@ -220,9 +220,9 @@ def setup_server():
_cp_dispatch = cherrypy.popargs('a')
+ @cherrypy.expose
def index(self, a):
- return "index: " + str(a)
- index.exposed = True
+ return 'index: ' + str(a)
class ParameterizedHandler:
@@ -231,13 +231,13 @@ def setup_server():
def __init__(self, a):
self.a = a
+ @cherrypy.expose
def index(self):
if 'a' in cherrypy.request.params:
raise Exception(
- "Parameterized handler argument ended up in "
- "request.params")
+ 'Parameterized handler argument ended up in '
+ 'request.params')
return self.a
- index.exposed = True
class ParameterizedPopArgs:
@@ -254,9 +254,10 @@ def setup_server():
md = cherrypy.dispatch.MethodDispatcher('dynamic_dispatch')
for url in script_names:
- conf = {'/': {
- 'user': (url or "/").split("/")[-2],
- },
+ conf = {
+ '/': {
+ 'user': (url or '/').split('/')[-2],
+ },
'/users': {
'request.dispatch': md
},
@@ -269,7 +270,7 @@ class DynamicObjectMappingTest(helper.CPWebCase):
def testObjectMapping(self):
for url in script_names:
- prefix = self.script_name = url
+ self.script_name = url
self.getPage('/')
self.assertBody('index')
@@ -322,7 +323,7 @@ class DynamicObjectMappingTest(helper.CPWebCase):
# The exposed dispatch will not be called as a dispatch
# method.
self.getPage('/2/2/foo/foo')
- self.assertBody("SubSubRoot default")
+ self.assertBody('SubSubRoot default')
# Dynamic dispatch will fail here for the subsubnodes
# so the SubRoot gets called
@@ -337,28 +338,28 @@ class DynamicObjectMappingTest(helper.CPWebCase):
def testMethodDispatch(self):
# GET acts like a container
- self.getPage("/users")
- self.assertBody("[1, 2]")
+ self.getPage('/users')
+ self.assertBody('[1, 2]')
self.assertHeader('Allow', 'GET, HEAD, POST')
# POST to the container URI allows creation
- self.getPage("/users", method="POST", body="name=baz")
- self.assertBody("POST 3")
+ self.getPage('/users', method='POST', body='name=baz')
+ self.assertBody('POST 3')
self.assertHeader('Allow', 'GET, HEAD, POST')
# POST to a specific instanct URI results in a 404
# as the resource does not exit.
- self.getPage("/users/5", method="POST", body="name=baz")
+ self.getPage('/users/5', method='POST', body='name=baz')
self.assertStatus(404)
# PUT to a specific instanct URI results in creation
- self.getPage("/users/5", method="PUT", body="name=boris")
- self.assertBody("PUT 5")
+ self.getPage('/users/5', method='PUT', body='name=boris')
+ self.assertBody('PUT 5')
self.assertHeader('Allow', 'DELETE, GET, HEAD, POST, PUT')
# GET acts like a container
- self.getPage("/users")
- self.assertBody("[1, 2, 3, 5]")
+ self.getPage('/users')
+ self.assertBody('[1, 2, 3, 5]')
self.assertHeader('Allow', 'GET, HEAD, POST')
test_cases = (
@@ -368,56 +369,56 @@ class DynamicObjectMappingTest(helper.CPWebCase):
(5, 'boris', 'borisupdated', 'DELETE, GET, HEAD, POST, PUT'),
)
for id, name, updatedname, headers in test_cases:
- self.getPage("/users/%d" % id)
+ self.getPage('/users/%d' % id)
self.assertBody(name)
self.assertHeader('Allow', headers)
# Make sure POSTs update already existings resources
- self.getPage("/users/%d" %
- id, method='POST', body="name=%s" % updatedname)
- self.assertBody("POST %d" % id)
+ self.getPage('/users/%d' %
+ id, method='POST', body='name=%s' % updatedname)
+ self.assertBody('POST %d' % id)
self.assertHeader('Allow', headers)
# Make sure PUTs Update already existing resources.
- self.getPage("/users/%d" %
- id, method='PUT', body="name=%s" % updatedname)
- self.assertBody("PUT %d" % id)
+ self.getPage('/users/%d' %
+ id, method='PUT', body='name=%s' % updatedname)
+ self.assertBody('PUT %d' % id)
self.assertHeader('Allow', headers)
# Make sure DELETES Remove already existing resources.
- self.getPage("/users/%d" % id, method='DELETE')
- self.assertBody("DELETE %d" % id)
+ self.getPage('/users/%d' % id, method='DELETE')
+ self.assertBody('DELETE %d' % id)
self.assertHeader('Allow', headers)
# GET acts like a container
- self.getPage("/users")
- self.assertBody("[]")
+ self.getPage('/users')
+ self.assertBody('[]')
self.assertHeader('Allow', 'GET, HEAD, POST')
def testVpathDispatch(self):
- self.getPage("/decorated/")
- self.assertBody("no params")
+ self.getPage('/decorated/')
+ self.assertBody('no params')
- self.getPage("/decorated/hi")
+ self.getPage('/decorated/hi')
self.assertBody("hi was not interpreted as 'a' param")
- self.getPage("/decorated/yo/")
- self.assertBody("a:yo")
+ self.getPage('/decorated/yo/')
+ self.assertBody('a:yo')
- self.getPage("/decorated/yo/there/")
- self.assertBody("a:yo,b:there")
+ self.getPage('/decorated/yo/there/')
+ self.assertBody('a:yo,b:there')
- self.getPage("/decorated/yo/there/delete")
- self.assertBody("deleting yo and there")
+ self.getPage('/decorated/yo/there/delete')
+ self.assertBody('deleting yo and there')
- self.getPage("/decorated/yo/there/handled_by_dispatch/")
- self.assertBody("custom")
+ self.getPage('/decorated/yo/there/handled_by_dispatch/')
+ self.assertBody('custom')
- self.getPage("/undecorated/blah/")
- self.assertBody("index: blah")
+ self.getPage('/undecorated/blah/')
+ self.assertBody('index: blah')
- self.getPage("/index_only/a/b/c/d/e/f/g/")
- self.assertBody("IndexOnly index")
+ self.getPage('/index_only/a/b/c/d/e/f/g/')
+ self.assertBody('IndexOnly index')
- self.getPage("/parameter_test/argument2/")
- self.assertBody("argument2")
+ self.getPage('/parameter_test/argument2/')
+ self.assertBody('argument2')
diff --git a/cherrypy/test/test_encoding.py b/cherrypy/test/test_encoding.py
index c6b4eb46..62d7fb16 100644
--- a/cherrypy/test/test_encoding.py
+++ b/cherrypy/test/test_encoding.py
@@ -1,37 +1,47 @@
+# coding: utf-8
+
import gzip
+import io
+from unittest import mock
+
+from six.moves.http_client import IncompleteRead
+from six.moves.urllib.parse import quote as url_quote
import cherrypy
-from cherrypy._cpcompat import BytesIO, IncompleteRead, ntob, ntou
+from cherrypy._cpcompat import ntob, ntou
-europoundUnicode = ntou(r'\x00\xa3')
-sing = ntou("\u6bdb\u6cfd\u4e1c: Sing, Little Birdie?", 'escape')
-sing8 = sing.encode('utf-8')
-sing16 = sing.encode('utf-16')
+from cherrypy.test import helper
-from cherrypy.test import helper
+europoundUnicode = ntou('£', encoding='utf-8')
+sing = ntou('毛泽东: Sing, Little Birdie?', encoding='utf-8')
+
+sing8 = sing.encode('utf-8')
+sing16 = sing.encode('utf-16')
class EncodingTests(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self, param):
- assert param == europoundUnicode, "%r != %r" % (
+ assert param == europoundUnicode, '%r != %r' % (
param, europoundUnicode)
yield europoundUnicode
- index.exposed = True
+ @cherrypy.expose
def mao_zedong(self):
return sing
- mao_zedong.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.encode.encoding': 'utf-8'})
def utf8(self):
return sing8
- utf8.exposed = True
- utf8._cp_config = {'tools.encode.encoding': 'utf-8'}
+ @cherrypy.expose
def cookies_and_headers(self):
# if the headers have non-ascii characters and a cookie has
# any part which is unicode (even ascii), the response
@@ -41,185 +51,187 @@ class EncodingTests(helper.CPWebCase):
cherrypy.response.headers[
'Some-Header'] = 'My d\xc3\xb6g has fleas'
return 'Any content'
- cookies_and_headers.exposed = True
+ @cherrypy.expose
def reqparams(self, *args, **kwargs):
return ntob(', ').join(
- [": ".join((k, v)).encode('utf8')
+ [': '.join((k, v)).encode('utf8')
for k, v in sorted(cherrypy.request.params.items())]
)
- reqparams.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{
+ 'tools.encode.text_only': False,
+ 'tools.encode.add_charset': True,
+ })
def nontext(self, *args, **kwargs):
cherrypy.response.headers[
'Content-Type'] = 'application/binary'
return '\x00\x01\x02\x03'
- nontext.exposed = True
- nontext._cp_config = {'tools.encode.text_only': False,
- 'tools.encode.add_charset': True,
- }
class GZIP:
+ @cherrypy.expose
def index(self):
- yield "Hello, world"
- index.exposed = True
+ yield 'Hello, world'
+ @cherrypy.expose
+ # Turn encoding off so the gzip tool is the one doing the collapse.
+ @cherrypy.config(**{'tools.encode.on': False})
def noshow(self):
# Test for ticket #147, where yield showed no exceptions
# (content-encoding was still gzip even though traceback
# wasn't zipped).
raise IndexError()
- yield "Here be dragons"
- noshow.exposed = True
- # Turn encoding off so the gzip tool is the one doing the collapse.
- noshow._cp_config = {'tools.encode.on': False}
+ yield 'Here be dragons'
+ @cherrypy.expose
+ @cherrypy.config(**{'response.stream': True})
def noshow_stream(self):
# Test for ticket #147, where yield showed no exceptions
# (content-encoding was still gzip even though traceback
# wasn't zipped).
raise IndexError()
- yield "Here be dragons"
- noshow_stream.exposed = True
- noshow_stream._cp_config = {'response.stream': True}
+ yield 'Here be dragons'
class Decode:
- def extra_charset(self, *args, **kwargs):
- return ', '.join([": ".join((k, v))
- for k, v in cherrypy.request.params.items()])
- extra_charset.exposed = True
- extra_charset._cp_config = {
+ @cherrypy.expose
+ @cherrypy.config(**{
'tools.decode.on': True,
'tools.decode.default_encoding': ['utf-16'],
- }
-
- def force_charset(self, *args, **kwargs):
- return ', '.join([": ".join((k, v))
+ })
+ def extra_charset(self, *args, **kwargs):
+ return ', '.join([': '.join((k, v))
for k, v in cherrypy.request.params.items()])
- force_charset.exposed = True
- force_charset._cp_config = {
+
+ @cherrypy.expose
+ @cherrypy.config(**{
'tools.decode.on': True,
'tools.decode.encoding': 'utf-16',
- }
+ })
+ def force_charset(self, *args, **kwargs):
+ return ', '.join([': '.join((k, v))
+ for k, v in cherrypy.request.params.items()])
root = Root()
root.gzip = GZIP()
root.decode = Decode()
cherrypy.tree.mount(root, config={'/gzip': {'tools.gzip.on': True}})
- setup_server = staticmethod(setup_server)
def test_query_string_decoding(self):
- europoundUtf8 = europoundUnicode.encode('utf-8')
- self.getPage(ntob('/?param=') + europoundUtf8)
- self.assertBody(europoundUtf8)
+ URI_TMPL = '/reqparams?q={q}'
+
+ europoundUtf8_2_bytes = europoundUnicode.encode('utf-8')
+ europoundUtf8_2nd_byte = europoundUtf8_2_bytes[1:2]
# Encoded utf8 query strings MUST be parsed correctly.
# Here, q is the POUND SIGN U+00A3 encoded in utf8 and then %HEX
- self.getPage("/reqparams?q=%C2%A3")
+ self.getPage(URI_TMPL.format(q=url_quote(europoundUtf8_2_bytes)))
# The return value will be encoded as utf8.
- self.assertBody(ntob("q: \xc2\xa3"))
+ self.assertBody(ntob('q: ') + europoundUtf8_2_bytes)
# Query strings that are incorrectly encoded MUST raise 404.
- # Here, q is the POUND SIGN U+00A3 encoded in latin1 and then %HEX
- self.getPage("/reqparams?q=%A3")
+ # Here, q is the second byte of POUND SIGN U+A3 encoded in utf8
+ # and then %HEX
+ # TODO: check whether this shouldn't raise 400 Bad Request instead
+ self.getPage(URI_TMPL.format(q=url_quote(europoundUtf8_2nd_byte)))
self.assertStatus(404)
self.assertErrorPage(
404,
- "The given query string could not be processed. Query "
+ 'The given query string could not be processed. Query '
"strings for this resource must be encoded with 'utf8'.")
def test_urlencoded_decoding(self):
# Test the decoding of an application/x-www-form-urlencoded entity.
europoundUtf8 = europoundUnicode.encode('utf-8')
- body = ntob("param=") + europoundUtf8
+ body = ntob('param=') + europoundUtf8
self.getPage('/',
method='POST',
headers=[
- ("Content-Type", "application/x-www-form-urlencoded"),
- ("Content-Length", str(len(body))),
+ ('Content-Type', 'application/x-www-form-urlencoded'),
+ ('Content-Length', str(len(body))),
],
body=body),
self.assertBody(europoundUtf8)
# Encoded utf8 entities MUST be parsed and decoded correctly.
# Here, q is the POUND SIGN U+00A3 encoded in utf8
- body = ntob("q=\xc2\xa3")
+ body = ntob('q=\xc2\xa3')
self.getPage('/reqparams', method='POST',
headers=[(
- "Content-Type", "application/x-www-form-urlencoded"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'application/x-www-form-urlencoded'),
+ ('Content-Length', str(len(body))),
],
body=body),
- self.assertBody(ntob("q: \xc2\xa3"))
+ self.assertBody(ntob('q: \xc2\xa3'))
# ...and in utf16, which is not in the default attempt_charsets list:
- body = ntob("\xff\xfeq\x00=\xff\xfe\xa3\x00")
+ body = ntob('\xff\xfeq\x00=\xff\xfe\xa3\x00')
self.getPage('/reqparams',
method='POST',
headers=[
- ("Content-Type",
- "application/x-www-form-urlencoded;charset=utf-16"),
- ("Content-Length", str(len(body))),
+ ('Content-Type',
+ 'application/x-www-form-urlencoded;charset=utf-16'),
+ ('Content-Length', str(len(body))),
],
body=body),
- self.assertBody(ntob("q: \xc2\xa3"))
+ self.assertBody(ntob('q: \xc2\xa3'))
# Entities that are incorrectly encoded MUST raise 400.
# Here, q is the POUND SIGN U+00A3 encoded in utf16, but
# the Content-Type incorrectly labels it utf-8.
- body = ntob("\xff\xfeq\x00=\xff\xfe\xa3\x00")
+ body = ntob('\xff\xfeq\x00=\xff\xfe\xa3\x00')
self.getPage('/reqparams',
method='POST',
headers=[
- ("Content-Type",
- "application/x-www-form-urlencoded;charset=utf-8"),
- ("Content-Length", str(len(body))),
+ ('Content-Type',
+ 'application/x-www-form-urlencoded;charset=utf-8'),
+ ('Content-Length', str(len(body))),
],
body=body),
self.assertStatus(400)
self.assertErrorPage(
400,
- "The request entity could not be decoded. The following charsets "
+ 'The request entity could not be decoded. The following charsets '
"were attempted: ['utf-8']")
def test_decode_tool(self):
# An extra charset should be tried first, and succeed if it matches.
# Here, we add utf-16 as a charset and pass a utf-16 body.
- body = ntob("\xff\xfeq\x00=\xff\xfe\xa3\x00")
+ body = ntob('\xff\xfeq\x00=\xff\xfe\xa3\x00')
self.getPage('/decode/extra_charset', method='POST',
headers=[(
- "Content-Type", "application/x-www-form-urlencoded"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'application/x-www-form-urlencoded'),
+ ('Content-Length', str(len(body))),
],
body=body),
- self.assertBody(ntob("q: \xc2\xa3"))
+ self.assertBody(ntob('q: \xc2\xa3'))
# An extra charset should be tried first, and continue to other default
# charsets if it doesn't match.
# Here, we add utf-16 as a charset but still pass a utf-8 body.
- body = ntob("q=\xc2\xa3")
+ body = ntob('q=\xc2\xa3')
self.getPage('/decode/extra_charset', method='POST',
headers=[(
- "Content-Type", "application/x-www-form-urlencoded"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'application/x-www-form-urlencoded'),
+ ('Content-Length', str(len(body))),
],
body=body),
- self.assertBody(ntob("q: \xc2\xa3"))
+ self.assertBody(ntob('q: \xc2\xa3'))
# An extra charset should error if force is True and it doesn't match.
# Here, we force utf-16 as a charset but still pass a utf-8 body.
- body = ntob("q=\xc2\xa3")
+ body = ntob('q=\xc2\xa3')
self.getPage('/decode/force_charset', method='POST',
headers=[(
- "Content-Type", "application/x-www-form-urlencoded"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'application/x-www-form-urlencoded'),
+ ('Content-Length', str(len(body))),
],
body=body),
self.assertErrorPage(
400,
- "The request entity could not be decoded. The following charsets "
+ 'The request entity could not be decoded. The following charsets '
"were attempted: ['utf-16']")
def test_multipart_decoding(self):
@@ -240,11 +252,19 @@ class EncodingTests(helper.CPWebCase):
]))
self.getPage('/reqparams', method='POST',
headers=[(
- "Content-Type", "multipart/form-data;boundary=X"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'multipart/form-data;boundary=X'),
+ ('Content-Length', str(len(body))),
],
body=body),
- self.assertBody(ntob("submit: Create, text: ab\xe2\x80\x9cc"))
+ self.assertBody(ntob('submit: Create, text: ab\xe2\x80\x9cc'))
+
+ @mock.patch('cherrypy._cpreqbody.Part.maxrambytes', 1)
+ def test_multipart_decoding_bigger_maxrambytes(self):
+ """
+ Decoding of a multipart entity should also pass when
+ the entity is bigger than maxrambytes. See ticket #1352.
+ """
+ self.test_multipart_decoding()
def test_multipart_decoding_no_charset(self):
# Test the decoding of a multipart entity when the charset (utf8) is
@@ -262,11 +282,11 @@ class EncodingTests(helper.CPWebCase):
]))
self.getPage('/reqparams', method='POST',
headers=[(
- "Content-Type", "multipart/form-data;boundary=X"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'multipart/form-data;boundary=X'),
+ ('Content-Length', str(len(body))),
],
body=body),
- self.assertBody(ntob("submit: Create, text: \xe2\x80\x9c"))
+ self.assertBody(ntob('submit: Create, text: \xe2\x80\x9c'))
def test_multipart_decoding_no_successful_charset(self):
# Test the decoding of a multipart entity when the charset (utf16) is
@@ -284,14 +304,14 @@ class EncodingTests(helper.CPWebCase):
]))
self.getPage('/reqparams', method='POST',
headers=[(
- "Content-Type", "multipart/form-data;boundary=X"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'multipart/form-data;boundary=X'),
+ ('Content-Length', str(len(body))),
],
body=body),
self.assertStatus(400)
self.assertErrorPage(
400,
- "The request entity could not be decoded. The following charsets "
+ 'The request entity could not be decoded. The following charsets '
"were attempted: ['us-ascii', 'utf-8']")
def test_nontext(self):
@@ -321,66 +341,72 @@ class EncodingTests(helper.CPWebCase):
# Only allow iso-8859-1, which should fail and raise 406.
self.getPage('/mao_zedong', [('Accept-Charset', 'iso-8859-1, *;q=0')])
- self.assertStatus("406 Not Acceptable")
- self.assertInBody("Your client sent this Accept-Charset header: "
- "iso-8859-1, *;q=0. We tried these charsets: "
- "iso-8859-1.")
+ self.assertStatus('406 Not Acceptable')
+ self.assertInBody('Your client sent this Accept-Charset header: '
+ 'iso-8859-1, *;q=0. We tried these charsets: '
+ 'iso-8859-1.')
# Ask for x-mac-ce, which should be unknown. See ticket #569.
self.getPage('/mao_zedong', [('Accept-Charset',
'us-ascii, ISO-8859-1, x-mac-ce')])
- self.assertStatus("406 Not Acceptable")
- self.assertInBody("Your client sent this Accept-Charset header: "
- "us-ascii, ISO-8859-1, x-mac-ce. We tried these "
- "charsets: ISO-8859-1, us-ascii, x-mac-ce.")
+ self.assertStatus('406 Not Acceptable')
+ self.assertInBody('Your client sent this Accept-Charset header: '
+ 'us-ascii, ISO-8859-1, x-mac-ce. We tried these '
+ 'charsets: ISO-8859-1, us-ascii, x-mac-ce.')
# Test the 'encoding' arg to encode.
self.getPage('/utf8')
self.assertBody(sing8)
self.getPage('/utf8', [('Accept-Charset', 'us-ascii, ISO-8859-1')])
- self.assertStatus("406 Not Acceptable")
+ self.assertStatus('406 Not Acceptable')
def testGzip(self):
- zbuf = BytesIO()
+ zbuf = io.BytesIO()
zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)
- zfile.write(ntob("Hello, world"))
+ zfile.write(ntob('Hello, world'))
zfile.close()
- self.getPage('/gzip/', headers=[("Accept-Encoding", "gzip")])
+ self.getPage('/gzip/', headers=[('Accept-Encoding', 'gzip')])
self.assertInBody(zbuf.getvalue()[:3])
- self.assertHeader("Vary", "Accept-Encoding")
- self.assertHeader("Content-Encoding", "gzip")
+ self.assertHeader('Vary', 'Accept-Encoding')
+ self.assertHeader('Content-Encoding', 'gzip')
# Test when gzip is denied.
- self.getPage('/gzip/', headers=[("Accept-Encoding", "identity")])
- self.assertHeader("Vary", "Accept-Encoding")
- self.assertNoHeader("Content-Encoding")
- self.assertBody("Hello, world")
+ self.getPage('/gzip/', headers=[('Accept-Encoding', 'identity')])
+ self.assertHeader('Vary', 'Accept-Encoding')
+ self.assertNoHeader('Content-Encoding')
+ self.assertBody('Hello, world')
- self.getPage('/gzip/', headers=[("Accept-Encoding", "gzip;q=0")])
- self.assertHeader("Vary", "Accept-Encoding")
- self.assertNoHeader("Content-Encoding")
- self.assertBody("Hello, world")
+ self.getPage('/gzip/', headers=[('Accept-Encoding', 'gzip;q=0')])
+ self.assertHeader('Vary', 'Accept-Encoding')
+ self.assertNoHeader('Content-Encoding')
+ self.assertBody('Hello, world')
+
+ # Test that trailing comma doesn't cause IndexError
+ # Ref: https://github.com/cherrypy/cherrypy/issues/988
+ self.getPage('/gzip/', headers=[('Accept-Encoding', 'gzip,deflate,')])
+ self.assertStatus(200)
+ self.assertNotInBody('IndexError')
- self.getPage('/gzip/', headers=[("Accept-Encoding", "*;q=0")])
+ self.getPage('/gzip/', headers=[('Accept-Encoding', '*;q=0')])
self.assertStatus(406)
- self.assertNoHeader("Content-Encoding")
- self.assertErrorPage(406, "identity, gzip")
+ self.assertNoHeader('Content-Encoding')
+ self.assertErrorPage(406, 'identity, gzip')
# Test for ticket #147
- self.getPage('/gzip/noshow', headers=[("Accept-Encoding", "gzip")])
+ self.getPage('/gzip/noshow', headers=[('Accept-Encoding', 'gzip')])
self.assertNoHeader('Content-Encoding')
self.assertStatus(500)
- self.assertErrorPage(500, pattern="IndexError\n")
+ self.assertErrorPage(500, pattern='IndexError\n')
# In this case, there's nothing we can do to deliver a
# readable page, since 1) the gzip header is already set,
# and 2) we may have already written some of the body.
# The fix is to never stream yields when using gzip.
- if (cherrypy.server.protocol_version == "HTTP/1.0" or
- getattr(cherrypy.server, "using_apache", False)):
+ if (cherrypy.server.protocol_version == 'HTTP/1.0' or
+ getattr(cherrypy.server, 'using_apache', False)):
self.getPage('/gzip/noshow_stream',
- headers=[("Accept-Encoding", "gzip")])
+ headers=[('Accept-Encoding', 'gzip')])
self.assertHeader('Content-Encoding', 'gzip')
self.assertInBody('\x1f\x8b\x08\x00')
else:
@@ -388,7 +414,7 @@ class EncodingTests(helper.CPWebCase):
# will error due to an incomplete chunk-encoded stream.
self.assertRaises((ValueError, IncompleteRead), self.getPage,
'/gzip/noshow_stream',
- headers=[("Accept-Encoding", "gzip")])
+ headers=[('Accept-Encoding', 'gzip')])
def test_UnicodeHeaders(self):
self.getPage('/cookies_and_headers')
diff --git a/cherrypy/test/test_etags.py b/cherrypy/test/test_etags.py
index 4a263f36..293eb866 100644
--- a/cherrypy/test/test_etags.py
+++ b/cherrypy/test/test_etags.py
@@ -5,80 +5,80 @@ from cherrypy.test import helper
class ETagTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def resource(self):
- return "Oh wah ta goo Siam."
- resource.exposed = True
+ return 'Oh wah ta goo Siam.'
+ @cherrypy.expose
def fail(self, code):
code = int(code)
if 300 <= code <= 399:
raise cherrypy.HTTPRedirect([], code)
else:
raise cherrypy.HTTPError(code)
- fail.exposed = True
+ @cherrypy.expose
+ # In Python 3, tools.encode is on by default
+ @cherrypy.config(**{'tools.encode.on': True})
def unicoded(self):
return ntou('I am a \u1ee4nicode string.', 'escape')
- unicoded.exposed = True
- # In Python 3, tools.encode is on by default
- unicoded._cp_config = {'tools.encode.on': True}
conf = {'/': {'tools.etags.on': True,
'tools.etags.autotags': True,
}}
cherrypy.tree.mount(Root(), config=conf)
- setup_server = staticmethod(setup_server)
def test_etags(self):
- self.getPage("/resource")
+ self.getPage('/resource')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
self.assertBody('Oh wah ta goo Siam.')
etag = self.assertHeader('ETag')
# Test If-Match (both valid and invalid)
- self.getPage("/resource", headers=[('If-Match', etag)])
- self.assertStatus("200 OK")
- self.getPage("/resource", headers=[('If-Match', "*")])
- self.assertStatus("200 OK")
- self.getPage("/resource", headers=[('If-Match', "*")], method="POST")
- self.assertStatus("200 OK")
- self.getPage("/resource", headers=[('If-Match', "a bogus tag")])
- self.assertStatus("412 Precondition Failed")
+ self.getPage('/resource', headers=[('If-Match', etag)])
+ self.assertStatus('200 OK')
+ self.getPage('/resource', headers=[('If-Match', '*')])
+ self.assertStatus('200 OK')
+ self.getPage('/resource', headers=[('If-Match', '*')], method='POST')
+ self.assertStatus('200 OK')
+ self.getPage('/resource', headers=[('If-Match', 'a bogus tag')])
+ self.assertStatus('412 Precondition Failed')
# Test If-None-Match (both valid and invalid)
- self.getPage("/resource", headers=[('If-None-Match', etag)])
+ self.getPage('/resource', headers=[('If-None-Match', etag)])
self.assertStatus(304)
- self.getPage("/resource", method='POST',
+ self.getPage('/resource', method='POST',
headers=[('If-None-Match', etag)])
- self.assertStatus("412 Precondition Failed")
- self.getPage("/resource", headers=[('If-None-Match', "*")])
+ self.assertStatus('412 Precondition Failed')
+ self.getPage('/resource', headers=[('If-None-Match', '*')])
self.assertStatus(304)
- self.getPage("/resource", headers=[('If-None-Match', "a bogus tag")])
- self.assertStatus("200 OK")
+ self.getPage('/resource', headers=[('If-None-Match', 'a bogus tag')])
+ self.assertStatus('200 OK')
def test_errors(self):
- self.getPage("/resource")
+ self.getPage('/resource')
self.assertStatus(200)
etag = self.assertHeader('ETag')
# Test raising errors in page handler
- self.getPage("/fail/412", headers=[('If-Match', etag)])
+ self.getPage('/fail/412', headers=[('If-Match', etag)])
self.assertStatus(412)
- self.getPage("/fail/304", headers=[('If-Match', etag)])
+ self.getPage('/fail/304', headers=[('If-Match', etag)])
self.assertStatus(304)
- self.getPage("/fail/412", headers=[('If-None-Match', "*")])
+ self.getPage('/fail/412', headers=[('If-None-Match', '*')])
self.assertStatus(412)
- self.getPage("/fail/304", headers=[('If-None-Match', "*")])
+ self.getPage('/fail/304', headers=[('If-None-Match', '*')])
self.assertStatus(304)
def test_unicode_body(self):
- self.getPage("/unicoded")
+ self.getPage('/unicoded')
self.assertStatus(200)
etag1 = self.assertHeader('ETag')
- self.getPage("/unicoded", headers=[('If-Match', etag1)])
+ self.getPage('/unicoded', headers=[('If-Match', etag1)])
self.assertStatus(200)
self.assertHeader('ETag', etag1)
diff --git a/cherrypy/test/test_http.py b/cherrypy/test/test_http.py
index 46ae226c..1481492c 100644
--- a/cherrypy/test/test_http.py
+++ b/cherrypy/test/test_http.py
@@ -4,11 +4,16 @@ import errno
import mimetypes
import socket
import sys
+from unittest import mock
-from mock import patch
+import six
+from six.moves.http_client import HTTPConnection
+from six.moves import urllib
import cherrypy
-from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob, py3k
+from cherrypy._cpcompat import HTTPSConnection, ntob
+
+from cherrypy.test import helper
def encode_multipart_formdata(files):
@@ -33,29 +38,28 @@ def encode_multipart_formdata(files):
return content_type, body
-from cherrypy.test import helper
-
-
class HTTPTests(helper.CPWebCase):
def make_connection(self):
- if self.scheme == "https":
+ if self.scheme == 'https':
return HTTPSConnection('%s:%s' % (self.interface(), self.PORT))
else:
return HTTPConnection('%s:%s' % (self.interface(), self.PORT))
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self, *args, **kwargs):
- return "Hello world!"
- index.exposed = True
+ return 'Hello world!'
+ @cherrypy.expose
+ @cherrypy.config(**{'request.process_request_body': False})
def no_body(self, *args, **kwargs):
- return "Hello world!"
- no_body.exposed = True
- no_body._cp_config = {'request.process_request_body': False}
+ return 'Hello world!'
+ @cherrypy.expose
def post_multipart(self, file):
"""Return a summary ("a * 65536\nb * 65536") of the uploaded
file.
@@ -69,17 +73,16 @@ class HTTPTests(helper.CPWebCase):
count += 1
else:
if count:
- if py3k:
+ if six.PY3:
curchar = chr(curchar)
- summary.append("%s * %d" % (curchar, count))
+ summary.append('%s * %d' % (curchar, count))
count = 1
curchar = c
if count:
- if py3k:
+ if six.PY3:
curchar = chr(curchar)
- summary.append("%s * %d" % (curchar, count))
- return ", ".join(summary)
- post_multipart.exposed = True
+ summary.append('%s * %d' % (curchar, count))
+ return ', '.join(summary)
@cherrypy.expose
def post_filename(self, myfile):
@@ -88,7 +91,6 @@ class HTTPTests(helper.CPWebCase):
cherrypy.tree.mount(Root())
cherrypy.config.update({'server.max_request_body_size': 30000000})
- setup_server = staticmethod(setup_server)
def test_no_content_length(self):
# "The presence of a message-body in a request is signaled by the
@@ -99,7 +101,7 @@ class HTTPTests(helper.CPWebCase):
# the request is of method POST, this should be OK because we set
# request.process_request_body to False for our handler.
c = self.make_connection()
- c.request("POST", "/no_body")
+ c.request('POST', '/no_body')
response = c.getresponse()
self.body = response.fp.read()
self.status = str(response.status)
@@ -109,24 +111,30 @@ class HTTPTests(helper.CPWebCase):
# Now send a message that has no Content-Length, but does send a body.
# Verify that CP times out the socket and responds
# with 411 Length Required.
- if self.scheme == "https":
+ if self.scheme == 'https':
c = HTTPSConnection('%s:%s' % (self.interface(), self.PORT))
else:
c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
- if hasattr(c, '_set_content_length'): # python 2.6 doesn't have it
- with patch.object(c, '_set_content_length'):
- c.request("POST", "/")
- else:
- c.request("POST", "/")
+
+ # `_get_content_length` is needed for Python 3.6+
+ with mock.patch.object(
+ c,
+ '_get_content_length',
+ lambda body, method: None,
+ create=True):
+ # `_set_content_length` is needed for Python 2.7-3.5
+ with mock.patch.object(c, '_set_content_length', create=True):
+ c.request('POST', '/')
+
response = c.getresponse()
self.body = response.fp.read()
self.status = str(response.status)
self.assertStatus(411)
def test_post_multipart(self):
- alphabet = "abcdefghijklmnopqrstuvwxyz"
+ alphabet = 'abcdefghijklmnopqrstuvwxyz'
# generate file contents for a large post
- contents = "".join([c * 65536 for c in alphabet])
+ contents = ''.join([c * 65536 for c in alphabet])
# encode as multipart form data
files = [('file', 'file.txt', contents)]
@@ -145,14 +153,18 @@ class HTTPTests(helper.CPWebCase):
self.body = response.fp.read()
self.status = str(response.status)
self.assertStatus(200)
- self.assertBody(", ".join(["%s * 65536" % c for c in alphabet]))
-
- def test_post_filename_with_commas(self):
- '''Testing that we can handle filenames with commas. This was
- reported as a bug in:
- https://github.com/cherrypy/cherrypy/issues/1146/'''
+ parts = ['%s * 65536' % ch for ch in alphabet]
+ self.assertBody(', '.join(parts))
+
+ def test_post_filename_with_special_characters(self):
+ '''Testing that we can handle filenames with special characters. This
+ was reported as a bug in:
+ https://github.com/cherrypy/cherrypy/issues/1146/
+ https://github.com/cherrypy/cherrypy/issues/1397'''
# We'll upload a bunch of files with differing names.
- for fname in ['boop.csv', 'foo, bar.csv', 'bar, xxxx.csv', 'file"name.csv']:
+ fnames = ['boop.csv', 'foo, bar.csv', 'bar, xxxx.csv', 'file"name.csv',
+ 'file;name.csv', 'file; name.csv']
+ for fname in fnames:
files = [('myfile', fname, 'yunyeenyunyue')]
content_type, body = encode_multipart_formdata(files)
body = body.encode('Latin-1')
@@ -172,8 +184,8 @@ class HTTPTests(helper.CPWebCase):
self.assertBody(fname)
def test_malformed_request_line(self):
- if getattr(cherrypy.server, "using_apache", False):
- return self.skip("skipped due to known Apache differences...")
+ if getattr(cherrypy.server, 'using_apache', False):
+ return self.skip('skipped due to known Apache differences...')
# Test missing version in Request-Line
c = self.make_connection()
@@ -187,14 +199,22 @@ class HTTPTests(helper.CPWebCase):
response = c.response_class(c.sock, method='GET')
response.begin()
self.assertEqual(response.status, 400)
- self.assertEqual(response.fp.read(22), ntob("Malformed Request-Line"))
+ self.assertEqual(response.fp.read(22), ntob('Malformed Request-Line'))
c.close()
def test_request_line_split_issue_1220(self):
- Request_URI = "/index?intervenant-entreprise-evenement_classaction=evenement-mailremerciements&_path=intervenant-entreprise-evenement&intervenant-entreprise-evenement_action-id=19404&intervenant-entreprise-evenement_id=19404&intervenant-entreprise_id=28092"
- self.assertEqual(len("GET %s HTTP/1.1\r\n" % Request_URI), 256)
+ params = {
+ 'intervenant-entreprise-evenement_classaction':
+ 'evenement-mailremerciements',
+ '_path': 'intervenant-entreprise-evenement',
+ 'intervenant-entreprise-evenement_action-id': 19404,
+ 'intervenant-entreprise-evenement_id': 19404,
+ 'intervenant-entreprise_id': 28092,
+ }
+ Request_URI = '/index?' + urllib.parse.urlencode(params)
+ self.assertEqual(len('GET %s HTTP/1.1\r\n' % Request_URI), 256)
self.getPage(Request_URI)
- self.assertBody("Hello world!")
+ self.assertBody('Hello world!')
def test_malformed_header(self):
c = self.make_connection()
@@ -208,24 +228,24 @@ class HTTPTests(helper.CPWebCase):
self.status = str(response.status)
self.assertStatus(400)
self.body = response.fp.read(20)
- self.assertBody("Illegal header line.")
+ self.assertBody('Illegal header line.')
def test_http_over_https(self):
if self.scheme != 'https':
- return self.skip("skipped (not running HTTPS)... ")
+ return self.skip('skipped (not running HTTPS)... ')
# Try connecting without SSL.
conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
- conn.putrequest("GET", "/", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
try:
response.begin()
self.assertEqual(response.status, 400)
self.body = response.read()
- self.assertBody("The client sent a plain HTTP request, but this "
- "server only speaks HTTPS on this port.")
+ self.assertBody('The client sent a plain HTTP request, but this '
+ 'server only speaks HTTPS on this port.')
except socket.error:
e = sys.exc_info()[1]
# "Connection reset by peer" is also acceptable.
@@ -237,12 +257,12 @@ class HTTPTests(helper.CPWebCase):
c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
c._output(ntob('gjkgjklsgjklsgjkljklsg'))
c._send_output()
- response = c.response_class(c.sock, method="GET")
+ response = c.response_class(c.sock, method='GET')
try:
response.begin()
self.assertEqual(response.status, 400)
self.assertEqual(response.fp.read(22),
- ntob("Malformed Request-Line"))
+ ntob('Malformed Request-Line'))
c.close()
except socket.error:
e = sys.exc_info()[1]
diff --git a/cherrypy/test/test_httpauth.py b/cherrypy/test/test_httpauth.py
index 8be48b6b..3a5cff27 100644
--- a/cherrypy/test/test_httpauth.py
+++ b/cherrypy/test/test_httpauth.py
@@ -9,33 +9,34 @@ from cherrypy.test import helper
class HTTPAuthTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "This is public."
- index.exposed = True
+ return 'This is public.'
class DigestProtected:
+ @cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
- index.exposed = True
class BasicProtected:
+ @cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
- index.exposed = True
class BasicProtected2:
+ @cherrypy.expose
def index(self):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
- index.exposed = True
def fetch_users():
return {'test': 'test'}
@@ -72,16 +73,15 @@ class HTTPAuthTest(helper.CPWebCase):
root.basic = BasicProtected()
root.basic2 = BasicProtected2()
cherrypy.tree.mount(root, config=conf)
- setup_server = staticmethod(setup_server)
def testPublic(self):
- self.getPage("/")
+ self.getPage('/')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
self.assertBody('This is public.')
def testBasic(self):
- self.getPage("/basic/")
+ self.getPage('/basic/')
self.assertStatus(401)
self.assertHeader('WWW-Authenticate', 'Basic realm="localhost"')
@@ -93,7 +93,7 @@ class HTTPAuthTest(helper.CPWebCase):
self.assertBody("Hello test, you've been authorized.")
def testBasic2(self):
- self.getPage("/basic2/")
+ self.getPage('/basic2/')
self.assertStatus(401)
self.assertHeader('WWW-Authenticate', 'Basic realm="localhost"')
@@ -105,19 +105,19 @@ class HTTPAuthTest(helper.CPWebCase):
self.assertBody("Hello test, you've been authorized.")
def testDigest(self):
- self.getPage("/digest/")
+ self.getPage('/digest/')
self.assertStatus(401)
value = None
for k, v in self.headers:
- if k.lower() == "www-authenticate":
- if v.startswith("Digest"):
+ if k.lower() == 'www-authenticate':
+ if v.startswith('Digest'):
value = v
break
if value is None:
self._handlewebError(
- "Digest authentification scheme was not found")
+ 'Digest authentification scheme was not found')
value = value[7:]
items = value.split(', ')
@@ -126,7 +126,7 @@ class HTTPAuthTest(helper.CPWebCase):
key, value = item.split('=')
tokens[key.lower()] = value
- missing_msg = "%s is missing"
+ missing_msg = '%s is missing'
bad_value_msg = "'%s' was expecting '%s' but found '%s'"
nonce = None
if 'realm' not in tokens:
diff --git a/cherrypy/test/test_httplib.py b/cherrypy/test/test_httplib.py
deleted file mode 100644
index 76ca7641..00000000
--- a/cherrypy/test/test_httplib.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""Tests for cherrypy/lib/httputil.py."""
-
-import unittest
-from cherrypy.lib import httputil
-
-
-class UtilityTests(unittest.TestCase):
-
- def test_urljoin(self):
- # Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO
- self.assertEqual(httputil.urljoin("/sn/", "/pi/"), "/sn/pi/")
- self.assertEqual(httputil.urljoin("/sn/", "/pi"), "/sn/pi")
- self.assertEqual(httputil.urljoin("/sn/", "/"), "/sn/")
- self.assertEqual(httputil.urljoin("/sn/", ""), "/sn/")
- self.assertEqual(httputil.urljoin("/sn", "/pi/"), "/sn/pi/")
- self.assertEqual(httputil.urljoin("/sn", "/pi"), "/sn/pi")
- self.assertEqual(httputil.urljoin("/sn", "/"), "/sn/")
- self.assertEqual(httputil.urljoin("/sn", ""), "/sn")
- self.assertEqual(httputil.urljoin("/", "/pi/"), "/pi/")
- self.assertEqual(httputil.urljoin("/", "/pi"), "/pi")
- self.assertEqual(httputil.urljoin("/", "/"), "/")
- self.assertEqual(httputil.urljoin("/", ""), "/")
- self.assertEqual(httputil.urljoin("", "/pi/"), "/pi/")
- self.assertEqual(httputil.urljoin("", "/pi"), "/pi")
- self.assertEqual(httputil.urljoin("", "/"), "/")
- self.assertEqual(httputil.urljoin("", ""), "/")
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/cherrypy/test/test_httputil.py b/cherrypy/test/test_httputil.py
new file mode 100644
index 00000000..656b8a3d
--- /dev/null
+++ b/cherrypy/test/test_httputil.py
@@ -0,0 +1,80 @@
+"""Test helpers from ``cherrypy.lib.httputil`` module."""
+import pytest
+from six.moves import http_client
+
+from cherrypy.lib import httputil
+
+
+@pytest.mark.parametrize(
+ 'script_name,path_info,expected_url',
+ [
+ ('/sn/', '/pi/', '/sn/pi/'),
+ ('/sn/', '/pi', '/sn/pi'),
+ ('/sn/', '/', '/sn/'),
+ ('/sn/', '', '/sn/'),
+ ('/sn', '/pi/', '/sn/pi/'),
+ ('/sn', '/pi', '/sn/pi'),
+ ('/sn', '/', '/sn/'),
+ ('/sn', '', '/sn'),
+ ('/', '/pi/', '/pi/'),
+ ('/', '/pi', '/pi'),
+ ('/', '/', '/'),
+ ('/', '', '/'),
+ ('', '/pi/', '/pi/'),
+ ('', '/pi', '/pi'),
+ ('', '/', '/'),
+ ('', '', '/'),
+ ]
+)
+def test_urljoin(script_name, path_info, expected_url):
+ """Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO."""
+ actual_url = httputil.urljoin(script_name, path_info)
+ assert actual_url == expected_url
+
+
+EXPECTED_200 = (200, 'OK', 'Request fulfilled, document follows')
+EXPECTED_500 = (
+ 500,
+ 'Internal Server Error',
+ 'The server encountered an unexpected condition which '
+ 'prevented it from fulfilling the request.',
+)
+EXPECTED_404 = (404, 'Not Found', 'Nothing matches the given URI')
+EXPECTED_444 = (444, 'Non-existent reason', '')
+
+
+@pytest.mark.parametrize(
+ 'status,expected_status',
+ [
+ (None, EXPECTED_200),
+ (200, EXPECTED_200),
+ ('500', EXPECTED_500),
+ (http_client.NOT_FOUND, EXPECTED_404),
+ ('444 Non-existent reason', EXPECTED_444),
+ ]
+)
+def test_valid_status(status, expected_status):
+ """Check valid int, string and http_client-constants
+ statuses processing."""
+ assert httputil.valid_status(status) == expected_status
+
+
+@pytest.mark.parametrize(
+ 'status_code,error_msg',
+ [
+ ('hey', "Illegal response status from server ('hey' is non-numeric)."),
+ (
+ {'hey': 'hi'},
+ 'Illegal response status from server '
+ "({'hey': 'hi'} is non-numeric).",
+ ),
+ (1, 'Illegal response status from server (1 is out of range).'),
+ (600, 'Illegal response status from server (600 is out of range).'),
+ ]
+)
+def test_invalid_status(status_code, error_msg):
+ """Check that invalid status cause certain errors."""
+ with pytest.raises(ValueError) as excinfo:
+ httputil.valid_status(status_code)
+
+ assert error_msg in str(excinfo)
diff --git a/cherrypy/test/test_iterator.py b/cherrypy/test/test_iterator.py
index c09a7cf9..92f08e7c 100644
--- a/cherrypy/test/test_iterator.py
+++ b/cherrypy/test/test_iterator.py
@@ -1,5 +1,8 @@
+import six
+
import cherrypy
-from cherrypy._cpcompat import unicodestr
+from cherrypy.test import helper
+
class IteratorBase(object):
@@ -14,6 +17,7 @@ class IteratorBase(object):
def decr(cls):
cls.created -= 1
+
class OurGenerator(IteratorBase):
def __iter__(self):
@@ -24,6 +28,7 @@ class OurGenerator(IteratorBase):
finally:
self.decr()
+
class OurIterator(IteratorBase):
started = False
@@ -55,21 +60,24 @@ class OurIterator(IteratorBase):
def __del__(self):
self.decrement()
+
class OurClosableIterator(OurIterator):
def close(self):
self.decrement()
+
class OurNotClosableIterator(OurIterator):
# We can't close something which requires an additional argument.
def close(self, somearg):
self.decrement()
+
class OurUnclosableIterator(OurIterator):
- close = 'close' # not callable!
+ close = 'close' # not callable!
+
-from cherrypy.test import helper
class IteratorTest(helper.CPWebCase):
@staticmethod
@@ -80,7 +88,7 @@ class IteratorTest(helper.CPWebCase):
@cherrypy.expose
def count(self, clsname):
cherrypy.response.headers['Content-Type'] = 'text/plain'
- return unicodestr(globals()[clsname].created)
+ return six.text_type(globals()[clsname].created)
@cherrypy.expose
def getall(self, clsname):
@@ -88,17 +96,23 @@ class IteratorTest(helper.CPWebCase):
return globals()[clsname]()
@cherrypy.expose
+ @cherrypy.config(**{'response.stream': True})
def stream(self, clsname):
return self.getall(clsname)
- stream._cp_config = {'response.stream': True}
cherrypy.tree.mount(Root())
def test_iterator(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ try:
+ self._test_iterator()
+ except Exception:
+ 'Test fails intermittently. See #1419'
+
+ def _test_iterator(self):
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Check the counts of all the classes, they should be zero.
closables = ['OurClosableIterator', 'OurGenerator']
@@ -109,7 +123,7 @@ class IteratorTest(helper.CPWebCase):
random.shuffle(all_classes)
for clsname in all_classes:
- self.getPage("/count/" + clsname)
+ self.getPage('/count/' + clsname)
self.assertStatus(200)
self.assertBody('0')
@@ -118,14 +132,15 @@ class IteratorTest(helper.CPWebCase):
# check the header.
for clsname in all_classes:
itr_conn = self.get_conn()
- itr_conn.putrequest("GET", "/getall/" + clsname)
+ itr_conn.putrequest('GET', '/getall/' + clsname)
itr_conn.endheaders()
response = itr_conn.getresponse()
self.assertEqual(response.status, 200)
headers = response.getheaders()
for header_name, header_value in headers:
if header_name.lower() == 'content-length':
- assert header_value == unicodestr(1024 * 16 * 256), header_value
+ expected = six.text_type(1024 * 16 * 256)
+ assert header_value == expected, header_value
break
else:
raise AssertionError('No Content-Length header found')
@@ -133,7 +148,7 @@ class IteratorTest(helper.CPWebCase):
# As the response should be fully consumed by CherryPy
# before sending back, the count should still be at zero
# by the time the response has been sent.
- self.getPage("/count/" + clsname)
+ self.getPage('/count/' + clsname)
self.assertStatus(200)
self.assertBody('0')
@@ -142,20 +157,20 @@ class IteratorTest(helper.CPWebCase):
stream_counts = {}
for clsname in all_classes:
itr_conn = self.get_conn()
- itr_conn.putrequest("GET", "/stream/" + clsname)
+ itr_conn.putrequest('GET', '/stream/' + clsname)
itr_conn.endheaders()
response = itr_conn.getresponse()
self.assertEqual(response.status, 200)
response.fp.read(65536)
# Let's check the count - this should always be one.
- self.getPage("/count/" + clsname)
+ self.getPage('/count/' + clsname)
self.assertBody('1')
# Now if we close the connection, the count should go back
# to zero.
itr_conn.close()
- self.getPage("/count/" + clsname)
+ self.getPage('/count/' + clsname)
# If this is a response which should be easily closed, then
# we will test to see if the value has gone back down to
@@ -168,7 +183,7 @@ class IteratorTest(helper.CPWebCase):
if self.body != '0':
import time
time.sleep(0.1)
- self.getPage("/count/" + clsname)
+ self.getPage('/count/' + clsname)
stream_counts[clsname] = int(self.body)
diff --git a/cherrypy/test/test_json.py b/cherrypy/test/test_json.py
index 8776d998..1585f6e6 100644
--- a/cherrypy/test/test_json.py
+++ b/cherrypy/test/test_json.py
@@ -4,97 +4,99 @@ from cherrypy.test import helper
from cherrypy._cpcompat import json
+json_out = cherrypy.config(**{'tools.json_out.on': True})
+json_in = cherrypy.config(**{'tools.json_in.on': True})
+
+
class JsonTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root(object):
+ @cherrypy.expose
def plain(self):
return 'hello'
- plain.exposed = True
+ @cherrypy.expose
+ @json_out
def json_string(self):
return 'hello'
- json_string.exposed = True
- json_string._cp_config = {'tools.json_out.on': True}
+ @cherrypy.expose
+ @json_out
def json_list(self):
return ['a', 'b', 42]
- json_list.exposed = True
- json_list._cp_config = {'tools.json_out.on': True}
+ @cherrypy.expose
+ @json_out
def json_dict(self):
return {'answer': 42}
- json_dict.exposed = True
- json_dict._cp_config = {'tools.json_out.on': True}
+ @cherrypy.expose
+ @json_in
def json_post(self):
if cherrypy.request.json == [13, 'c']:
return 'ok'
else:
return 'nok'
- json_post.exposed = True
- json_post._cp_config = {'tools.json_in.on': True}
+ @cherrypy.expose
+ @json_out
+ @cherrypy.config(**{'tools.caching.on': True})
def json_cached(self):
return 'hello there'
- json_cached.exposed = True
- json_cached._cp_config = {
- 'tools.json_out.on': True,
- 'tools.caching.on': True,
- }
root = Root()
cherrypy.tree.mount(root)
- setup_server = staticmethod(setup_server)
def test_json_output(self):
if json is None:
- self.skip("json not found ")
+ self.skip('json not found ')
return
- self.getPage("/plain")
- self.assertBody("hello")
+ self.getPage('/plain')
+ self.assertBody('hello')
- self.getPage("/json_string")
+ self.getPage('/json_string')
self.assertBody('"hello"')
- self.getPage("/json_list")
+ self.getPage('/json_list')
self.assertBody('["a", "b", 42]')
- self.getPage("/json_dict")
+ self.getPage('/json_dict')
self.assertBody('{"answer": 42}')
def test_json_input(self):
if json is None:
- self.skip("json not found ")
+ self.skip('json not found ')
return
body = '[13, "c"]'
headers = [('Content-Type', 'application/json'),
('Content-Length', str(len(body)))]
- self.getPage("/json_post", method="POST", headers=headers, body=body)
+ self.getPage('/json_post', method='POST', headers=headers, body=body)
self.assertBody('ok')
body = '[13, "c"]'
headers = [('Content-Type', 'text/plain'),
('Content-Length', str(len(body)))]
- self.getPage("/json_post", method="POST", headers=headers, body=body)
+ self.getPage('/json_post', method='POST', headers=headers, body=body)
self.assertStatus(415, 'Expected an application/json content type')
body = '[13, -]'
headers = [('Content-Type', 'application/json'),
('Content-Length', str(len(body)))]
- self.getPage("/json_post", method="POST", headers=headers, body=body)
+ self.getPage('/json_post', method='POST', headers=headers, body=body)
self.assertStatus(400, 'Invalid JSON document')
def test_cached(self):
if json is None:
- self.skip("json not found ")
+ self.skip('json not found ')
return
- self.getPage("/json_cached")
+ self.getPage('/json_cached')
self.assertStatus(200, '"hello"')
- self.getPage("/json_cached") # 2'nd time to hit cache
+ self.getPage('/json_cached') # 2'nd time to hit cache
self.assertStatus(200, '"hello"')
diff --git a/cherrypy/test/test_logging.py b/cherrypy/test/test_logging.py
index 429b8f2f..4d686775 100644
--- a/cherrypy/test/test_logging.py
+++ b/cherrypy/test/test_logging.py
@@ -1,13 +1,17 @@
"""Basic tests for the CherryPy core: request handling."""
import os
-localDir = os.path.dirname(__file__)
+from unittest import mock
+
+import six
import cherrypy
-from cherrypy._cpcompat import ntob, ntou, py3k
+from cherrypy._cpcompat import ntob, ntou
+from cherrypy.test import helper, logtest
-access_log = os.path.join(localDir, "access.log")
-error_log = os.path.join(localDir, "error.log")
+localDir = os.path.dirname(__file__)
+access_log = os.path.join(localDir, 'access.log')
+error_log = os.path.join(localDir, 'error.log')
# Some unicode strings.
tartaros = ntou('\u03a4\u1f71\u03c1\u03c4\u03b1\u03c1\u03bf\u03c2', 'escape')
@@ -17,19 +21,20 @@ erebos = ntou('\u0388\u03c1\u03b5\u03b2\u03bf\u03c2.com', 'escape')
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "hello"
- index.exposed = True
+ return 'hello'
+ @cherrypy.expose
def uni_code(self):
cherrypy.request.login = tartaros
cherrypy.request.remote.name = erebos
- uni_code.exposed = True
+ @cherrypy.expose
def slashes(self):
cherrypy.request.request_line = r'GET /slashed\path HTTP/1.1'
- slashes.exposed = True
+ @cherrypy.expose
def whitespace(self):
# User-Agent = "User-Agent" ":" 1*( product | comment )
# comment = "(" *( ctext | quoted-pair | comment ) ")"
@@ -37,32 +42,29 @@ def setup_server():
# TEXT = <any OCTET except CTLs, but including LWS>
# LWS = [CRLF] 1*( SP | HT )
cherrypy.request.headers['User-Agent'] = 'Browzuh (1.0\r\n\t\t.3)'
- whitespace.exposed = True
+ @cherrypy.expose
def as_string(self):
- return "content"
- as_string.exposed = True
+ return 'content'
+ @cherrypy.expose
def as_yield(self):
- yield "content"
- as_yield.exposed = True
+ yield 'content'
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.log_tracebacks.on': True})
def error(self):
raise ValueError()
- error.exposed = True
- error._cp_config = {'tools.log_tracebacks.on': True}
root = Root()
- cherrypy.config.update({'log.error_file': error_log,
- 'log.access_file': access_log,
- })
+ cherrypy.config.update({
+ 'log.error_file': error_log,
+ 'log.access_file': access_log,
+ })
cherrypy.tree.mount(root)
-from cherrypy.test import helper, logtest
-
-
class AccessLogTests(helper.CPWebCase, logtest.LogCase):
setup_server = staticmethod(setup_server)
@@ -70,7 +72,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase):
def testNormalReturn(self):
self.markLog()
- self.getPage("/as_string",
+ self.getPage('/as_string',
headers=[('Referer', 'http://www.cherrypy.org/'),
('User-Agent', 'Mozilla/5.0')])
self.assertBody('content')
@@ -91,7 +93,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase):
def testNormalYield(self):
self.markLog()
- self.getPage("/as_yield")
+ self.getPage('/as_yield')
self.assertBody('content')
self.assertStatus(200)
@@ -105,33 +107,64 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase):
self.assertLog(-1, '] "GET %s/as_yield HTTP/1.1" 200 - "" ""'
% self.prefix())
+ @mock.patch(
+ 'cherrypy._cplogging.LogManager.access_log_format',
+ '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}" {o}'
+ if six.PY3 else
+ '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(o)s'
+ )
def testCustomLogFormat(self):
- '''Test a customized access_log_format string,
- which is a feature of _cplogging.LogManager.access() '''
-
- original_logformat = cherrypy._cplogging.LogManager.access_log_format
- cherrypy._cplogging.LogManager.access_log_format = \
- '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}" {o}' \
- if py3k else \
- '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(o)s'
-
+ """Test a customized access_log_format string, which is a
+ feature of _cplogging.LogManager.access()."""
self.markLog()
- self.getPage("/as_string", headers=[('Referer', 'REFERER'),
+ self.getPage('/as_string', headers=[('Referer', 'REFERER'),
('User-Agent', 'USERAGENT'),
('Host', 'HOST')])
self.assertLog(-1, '%s - - [' % self.interface())
self.assertLog(-1, '] "GET /as_string HTTP/1.1" '
'200 7 "REFERER" "USERAGENT" HOST')
- cherrypy._cplogging.LogManager.access_log_format = original_logformat
+ @mock.patch(
+ 'cherrypy._cplogging.LogManager.access_log_format',
+ '{h} {l} {u} {z} "{r}" {s} {b} "{f}" "{a}" {o}'
+ if six.PY3 else
+ '%(h)s %(l)s %(u)s %(z)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(o)s'
+ )
+ def testTimezLogFormat(self):
+ """Test a customized access_log_format string, which is a
+ feature of _cplogging.LogManager.access()."""
+ self.markLog()
+
+ expected_time = str(cherrypy._cplogging.LazyRfc3339UtcTime())
+ with mock.patch(
+ 'cherrypy._cplogging.LazyRfc3339UtcTime',
+ lambda: expected_time):
+ self.getPage('/as_string', headers=[('Referer', 'REFERER'),
+ ('User-Agent', 'USERAGENT'),
+ ('Host', 'HOST')])
+
+ self.assertLog(-1, '%s - - ' % self.interface())
+ self.assertLog(-1, expected_time)
+ self.assertLog(-1, ' "GET /as_string HTTP/1.1" '
+ '200 7 "REFERER" "USERAGENT" HOST')
+
+ @mock.patch(
+ 'cherrypy._cplogging.LogManager.access_log_format',
+ '{i}' if six.PY3 else '%(i)s'
+ )
+ def testUUIDv4ParameterLogFormat(self):
+ """Test rendering of UUID4 within access log."""
+ self.markLog()
+ self.getPage('/as_string')
+ self.assertValidUUIDv4()
def testEscapedOutput(self):
# Test unicode in access log pieces.
self.markLog()
- self.getPage("/uni_code")
+ self.getPage('/uni_code')
self.assertStatus(200)
- if py3k:
- # The repr of a bytestring in py3k includes a b'' prefix
+ if six.PY3:
+ # The repr of a bytestring in six.PY3 includes a b'' prefix
self.assertLog(-1, repr(tartaros.encode('utf8'))[2:-1])
else:
self.assertLog(-1, repr(tartaros.encode('utf8'))[1:-1])
@@ -141,16 +174,16 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase):
# Test backslashes in output.
self.markLog()
- self.getPage("/slashes")
+ self.getPage('/slashes')
self.assertStatus(200)
- if py3k:
+ if six.PY3:
self.assertLog(-1, ntob('"GET /slashed\\path HTTP/1.1"'))
else:
self.assertLog(-1, r'"GET /slashed\\path HTTP/1.1"')
# Test whitespace in output.
self.markLog()
- self.getPage("/whitespace")
+ self.getPage('/whitespace')
self.assertStatus(200)
# Again, note the 'r' prefix.
self.assertLog(-1, r'"Browzuh (1.0\r\n\t\t.3)"')
@@ -167,8 +200,8 @@ class ErrorLogTests(helper.CPWebCase, logtest.LogCase):
ignore = helper.webtest.ignored_exceptions
ignore.append(ValueError)
try:
- self.getPage("/error")
- self.assertInBody("raise ValueError()")
+ self.getPage('/error')
+ self.assertInBody('raise ValueError()')
self.assertLog(0, 'HTTP')
self.assertLog(1, 'Traceback (most recent call last):')
self.assertLog(-2, 'raise ValueError()')
diff --git a/cherrypy/test/test_mime.py b/cherrypy/test/test_mime.py
index ca2f9c63..6f5987c1 100644
--- a/cherrypy/test/test_mime.py
+++ b/cherrypy/test/test_mime.py
@@ -1,25 +1,26 @@
"""Tests for various MIME issues, including the safe_multipart Tool."""
import cherrypy
-from cherrypy._cpcompat import ntob, ntou, sorted
+from cherrypy._cpcompat import ntob, ntou
+from cherrypy.test import helper
def setup_server():
class Root:
+ @cherrypy.expose
def multipart(self, parts):
return repr(parts)
- multipart.exposed = True
+ @cherrypy.expose
def multipart_form_data(self, **kwargs):
return repr(list(sorted(kwargs.items())))
- multipart_form_data.exposed = True
+ @cherrypy.expose
def flashupload(self, Filedata, Upload, Filename):
- return ("Upload: %s, Filename: %s, Filedata: %r" %
+ return ('Upload: %s, Filename: %s, Filedata: %r' %
(Upload, Filename, Filedata.file.read()))
- flashupload.exposed = True
cherrypy.config.update({'server.max_request_body_size': 0})
cherrypy.tree.mount(Root())
@@ -27,14 +28,12 @@ def setup_server():
# Client-side code #
-from cherrypy.test import helper
-
class MultipartTest(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def test_multipart(self):
- text_part = ntou("This is the text version")
+ text_part = ntou('This is the text version')
html_part = ntou(
"""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
@@ -48,21 +47,21 @@ This is the <strong>HTML</strong> version
</html>
""")
body = '\r\n'.join([
- "--123456789",
+ '--123456789',
"Content-Type: text/plain; charset='ISO-8859-1'",
- "Content-Transfer-Encoding: 7bit",
- "",
+ 'Content-Transfer-Encoding: 7bit',
+ '',
text_part,
- "--123456789",
+ '--123456789',
"Content-Type: text/html; charset='ISO-8859-1'",
- "",
+ '',
html_part,
- "--123456789--"])
+ '--123456789--'])
headers = [
('Content-Type', 'multipart/mixed; boundary=123456789'),
('Content-Length', str(len(body))),
]
- self.getPage('/multipart', headers, "POST", body)
+ self.getPage('/multipart', headers, 'POST', body)
self.assertBody(repr([text_part, html_part]))
def test_multipart_form_data(self):
@@ -86,8 +85,8 @@ This is the <strong>HTML</strong> version
])
self.getPage('/multipart_form_data', method='POST',
headers=[(
- "Content-Type", "multipart/form-data;boundary=X"),
- ("Content-Length", str(len(body))),
+ 'Content-Type', 'multipart/form-data;boundary=X'),
+ ('Content-Length', str(len(body))),
],
body=body),
self.assertBody(
@@ -118,10 +117,10 @@ class SafeMultipartHandlingTest(helper.CPWebCase):
'.project\r\n'
'------------KM7Ij5cH2KM7Ef1gL6ae0ae0cH2gL6\r\n'
'Content-Disposition: form-data; '
- 'name="Filedata"; filename=".project"\r\n'
+ 'name="Filedata"; filename=".project"\r\n'
'Content-Type: application/octet-stream\r\n'
- '\r\n')
- + filedata +
+ '\r\n') +
+ filedata +
ntob('\r\n'
'------------KM7Ij5cH2KM7Ef1gL6ae0ae0cH2gL6\r\n'
'Content-Disposition: form-data; name="Upload"\r\n'
@@ -130,6 +129,6 @@ class SafeMultipartHandlingTest(helper.CPWebCase):
# Flash apps omit the trailing \r\n on the last line:
'------------KM7Ij5cH2KM7Ef1gL6ae0ae0cH2gL6--'
))
- self.getPage('/flashupload', headers, "POST", body)
- self.assertBody("Upload: Submit Query, Filename: .project, "
- "Filedata: %r" % filedata)
+ self.getPage('/flashupload', headers, 'POST', body)
+ self.assertBody('Upload: Submit Query, Filename: .project, '
+ 'Filedata: %r' % filedata)
diff --git a/cherrypy/test/test_misc_tools.py b/cherrypy/test/test_misc_tools.py
index df3e2e65..fb85b8f8 100644
--- a/cherrypy/test/test_misc_tools.py
+++ b/cherrypy/test/test_misc_tools.py
@@ -1,83 +1,81 @@
import os
-localDir = os.path.dirname(__file__)
-logfile = os.path.join(localDir, "test_misc_tools.log")
import cherrypy
from cherrypy import tools
+from cherrypy.test import helper
+
+
+localDir = os.path.dirname(__file__)
+logfile = os.path.join(localDir, 'test_misc_tools.log')
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- yield "Hello, world"
- index.exposed = True
- h = [("Content-Language", "en-GB"), ('Content-Type', 'text/plain')]
+ yield 'Hello, world'
+ h = [('Content-Language', 'en-GB'), ('Content-Type', 'text/plain')]
tools.response_headers(headers=h)(index)
- def other(self):
- return "salut"
- other.exposed = True
- other._cp_config = {
+ @cherrypy.expose
+ @cherrypy.config(**{
'tools.response_headers.on': True,
- 'tools.response_headers.headers': [("Content-Language", "fr"),
- ('Content-Type', 'text/plain')],
+ 'tools.response_headers.headers': [
+ ('Content-Language', 'fr'),
+ ('Content-Type', 'text/plain'),
+ ],
'tools.log_hooks.on': True,
- }
+ })
+ def other(self):
+ return 'salut'
+ @cherrypy.config(**{'tools.accept.on': True})
class Accept:
- _cp_config = {'tools.accept.on': True}
+ @cherrypy.expose
def index(self):
return '<a href="feed">Atom feed</a>'
- index.exposed = True
- # In Python 2.4+, we could use a decorator instead:
- # @tools.accept('application/atom+xml')
+ @cherrypy.expose
+ @tools.accept(media='application/atom+xml')
def feed(self):
return """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Unknown Blog</title>
</feed>"""
- feed.exposed = True
- feed._cp_config = {'tools.accept.media': 'application/atom+xml'}
+ @cherrypy.expose
def select(self):
# We could also write this: mtype = cherrypy.lib.accept.accept(...)
mtype = tools.accept.callable(['text/html', 'text/plain'])
if mtype == 'text/html':
- return "<h2>Page Title</h2>"
+ return '<h2>Page Title</h2>'
else:
- return "PAGE TITLE"
- select.exposed = True
+ return 'PAGE TITLE'
class Referer:
+ @cherrypy.expose
def accept(self):
- return "Accepted!"
- accept.exposed = True
+ return 'Accepted!'
reject = accept
class AutoVary:
+ @cherrypy.expose
def index(self):
# Read a header directly with 'get'
- ae = cherrypy.request.headers.get('Accept-Encoding')
+ cherrypy.request.headers.get('Accept-Encoding')
# Read a header directly with '__getitem__'
- cl = cherrypy.request.headers['Host']
+ cherrypy.request.headers['Host']
# Read a header directly with '__contains__'
- hasif = 'If-Modified-Since' in cherrypy.request.headers
- # Read a header directly with 'has_key'
- if hasattr(dict, 'has_key'):
- # Python 2
- has = cherrypy.request.headers.has_key('Range')
- else:
- # Python 3
- has = 'Range' in cherrypy.request.headers
+ 'If-Modified-Since' in cherrypy.request.headers
+ # Read a header directly
+ 'Range' in cherrypy.request.headers
# Call a lib function
- mtype = tools.accept.callable(['text/html', 'text/plain'])
- return "Hello, world!"
- index.exposed = True
+ tools.accept.callable(['text/html', 'text/plain'])
+ return 'Hello, world!'
conf = {'/referer': {'tools.referer.on': True,
'tools.referer.pattern': r'http://[^/]*example\.com',
@@ -96,20 +94,17 @@ def setup_server():
cherrypy.config.update({'log.error_file': logfile})
-from cherrypy.test import helper
-
-
class ResponseHeadersTest(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def testResponseHeadersDecorator(self):
self.getPage('/')
- self.assertHeader("Content-Language", "en-GB")
+ self.assertHeader('Content-Language', 'en-GB')
self.assertHeader('Content-Type', 'text/plain;charset=utf-8')
def testResponseHeaders(self):
self.getPage('/other')
- self.assertHeader("Content-Language", "fr")
+ self.assertHeader('Content-Language', 'fr')
self.assertHeader('Content-Type', 'text/plain;charset=utf-8')
@@ -163,9 +158,9 @@ class AcceptTest(helper.CPWebCase):
# Specify unacceptable media types
self.getPage('/accept/feed', headers=[('Accept', 'text/html')])
self.assertErrorPage(406,
- "Your client sent this Accept header: text/html. "
- "But this resource only emits these media types: "
- "application/atom+xml.")
+ 'Your client sent this Accept header: text/html. '
+ 'But this resource only emits these media types: '
+ 'application/atom+xml.')
# Test resource where tool is 'on' but media is None (not set).
self.getPage('/accept/')
@@ -198,9 +193,9 @@ class AcceptTest(helper.CPWebCase):
self.getPage('/accept/select', [('Accept', 'application/xml')])
self.assertErrorPage(
406,
- "Your client sent this Accept header: application/xml. "
- "But this resource only emits these media types: "
- "text/html, text/plain.")
+ 'Your client sent this Accept header: application/xml. '
+ 'But this resource only emits these media types: '
+ 'text/html, text/plain.')
class AutoVaryTest(helper.CPWebCase):
@@ -209,7 +204,7 @@ class AutoVaryTest(helper.CPWebCase):
def testAutoVary(self):
self.getPage('/autovary/')
self.assertHeader(
- "Vary",
+ 'Vary',
'Accept, Accept-Charset, Accept-Encoding, '
'Host, If-Modified-Since, Range'
)
diff --git a/cherrypy/test/test_objectmapping.py b/cherrypy/test/test_objectmapping.py
index a24e84e1..98402b8b 100644
--- a/cherrypy/test/test_objectmapping.py
+++ b/cherrypy/test/test_objectmapping.py
@@ -4,127 +4,128 @@ from cherrypy._cpcompat import ntou
from cherrypy._cptree import Application
from cherrypy.test import helper
-script_names = ["", "/foo", "/users/fred/blog", "/corp/blog"]
+script_names = ['', '/foo', '/users/fred/blog', '/corp/blog']
class ObjectMappingTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
- def index(self, name="world"):
+ @cherrypy.expose
+ def index(self, name='world'):
return name
- index.exposed = True
+ @cherrypy.expose
def foobar(self):
- return "bar"
- foobar.exposed = True
+ return 'bar'
+ @cherrypy.expose
def default(self, *params, **kwargs):
- return "default:" + repr(params)
- default.exposed = True
+ return 'default:' + repr(params)
+ @cherrypy.expose
def other(self):
- return "other"
- other.exposed = True
+ return 'other'
+ @cherrypy.expose
def extra(self, *p):
return repr(p)
- extra.exposed = True
+ @cherrypy.expose
def redirect(self):
raise cherrypy.HTTPRedirect('dir1/', 302)
- redirect.exposed = True
def notExposed(self):
- return "not exposed"
+ return 'not exposed'
+ @cherrypy.expose
def confvalue(self):
- return cherrypy.request.config.get("user")
- confvalue.exposed = True
+ return cherrypy.request.config.get('user')
+ @cherrypy.expose
def redirect_via_url(self, path):
raise cherrypy.HTTPRedirect(cherrypy.url(path))
- redirect_via_url.exposed = True
+ @cherrypy.expose
def translate_html(self):
- return "OK"
- translate_html.exposed = True
+ return 'OK'
+ @cherrypy.expose
def mapped_func(self, ID=None):
- return "ID is %s" % ID
- mapped_func.exposed = True
- setattr(Root, "Von B\xfclow", mapped_func)
+ return 'ID is %s' % ID
+ setattr(Root, 'Von B\xfclow', mapped_func)
class Exposing:
+ @cherrypy.expose
def base(self):
- return "expose works!"
- cherrypy.expose(base)
- cherrypy.expose(base, "1")
- cherrypy.expose(base, "2")
+ return 'expose works!'
+ cherrypy.expose(base, '1')
+ cherrypy.expose(base, '2')
class ExposingNewStyle(object):
+ @cherrypy.expose
def base(self):
- return "expose works!"
- cherrypy.expose(base)
- cherrypy.expose(base, "1")
- cherrypy.expose(base, "2")
+ return 'expose works!'
+ cherrypy.expose(base, '1')
+ cherrypy.expose(base, '2')
class Dir1:
+ @cherrypy.expose
def index(self):
- return "index for dir1"
- index.exposed = True
+ return 'index for dir1'
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.trailing_slash.extra': True})
def myMethod(self):
- return "myMethod from dir1, path_info is:" + repr(
+ return 'myMethod from dir1, path_info is:' + repr(
cherrypy.request.path_info)
- myMethod.exposed = True
- myMethod._cp_config = {'tools.trailing_slash.extra': True}
+ @cherrypy.expose
def default(self, *params):
- return "default for dir1, param is:" + repr(params)
- default.exposed = True
+ return 'default for dir1, param is:' + repr(params)
class Dir2:
+ @cherrypy.expose
def index(self):
- return "index for dir2, path is:" + cherrypy.request.path_info
- index.exposed = True
+ return 'index for dir2, path is:' + cherrypy.request.path_info
+ @cherrypy.expose
def script_name(self):
return cherrypy.tree.script_name()
- script_name.exposed = True
+ @cherrypy.expose
def cherrypy_url(self):
- return cherrypy.url("/extra")
- cherrypy_url.exposed = True
+ return cherrypy.url('/extra')
+ @cherrypy.expose
def posparam(self, *vpath):
- return "/".join(vpath)
- posparam.exposed = True
+ return '/'.join(vpath)
class Dir3:
def default(self):
- return "default for dir3, not exposed"
+ return 'default for dir3, not exposed'
class Dir4:
def index(self):
- return "index for dir4, not exposed"
+ return 'index for dir4, not exposed'
class DefNoIndex:
+ @cherrypy.expose
def default(self, *args):
- raise cherrypy.HTTPRedirect("contact")
- default.exposed = True
+ raise cherrypy.HTTPRedirect('contact')
# MethodDispatcher code
+ @cherrypy.expose
class ByMethod:
- exposed = True
def __init__(self, *things):
self.things = list(things)
@@ -150,7 +151,7 @@ class ObjectMappingTest(helper.CPWebCase):
d = cherrypy.dispatch.MethodDispatcher()
for url in script_names:
- conf = {'/': {'user': (url or "/").split("/")[-2]},
+ conf = {'/': {'user': (url or '/').split('/')[-2]},
'/bymethod': {'request.dispatch': d},
'/collection': {'request.dispatch': d},
}
@@ -158,106 +159,104 @@ class ObjectMappingTest(helper.CPWebCase):
class Isolated:
+ @cherrypy.expose
def index(self):
- return "made it!"
- index.exposed = True
+ return 'made it!'
- cherrypy.tree.mount(Isolated(), "/isolated")
+ cherrypy.tree.mount(Isolated(), '/isolated')
+ @cherrypy.expose
class AnotherApp:
- exposed = True
-
def GET(self):
- return "milk"
+ return 'milk'
- cherrypy.tree.mount(AnotherApp(), "/app",
+ cherrypy.tree.mount(AnotherApp(), '/app',
{'/': {'request.dispatch': d}})
- setup_server = staticmethod(setup_server)
def testObjectMapping(self):
for url in script_names:
- prefix = self.script_name = url
+ self.script_name = url
self.getPage('/')
self.assertBody('world')
- self.getPage("/dir1/myMethod")
+ self.getPage('/dir1/myMethod')
self.assertBody(
"myMethod from dir1, path_info is:'/dir1/myMethod'")
- self.getPage("/this/method/does/not/exist")
+ self.getPage('/this/method/does/not/exist')
self.assertBody(
"default:('this', 'method', 'does', 'not', 'exist')")
- self.getPage("/extra/too/much")
+ self.getPage('/extra/too/much')
self.assertBody("('too', 'much')")
- self.getPage("/other")
+ self.getPage('/other')
self.assertBody('other')
- self.getPage("/notExposed")
+ self.getPage('/notExposed')
self.assertBody("default:('notExposed',)")
- self.getPage("/dir1/dir2/")
+ self.getPage('/dir1/dir2/')
self.assertBody('index for dir2, path is:/dir1/dir2/')
# Test omitted trailing slash (should be redirected by default).
- self.getPage("/dir1/dir2")
+ self.getPage('/dir1/dir2')
self.assertStatus(301)
self.assertHeader('Location', '%s/dir1/dir2/' % self.base())
# Test extra trailing slash (should be redirected if configured).
- self.getPage("/dir1/myMethod/")
+ self.getPage('/dir1/myMethod/')
self.assertStatus(301)
self.assertHeader('Location', '%s/dir1/myMethod' % self.base())
# Test that default method must be exposed in order to match.
- self.getPage("/dir1/dir2/dir3/dir4/index")
+ self.getPage('/dir1/dir2/dir3/dir4/index')
self.assertBody(
"default for dir1, param is:('dir2', 'dir3', 'dir4', 'index')")
# Test *vpath when default() is defined but not index()
# This also tests HTTPRedirect with default.
- self.getPage("/defnoindex")
+ self.getPage('/defnoindex')
self.assertStatus((302, 303))
self.assertHeader('Location', '%s/contact' % self.base())
- self.getPage("/defnoindex/")
+ self.getPage('/defnoindex/')
self.assertStatus((302, 303))
self.assertHeader('Location', '%s/defnoindex/contact' %
self.base())
- self.getPage("/defnoindex/page")
+ self.getPage('/defnoindex/page')
self.assertStatus((302, 303))
self.assertHeader('Location', '%s/defnoindex/contact' %
self.base())
- self.getPage("/redirect")
+ self.getPage('/redirect')
self.assertStatus('302 Found')
self.assertHeader('Location', '%s/dir1/' % self.base())
- if not getattr(cherrypy.server, "using_apache", False):
+ if not getattr(cherrypy.server, 'using_apache', False):
# Test that we can use URL's which aren't all valid Python
# identifiers
# This should also test the %XX-unquoting of URL's.
- self.getPage("/Von%20B%fclow?ID=14")
- self.assertBody("ID is 14")
+ self.getPage('/Von%20B%fclow?ID=14')
+ self.assertBody('ID is 14')
# Test that %2F in the path doesn't get unquoted too early;
# that is, it should not be used to separate path components.
# See ticket #393.
- self.getPage("/page%2Fname")
+ self.getPage('/page%2Fname')
self.assertBody("default:('page/name',)")
- self.getPage("/dir1/dir2/script_name")
+ self.getPage('/dir1/dir2/script_name')
self.assertBody(url)
- self.getPage("/dir1/dir2/cherrypy_url")
- self.assertBody("%s/extra" % self.base())
+ self.getPage('/dir1/dir2/cherrypy_url')
+ self.assertBody('%s/extra' % self.base())
- # Test that configs don't overwrite each other from diferent apps
- self.getPage("/confvalue")
- self.assertBody((url or "/").split("/")[-2])
+ # Test that configs don't overwrite each other from different apps
+ self.getPage('/confvalue')
+ self.assertBody((url or '/').split('/')[-2])
- self.script_name = ""
+ self.script_name = ''
# Test absoluteURI's in the Request-Line
self.getPage('http://%s:%s/' % (self.interface(), self.PORT))
@@ -273,34 +272,34 @@ class ObjectMappingTest(helper.CPWebCase):
# Test that the "isolated" app doesn't leak url's into the root app.
# If it did leak, Root.default() would answer with
# "default:('isolated', 'doesnt', 'exist')".
- self.getPage("/isolated/")
- self.assertStatus("200 OK")
- self.assertBody("made it!")
- self.getPage("/isolated/doesnt/exist")
- self.assertStatus("404 Not Found")
+ self.getPage('/isolated/')
+ self.assertStatus('200 OK')
+ self.assertBody('made it!')
+ self.getPage('/isolated/doesnt/exist')
+ self.assertStatus('404 Not Found')
# Make sure /foobar maps to Root.foobar and not to the app
# mounted at /foo. See
# https://github.com/cherrypy/cherrypy/issues/573
- self.getPage("/foobar")
- self.assertBody("bar")
+ self.getPage('/foobar')
+ self.assertBody('bar')
def test_translate(self):
- self.getPage("/translate_html")
- self.assertStatus("200 OK")
- self.assertBody("OK")
+ self.getPage('/translate_html')
+ self.assertStatus('200 OK')
+ self.assertBody('OK')
- self.getPage("/translate.html")
- self.assertStatus("200 OK")
- self.assertBody("OK")
+ self.getPage('/translate.html')
+ self.assertStatus('200 OK')
+ self.assertBody('OK')
- self.getPage("/translate-html")
- self.assertStatus("200 OK")
- self.assertBody("OK")
+ self.getPage('/translate-html')
+ self.assertStatus('200 OK')
+ self.assertBody('OK')
def test_redir_using_url(self):
for url in script_names:
- prefix = self.script_name = url
+ self.script_name = url
# Test the absolute path to the parent (leading slash)
self.getPage('/redirect_via_url?path=./')
@@ -323,75 +322,75 @@ class ObjectMappingTest(helper.CPWebCase):
self.assertHeader('Location', '%s/' % self.base())
def testPositionalParams(self):
- self.getPage("/dir1/dir2/posparam/18/24/hut/hike")
- self.assertBody("18/24/hut/hike")
+ self.getPage('/dir1/dir2/posparam/18/24/hut/hike')
+ self.assertBody('18/24/hut/hike')
# intermediate index methods should not receive posparams;
# only the "final" index method should do so.
- self.getPage("/dir1/dir2/5/3/sir")
+ self.getPage('/dir1/dir2/5/3/sir')
self.assertBody("default for dir1, param is:('dir2', '5', '3', 'sir')")
# test that extra positional args raises an 404 Not Found
# See https://github.com/cherrypy/cherrypy/issues/733.
- self.getPage("/dir1/dir2/script_name/extra/stuff")
+ self.getPage('/dir1/dir2/script_name/extra/stuff')
self.assertStatus(404)
def testExpose(self):
# Test the cherrypy.expose function/decorator
- self.getPage("/exposing/base")
- self.assertBody("expose works!")
+ self.getPage('/exposing/base')
+ self.assertBody('expose works!')
- self.getPage("/exposing/1")
- self.assertBody("expose works!")
+ self.getPage('/exposing/1')
+ self.assertBody('expose works!')
- self.getPage("/exposing/2")
- self.assertBody("expose works!")
+ self.getPage('/exposing/2')
+ self.assertBody('expose works!')
- self.getPage("/exposingnew/base")
- self.assertBody("expose works!")
+ self.getPage('/exposingnew/base')
+ self.assertBody('expose works!')
- self.getPage("/exposingnew/1")
- self.assertBody("expose works!")
+ self.getPage('/exposingnew/1')
+ self.assertBody('expose works!')
- self.getPage("/exposingnew/2")
- self.assertBody("expose works!")
+ self.getPage('/exposingnew/2')
+ self.assertBody('expose works!')
def testMethodDispatch(self):
- self.getPage("/bymethod")
+ self.getPage('/bymethod')
self.assertBody("['another']")
self.assertHeader('Allow', 'GET, HEAD, POST')
- self.getPage("/bymethod", method="HEAD")
- self.assertBody("")
+ self.getPage('/bymethod', method='HEAD')
+ self.assertBody('')
self.assertHeader('Allow', 'GET, HEAD, POST')
- self.getPage("/bymethod", method="POST", body="thing=one")
- self.assertBody("")
+ self.getPage('/bymethod', method='POST', body='thing=one')
+ self.assertBody('')
self.assertHeader('Allow', 'GET, HEAD, POST')
- self.getPage("/bymethod")
+ self.getPage('/bymethod')
self.assertBody(repr(['another', ntou('one')]))
self.assertHeader('Allow', 'GET, HEAD, POST')
- self.getPage("/bymethod", method="PUT")
+ self.getPage('/bymethod', method='PUT')
self.assertErrorPage(405)
self.assertHeader('Allow', 'GET, HEAD, POST')
# Test default with posparams
- self.getPage("/collection/silly", method="POST")
- self.getPage("/collection", method="GET")
+ self.getPage('/collection/silly', method='POST')
+ self.getPage('/collection', method='GET')
self.assertBody("['a', 'bit', 'silly']")
# Test custom dispatcher set on app root (see #737).
- self.getPage("/app")
- self.assertBody("milk")
+ self.getPage('/app')
+ self.assertBody('milk')
def testTreeMounting(self):
class Root(object):
+ @cherrypy.expose
def hello(self):
- return "Hello world!"
- hello.exposed = True
+ return 'Hello world!'
# When mounting an application instance,
# we can't specify a different script name in the call to mount.
@@ -418,7 +417,7 @@ class ObjectMappingTest(helper.CPWebCase):
def testKeywords(self):
if sys.version_info < (3,):
- return self.skip("skipped (Python 3 only)")
+ return self.skip('skipped (Python 3 only)')
exec("""class Root(object):
@cherrypy.expose
def hello(self, *, name='world'):
diff --git a/cherrypy/test/test_params.py b/cherrypy/test/test_params.py
new file mode 100644
index 00000000..f40de030
--- /dev/null
+++ b/cherrypy/test/test_params.py
@@ -0,0 +1,60 @@
+import sys
+import textwrap
+
+import cherrypy
+from cherrypy.test import helper
+
+
+class ParamsTest(helper.CPWebCase):
+ @staticmethod
+ def setup_server():
+ class Root:
+ @cherrypy.expose
+ @cherrypy.tools.params()
+ def resource(self, limit=None, sort=None):
+ return type(limit).__name__
+ # for testing on Py 2
+ resource.__annotations__ = {'limit': int}
+ conf = {'/': {'tools.params.on': True}}
+ cherrypy.tree.mount(Root(), config=conf)
+
+ def test_pass(self):
+ self.getPage('/resource')
+ self.assertStatus(200)
+ self.assertBody('NoneType')
+
+ self.getPage('/resource?limit=0')
+ self.assertStatus(200)
+ self.assertBody('int')
+
+ def test_error(self):
+ self.getPage('/resource?limit=')
+ self.assertStatus(400)
+ self.assertInBody('invalid literal for int')
+
+ cherrypy.config['tools.params.error'] = 422
+ self.getPage('/resource?limit=')
+ self.assertStatus(422)
+ self.assertInBody('invalid literal for int')
+
+ cherrypy.config['tools.params.exception'] = TypeError
+ self.getPage('/resource?limit=')
+ self.assertStatus(500)
+
+ def test_syntax(self):
+ if sys.version_info < (3,):
+ return self.skip('skipped (Python 3 only)')
+ code = textwrap.dedent("""
+ class Root:
+ @cherrypy.expose
+ @cherrypy.tools.params()
+ def resource(self, limit: int):
+ return type(limit).__name__
+ conf = {'/': {'tools.params.on': True}}
+ cherrypy.tree.mount(Root(), config=conf)
+ """)
+ exec(code)
+
+ self.getPage('/resource?limit=0')
+ self.assertStatus(200)
+ self.assertBody('int')
diff --git a/cherrypy/test/test_proxy.py b/cherrypy/test/test_proxy.py
index bdc5eada..4d34440a 100644
--- a/cherrypy/test/test_proxy.py
+++ b/cherrypy/test/test_proxy.py
@@ -1,11 +1,12 @@
import cherrypy
from cherrypy.test import helper
-script_names = ["", "/path/to/myapp"]
+script_names = ['', '/path/to/myapp']
class ProxyTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
# Set up site
@@ -21,117 +22,133 @@ class ProxyTest(helper.CPWebCase):
def __init__(self, sn):
# Calculate a URL outside of any requests.
self.thisnewpage = cherrypy.url(
- "/this/new/page", script_name=sn)
+ '/this/new/page', script_name=sn)
+ @cherrypy.expose
def pageurl(self):
return self.thisnewpage
- pageurl.exposed = True
+ @cherrypy.expose
def index(self):
raise cherrypy.HTTPRedirect('dummy')
- index.exposed = True
+ @cherrypy.expose
def remoteip(self):
return cherrypy.request.remote.ip
- remoteip.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{
+ 'tools.proxy.local': 'X-Host',
+ 'tools.trailing_slash.extra': True,
+ })
def xhost(self):
raise cherrypy.HTTPRedirect('blah')
- xhost.exposed = True
- xhost._cp_config = {'tools.proxy.local': 'X-Host',
- 'tools.trailing_slash.extra': True,
- }
+ @cherrypy.expose
def base(self):
return cherrypy.request.base
- base.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.proxy.scheme': 'X-Forwarded-Ssl'})
def ssl(self):
return cherrypy.request.base
- ssl.exposed = True
- ssl._cp_config = {'tools.proxy.scheme': 'X-Forwarded-Ssl'}
+ @cherrypy.expose
def newurl(self):
return ("Browse to <a href='%s'>this page</a>."
- % cherrypy.url("/this/new/page"))
- newurl.exposed = True
+ % cherrypy.url('/this/new/page'))
+
+ @cherrypy.expose
+ @cherrypy.config(**{
+ 'tools.proxy.base': None,
+ })
+ def base_no_base(self):
+ return cherrypy.request.base
for sn in script_names:
cherrypy.tree.mount(Root(sn), sn)
- setup_server = staticmethod(setup_server)
def testProxy(self):
- self.getPage("/")
+ self.getPage('/')
self.assertHeader('Location',
- "%s://www.mydomain.test%s/dummy" %
+ '%s://www.mydomain.test%s/dummy' %
(self.scheme, self.prefix()))
# Test X-Forwarded-Host (Apache 1.3.33+ and Apache 2)
self.getPage(
- "/", headers=[('X-Forwarded-Host', 'http://www.example.test')])
- self.assertHeader('Location', "http://www.example.test/dummy")
- self.getPage("/", headers=[('X-Forwarded-Host', 'www.example.test')])
- self.assertHeader('Location', "%s://www.example.test/dummy" %
+ '/', headers=[('X-Forwarded-Host', 'http://www.example.test')])
+ self.assertHeader('Location', 'http://www.example.test/dummy')
+ self.getPage('/', headers=[('X-Forwarded-Host', 'www.example.test')])
+ self.assertHeader('Location', '%s://www.example.test/dummy' %
self.scheme)
# Test multiple X-Forwarded-Host headers
- self.getPage("/", headers=[
+ self.getPage('/', headers=[
('X-Forwarded-Host', 'http://www.example.test, www.cherrypy.test'),
])
- self.assertHeader('Location', "http://www.example.test/dummy")
+ self.assertHeader('Location', 'http://www.example.test/dummy')
# Test X-Forwarded-For (Apache2)
- self.getPage("/remoteip",
+ self.getPage('/remoteip',
headers=[('X-Forwarded-For', '192.168.0.20')])
- self.assertBody("192.168.0.20")
- #Fix bug #1268
- self.getPage("/remoteip",
+ self.assertBody('192.168.0.20')
+ # Fix bug #1268
+ self.getPage('/remoteip',
headers=[
('X-Forwarded-For', '67.15.36.43, 192.168.0.20')
])
- self.assertBody("67.15.36.43")
+ self.assertBody('67.15.36.43')
# Test X-Host (lighttpd; see https://trac.lighttpd.net/trac/ticket/418)
- self.getPage("/xhost", headers=[('X-Host', 'www.example.test')])
- self.assertHeader('Location', "%s://www.example.test/blah" %
+ self.getPage('/xhost', headers=[('X-Host', 'www.example.test')])
+ self.assertHeader('Location', '%s://www.example.test/blah' %
self.scheme)
# Test X-Forwarded-Proto (lighttpd)
- self.getPage("/base", headers=[('X-Forwarded-Proto', 'https')])
- self.assertBody("https://www.mydomain.test")
+ self.getPage('/base', headers=[('X-Forwarded-Proto', 'https')])
+ self.assertBody('https://www.mydomain.test')
# Test X-Forwarded-Ssl (webfaction?)
- self.getPage("/ssl", headers=[('X-Forwarded-Ssl', 'on')])
- self.assertBody("https://www.mydomain.test")
+ self.getPage('/ssl', headers=[('X-Forwarded-Ssl', 'on')])
+ self.assertBody('https://www.mydomain.test')
# Test cherrypy.url()
for sn in script_names:
# Test the value inside requests
- self.getPage(sn + "/newurl")
+ self.getPage(sn + '/newurl')
self.assertBody(
- "Browse to <a href='%s://www.mydomain.test" % self.scheme
- + sn + "/this/new/page'>this page</a>.")
- self.getPage(sn + "/newurl", headers=[('X-Forwarded-Host',
+ "Browse to <a href='%s://www.mydomain.test" % self.scheme +
+ sn + "/this/new/page'>this page</a>.")
+ self.getPage(sn + '/newurl', headers=[('X-Forwarded-Host',
'http://www.example.test')])
- self.assertBody("Browse to <a href='http://www.example.test"
- + sn + "/this/new/page'>this page</a>.")
+ self.assertBody("Browse to <a href='http://www.example.test" +
+ sn + "/this/new/page'>this page</a>.")
# Test the value outside requests
- port = ""
- if self.scheme == "http" and self.PORT != 80:
- port = ":%s" % self.PORT
- elif self.scheme == "https" and self.PORT != 443:
- port = ":%s" % self.PORT
+ port = ''
+ if self.scheme == 'http' and self.PORT != 80:
+ port = ':%s' % self.PORT
+ elif self.scheme == 'https' and self.PORT != 443:
+ port = ':%s' % self.PORT
host = self.HOST
if host in ('0.0.0.0', '::'):
import socket
host = socket.gethostname()
- expected = ("%s://%s%s%s/this/new/page"
+ expected = ('%s://%s%s%s/this/new/page'
% (self.scheme, host, port, sn))
- self.getPage(sn + "/pageurl")
+ self.getPage(sn + '/pageurl')
self.assertBody(expected)
# Test trailing slash (see
# https://github.com/cherrypy/cherrypy/issues/562).
- self.getPage("/xhost/", headers=[('X-Host', 'www.example.test')])
- self.assertHeader('Location', "%s://www.example.test/xhost"
+ self.getPage('/xhost/', headers=[('X-Host', 'www.example.test')])
+ self.assertHeader('Location', '%s://www.example.test/xhost'
% self.scheme)
+
+ def test_no_base_port_in_host(self):
+ """
+ If no base is indicated, and the host header is used to resolve
+ the base, it should rely on the host header for the port also.
+ """
+ headers = {'Host': 'localhost:8080'}.items()
+ self.getPage('/base_no_base', headers=headers)
+ self.assertBody('http://localhost:8080')
diff --git a/cherrypy/test/test_refleaks.py b/cherrypy/test/test_refleaks.py
index a87b8df7..c2fe9e66 100644
--- a/cherrypy/test/test_refleaks.py
+++ b/cherrypy/test/test_refleaks.py
@@ -1,33 +1,37 @@
"""Tests for refleaks."""
-from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob
+import itertools
+import platform
import threading
+from six.moves.http_client import HTTPConnection
+
import cherrypy
+from cherrypy._cpcompat import HTTPSConnection
+from cherrypy.test import helper
data = object()
-from cherrypy.test import helper
-
-
class ReferenceTests(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self, *args, **kwargs):
cherrypy.request.thing = data
- return "Hello world!"
- index.exposed = True
+ return 'Hello world!'
cherrypy.tree.mount(Root())
- setup_server = staticmethod(setup_server)
def test_threadlocal_garbage(self):
- success = []
+ if platform.system() == 'Darwin':
+ self.skip('queue issues; see #1474')
+ success = itertools.count()
def getpage():
host = '%s:%s' % (self.interface(), self.PORT)
@@ -41,19 +45,22 @@ class ReferenceTests(helper.CPWebCase):
response = c.getresponse()
body = response.read()
self.assertEqual(response.status, 200)
- self.assertEqual(body, ntob("Hello world!"))
+ self.assertEqual(body, b'Hello world!')
finally:
c.close()
- success.append(True)
+ next(success)
ITERATIONS = 25
- ts = []
- for _ in range(ITERATIONS):
- t = threading.Thread(target=getpage)
- ts.append(t)
+
+ ts = [
+ threading.Thread(target=getpage)
+ for _ in range(ITERATIONS)
+ ]
+
+ for t in ts:
t.start()
for t in ts:
t.join()
- self.assertEqual(len(success), ITERATIONS)
+ self.assertEqual(next(success), ITERATIONS)
diff --git a/cherrypy/test/test_request_obj.py b/cherrypy/test/test_request_obj.py
index 58736b54..232440c9 100644
--- a/cherrypy/test/test_request_obj.py
+++ b/cherrypy/test/test_request_obj.py
@@ -1,36 +1,63 @@
"""Basic tests for the cherrypy.Request object."""
+from functools import wraps
import os
-localDir = os.path.dirname(__file__)
import sys
import types
-from cherrypy._cpcompat import IncompleteRead, ntob, ntou, unicodestr
+import uuid
+
+import six
+from six.moves.http_client import IncompleteRead
import cherrypy
-from cherrypy import _cptools, tools
+from cherrypy._cpcompat import ntob, ntou
from cherrypy.lib import httputil
+from cherrypy.test import helper
-defined_http_methods = ("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE",
- "TRACE", "PROPFIND")
+localDir = os.path.dirname(__file__)
+defined_http_methods = ('OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE',
+ 'TRACE', 'PROPFIND', 'PATCH')
-# Client-side code #
-from cherrypy.test import helper
+# Client-side code #
class RequestObjectTests(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "hello"
- index.exposed = True
+ return 'hello'
+ @cherrypy.expose
def scheme(self):
return cherrypy.request.scheme
- scheme.exposed = True
+
+ @cherrypy.expose
+ def created_example_com_3128(self):
+ """Handle CONNECT method."""
+ cherrypy.response.status = 204
+
+ @cherrypy.expose
+ def body_example_com_3128(self):
+ """Handle CONNECT method."""
+ return (
+ cherrypy.request.method
+ + 'ed to '
+ + cherrypy.request.path_info
+ )
+
+ @cherrypy.expose
+ def request_uuid4(self):
+ return [
+ str(cherrypy.request.unique_id),
+ ' ',
+ str(cherrypy.request.unique_id),
+ ]
root = Root()
@@ -58,121 +85,130 @@ class RequestObjectTests(helper.CPWebCase):
return repr(thing)
def ismap(self, x, y):
- return "Coordinates: %s, %s" % (x, y)
+ return 'Coordinates: %s, %s' % (x, y)
+ @cherrypy.config(**{'request.query_string_encoding': 'latin1'})
def default(self, *args, **kwargs):
- return "args: %s kwargs: %s" % (args, sorted(kwargs.items()))
- default._cp_config = {'request.query_string_encoding': 'latin1'}
+ return 'args: %s kwargs: %s' % (args, sorted(kwargs.items()))
+ @cherrypy.expose
class ParamErrorsCallable(object):
- exposed = True
def __call__(self):
- return "data"
+ return 'data'
+
+ def handler_dec(f):
+ @wraps(f)
+ def wrapper(handler, *args, **kwargs):
+ return f(handler, *args, **kwargs)
+ return wrapper
class ParamErrors(Test):
+ @cherrypy.expose
def one_positional(self, param1):
- return "data"
- one_positional.exposed = True
+ return 'data'
+ @cherrypy.expose
def one_positional_args(self, param1, *args):
- return "data"
- one_positional_args.exposed = True
+ return 'data'
+ @cherrypy.expose
def one_positional_args_kwargs(self, param1, *args, **kwargs):
- return "data"
- one_positional_args_kwargs.exposed = True
+ return 'data'
+ @cherrypy.expose
def one_positional_kwargs(self, param1, **kwargs):
- return "data"
- one_positional_kwargs.exposed = True
+ return 'data'
+ @cherrypy.expose
def no_positional(self):
- return "data"
- no_positional.exposed = True
+ return 'data'
+ @cherrypy.expose
def no_positional_args(self, *args):
- return "data"
- no_positional_args.exposed = True
+ return 'data'
+ @cherrypy.expose
def no_positional_args_kwargs(self, *args, **kwargs):
- return "data"
- no_positional_args_kwargs.exposed = True
+ return 'data'
+ @cherrypy.expose
def no_positional_kwargs(self, **kwargs):
- return "data"
- no_positional_kwargs.exposed = True
+ return 'data'
callable_object = ParamErrorsCallable()
+ @cherrypy.expose
def raise_type_error(self, **kwargs):
- raise TypeError("Client Error")
- raise_type_error.exposed = True
+ raise TypeError('Client Error')
+ @cherrypy.expose
def raise_type_error_with_default_param(self, x, y=None):
return '%d' % 'a' # throw an exception
- raise_type_error_with_default_param.exposed = True
+
+ @cherrypy.expose
+ @handler_dec
+ def raise_type_error_decorated(self, *args, **kwargs):
+ raise TypeError('Client Error')
def callable_error_page(status, **kwargs):
return "Error %s - Well, I'm very sorry but you haven't paid!" % (
status)
+ @cherrypy.config(**{'tools.log_tracebacks.on': True})
class Error(Test):
- _cp_config = {'tools.log_tracebacks.on': True,
- }
-
def reason_phrase(self):
raise cherrypy.HTTPError("410 Gone fishin'")
+ @cherrypy.config(**{
+ 'error_page.404': os.path.join(localDir, 'static/index.html'),
+ 'error_page.401': callable_error_page,
+ })
def custom(self, err='404'):
raise cherrypy.HTTPError(
- int(err), "No, <b>really</b>, not found!")
- custom._cp_config = {
- 'error_page.404': os.path.join(localDir, "static/index.html"),
- 'error_page.401': callable_error_page,
- }
+ int(err), 'No, <b>really</b>, not found!')
+ @cherrypy.config(**{
+ 'error_page.default': callable_error_page,
+ })
def custom_default(self):
return 1 + 'a' # raise an unexpected error
- custom_default._cp_config = {
- 'error_page.default': callable_error_page}
+ @cherrypy.config(**{'error_page.404': 'nonexistent.html'})
def noexist(self):
- raise cherrypy.HTTPError(404, "No, <b>really</b>, not found!")
- noexist._cp_config = {'error_page.404': "nonexistent.html"}
+ raise cherrypy.HTTPError(404, 'No, <b>really</b>, not found!')
def page_method(self):
raise ValueError()
def page_yield(self):
- yield "howdy"
+ yield 'howdy'
raise ValueError()
+ @cherrypy.config(**{'response.stream': True})
def page_streamed(self):
- yield "word up"
+ yield 'word up'
raise ValueError()
- yield "very oops"
- page_streamed._cp_config = {"response.stream": True}
+ yield 'very oops'
+ @cherrypy.config(**{'request.show_tracebacks': False})
def cause_err_in_finalize(self):
# Since status must start with an int, this should error.
- cherrypy.response.status = "ZOO OK"
- cause_err_in_finalize._cp_config = {
- 'request.show_tracebacks': False}
+ cherrypy.response.status = 'ZOO OK'
+ @cherrypy.config(**{'request.throw_errors': True})
def rethrow(self):
"""Test that an error raised here will be thrown out to
the server.
"""
raise ValueError()
- rethrow._cp_config = {'request.throw_errors': True}
class Expect(Test):
def expectation_failed(self):
- expect = cherrypy.request.headers.elements("Expect")
+ expect = cherrypy.request.headers.elements('Expect')
if expect and expect[0].value != '100-continue':
raise cherrypy.HTTPError(400)
raise cherrypy.HTTPError(417, 'Expectation Failed')
@@ -192,7 +228,7 @@ class RequestObjectTests(helper.CPWebCase):
# Set the most common headers
hMap = cherrypy.response.headers
- hMap['content-type'] = "text/html"
+ hMap['content-type'] = 'text/html'
hMap['content-length'] = 18
hMap['server'] = 'CherryPy headertest'
hMap['location'] = ('%s://%s:%s/headers/'
@@ -203,11 +239,11 @@ class RequestObjectTests(helper.CPWebCase):
# Set a rare header for fun
hMap['Expires'] = 'Thu, 01 Dec 2194 16:00:00 GMT'
- return "double header test"
+ return 'double header test'
def ifmatch(self):
val = cherrypy.request.headers['If-Match']
- assert isinstance(val, unicodestr)
+ assert isinstance(val, six.text_type)
cherrypy.response.headers['ETag'] = val
return val
@@ -215,16 +251,16 @@ class RequestObjectTests(helper.CPWebCase):
def get_elements(self, headername):
e = cherrypy.request.headers.elements(headername)
- return "\n".join([unicodestr(x) for x in e])
+ return '\n'.join([six.text_type(x) for x in e])
class Method(Test):
def index(self):
m = cherrypy.request.method
- if m in defined_http_methods or m == "CONNECT":
+ if m in defined_http_methods or m == 'CONNECT':
return m
- if m == "LINK":
+ if m == 'LINK':
raise cherrypy.HTTPError(405)
else:
raise cherrypy.HTTPError(501)
@@ -238,9 +274,9 @@ class RequestObjectTests(helper.CPWebCase):
return cherrypy.request.body
def reachable(self):
- return "success"
+ return 'success'
- class Divorce:
+ class Divorce(Test):
"""HTTP Method handlers shouldn't collide with normal method names.
For example, a GET-handler shouldn't collide with a method named
@@ -254,92 +290,105 @@ class RequestObjectTests(helper.CPWebCase):
documents = {}
+ @cherrypy.expose
def index(self):
- yield "<h1>Choose your document</h1>\n"
- yield "<ul>\n"
+ yield '<h1>Choose your document</h1>\n'
+ yield '<ul>\n'
for id, contents in self.documents.items():
yield (
" <li><a href='/divorce/get?ID=%s'>%s</a>:"
- " %s</li>\n" % (id, id, contents))
- yield "</ul>"
- index.exposed = True
+ ' %s</li>\n' % (id, id, contents))
+ yield '</ul>'
+ @cherrypy.expose
def get(self, ID):
- return ("Divorce document %s: %s" %
- (ID, self.documents.get(ID, "empty")))
- get.exposed = True
-
- root.divorce = Divorce()
+ return ('Divorce document %s: %s' %
+ (ID, self.documents.get(ID, 'empty')))
class ThreadLocal(Test):
def index(self):
- existing = repr(getattr(cherrypy.request, "asdf", None))
- cherrypy.request.asdf = "rassfrassin"
+ existing = repr(getattr(cherrypy.request, 'asdf', None))
+ cherrypy.request.asdf = 'rassfrassin'
return existing
appconf = {
'/method': {
- 'request.methods_with_bodies': ("POST", "PUT", "PROPFIND")
+ 'request.methods_with_bodies': ('POST', 'PUT', 'PROPFIND',
+ 'PATCH')
},
}
cherrypy.tree.mount(root, config=appconf)
- setup_server = staticmethod(setup_server)
def test_scheme(self):
- self.getPage("/scheme")
+ self.getPage('/scheme')
self.assertBody(self.scheme)
+ def test_per_request_uuid4(self):
+ self.getPage('/request_uuid4')
+ first_uuid4, _, second_uuid4 = self.body.decode().partition(' ')
+ assert (
+ uuid.UUID(first_uuid4, version=4)
+ == uuid.UUID(second_uuid4, version=4)
+ )
+
+ self.getPage('/request_uuid4')
+ third_uuid4, _, _ = self.body.decode().partition(' ')
+ assert (
+ uuid.UUID(first_uuid4, version=4)
+ != uuid.UUID(third_uuid4, version=4)
+ )
+
def testRelativeURIPathInfo(self):
- self.getPage("/pathinfo/foo/bar")
- self.assertBody("/pathinfo/foo/bar")
+ self.getPage('/pathinfo/foo/bar')
+ self.assertBody('/pathinfo/foo/bar')
def testAbsoluteURIPathInfo(self):
# http://cherrypy.org/ticket/1061
- self.getPage("http://localhost/pathinfo/foo/bar")
- self.assertBody("/pathinfo/foo/bar")
+ self.getPage('http://localhost/pathinfo/foo/bar')
+ self.assertBody('/pathinfo/foo/bar')
def testParams(self):
- self.getPage("/params/?thing=a")
- self.assertBody(repr(ntou("a")))
+ self.getPage('/params/?thing=a')
+ self.assertBody(repr(ntou('a')))
- self.getPage("/params/?thing=a&thing=b&thing=c")
+ self.getPage('/params/?thing=a&thing=b&thing=c')
self.assertBody(repr([ntou('a'), ntou('b'), ntou('c')]))
# Test friendly error message when given params are not accepted.
- cherrypy.config.update({"request.show_mismatched_params": True})
- self.getPage("/params/?notathing=meeting")
- self.assertInBody("Missing parameters: thing")
- self.getPage("/params/?thing=meeting&notathing=meeting")
- self.assertInBody("Unexpected query string parameters: notathing")
+ cherrypy.config.update({'request.show_mismatched_params': True})
+ self.getPage('/params/?notathing=meeting')
+ self.assertInBody('Missing parameters: thing')
+ self.getPage('/params/?thing=meeting&notathing=meeting')
+ self.assertInBody('Unexpected query string parameters: notathing')
# Test ability to turn off friendly error messages
- cherrypy.config.update({"request.show_mismatched_params": False})
- self.getPage("/params/?notathing=meeting")
- self.assertInBody("Not Found")
- self.getPage("/params/?thing=meeting&notathing=meeting")
- self.assertInBody("Not Found")
+ cherrypy.config.update({'request.show_mismatched_params': False})
+ self.getPage('/params/?notathing=meeting')
+ self.assertInBody('Not Found')
+ self.getPage('/params/?thing=meeting&notathing=meeting')
+ self.assertInBody('Not Found')
# Test "% HEX HEX"-encoded URL, param keys, and values
- self.getPage("/params/%d4%20%e3/cheese?Gruy%E8re=Bulgn%e9ville")
- self.assertBody("args: %s kwargs: %s" %
+ self.getPage('/params/%d4%20%e3/cheese?Gruy%E8re=Bulgn%e9ville')
+ self.assertBody('args: %s kwargs: %s' %
(('\xd4 \xe3', 'cheese'),
[('Gruy\xe8re', ntou('Bulgn\xe9ville'))]))
# Make sure that encoded = and & get parsed correctly
self.getPage(
- "/params/code?url=http%3A//cherrypy.org/index%3Fa%3D1%26b%3D2")
- self.assertBody("args: %s kwargs: %s" %
+ '/params/code?url=http%3A//cherrypy.org/index%3Fa%3D1%26b%3D2')
+ self.assertBody('args: %s kwargs: %s' %
(('code',),
[('url', ntou('http://cherrypy.org/index?a=1&b=2'))]))
# Test coordinates sent by <img ismap>
- self.getPage("/params/ismap?223,114")
- self.assertBody("Coordinates: 223, 114")
+ self.getPage('/params/ismap?223,114')
+ self.assertBody('Coordinates: 223, 114')
# Test "name[key]" dict-like params
- self.getPage("/params/dictlike?a[1]=1&a[2]=2&b=foo&b[bar]=baz")
- self.assertBody("args: %s kwargs: %s" %
+ self.getPage('/params/dictlike?a[1]=1&a[2]=2&b=foo&b[bar]=baz')
+ self.assertBody('args: %s kwargs: %s' %
(('dictlike',),
[('a[1]', ntou('1')), ('a[2]', ntou('2')),
('b', ntou('foo')), ('b[bar]', ntou('baz'))]))
@@ -431,7 +480,7 @@ class RequestObjectTests(helper.CPWebCase):
if show_mismatched_params:
self.assertInBody(msg)
else:
- self.assertInBody("Not Found")
+ self.assertInBody('Not Found')
# if body parameters are wrong, a 400 must be returned.
for uri, body, msg in (
@@ -460,7 +509,7 @@ class RequestObjectTests(helper.CPWebCase):
if show_mismatched_params:
self.assertInBody(msg)
else:
- self.assertInBody("400 Bad")
+ self.assertInBody('400 Bad')
# even if body parameters are wrong, if we get the uri wrong, then
# it's a 404
@@ -488,7 +537,7 @@ class RequestObjectTests(helper.CPWebCase):
if show_mismatched_params:
self.assertInBody(msg)
else:
- self.assertInBody("Not Found")
+ self.assertInBody('Not Found')
# In the case that a handler raises a TypeError we should
# let that type error through.
@@ -496,13 +545,14 @@ class RequestObjectTests(helper.CPWebCase):
'/paramerrors/raise_type_error',
'/paramerrors/raise_type_error_with_default_param?x=0',
'/paramerrors/raise_type_error_with_default_param?x=0&y=0',
+ '/paramerrors/raise_type_error_decorated',
):
self.getPage(uri, method='GET')
self.assertStatus(500)
self.assertTrue('Client Error', self.body)
def testErrorHandling(self):
- self.getPage("/error/missing")
+ self.getPage('/error/missing')
self.assertStatus(404)
self.assertErrorPage(404, "The path '/error/missing' was not found.")
@@ -510,27 +560,27 @@ class RequestObjectTests(helper.CPWebCase):
ignore.append(ValueError)
try:
valerr = '\n raise ValueError()\nValueError'
- self.getPage("/error/page_method")
+ self.getPage('/error/page_method')
self.assertErrorPage(500, pattern=valerr)
- self.getPage("/error/page_yield")
+ self.getPage('/error/page_yield')
self.assertErrorPage(500, pattern=valerr)
- if (cherrypy.server.protocol_version == "HTTP/1.0" or
- getattr(cherrypy.server, "using_apache", False)):
- self.getPage("/error/page_streamed")
+ if (cherrypy.server.protocol_version == 'HTTP/1.0' or
+ getattr(cherrypy.server, 'using_apache', False)):
+ self.getPage('/error/page_streamed')
# Because this error is raised after the response body has
# started, the status should not change to an error status.
self.assertStatus(200)
- self.assertBody("word up")
+ self.assertBody('word up')
else:
# Under HTTP/1.1, the chunked transfer-coding is used.
# The HTTP client will choke when the output is incomplete.
self.assertRaises((ValueError, IncompleteRead), self.getPage,
- "/error/page_streamed")
+ '/error/page_streamed')
# No traceback should be present
- self.getPage("/error/cause_err_in_finalize")
+ self.getPage('/error/cause_err_in_finalize')
msg = "Illegal response status from server ('ZOO' is non-numeric)."
self.assertErrorPage(500, msg, None)
finally:
@@ -541,126 +591,126 @@ class RequestObjectTests(helper.CPWebCase):
self.assertStatus("410 Gone fishin'")
# Test custom error page for a specific error.
- self.getPage("/error/custom")
+ self.getPage('/error/custom')
self.assertStatus(404)
- self.assertBody("Hello, world\r\n" + (" " * 499))
+ self.assertBody('Hello, world\r\n' + (' ' * 499))
# Test custom error page for a specific error.
- self.getPage("/error/custom?err=401")
+ self.getPage('/error/custom?err=401')
self.assertStatus(401)
self.assertBody(
- "Error 401 Unauthorized - "
+ 'Error 401 Unauthorized - '
"Well, I'm very sorry but you haven't paid!")
# Test default custom error page.
- self.getPage("/error/custom_default")
+ self.getPage('/error/custom_default')
self.assertStatus(500)
self.assertBody(
- "Error 500 Internal Server Error - "
+ 'Error 500 Internal Server Error - '
"Well, I'm very sorry but you haven't paid!".ljust(513))
# Test error in custom error page (ticket #305).
# Note that the message is escaped for HTML (ticket #310).
- self.getPage("/error/noexist")
+ self.getPage('/error/noexist')
self.assertStatus(404)
if sys.version_info >= (3, 3):
- exc_name = "FileNotFoundError"
+ exc_name = 'FileNotFoundError'
else:
- exc_name = "IOError"
- msg = ("No, &lt;b&gt;really&lt;/b&gt;, not found!<br />"
- "In addition, the custom error page failed:\n<br />"
- "%s: [Errno 2] "
+ exc_name = 'IOError'
+ msg = ('No, &lt;b&gt;really&lt;/b&gt;, not found!<br />'
+ 'In addition, the custom error page failed:\n<br />'
+ '%s: [Errno 2] '
"No such file or directory: 'nonexistent.html'") % (exc_name,)
self.assertInBody(msg)
- if getattr(cherrypy.server, "using_apache", False):
+ if getattr(cherrypy.server, 'using_apache', False):
pass
else:
# Test throw_errors (ticket #186).
- self.getPage("/error/rethrow")
- self.assertInBody("raise ValueError()")
+ self.getPage('/error/rethrow')
+ self.assertInBody('raise ValueError()')
def testExpect(self):
e = ('Expect', '100-continue')
- self.getPage("/headerelements/get_elements?headername=Expect", [e])
+ self.getPage('/headerelements/get_elements?headername=Expect', [e])
self.assertBody('100-continue')
- self.getPage("/expect/expectation_failed", [e])
+ self.getPage('/expect/expectation_failed', [e])
self.assertStatus(417)
def testHeaderElements(self):
# Accept-* header elements should be sorted, with most preferred first.
h = [('Accept', 'audio/*; q=0.2, audio/basic')]
- self.getPage("/headerelements/get_elements?headername=Accept", h)
+ self.getPage('/headerelements/get_elements?headername=Accept', h)
self.assertStatus(200)
- self.assertBody("audio/basic\n"
- "audio/*;q=0.2")
+ self.assertBody('audio/basic\n'
+ 'audio/*;q=0.2')
h = [
('Accept',
'text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c')
]
- self.getPage("/headerelements/get_elements?headername=Accept", h)
+ self.getPage('/headerelements/get_elements?headername=Accept', h)
self.assertStatus(200)
- self.assertBody("text/x-c\n"
- "text/html\n"
- "text/x-dvi;q=0.8\n"
- "text/plain;q=0.5")
+ self.assertBody('text/x-c\n'
+ 'text/html\n'
+ 'text/x-dvi;q=0.8\n'
+ 'text/plain;q=0.5')
# Test that more specific media ranges get priority.
h = [('Accept', 'text/*, text/html, text/html;level=1, */*')]
- self.getPage("/headerelements/get_elements?headername=Accept", h)
+ self.getPage('/headerelements/get_elements?headername=Accept', h)
self.assertStatus(200)
- self.assertBody("text/html;level=1\n"
- "text/html\n"
- "text/*\n"
- "*/*")
+ self.assertBody('text/html;level=1\n'
+ 'text/html\n'
+ 'text/*\n'
+ '*/*')
# Test Accept-Charset
h = [('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8')]
self.getPage(
- "/headerelements/get_elements?headername=Accept-Charset", h)
- self.assertStatus("200 OK")
- self.assertBody("iso-8859-5\n"
- "unicode-1-1;q=0.8")
+ '/headerelements/get_elements?headername=Accept-Charset', h)
+ self.assertStatus('200 OK')
+ self.assertBody('iso-8859-5\n'
+ 'unicode-1-1;q=0.8')
# Test Accept-Encoding
h = [('Accept-Encoding', 'gzip;q=1.0, identity; q=0.5, *;q=0')]
self.getPage(
- "/headerelements/get_elements?headername=Accept-Encoding", h)
- self.assertStatus("200 OK")
- self.assertBody("gzip;q=1.0\n"
- "identity;q=0.5\n"
- "*;q=0")
+ '/headerelements/get_elements?headername=Accept-Encoding', h)
+ self.assertStatus('200 OK')
+ self.assertBody('gzip;q=1.0\n'
+ 'identity;q=0.5\n'
+ '*;q=0')
# Test Accept-Language
h = [('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7')]
self.getPage(
- "/headerelements/get_elements?headername=Accept-Language", h)
- self.assertStatus("200 OK")
- self.assertBody("da\n"
- "en-gb;q=0.8\n"
- "en;q=0.7")
+ '/headerelements/get_elements?headername=Accept-Language', h)
+ self.assertStatus('200 OK')
+ self.assertBody('da\n'
+ 'en-gb;q=0.8\n'
+ 'en;q=0.7')
# Test malformed header parsing. See
# https://github.com/cherrypy/cherrypy/issues/763.
- self.getPage("/headerelements/get_elements?headername=Content-Type",
+ self.getPage('/headerelements/get_elements?headername=Content-Type',
# Note the illegal trailing ";"
headers=[('Content-Type', 'text/html; charset=utf-8;')])
self.assertStatus(200)
- self.assertBody("text/html;charset=utf-8")
+ self.assertBody('text/html;charset=utf-8')
def test_repeated_headers(self):
# Test that two request headers are collapsed into one.
# See https://github.com/cherrypy/cherrypy/issues/542.
- self.getPage("/headers/Accept-Charset",
- headers=[("Accept-Charset", "iso-8859-5"),
- ("Accept-Charset", "unicode-1-1;q=0.8")])
- self.assertBody("iso-8859-5, unicode-1-1;q=0.8")
+ self.getPage('/headers/Accept-Charset',
+ headers=[('Accept-Charset', 'iso-8859-5'),
+ ('Accept-Charset', 'unicode-1-1;q=0.8')])
+ self.assertBody('iso-8859-5, unicode-1-1;q=0.8')
# Tests that each header only appears once, regardless of case.
- self.getPage("/headers/doubledheaders")
- self.assertBody("double header test")
+ self.getPage('/headers/doubledheaders')
+ self.assertBody('double header test')
hnames = [name.title() for name, val in self.headers]
for key in ['Content-Length', 'Content-Type', 'Date',
'Expires', 'Location', 'Server']:
@@ -669,26 +719,26 @@ class RequestObjectTests(helper.CPWebCase):
def test_encoded_headers(self):
# First, make sure the innards work like expected.
self.assertEqual(
- httputil.decode_TEXT(ntou("=?utf-8?q?f=C3=BCr?=")), ntou("f\xfcr"))
+ httputil.decode_TEXT(ntou('=?utf-8?q?f=C3=BCr?=')), ntou('f\xfcr'))
- if cherrypy.server.protocol_version == "HTTP/1.1":
+ if cherrypy.server.protocol_version == 'HTTP/1.1':
# Test RFC-2047-encoded request and response header values
u = ntou('\u212bngstr\xf6m', 'escape')
- c = ntou("=E2=84=ABngstr=C3=B6m")
- self.getPage("/headers/ifmatch",
+ c = ntou('=E2=84=ABngstr=C3=B6m')
+ self.getPage('/headers/ifmatch',
[('If-Match', ntou('=?utf-8?q?%s?=') % c)])
# The body should be utf-8 encoded.
- self.assertBody(ntob("\xe2\x84\xabngstr\xc3\xb6m"))
+ self.assertBody(ntob('\xe2\x84\xabngstr\xc3\xb6m'))
# But the Etag header should be RFC-2047 encoded (binary)
- self.assertHeader("ETag", ntou('=?utf-8?b?4oSrbmdzdHLDtm0=?='))
+ self.assertHeader('ETag', ntou('=?utf-8?b?4oSrbmdzdHLDtm0=?='))
# Test a *LONG* RFC-2047-encoded request and response header value
- self.getPage("/headers/ifmatch",
+ self.getPage('/headers/ifmatch',
[('If-Match', ntou('=?utf-8?q?%s?=') % (c * 10))])
- self.assertBody(ntob("\xe2\x84\xabngstr\xc3\xb6m") * 10)
+ self.assertBody(ntob('\xe2\x84\xabngstr\xc3\xb6m') * 10)
# Note: this is different output for Python3, but it decodes fine.
etag = self.assertHeader(
- "ETag",
+ 'ETag',
'=?utf-8?b?4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt'
'4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt'
'4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt'
@@ -698,57 +748,99 @@ class RequestObjectTests(helper.CPWebCase):
def test_header_presence(self):
# If we don't pass a Content-Type header, it should not be present
# in cherrypy.request.headers
- self.getPage("/headers/Content-Type",
+ self.getPage('/headers/Content-Type',
headers=[])
self.assertStatus(500)
# If Content-Type is present in the request, it should be present in
# cherrypy.request.headers
- self.getPage("/headers/Content-Type",
- headers=[("Content-type", "application/json")])
- self.assertBody("application/json")
+ self.getPage('/headers/Content-Type',
+ headers=[('Content-type', 'application/json')])
+ self.assertBody('application/json')
def test_basic_HTTPMethods(self):
- helper.webtest.methods_with_bodies = ("POST", "PUT", "PROPFIND")
+ helper.webtest.methods_with_bodies = ('POST', 'PUT', 'PROPFIND',
+ 'PATCH')
# Test that all defined HTTP methods work.
for m in defined_http_methods:
- self.getPage("/method/", method=m)
+ self.getPage('/method/', method=m)
# HEAD requests should not return any body.
- if m == "HEAD":
- self.assertBody("")
- elif m == "TRACE":
+ if m == 'HEAD':
+ self.assertBody('')
+ elif m == 'TRACE':
# Some HTTP servers (like modpy) have their own TRACE support
- self.assertEqual(self.body[:5], ntob("TRACE"))
+ self.assertEqual(self.body[:5], ntob('TRACE'))
else:
self.assertBody(m)
+ # test of PATCH requests
+ # Request a PATCH method with a form-urlencoded body
+ self.getPage('/method/parameterized', method='PATCH',
+ body='data=on+top+of+other+things')
+ self.assertBody('on top of other things')
+
+ # Request a PATCH method with a file body
+ b = 'one thing on top of another'
+ h = [('Content-Type', 'text/plain'),
+ ('Content-Length', str(len(b)))]
+ self.getPage('/method/request_body', headers=h, method='PATCH', body=b)
+ self.assertStatus(200)
+ self.assertBody(b)
+
+ # Request a PATCH method with a file body but no Content-Type.
+ # See https://github.com/cherrypy/cherrypy/issues/790.
+ b = ntob('one thing on top of another')
+ self.persistent = True
+ try:
+ conn = self.HTTP_CONN
+ conn.putrequest('PATCH', '/method/request_body', skip_host=True)
+ conn.putheader('Host', self.HOST)
+ conn.putheader('Content-Length', str(len(b)))
+ conn.endheaders()
+ conn.send(b)
+ response = conn.response_class(conn.sock, method='PATCH')
+ response.begin()
+ self.assertEqual(response.status, 200)
+ self.body = response.read()
+ self.assertBody(b)
+ finally:
+ self.persistent = False
+
+ # Request a PATCH method with no body whatsoever (not an empty one).
+ # See https://github.com/cherrypy/cherrypy/issues/650.
+ # Provide a C-T or webtest will provide one (and a C-L) for us.
+ h = [('Content-Type', 'text/plain')]
+ self.getPage('/method/reachable', headers=h, method='PATCH')
+ self.assertStatus(411)
+
+ # HTTP PUT tests
# Request a PUT method with a form-urlencoded body
- self.getPage("/method/parameterized", method="PUT",
- body="data=on+top+of+other+things")
- self.assertBody("on top of other things")
+ self.getPage('/method/parameterized', method='PUT',
+ body='data=on+top+of+other+things')
+ self.assertBody('on top of other things')
# Request a PUT method with a file body
- b = "one thing on top of another"
- h = [("Content-Type", "text/plain"),
- ("Content-Length", str(len(b)))]
- self.getPage("/method/request_body", headers=h, method="PUT", body=b)
+ b = 'one thing on top of another'
+ h = [('Content-Type', 'text/plain'),
+ ('Content-Length', str(len(b)))]
+ self.getPage('/method/request_body', headers=h, method='PUT', body=b)
self.assertStatus(200)
self.assertBody(b)
# Request a PUT method with a file body but no Content-Type.
# See https://github.com/cherrypy/cherrypy/issues/790.
- b = ntob("one thing on top of another")
+ b = ntob('one thing on top of another')
self.persistent = True
try:
conn = self.HTTP_CONN
- conn.putrequest("PUT", "/method/request_body", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('PUT', '/method/request_body', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.putheader('Content-Length', str(len(b)))
conn.endheaders()
conn.send(b)
- response = conn.response_class(conn.sock, method="PUT")
+ response = conn.response_class(conn.sock, method='PUT')
response.begin()
self.assertEqual(response.status, 200)
self.body = response.read()
@@ -759,8 +851,8 @@ class RequestObjectTests(helper.CPWebCase):
# Request a PUT method with no body whatsoever (not an empty one).
# See https://github.com/cherrypy/cherrypy/issues/650.
# Provide a C-T or webtest will provide one (and a C-L) for us.
- h = [("Content-Type", "text/plain")]
- self.getPage("/method/reachable", headers=h, method="PUT")
+ h = [('Content-Type', 'text/plain')]
+ self.getPage('/method/reachable', headers=h, method='PUT')
self.assertStatus(411)
# Request a custom method with a request body
@@ -769,40 +861,72 @@ class RequestObjectTests(helper.CPWebCase):
'</prop></propfind>')
h = [('Content-Type', 'text/xml'),
('Content-Length', str(len(b)))]
- self.getPage("/method/request_body", headers=h,
- method="PROPFIND", body=b)
+ self.getPage('/method/request_body', headers=h,
+ method='PROPFIND', body=b)
self.assertStatus(200)
self.assertBody(b)
# Request a disallowed method
- self.getPage("/method/", method="LINK")
+ self.getPage('/method/', method='LINK')
self.assertStatus(405)
# Request an unknown method
- self.getPage("/method/", method="SEARCH")
+ self.getPage('/method/', method='SEARCH')
self.assertStatus(501)
# For method dispatchers: make sure that an HTTP method doesn't
# collide with a virtual path atom. If you build HTTP-method
# dispatching into the core, rewrite these handlers to use
# your dispatch idioms.
- self.getPage("/divorce/get?ID=13")
+ self.getPage('/divorce/get?ID=13')
self.assertBody('Divorce document 13: empty')
self.assertStatus(200)
- self.getPage("/divorce/", method="GET")
+ self.getPage('/divorce/', method='GET')
self.assertBody('<h1>Choose your document</h1>\n<ul>\n</ul>')
self.assertStatus(200)
def test_CONNECT_method(self):
- if getattr(cherrypy.server, "using_apache", False):
- return self.skip("skipped due to known Apache differences... ")
+ self.persistent = True
+ try:
+ conn = self.HTTP_CONN
+ conn.request('CONNECT', 'created.example.com:3128')
+ response = conn.response_class(conn.sock, method='CONNECT')
+ response.begin()
+ self.assertEqual(response.status, 204)
+ finally:
+ self.persistent = False
+
+ self.persistent = True
+ try:
+ conn = self.HTTP_CONN
+ conn.request('CONNECT', 'body.example.com:3128')
+ response = conn.response_class(conn.sock, method='CONNECT')
+ response.begin()
+ self.assertEqual(response.status, 200)
+ self.body = response.read()
+ self.assertBody(b'CONNECTed to /body.example.com:3128')
+ finally:
+ self.persistent = False
- self.getPage("/method/", method="CONNECT")
- self.assertBody("CONNECT")
+ def test_CONNECT_method_invalid_authority(self):
+ for request_target in ['example.com', 'http://example.com:33',
+ '/path/', 'path/', '/?q=f', '#f']:
+ self.persistent = True
+ try:
+ conn = self.HTTP_CONN
+ conn.request('CONNECT', request_target)
+ response = conn.response_class(conn.sock, method='CONNECT')
+ response.begin()
+ self.assertEqual(response.status, 400)
+ self.body = response.read()
+ self.assertBody(b'Invalid path in Request-URI: request-target '
+ b'must match authority-form.')
+ finally:
+ self.persistent = False
def testEmptyThreadlocals(self):
results = []
for x in range(20):
- self.getPage("/threadlocal/")
+ self.getPage('/threadlocal/')
results.append(self.body)
- self.assertEqual(results, [ntob("None")] * 20)
+ self.assertEqual(results, [ntob('None')] * 20)
diff --git a/cherrypy/test/test_routes.py b/cherrypy/test/test_routes.py
index 41f744f9..cc714765 100644
--- a/cherrypy/test/test_routes.py
+++ b/cherrypy/test/test_routes.py
@@ -1,25 +1,30 @@
+"""Test Routes dispatcher."""
import os
-curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+import importlib
-import cherrypy
+import pytest
+import cherrypy
from cherrypy.test import helper
-import nose
+
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
class RoutesDispatchTest(helper.CPWebCase):
+ """Routes dispatcher test suite."""
+ @staticmethod
def setup_server():
-
+ """Set up cherrypy test instance."""
try:
- import routes
+ importlib.import_module('routes')
except ImportError:
- raise nose.SkipTest('Install routes to test RoutesDispatcher code')
+ pytest.skip('Install routes to test RoutesDispatcher code')
class Dummy:
def index(self):
- return "I said good day!"
+ return 'I said good day!'
class City:
@@ -27,18 +32,18 @@ class RoutesDispatchTest(helper.CPWebCase):
self.name = name
self.population = 10000
- def index(self, **kwargs):
- return "Welcome to %s, pop. %s" % (self.name, self.population)
- index._cp_config = {
+ @cherrypy.config(**{
'tools.response_headers.on': True,
'tools.response_headers.headers': [
- ('Content-Language', 'en-GB')
- ]
- }
+ ('Content-Language', 'en-GB'),
+ ],
+ })
+ def index(self, **kwargs):
+ return 'Welcome to %s, pop. %s' % (self.name, self.population)
def update(self, **kwargs):
self.population = kwargs['pop']
- return "OK"
+ return 'OK'
d = cherrypy.dispatch.RoutesDispatcher()
d.connect(action='index', name='hounslow', route='/hounslow',
@@ -52,24 +57,24 @@ class RoutesDispatchTest(helper.CPWebCase):
conf = {'/': {'request.dispatch': d}}
cherrypy.tree.mount(root=None, config=conf)
- setup_server = staticmethod(setup_server)
def test_Routes_Dispatch(self):
- self.getPage("/hounslow")
- self.assertStatus("200 OK")
- self.assertBody("Welcome to Hounslow, pop. 10000")
-
- self.getPage("/foo")
- self.assertStatus("404 Not Found")
-
- self.getPage("/surbiton")
- self.assertStatus("200 OK")
- self.assertBody("Welcome to Surbiton, pop. 10000")
-
- self.getPage("/surbiton", method="POST", body="pop=1327")
- self.assertStatus("200 OK")
- self.assertBody("OK")
- self.getPage("/surbiton")
- self.assertStatus("200 OK")
- self.assertHeader("Content-Language", "en-GB")
- self.assertBody("Welcome to Surbiton, pop. 1327")
+ """Check that routes package based URI dispatching works correctly."""
+ self.getPage('/hounslow')
+ self.assertStatus('200 OK')
+ self.assertBody('Welcome to Hounslow, pop. 10000')
+
+ self.getPage('/foo')
+ self.assertStatus('404 Not Found')
+
+ self.getPage('/surbiton')
+ self.assertStatus('200 OK')
+ self.assertBody('Welcome to Surbiton, pop. 10000')
+
+ self.getPage('/surbiton', method='POST', body='pop=1327')
+ self.assertStatus('200 OK')
+ self.assertBody('OK')
+ self.getPage('/surbiton')
+ self.assertStatus('200 OK')
+ self.assertHeader('Content-Language', 'en-GB')
+ self.assertBody('Welcome to Surbiton, pop. 1327')
diff --git a/cherrypy/test/test_session.py b/cherrypy/test/test_session.py
index 4bea7f6f..0083c97c 100755
--- a/cherrypy/test/test_session.py
+++ b/cherrypy/test/test_session.py
@@ -1,130 +1,144 @@
import os
-localDir = os.path.dirname(__file__)
import threading
import time
+import socket
+import importlib
+
+from six.moves.http_client import HTTPConnection
+
+import pytest
+from path import Path
import cherrypy
-from cherrypy._cpcompat import copykeys, HTTPConnection, HTTPSConnection
+from cherrypy._cpcompat import (
+ json_decode,
+ HTTPSConnection,
+)
from cherrypy.lib import sessions
+from cherrypy.lib import reprconf
from cherrypy.lib.httputil import response_codes
+from cherrypy.test import helper
+
+localDir = os.path.dirname(__file__)
def http_methods_allowed(methods=['GET', 'HEAD']):
method = cherrypy.request.method.upper()
if method not in methods:
- cherrypy.response.headers['Allow'] = ", ".join(methods)
+ cherrypy.response.headers['Allow'] = ', '.join(methods)
raise cherrypy.HTTPError(405)
+
cherrypy.tools.allow = cherrypy.Tool('on_start_resource', http_methods_allowed)
def setup_server():
+ @cherrypy.config(**{
+ 'tools.sessions.on': True,
+ 'tools.sessions.storage_class': sessions.RamSession,
+ 'tools.sessions.storage_path': localDir,
+ 'tools.sessions.timeout': (1.0 / 60),
+ 'tools.sessions.clean_freq': (1.0 / 60),
+ })
class Root:
- _cp_config = {'tools.sessions.on': True,
- 'tools.sessions.storage_type': 'ram',
- 'tools.sessions.storage_path': localDir,
- 'tools.sessions.timeout': (1.0 / 60),
- 'tools.sessions.clean_freq': (1.0 / 60),
- }
-
+ @cherrypy.expose
def clear(self):
cherrypy.session.cache.clear()
- clear.exposed = True
+ @cherrypy.expose
def data(self):
cherrypy.session['aha'] = 'foo'
return repr(cherrypy.session._data)
- data.exposed = True
+ @cherrypy.expose
def testGen(self):
counter = cherrypy.session.get('counter', 0) + 1
cherrypy.session['counter'] = counter
yield str(counter)
- testGen.exposed = True
+ @cherrypy.expose
def testStr(self):
counter = cherrypy.session.get('counter', 0) + 1
cherrypy.session['counter'] = counter
return str(counter)
- testStr.exposed = True
- def setsessiontype(self, newtype):
- self.__class__._cp_config.update(
- {'tools.sessions.storage_type': newtype})
- if hasattr(cherrypy, "session"):
+ @cherrypy.expose
+ @cherrypy.config(**{'tools.sessions.on': False})
+ def set_session_cls(self, new_cls_name):
+ new_cls = reprconf.attributes(new_cls_name)
+ cfg = {'tools.sessions.storage_class': new_cls}
+ self.__class__._cp_config.update(cfg)
+ if hasattr(cherrypy, 'session'):
del cherrypy.session
- cls = getattr(sessions, newtype.title() + 'Session')
- if cls.clean_thread:
- cls.clean_thread.stop()
- cls.clean_thread.unsubscribe()
- del cls.clean_thread
- setsessiontype.exposed = True
- setsessiontype._cp_config = {'tools.sessions.on': False}
+ if new_cls.clean_thread:
+ new_cls.clean_thread.stop()
+ new_cls.clean_thread.unsubscribe()
+ del new_cls.clean_thread
+ @cherrypy.expose
def index(self):
sess = cherrypy.session
c = sess.get('counter', 0) + 1
time.sleep(0.01)
sess['counter'] = c
return str(c)
- index.exposed = True
+ @cherrypy.expose
def keyin(self, key):
return str(key in cherrypy.session)
- keyin.exposed = True
+ @cherrypy.expose
def delete(self):
cherrypy.session.delete()
sessions.expire()
- return "done"
- delete.exposed = True
+ return 'done'
+ @cherrypy.expose
def delkey(self, key):
del cherrypy.session[key]
- return "OK"
- delkey.exposed = True
+ return 'OK'
- def blah(self):
- return self._cp_config['tools.sessions.storage_type']
- blah.exposed = True
+ @cherrypy.expose
+ def redir_target(self):
+ return self._cp_config['tools.sessions.storage_class'].__name__
+ @cherrypy.expose
def iredir(self):
- raise cherrypy.InternalRedirect('/blah')
- iredir.exposed = True
+ raise cherrypy.InternalRedirect('/redir_target')
+ @cherrypy.expose
+ @cherrypy.config(**{
+ 'tools.allow.on': True,
+ 'tools.allow.methods': ['GET'],
+ })
def restricted(self):
return cherrypy.request.method
- restricted.exposed = True
- restricted._cp_config = {'tools.allow.on': True,
- 'tools.allow.methods': ['GET']}
+ @cherrypy.expose
def regen(self):
cherrypy.tools.sessions.regenerate()
- return "logged in"
- regen.exposed = True
+ return 'logged in'
+ @cherrypy.expose
def length(self):
return str(len(cherrypy.session))
- length.exposed = True
+ @cherrypy.expose
+ @cherrypy.config(**{
+ 'tools.sessions.path': '/session_cookie',
+ 'tools.sessions.name': 'temp',
+ 'tools.sessions.persistent': False,
+ })
def session_cookie(self):
# Must load() to start the clean thread.
cherrypy.session.load()
return cherrypy.session.id
- session_cookie.exposed = True
- session_cookie._cp_config = {
- 'tools.sessions.path': '/session_cookie',
- 'tools.sessions.name': 'temp',
- 'tools.sessions.persistent': False}
cherrypy.tree.mount(Root())
-from cherrypy.test import helper
-
-
class SessionTest(helper.CPWebCase):
setup_server = staticmethod(setup_server)
@@ -132,10 +146,12 @@ class SessionTest(helper.CPWebCase):
# Clean up sessions.
for fname in os.listdir(localDir):
if fname.startswith(sessions.FileSession.SESSION_PREFIX):
- os.unlink(os.path.join(localDir, fname))
+ path = Path(localDir) / fname
+ path.remove_p()
+ @pytest.mark.xfail(reason='#1534')
def test_0_Session(self):
- self.getPage('/setsessiontype/ram')
+ self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
self.getPage('/clear')
# Test that a normal request gets the same id in the cookies.
@@ -149,7 +165,7 @@ class SessionTest(helper.CPWebCase):
self.getPage('/testStr')
self.assertBody('1')
cookie_parts = dict([p.strip().split('=')
- for p in self.cookies[0][1].split(";")])
+ for p in self.cookies[0][1].split(';')])
# Assert there is an 'expires' param
self.assertEqual(set(cookie_parts.keys()),
set(['session_id', 'expires', 'Path']))
@@ -158,13 +174,14 @@ class SessionTest(helper.CPWebCase):
self.getPage('/testStr', self.cookies)
self.assertBody('3')
self.getPage('/data', self.cookies)
- self.assertBody("{'aha': 'foo', 'counter': 3}")
+ self.assertDictEqual(json_decode(self.body),
+ {'counter': 3, 'aha': 'foo'})
self.getPage('/length', self.cookies)
self.assertBody('2')
self.getPage('/delkey?key=counter', self.cookies)
self.assertStatus(200)
- self.getPage('/setsessiontype/file')
+ self.getPage('/set_session_cls/cherrypy.lib.sessions.FileSession')
self.getPage('/testStr')
self.assertBody('1')
self.getPage('/testGen', self.cookies)
@@ -183,7 +200,7 @@ class SessionTest(helper.CPWebCase):
# Test session __contains__
self.getPage('/keyin?key=counter', self.cookies)
- self.assertBody("True")
+ self.assertBody('True')
cookieset1 = self.cookies
# Make a new session and test __len__ again
@@ -193,27 +210,31 @@ class SessionTest(helper.CPWebCase):
# Test session delete
self.getPage('/delete', self.cookies)
- self.assertBody("done")
+ self.assertBody('done')
self.getPage('/delete', cookieset1)
- self.assertBody("done")
- f = lambda: [
- x for x in os.listdir(localDir) if x.startswith('session-')]
+ self.assertBody('done')
+
+ def f():
+ return [
+ x
+ for x in os.listdir(localDir)
+ if x.startswith('session-')
+ ]
self.assertEqual(f(), [])
# Wait for the cleanup thread to delete remaining session files
self.getPage('/')
- f = lambda: [
- x for x in os.listdir(localDir) if x.startswith('session-')]
self.assertNotEqual(f(), [])
time.sleep(2)
self.assertEqual(f(), [])
def test_1_Ram_Concurrency(self):
- self.getPage('/setsessiontype/ram')
+ self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
self._test_Concurrency()
+ @pytest.mark.xfail(reason='#1306')
def test_2_File_Concurrency(self):
- self.getPage('/setsessiontype/file')
+ self.getPage('/set_session_cls/cherrypy.lib.sessions.FileSession')
self._test_Concurrency()
def _test_Concurrency(self):
@@ -221,8 +242,8 @@ class SessionTest(helper.CPWebCase):
request_count = 30
# Get initial cookie
- self.getPage("/")
- self.assertBody("1")
+ self.getPage('/')
+ self.assertBody('1')
cookies = self.cookies
data_dict = {}
@@ -245,7 +266,7 @@ class SessionTest(helper.CPWebCase):
else:
data_dict[index] = max(data_dict[index], int(body))
# Uncomment the following line to prove threads overlap.
-## sys.stdout.write("%d " % index)
+ # sys.stdout.write("%d " % index)
# Start <request_count> requests from each of
# <client_thread_count> concurrent clients
@@ -270,14 +291,14 @@ class SessionTest(helper.CPWebCase):
# Start a new session
self.getPage('/testStr')
self.getPage('/iredir', self.cookies)
- self.assertBody("file")
+ self.assertBody('FileSession')
def test_4_File_deletion(self):
# Start a new session
self.getPage('/testStr')
# Delete the session file manually and retry.
- id = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1]
- path = os.path.join(localDir, "session-" + id)
+ id = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
+ path = os.path.join(localDir, 'session-' + id)
os.unlink(path)
self.getPage('/testStr', self.cookies)
@@ -296,50 +317,50 @@ class SessionTest(helper.CPWebCase):
def test_6_regenerate(self):
self.getPage('/testStr')
# grab the cookie ID
- id1 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1]
+ id1 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
self.getPage('/regen')
self.assertBody('logged in')
- id2 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1]
+ id2 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
self.assertNotEqual(id1, id2)
self.getPage('/testStr')
# grab the cookie ID
- id1 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1]
+ id1 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
self.getPage('/testStr',
headers=[
('Cookie',
'session_id=maliciousid; '
'expires=Sat, 27 Oct 2017 04:18:28 GMT; Path=/;')])
- id2 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1]
+ id2 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
self.assertNotEqual(id1, id2)
self.assertNotEqual(id2, 'maliciousid')
def test_7_session_cookies(self):
- self.getPage('/setsessiontype/ram')
+ self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
self.getPage('/clear')
self.getPage('/session_cookie')
# grab the cookie ID
cookie_parts = dict([p.strip().split('=')
- for p in self.cookies[0][1].split(";")])
+ for p in self.cookies[0][1].split(';')])
# Assert there is no 'expires' param
self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
id1 = cookie_parts['temp']
- self.assertEqual(copykeys(sessions.RamSession.cache), [id1])
+ self.assertEqual(list(sessions.RamSession.cache), [id1])
# Send another request in the same "browser session".
self.getPage('/session_cookie', self.cookies)
cookie_parts = dict([p.strip().split('=')
- for p in self.cookies[0][1].split(";")])
+ for p in self.cookies[0][1].split(';')])
# Assert there is no 'expires' param
self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
self.assertBody(id1)
- self.assertEqual(copykeys(sessions.RamSession.cache), [id1])
+ self.assertEqual(list(sessions.RamSession.cache), [id1])
# Simulate a browser close by just not sending the cookies
self.getPage('/session_cookie')
# grab the cookie ID
cookie_parts = dict([p.strip().split('=')
- for p in self.cookies[0][1].split(";")])
+ for p in self.cookies[0][1].split(';')])
# Assert there is no 'expires' param
self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
# Assert a new id has been generated...
@@ -350,12 +371,12 @@ class SessionTest(helper.CPWebCase):
# Wait for the session.timeout on both sessions
time.sleep(2.5)
- cache = copykeys(sessions.RamSession.cache)
+ cache = list(sessions.RamSession.cache)
if cache:
if cache == [id2]:
- self.fail("The second session did not time out.")
+ self.fail('The second session did not time out.')
else:
- self.fail("Unknown session id in cache: %r", cache)
+ self.fail('Unknown session id in cache: %r', cache)
def test_8_Ram_Cleanup(self):
def lock():
@@ -366,15 +387,19 @@ class SessionTest(helper.CPWebCase):
t = threading.Thread(target=lock)
t.start()
+ start = time.time()
+ while not sessions.RamSession.locks and time.time() - start < 5:
+ time.sleep(0.01)
+ assert len(sessions.RamSession.locks) == 1, 'Lock not acquired'
s2 = sessions.RamSession()
s2.clean_up()
- self.assertEqual(len(sessions.RamSession.locks), 1, 'Clean up should not remove active lock')
+ msg = 'Clean up should not remove active lock'
+ assert len(sessions.RamSession.locks) == 1, msg
t.join()
-import socket
try:
- import memcache # NOQA
+ importlib.import_module('memcache')
host, port = '127.0.0.1', 11211
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
@@ -398,13 +423,13 @@ except (ImportError, socket.error):
setup_server = staticmethod(setup_server)
def test(self):
- return self.skip("memcached not reachable ")
+ return self.skip('memcached not reachable ')
else:
class MemcachedSessionTest(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def test_0_Session(self):
- self.getPage('/setsessiontype/memcached')
+ self.getPage('/set_session_cls/cherrypy.Sessions.MemcachedSession')
self.getPage('/testStr')
self.assertBody('1')
@@ -414,7 +439,7 @@ else:
self.assertBody('3')
self.getPage('/length', self.cookies)
self.assertErrorPage(500)
- self.assertInBody("NotImplementedError")
+ self.assertInBody('NotImplementedError')
self.getPage('/delkey?key=counter', self.cookies)
self.assertStatus(200)
@@ -425,28 +450,28 @@ else:
# Test session __contains__
self.getPage('/keyin?key=counter', self.cookies)
- self.assertBody("True")
+ self.assertBody('True')
# Test session delete
self.getPage('/delete', self.cookies)
- self.assertBody("done")
+ self.assertBody('done')
def test_1_Concurrency(self):
client_thread_count = 5
request_count = 30
# Get initial cookie
- self.getPage("/")
- self.assertBody("1")
+ self.getPage('/')
+ self.assertBody('1')
cookies = self.cookies
data_dict = {}
def request(index):
for i in range(request_count):
- self.getPage("/", cookies)
+ self.getPage('/', cookies)
# Uncomment the following line to prove threads overlap.
-## sys.stdout.write("%d " % index)
+ # sys.stdout.write("%d " % index)
if not self.body.isdigit():
self.fail(self.body)
data_dict[index] = int(self.body)
@@ -471,7 +496,7 @@ else:
# Start a new session
self.getPage('/testStr')
self.getPage('/iredir', self.cookies)
- self.assertBody("memcached")
+ self.assertBody('memcached')
def test_5_Error_paths(self):
self.getPage('/unknown/page')
diff --git a/cherrypy/test/test_sessionauthenticate.py b/cherrypy/test/test_sessionauthenticate.py
index 2a6aa8d0..63053fcb 100644
--- a/cherrypy/test/test_sessionauthenticate.py
+++ b/cherrypy/test/test_sessionauthenticate.py
@@ -4,6 +4,7 @@ from cherrypy.test import helper
class SessionAuthenticateTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
def check(username, password):
@@ -15,7 +16,7 @@ class SessionAuthenticateTest(helper.CPWebCase):
# A simple tool to add some things to request.params
# This is to check to make sure that session_auth can handle
# request params (ticket #780)
- cherrypy.request.params["test"] = "test"
+ cherrypy.request.params['test'] = 'test'
cherrypy.tools.augment_params = cherrypy.Tool(
'before_handler', augment_params, None, priority=30)
@@ -29,12 +30,11 @@ class SessionAuthenticateTest(helper.CPWebCase):
'tools.augment_params.on': True,
}
+ @cherrypy.expose
def index(self, **kwargs):
- return "Hi %s, you are logged in" % cherrypy.request.login
- index.exposed = True
+ return 'Hi %s, you are logged in' % cherrypy.request.login
cherrypy.tree.mount(Test())
- setup_server = staticmethod(setup_server)
def testSessionAuthenticate(self):
# request a page and check for login form
diff --git a/cherrypy/test/test_states.py b/cherrypy/test/test_states.py
index dc6891bc..09a5ec7e 100644
--- a/cherrypy/test/test_states.py
+++ b/cherrypy/test/test_states.py
@@ -1,14 +1,16 @@
import os
import signal
-import socket
-import sys
import time
import unittest
import warnings
+from six.moves.http_client import BadStatusLine
+
+import pytest
+import portend
+
import cherrypy
import cherrypy.process.servers
-from cherrypy._cpcompat import BadStatusLine, ntob
from cherrypy.test import helper
engine = cherrypy.engine
@@ -47,42 +49,29 @@ class Dependency:
def stopthread(self, thread_id):
del self.threads[thread_id]
+
db_connection = Dependency(engine)
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "Hello World"
- index.exposed = True
+ return 'Hello World'
+ @cherrypy.expose
def ctrlc(self):
raise KeyboardInterrupt()
- ctrlc.exposed = True
+ @cherrypy.expose
def graceful(self):
engine.graceful()
- return "app was (gracefully) restarted succesfully"
- graceful.exposed = True
-
- def block_explicit(self):
- while True:
- if cherrypy.response.timed_out:
- cherrypy.response.timed_out = False
- return "broken!"
- time.sleep(0.01)
- block_explicit.exposed = True
-
- def block_implicit(self):
- time.sleep(0.5)
- return "response.timeout = %s" % cherrypy.response.timeout
- block_implicit.exposed = True
+ return 'app was (gracefully) restarted succesfully'
cherrypy.tree.mount(Root())
cherrypy.config.update({
'environment': 'test_suite',
- 'engine.deadlock_poll_freq': 0.1,
})
db_connection.subscribe()
@@ -110,15 +99,15 @@ class ServerStateTests(helper.CPWebCase):
host = cherrypy.server.socket_host
port = cherrypy.server.socket_port
- self.assertRaises(IOError, cherrypy._cpserver.check_port, host, port)
+ portend.occupied(host, port, timeout=0.1)
# The db_connection should be running now
self.assertEqual(db_connection.running, True)
self.assertEqual(db_connection.startcount, 2)
self.assertEqual(len(db_connection.threads), 0)
- self.getPage("/")
- self.assertBody("Hello World")
+ self.getPage('/')
+ self.assertBody('Hello World')
self.assertEqual(len(db_connection.threads), 1)
# Test engine stop. This will also stop the HTTP server.
@@ -131,8 +120,8 @@ class ServerStateTests(helper.CPWebCase):
# Block the main thread now and verify that exit() works.
def exittest():
- self.getPage("/")
- self.assertBody("Hello World")
+ self.getPage('/')
+ self.assertBody('Hello World')
engine.exit()
cherrypy.server.start()
engine.start_with_callback(exittest)
@@ -147,23 +136,23 @@ class ServerStateTests(helper.CPWebCase):
self.assertEqual(db_connection.running, True)
grace = db_connection.gracecount
- self.getPage("/")
- self.assertBody("Hello World")
+ self.getPage('/')
+ self.assertBody('Hello World')
self.assertEqual(len(db_connection.threads), 1)
# Test server restart from this thread
engine.graceful()
self.assertEqual(engine.state, engine.states.STARTED)
- self.getPage("/")
- self.assertBody("Hello World")
+ self.getPage('/')
+ self.assertBody('Hello World')
self.assertEqual(db_connection.running, True)
self.assertEqual(db_connection.gracecount, grace + 1)
self.assertEqual(len(db_connection.threads), 1)
# Test server restart from inside a page handler
- self.getPage("/graceful")
+ self.getPage('/graceful')
self.assertEqual(engine.state, engine.states.STARTED)
- self.assertBody("app was (gracefully) restarted succesfully")
+ self.assertBody('app was (gracefully) restarted succesfully')
self.assertEqual(db_connection.running, True)
self.assertEqual(db_connection.gracecount, grace + 2)
# Since we are requesting synchronously, is only one thread used?
@@ -184,10 +173,10 @@ class ServerStateTests(helper.CPWebCase):
self.persistent = True
try:
# Make the first request and assert there's no "Connection: close".
- self.getPage("/")
+ self.getPage('/')
self.assertStatus('200 OK')
- self.assertBody("Hello World")
- self.assertNoHeader("Connection")
+ self.assertBody('Hello World')
+ self.assertNoHeader('Connection')
cherrypy.server.httpserver.interrupt = KeyboardInterrupt
engine.block()
@@ -222,48 +211,17 @@ class ServerStateTests(helper.CPWebCase):
# sideffects. python < 3.5 will raise directly BadStatusLine
# which is not a subclass for socket.error/OSError.
try:
- self.getPage("/ctrlc", raise_subcls=BadStatusLine)
+ self.getPage('/ctrlc', raise_subcls=BadStatusLine)
except BadStatusLine:
pass
else:
print(self.body)
- self.fail("AssertionError: BadStatusLine not raised")
+ self.fail('AssertionError: BadStatusLine not raised')
engine.block()
self.assertEqual(db_connection.running, False)
self.assertEqual(len(db_connection.threads), 0)
- def test_3_Deadlocks(self):
- cherrypy.config.update({'response.timeout': 0.2})
-
- engine.start()
- cherrypy.server.start()
- try:
- self.assertNotEqual(engine.timeout_monitor.thread, None)
-
- # Request a "normal" page.
- self.assertEqual(engine.timeout_monitor.servings, [])
- self.getPage("/")
- self.assertBody("Hello World")
- # request.close is called async.
- while engine.timeout_monitor.servings:
- sys.stdout.write(".")
- time.sleep(0.01)
-
- # Request a page that explicitly checks itself for deadlock.
- # The deadlock_timeout should be 2 secs.
- self.getPage("/block_explicit")
- self.assertBody("broken!")
-
- # Request a page that implicitly breaks deadlock.
- # If we deadlock, we want to touch as little code as possible,
- # so we won't even call handle_error, just bail ASAP.
- self.getPage("/block_implicit")
- self.assertStatus(500)
- self.assertInBody("raise cherrypy.TimeoutError()")
- finally:
- engine.exit()
-
def test_4_Autoreload(self):
# If test_3 has not been executed, the server won't be stopped,
# so we'll have to do it.
@@ -275,28 +233,28 @@ class ServerStateTests(helper.CPWebCase):
p.write_conf(extra='test_case_name: "test_4_Autoreload"')
p.start(imports='cherrypy.test._test_states_demo')
try:
- self.getPage("/start")
+ self.getPage('/start')
start = float(self.body)
# Give the autoreloader time to cache the file time.
time.sleep(2)
# Touch the file
- os.utime(os.path.join(thisdir, "_test_states_demo.py"), None)
+ os.utime(os.path.join(thisdir, '_test_states_demo.py'), None)
# Give the autoreloader time to re-exec the process
time.sleep(2)
host = cherrypy.server.socket_host
port = cherrypy.server.socket_port
- cherrypy._cpserver.wait_for_occupied_port(host, port)
+ portend.occupied(host, port, timeout=5)
- self.getPage("/start")
+ self.getPage('/start')
if not (float(self.body) > start):
- raise AssertionError("start time %s not greater than %s" %
+ raise AssertionError('start time %s not greater than %s' %
(float(self.body), start))
finally:
# Shut down the spawned process
- self.getPage("/exit")
+ self.getPage('/exit')
p.join()
def test_5_Start_Error(self):
@@ -316,14 +274,14 @@ test_case_name: "test_5_Start_Error"
)
p.start(imports='cherrypy.test._test_states_demo')
if p.exit_code == 0:
- self.fail("Process failed to return nonzero exit code.")
+ self.fail('Process failed to return nonzero exit code.')
class PluginTests(helper.CPWebCase):
def test_daemonize(self):
if os.name not in ['posix']:
- return self.skip("skipped (not on posix) ")
+ return self.skip('skipped (not on posix) ')
self.HOST = '127.0.0.1'
self.PORT = 8081
# Spawn the process and wait, when this returns, the original process
@@ -338,19 +296,19 @@ class PluginTests(helper.CPWebCase):
p.start(imports='cherrypy.test._test_states_demo')
try:
# Just get the pid of the daemonization process.
- self.getPage("/pid")
+ self.getPage('/pid')
self.assertStatus(200)
page_pid = int(self.body)
self.assertEqual(page_pid, p.get_pid())
finally:
# Shut down the spawned process
- self.getPage("/exit")
+ self.getPage('/exit')
p.join()
# Wait until here to test the exit code because we want to ensure
# that we wait for the daemon to finish running before we fail.
if p.exit_code != 0:
- self.fail("Daemonized parent process failed to exit cleanly.")
+ self.fail('Daemonized parent process failed to exit cleanly.')
class SignalHandlingTests(helper.CPWebCase):
@@ -360,7 +318,7 @@ class SignalHandlingTests(helper.CPWebCase):
try:
from signal import SIGHUP
except ImportError:
- return self.skip("skipped (no SIGHUP) ")
+ return self.skip('skipped (no SIGHUP) ')
# Spawn the process.
p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
@@ -377,10 +335,10 @@ class SignalHandlingTests(helper.CPWebCase):
try:
from signal import SIGHUP
except ImportError:
- return self.skip("skipped (no SIGHUP) ")
+ return self.skip('skipped (no SIGHUP) ')
if os.name not in ['posix']:
- return self.skip("skipped (not on posix) ")
+ return self.skip('skipped (not on posix) ')
# Spawn the process and wait, when this returns, the original process
# is finished. If it daemonized properly, we should still be able
@@ -397,24 +355,24 @@ class SignalHandlingTests(helper.CPWebCase):
os.kill(pid, SIGHUP)
# Give the server some time to restart
time.sleep(2)
- self.getPage("/pid")
+ self.getPage('/pid')
self.assertStatus(200)
new_pid = int(self.body)
self.assertNotEqual(new_pid, pid)
finally:
# Shut down the spawned process
- self.getPage("/exit")
+ self.getPage('/exit')
p.join()
def _require_signal_and_kill(self, signal_name):
if not hasattr(signal, signal_name):
- self.skip("skipped (no %(signal_name)s)" % vars())
+ self.skip('skipped (no %(signal_name)s)' % vars())
if not hasattr(os, 'kill'):
- self.skip("skipped (no os.kill)")
+ self.skip('skipped (no os.kill)')
def test_SIGTERM(self):
- "SIGTERM should shut down the server whether daemonized or not."
+ 'SIGTERM should shut down the server whether daemonized or not.'
self._require_signal_and_kill('SIGTERM')
# Spawn a normal, undaemonized process.
@@ -447,7 +405,7 @@ class SignalHandlingTests(helper.CPWebCase):
# will result in a forced termination of the process.
# Therefore, this test is not suitable for Windows.
if os.name == 'nt':
- self.skip("SIGTERM not available")
+ self.skip('SIGTERM not available')
# Spawn a normal, undaemonized process.
p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
@@ -462,14 +420,16 @@ test_case_name: "test_signal_handler_unsubscribe"
p.join()
# Assert the old handler ran.
- target_line = open(p.error_log, 'rb').readlines()[-10]
- if not ntob("I am an old SIGTERM handler.") in target_line:
- self.fail("Old SIGTERM handler did not run.\n%r" % target_line)
+ log_lines = list(open(p.error_log, 'rb'))
+ assert any(
+ line.endswith(b'I am an old SIGTERM handler.\n')
+ for line in log_lines
+ )
class WaitTests(unittest.TestCase):
- def test_wait_for_occupied_port_INADDR_ANY(self):
+ def test_safe_wait_INADDR_ANY(self):
"""
Wait on INADDR_ANY should not raise IOError
@@ -485,43 +445,23 @@ class WaitTests(unittest.TestCase):
# Simulate the behavior we observe when no loopback interface is
# present by: finding a port that's not occupied, then wait on it.
- free_port = self.find_free_port()
+ free_port = portend.find_available_local_port()
servers = cherrypy.process.servers
- def with_shorter_timeouts(func):
- """
- A context where occupied_port_timeout is much smaller to speed
- test runs.
- """
- # When we have Python 2.5, simplify using the with_statement.
- orig_timeout = servers.occupied_port_timeout
- servers.occupied_port_timeout = .07
- try:
- func()
- finally:
- servers.occupied_port_timeout = orig_timeout
-
- def do_waiting():
- # Wait on the free port that's unbound
- with warnings.catch_warnings(record=True) as w:
- servers.wait_for_occupied_port('0.0.0.0', free_port)
- self.assertEqual(len(w), 1)
- self.assertTrue(isinstance(w[0], warnings.WarningMessage))
- self.assertTrue(
- 'Unable to verify that the server is bound on ' in str(w[0]))
-
- # The wait should still raise an IO error if INADDR_ANY was
- # not supplied.
- self.assertRaises(IOError, servers.wait_for_occupied_port,
- '127.0.0.1', free_port)
-
- with_shorter_timeouts(do_waiting)
-
- def find_free_port(self):
- "Find a free port by binding to port 0 then unbinding."
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.bind(('', 0))
- free_port = sock.getsockname()[1]
- sock.close()
- return free_port
+ inaddr_any = '0.0.0.0'
+
+ # Wait on the free port that's unbound
+ with warnings.catch_warnings(record=True) as w:
+ with servers._safe_wait(inaddr_any, free_port):
+ portend.occupied(inaddr_any, free_port, timeout=1)
+ self.assertEqual(len(w), 1)
+ self.assertTrue(isinstance(w[0], warnings.WarningMessage))
+ self.assertTrue(
+ 'Unable to verify that the server is bound on ' in str(w[0]))
+
+ # The wait should still raise an IO error if INADDR_ANY was
+ # not supplied.
+ with pytest.raises(IOError):
+ with servers._safe_wait('127.0.0.1', free_port):
+ portend.occupied('127.0.0.1', free_port, timeout=1)
diff --git a/cherrypy/test/test_static.py b/cherrypy/test/test_static.py
index 70412c90..5dc5a144 100644
--- a/cherrypy/test/test_static.py
+++ b/cherrypy/test/test_static.py
@@ -1,66 +1,106 @@
+# -*- coding: utf-8 -*-
+import contextlib
+import io
import os
import sys
+import platform
+import tempfile
+
+from six import text_type as str
+from six.moves import urllib
+from six.moves.http_client import HTTPConnection
+
+import pytest
+import py.path
+
+import cherrypy
+from cherrypy.lib import static
+from cherrypy._cpcompat import HTTPSConnection, ntou, tonative
+from cherrypy.test import helper
+
+
+@pytest.fixture
+def unicode_filesystem(tmpdir):
+ filename = tmpdir / ntou('☃', 'utf-8')
+ tmpl = 'File system encoding ({encoding}) cannot support unicode filenames'
+ msg = tmpl.format(encoding=sys.getfilesystemencoding())
+ try:
+ io.open(str(filename), 'w').close()
+ except UnicodeEncodeError:
+ pytest.skip(msg)
+
+
+def ensure_unicode_filesystem():
+ """
+ TODO: replace with simply pytest fixtures once webtest.TestCase
+ no longer implies unittest.
+ """
+ tmpdir = py.path.local(tempfile.mkdtemp())
+ try:
+ unicode_filesystem(tmpdir)
+ finally:
+ tmpdir.remove()
-from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob
-from cherrypy._cpcompat import BytesIO
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
has_space_filepath = os.path.join(curdir, 'static', 'has space.html')
-bigfile_filepath = os.path.join(curdir, "static", "bigfile.log")
+bigfile_filepath = os.path.join(curdir, 'static', 'bigfile.log')
# The file size needs to be big enough such that half the size of it
# won't be socket-buffered (or server-buffered) all in one go. See
# test_file_stream.
-BIGFILE_SIZE = 1024 * 1024 * 20
-
-import cherrypy
-from cherrypy.lib import static
-from cherrypy.test import helper
+MB = 2 ** 20
+BIGFILE_SIZE = 32 * MB
class StaticTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
if not os.path.exists(has_space_filepath):
- open(has_space_filepath, 'wb').write(ntob('Hello, world\r\n'))
- if not os.path.exists(bigfile_filepath) or \
- os.path.getsize(bigfile_filepath) != BIGFILE_SIZE:
- open(bigfile_filepath, 'wb').write(ntob("x" * BIGFILE_SIZE))
+ with open(has_space_filepath, 'wb') as f:
+ f.write(b'Hello, world\r\n')
+ needs_bigfile = (
+ not os.path.exists(bigfile_filepath) or
+ os.path.getsize(bigfile_filepath) != BIGFILE_SIZE
+ )
+ if needs_bigfile:
+ with open(bigfile_filepath, 'wb') as f:
+ f.write(b'x' * BIGFILE_SIZE)
class Root:
+ @cherrypy.expose
+ @cherrypy.config(**{'response.stream': True})
def bigfile(self):
- from cherrypy.lib import static
self.f = static.serve_file(bigfile_filepath)
return self.f
- bigfile.exposed = True
- bigfile._cp_config = {'response.stream': True}
+ @cherrypy.expose
def tell(self):
if self.f.input.closed:
return ''
return repr(self.f.input.tell()).rstrip('L')
- tell.exposed = True
+ @cherrypy.expose
def fileobj(self):
f = open(os.path.join(curdir, 'style.css'), 'rb')
return static.serve_fileobj(f, content_type='text/css')
- fileobj.exposed = True
+ @cherrypy.expose
def bytesio(self):
- f = BytesIO(ntob('Fee\nfie\nfo\nfum'))
+ f = io.BytesIO(b'Fee\nfie\nfo\nfum')
return static.serve_fileobj(f, content_type='text/plain')
- bytesio.exposed = True
class Static:
+ @cherrypy.expose
def index(self):
return 'You want the Baron? You can have the Baron!'
- index.exposed = True
+ @cherrypy.expose
def dynamic(self):
- return "This is a DYNAMIC page"
- dynamic.exposed = True
+ return 'This is a DYNAMIC page'
root = Root()
root.static = Static()
@@ -71,6 +111,10 @@ class StaticTest(helper.CPWebCase):
'tools.staticdir.dir': 'static',
'tools.staticdir.root': curdir,
},
+ '/static-long': {
+ 'tools.staticdir.on': True,
+ 'tools.staticdir.dir': r'\\?\%s' % curdir,
+ },
'/style.css': {
'tools.staticfile.on': True,
'tools.staticfile.filename': os.path.join(curdir, 'style.css'),
@@ -108,36 +152,35 @@ class StaticTest(helper.CPWebCase):
vhost = cherrypy._cpwsgi.VirtualHost(rootApp, {'virt.net': testApp})
cherrypy.tree.graft(vhost)
- setup_server = staticmethod(setup_server)
+ @staticmethod
def teardown_server():
for f in (has_space_filepath, bigfile_filepath):
if os.path.exists(f):
try:
os.unlink(f)
- except:
+ except Exception:
pass
- teardown_server = staticmethod(teardown_server)
def test_static(self):
- self.getPage("/static/index.html")
+ self.getPage('/static/index.html')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html')
self.assertBody('Hello, world\r\n')
# Using a staticdir.root value in a subdir...
- self.getPage("/docroot/index.html")
+ self.getPage('/docroot/index.html')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html')
self.assertBody('Hello, world\r\n')
# Check a filename with spaces in it
- self.getPage("/static/has%20space.html")
+ self.getPage('/static/has%20space.html')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html')
self.assertBody('Hello, world\r\n')
- self.getPage("/style.css")
+ self.getPage('/style.css')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/css')
# Note: The body should be exactly 'Dummy stylesheet\n', but
@@ -146,100 +189,117 @@ class StaticTest(helper.CPWebCase):
# we just check the content
self.assertMatchesBody('^Dummy stylesheet')
+ @pytest.mark.skipif(platform.system() != 'Windows', reason='Windows only')
+ def test_static_longpath(self):
+ """Test serving of a file in subdir of a Windows long-path
+ staticdir."""
+ self.getPage('/static-long/static/index.html')
+ self.assertStatus('200 OK')
+ self.assertHeader('Content-Type', 'text/html')
+ self.assertBody('Hello, world\r\n')
+
def test_fallthrough(self):
# Test that NotFound will then try dynamic handlers (see [878]).
- self.getPage("/static/dynamic")
- self.assertBody("This is a DYNAMIC page")
+ self.getPage('/static/dynamic')
+ self.assertBody('This is a DYNAMIC page')
# Check a directory via fall-through to dynamic handler.
- self.getPage("/static/")
+ self.getPage('/static/')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
self.assertBody('You want the Baron? You can have the Baron!')
def test_index(self):
# Check a directory via "staticdir.index".
- self.getPage("/docroot/")
+ self.getPage('/docroot/')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html')
self.assertBody('Hello, world\r\n')
# The same page should be returned even if redirected.
- self.getPage("/docroot")
+ self.getPage('/docroot')
self.assertStatus(301)
self.assertHeader('Location', '%s/docroot/' % self.base())
- self.assertMatchesBody("This resource .* <a href=(['\"])%s/docroot/\\1>"
- "%s/docroot/</a>." % (self.base(), self.base()))
+ self.assertMatchesBody(
+ "This resource .* <a href=(['\"])%s/docroot/\\1>"
+ '%s/docroot/</a>.'
+ % (self.base(), self.base())
+ )
def test_config_errors(self):
# Check that we get an error if no .file or .dir
- self.getPage("/error/thing.html")
+ self.getPage('/error/thing.html')
self.assertErrorPage(500)
if sys.version_info >= (3, 3):
- errmsg = ntob("TypeError: staticdir\(\) missing 2 "
- "required positional arguments")
+ errmsg = (
+ r'TypeError: staticdir\(\) missing 2 '
+ 'required positional arguments'
+ )
else:
- errmsg = ntob("TypeError: staticdir\(\) takes at least 2 "
- "(positional )?arguments \(0 given\)")
- self.assertMatchesBody(errmsg)
+ errmsg = (
+ r'TypeError: staticdir\(\) takes at least 2 '
+ r'(positional )?arguments \(0 given\)'
+ )
+ self.assertMatchesBody(errmsg.encode('ascii'))
def test_security(self):
# Test up-level security
- self.getPage("/static/../../test/style.css")
+ self.getPage('/static/../../test/style.css')
self.assertStatus((400, 403))
def test_modif(self):
# Test modified-since on a reasonably-large file
- self.getPage("/static/dirback.jpg")
- self.assertStatus("200 OK")
- lastmod = ""
+ self.getPage('/static/dirback.jpg')
+ self.assertStatus('200 OK')
+ lastmod = ''
for k, v in self.headers:
if k == 'Last-Modified':
lastmod = v
- ims = ("If-Modified-Since", lastmod)
- self.getPage("/static/dirback.jpg", headers=[ims])
+ ims = ('If-Modified-Since', lastmod)
+ self.getPage('/static/dirback.jpg', headers=[ims])
self.assertStatus(304)
- self.assertNoHeader("Content-Type")
- self.assertNoHeader("Content-Length")
- self.assertNoHeader("Content-Disposition")
- self.assertBody("")
+ self.assertNoHeader('Content-Type')
+ self.assertNoHeader('Content-Length')
+ self.assertNoHeader('Content-Disposition')
+ self.assertBody('')
def test_755_vhost(self):
- self.getPage("/test/", [('Host', 'virt.net')])
+ self.getPage('/test/', [('Host', 'virt.net')])
self.assertStatus(200)
- self.getPage("/test", [('Host', 'virt.net')])
+ self.getPage('/test', [('Host', 'virt.net')])
self.assertStatus(301)
self.assertHeader('Location', self.scheme + '://virt.net/test/')
def test_serve_fileobj(self):
- self.getPage("/fileobj")
+ self.getPage('/fileobj')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/css;charset=utf-8')
self.assertMatchesBody('^Dummy stylesheet')
def test_serve_bytesio(self):
- self.getPage("/bytesio")
+ self.getPage('/bytesio')
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/plain;charset=utf-8')
self.assertHeader('Content-Length', 14)
self.assertMatchesBody('Fee\nfie\nfo\nfum')
+ @pytest.mark.xfail(reason='#1475')
def test_file_stream(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Make an initial request
self.persistent = True
conn = self.HTTP_CONN
- conn.putrequest("GET", "/bigfile", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/bigfile', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 200)
- body = ntob('')
+ body = b''
remaining = BIGFILE_SIZE
while remaining > 0:
data = response.fp.read(65536)
@@ -248,12 +308,12 @@ class StaticTest(helper.CPWebCase):
body += data
remaining -= len(data)
- if self.scheme == "https":
+ if self.scheme == 'https':
newconn = HTTPSConnection
else:
newconn = HTTPConnection
s, h, b = helper.webtest.openURL(
- ntob("/tell"), headers=[], host=self.HOST, port=self.PORT,
+ b'/tell', headers=[], host=self.HOST, port=self.PORT,
http_conn=newconn)
if not b:
# The file was closed on the server.
@@ -279,45 +339,45 @@ class StaticTest(helper.CPWebCase):
#
# At the time of writing, we seem to have encountered
# buffer sizes bigger than 512K, so we've increased
- # BIGFILE_SIZE to 4MB and in 2016 to 20MB.
+ # BIGFILE_SIZE to 4MB and in 2016 to 20MB and then 32MB.
# This test is going to keep failing according to the
# improvements in hardware and OS buffers.
if tell_position >= BIGFILE_SIZE:
if read_so_far < (BIGFILE_SIZE / 2):
self.fail(
- "The file should have advanced to position %r, but "
- "has already advanced to the end of the file. It "
- "may not be streamed as intended, or at the wrong "
- "chunk size (64k)" % read_so_far)
+ 'The file should have advanced to position %r, but '
+ 'has already advanced to the end of the file. It '
+ 'may not be streamed as intended, or at the wrong '
+ 'chunk size (64k)' % read_so_far)
elif tell_position < read_so_far:
self.fail(
- "The file should have advanced to position %r, but has "
- "only advanced to position %r. It may not be streamed "
- "as intended, or at the wrong chunk size (64k)" %
+ 'The file should have advanced to position %r, but has '
+ 'only advanced to position %r. It may not be streamed '
+ 'as intended, or at the wrong chunk size (64k)' %
(read_so_far, tell_position))
- if body != ntob("x" * BIGFILE_SIZE):
+ if body != b'x' * BIGFILE_SIZE:
self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." %
(BIGFILE_SIZE, body[:50], len(body)))
conn.close()
def test_file_stream_deadlock(self):
- if cherrypy.server.protocol_version != "HTTP/1.1":
+ if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
- self.PROTOCOL = "HTTP/1.1"
+ self.PROTOCOL = 'HTTP/1.1'
# Make an initial request but abort early.
self.persistent = True
conn = self.HTTP_CONN
- conn.putrequest("GET", "/bigfile", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/bigfile', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
- response = conn.response_class(conn.sock, method="GET")
+ response = conn.response_class(conn.sock, method='GET')
response.begin()
self.assertEqual(response.status, 200)
body = response.fp.read(65536)
- if body != ntob("x" * len(body)):
+ if body != b'x' * len(body):
self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." %
(65536, body[:50], len(body)))
response.close()
@@ -325,21 +385,50 @@ class StaticTest(helper.CPWebCase):
# Make a second request, which should fetch the whole file.
self.persistent = False
- self.getPage("/bigfile")
- if self.body != ntob("x" * BIGFILE_SIZE):
+ self.getPage('/bigfile')
+ if self.body != b'x' * BIGFILE_SIZE:
self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." %
(BIGFILE_SIZE, self.body[:50], len(body)))
def test_error_page_with_serve_file(self):
- self.getPage("/404test/yunyeen")
+ self.getPage('/404test/yunyeen')
self.assertStatus(404)
self.assertInBody("I couldn't find that thing")
def test_null_bytes(self):
- self.getPage("/static/\x00")
+ self.getPage('/static/\x00')
self.assertStatus('404 Not Found')
+ @staticmethod
+ @contextlib.contextmanager
+ def unicode_file():
+ filename = ntou('Слава Україні.html', 'utf-8')
+ filepath = os.path.join(curdir, 'static', filename)
+ with io.open(filepath, 'w', encoding='utf-8') as strm:
+ strm.write(ntou('Героям Слава!', 'utf-8'))
+ try:
+ yield
+ finally:
+ os.remove(filepath)
+
+ py27_on_windows = (
+ platform.system() == 'Windows' and
+ sys.version_info < (3,)
+ )
+ @pytest.mark.xfail(py27_on_windows, reason='#1544') # noqa: E301
+ def test_unicode(self):
+ ensure_unicode_filesystem()
+ with self.unicode_file():
+ url = ntou('/static/Слава Україні.html', 'utf-8')
+ # quote function requires str
+ url = tonative(url, 'utf-8')
+ url = urllib.parse.quote(url)
+ self.getPage(url)
+
+ expected = ntou('Героям Слава!', 'utf-8')
+ self.assertInBody(expected)
+
+
def error_page_404(status, message, traceback, version):
- import os.path
- return static.serve_file(os.path.join(curdir, 'static', '404.html'),
- content_type='text/html')
+ path = os.path.join(curdir, 'static', '404.html')
+ return static.serve_file(path, content_type='text/html')
diff --git a/cherrypy/test/test_tools.py b/cherrypy/test/test_tools.py
index 4fb1a555..4e7b83f1 100644
--- a/cherrypy/test/test_tools.py
+++ b/cherrypy/test/test_tools.py
@@ -1,36 +1,40 @@
"""Test the various means of instantiating and invoking tools."""
import gzip
+import io
import sys
-import unittest
-from cherrypy._cpcompat import BytesIO, copyitems, itervalues
-from cherrypy._cpcompat import IncompleteRead, ntob, ntou, py3k, xrange
-from cherrypy._cpcompat import bytestr, unicodestr
import time
-timeout = 0.2
import types
+import unittest
+import operator
+
+import six
+from six.moves import range, map
+from six.moves.http_client import IncompleteRead
import cherrypy
from cherrypy import tools
+from cherrypy._cpcompat import ntob, ntou
+from cherrypy.test import helper, _test_decorators
+timeout = 0.2
europoundUnicode = ntou('\x80\xa3')
# Client-side code #
-from cherrypy.test import helper
-
class ToolTests(helper.CPWebCase):
+ @staticmethod
def setup_server():
# Put check_access in a custom toolbox with its own namespace
- myauthtools = cherrypy._cptools.Toolbox("myauth")
+ myauthtools = cherrypy._cptools.Toolbox('myauth')
def check_access(default=False):
- if not getattr(cherrypy.request, "userid", default):
+ if not getattr(cherrypy.request, 'userid', default):
raise cherrypy.HTTPError(401)
myauthtools.check_access = cherrypy.Tool(
'before_request_body', check_access)
@@ -47,8 +51,8 @@ class ToolTests(helper.CPWebCase):
def _setup(self):
def makemap():
- m = self._merged_args().get("map", {})
- cherrypy.request.numerify_map = copyitems(m)
+ m = self._merged_args().get('map', {})
+ cherrypy.request.numerify_map = list(six.iteritems(m))
cherrypy.request.hooks.attach('on_start_resource', makemap)
def critical():
@@ -66,21 +70,21 @@ class ToolTests(helper.CPWebCase):
def __init__(self):
self.ended = {}
- self._name = "nadsat"
+ self._name = 'nadsat'
def nadsat(self):
def nadsat_it_up(body):
for chunk in body:
- chunk = chunk.replace(ntob("good"), ntob("horrorshow"))
- chunk = chunk.replace(ntob("piece"), ntob("lomtick"))
+ chunk = chunk.replace(ntob('good'), ntob('horrorshow'))
+ chunk = chunk.replace(ntob('piece'), ntob('lomtick'))
yield chunk
cherrypy.response.body = nadsat_it_up(cherrypy.response.body)
nadsat.priority = 0
def cleanup(self):
# This runs after the request has been completely written out.
- cherrypy.response.body = [ntob("razdrez")]
- id = cherrypy.request.params.get("id")
+ cherrypy.response.body = [ntob('razdrez')]
+ id = cherrypy.request.params.get('id')
if id:
self.ended[id] = True
cleanup.failsafe = True
@@ -101,17 +105,18 @@ class ToolTests(helper.CPWebCase):
def __call__(self, scale):
r = cherrypy.response
r.collapse_body()
- if py3k:
+ if six.PY3:
r.body = [bytes([(x + scale) % 256 for x in r.body[0]])]
else:
r.body = [chr((ord(x) + scale) % 256) for x in r.body[0]]
cherrypy.tools.rotator = cherrypy.Tool('before_finalize', Rotator())
def stream_handler(next_handler, *args, **kwargs):
- assert cherrypy.request.config.get('tools.streamer.arg') == 'arg value'
- cherrypy.response.output = o = BytesIO()
+ actual = cherrypy.request.config.get('tools.streamer.arg')
+ assert actual == 'arg value'
+ cherrypy.response.output = o = io.BytesIO()
try:
- response = next_handler(*args, **kwargs)
+ next_handler(*args, **kwargs)
# Ignore the response and return our accumulated output
# instead.
return o.getvalue()
@@ -122,17 +127,22 @@ class ToolTests(helper.CPWebCase):
class Root:
+ @cherrypy.expose
def index(self):
- return "Howdy earth!"
- index.exposed = True
+ return 'Howdy earth!'
+ @cherrypy.expose
+ @cherrypy.config(**{
+ 'tools.streamer.on': True,
+ 'tools.streamer.arg': 'arg value',
+ })
def tarfile(self):
- assert cherrypy.request.config.get('tools.streamer.arg') == 'arg value'
+ actual = cherrypy.request.config.get('tools.streamer.arg')
+ assert actual == 'arg value'
cherrypy.response.output.write(ntob('I am '))
cherrypy.response.output.write(ntob('a tarfile'))
- tarfile.exposed = True
- tarfile._cp_config = {'tools.streamer.on': True, 'tools.streamer.arg': 'arg value'}
+ @cherrypy.expose
def euro(self):
hooks = list(cherrypy.request.hooks['before_finalize'])
hooks.sort()
@@ -140,24 +150,23 @@ class ToolTests(helper.CPWebCase):
assert cbnames == ['gzip'], cbnames
priorities = [x.priority for x in hooks]
assert priorities == [80], priorities
- yield ntou("Hello,")
- yield ntou("world")
+ yield ntou('Hello,')
+ yield ntou('world')
yield europoundUnicode
- euro.exposed = True
# Bare hooks
+ @cherrypy.expose
+ @cherrypy.config(**{'hooks.before_request_body': pipe_body})
def pipe(self):
return cherrypy.request.body
- pipe.exposed = True
- pipe._cp_config = {'hooks.before_request_body': pipe_body}
# Multiple decorators; include kwargs just for fun.
# Note that rotator must run before gzip.
+ @cherrypy.expose
def decorated_euro(self, *vpath):
- yield ntou("Hello,")
- yield ntou("world")
+ yield ntou('Hello,')
+ yield ntou('world')
yield europoundUnicode
- decorated_euro.exposed = True
decorated_euro = tools.gzip(compress_level=6)(decorated_euro)
decorated_euro = tools.rotator(scale=3)(decorated_euro)
@@ -170,20 +179,19 @@ class ToolTests(helper.CPWebCase):
"""
def __init__(cls, name, bases, dct):
type.__init__(cls, name, bases, dct)
- for value in itervalues(dct):
+ for value in six.itervalues(dct):
if isinstance(value, types.FunctionType):
- value.exposed = True
+ cherrypy.expose(value)
setattr(root, name.lower(), cls())
Test = TestType('Test', (object,), {})
# METHOD ONE:
# Declare Tools in _cp_config
+ @cherrypy.config(**{'tools.nadsat.on': True})
class Demo(Test):
- _cp_config = {"tools.nadsat.on": True}
-
def index(self, id=None):
- return "A good piece of cherry pie"
+ return 'A good piece of cherry pie'
def ended(self, id):
return repr(tools.nadsat.ended[id])
@@ -192,33 +200,33 @@ class ToolTests(helper.CPWebCase):
raise ValueError()
def errinstream(self, id=None):
- yield "nonconfidential"
+ yield 'nonconfidential'
raise ValueError()
- yield "confidential"
+ yield 'confidential'
# METHOD TWO: decorator using Tool()
# We support Python 2.3, but the @-deco syntax would look like
# this:
# @tools.check_access()
def restricted(self):
- return "Welcome!"
+ return 'Welcome!'
restricted = myauthtools.check_access()(restricted)
userid = restricted
def err_in_onstart(self):
- return "success!"
+ return 'success!'
+ @cherrypy.config(**{'response.stream': True})
def stream(self, id=None):
- for x in xrange(100000000):
+ for x in range(100000000):
yield str(x)
- stream._cp_config = {'response.stream': True}
conf = {
# METHOD THREE:
# Declare Tools in detached config
'/demo': {
'tools.numerify.on': True,
- 'tools.numerify.map': {ntob("pie"): ntob("3.14159")},
+ 'tools.numerify.map': {ntob('pie'): ntob('3.14159')},
},
'/demo/restricted': {
'request.show_tracebacks': False,
@@ -232,7 +240,7 @@ class ToolTests(helper.CPWebCase):
},
'/demo/err_in_onstart': {
# Because this isn't a dict, on_start_resource will error.
- 'tools.numerify.map': "pie->3.14159"
+ 'tools.numerify.map': 'pie->3.14159'
},
# Combined tools
'/euro': {
@@ -249,55 +257,52 @@ class ToolTests(helper.CPWebCase):
app = cherrypy.tree.mount(root, config=conf)
app.request_class.namespaces['myauth'] = myauthtools
- if sys.version_info >= (2, 5):
- from cherrypy.test import _test_decorators
- root.tooldecs = _test_decorators.ToolExamples()
- setup_server = staticmethod(setup_server)
+ root.tooldecs = _test_decorators.ToolExamples()
def testHookErrors(self):
- self.getPage("/demo/?id=1")
+ self.getPage('/demo/?id=1')
# If body is "razdrez", then on_end_request is being called too early.
- self.assertBody("A horrorshow lomtick of cherry 3.14159")
+ self.assertBody('A horrorshow lomtick of cherry 3.14159')
# If this fails, then on_end_request isn't being called at all.
time.sleep(0.1)
- self.getPage("/demo/ended/1")
- self.assertBody("True")
+ self.getPage('/demo/ended/1')
+ self.assertBody('True')
valerr = '\n raise ValueError()\nValueError'
- self.getPage("/demo/err?id=3")
+ self.getPage('/demo/err?id=3')
# If body is "razdrez", then on_end_request is being called too early.
self.assertErrorPage(502, pattern=valerr)
# If this fails, then on_end_request isn't being called at all.
time.sleep(0.1)
- self.getPage("/demo/ended/3")
- self.assertBody("True")
+ self.getPage('/demo/ended/3')
+ self.assertBody('True')
# If body is "razdrez", then on_end_request is being called too early.
- if (cherrypy.server.protocol_version == "HTTP/1.0" or
- getattr(cherrypy.server, "using_apache", False)):
- self.getPage("/demo/errinstream?id=5")
+ if (cherrypy.server.protocol_version == 'HTTP/1.0' or
+ getattr(cherrypy.server, 'using_apache', False)):
+ self.getPage('/demo/errinstream?id=5')
# Because this error is raised after the response body has
# started, the status should not change to an error status.
- self.assertStatus("200 OK")
- self.assertBody("nonconfidential")
+ self.assertStatus('200 OK')
+ self.assertBody('nonconfidential')
else:
# Because this error is raised after the response body has
# started, and because it's chunked output, an error is raised by
# the HTTP client when it encounters incomplete output.
self.assertRaises((ValueError, IncompleteRead), self.getPage,
- "/demo/errinstream?id=5")
+ '/demo/errinstream?id=5')
# If this fails, then on_end_request isn't being called at all.
time.sleep(0.1)
- self.getPage("/demo/ended/5")
- self.assertBody("True")
+ self.getPage('/demo/ended/5')
+ self.assertBody('True')
# Test the "__call__" technique (compile-time decorator).
- self.getPage("/demo/restricted")
+ self.getPage('/demo/restricted')
self.assertErrorPage(401)
# Test compile-time decorator with kwargs from config.
- self.getPage("/demo/userid")
- self.assertBody("Welcome!")
+ self.getPage('/demo/userid')
+ self.assertBody('Welcome!')
def testEndRequestOnDrop(self):
old_timeout = None
@@ -314,8 +319,8 @@ class ToolTests(helper.CPWebCase):
self.persistent = True
try:
conn = self.HTTP_CONN
- conn.putrequest("GET", "/demo/stream?id=9", skip_host=True)
- conn.putheader("Host", self.HOST)
+ conn.putrequest('GET', '/demo/stream?id=9', skip_host=True)
+ conn.putheader('Host', self.HOST)
conn.endheaders()
# Skip the rest of the request and close the conn. This will
# cause the server's active socket to error, which *should*
@@ -326,8 +331,8 @@ class ToolTests(helper.CPWebCase):
self.persistent = False
time.sleep(timeout * 2)
# Test that the on_end_request hook was called.
- self.getPage("/demo/ended/9")
- self.assertBody("True")
+ self.getPage('/demo/ended/9')
+ self.assertBody('True')
finally:
if old_timeout is not None:
httpserver.timeout = old_timeout
@@ -338,60 +343,61 @@ class ToolTests(helper.CPWebCase):
# This is NOT true of the other hooks.
# Here, we have set up a failure in NumerifyTool.numerify_map,
# but our 'critical' hook should run and set the error to 502.
- self.getPage("/demo/err_in_onstart")
+ self.getPage('/demo/err_in_onstart')
self.assertErrorPage(502)
- self.assertInBody(
- "AttributeError: 'str' object has no attribute 'items'")
+ tmpl = "AttributeError: 'str' object has no attribute '{attr}'"
+ expected_msg = tmpl.format(attr='items' if six.PY3 else 'iteritems')
+ self.assertInBody(expected_msg)
def testCombinedTools(self):
- expectedResult = (ntou("Hello,world") +
+ expectedResult = (ntou('Hello,world') +
europoundUnicode).encode('utf-8')
- zbuf = BytesIO()
+ zbuf = io.BytesIO()
zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)
zfile.write(expectedResult)
zfile.close()
- self.getPage("/euro",
+ self.getPage('/euro',
headers=[
- ("Accept-Encoding", "gzip"),
- ("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")])
+ ('Accept-Encoding', 'gzip'),
+ ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')])
self.assertInBody(zbuf.getvalue()[:3])
- zbuf = BytesIO()
+ zbuf = io.BytesIO()
zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=6)
zfile.write(expectedResult)
zfile.close()
- self.getPage("/decorated_euro", headers=[("Accept-Encoding", "gzip")])
+ self.getPage('/decorated_euro', headers=[('Accept-Encoding', 'gzip')])
self.assertInBody(zbuf.getvalue()[:3])
# This returns a different value because gzip's priority was
# lowered in conf, allowing the rotator to run after gzip.
# Of course, we don't want breakage in production apps,
# but it proves the priority was changed.
- self.getPage("/decorated_euro/subpath",
- headers=[("Accept-Encoding", "gzip")])
- if py3k:
+ self.getPage('/decorated_euro/subpath',
+ headers=[('Accept-Encoding', 'gzip')])
+ if six.PY3:
self.assertInBody(bytes([(x + 3) % 256 for x in zbuf.getvalue()]))
else:
self.assertInBody(''.join([chr((ord(x) + 3) % 256)
for x in zbuf.getvalue()]))
def testBareHooks(self):
- content = "bit of a pain in me gulliver"
- self.getPage("/pipe",
- headers=[("Content-Length", str(len(content))),
- ("Content-Type", "text/plain")],
- method="POST", body=content)
+ content = 'bit of a pain in me gulliver'
+ self.getPage('/pipe',
+ headers=[('Content-Length', str(len(content))),
+ ('Content-Type', 'text/plain')],
+ method='POST', body=content)
self.assertBody(content)
def testHandlerWrapperTool(self):
- self.getPage("/tarfile")
- self.assertBody("I am a tarfile")
+ self.getPage('/tarfile')
+ self.assertBody('I am a tarfile')
def testToolWithConfig(self):
if not sys.version_info >= (2, 5):
- return self.skip("skipped (Python 2.5+ only)")
+ return self.skip('skipped (Python 2.5+ only)')
self.getPage('/tooldecs/blah')
self.assertHeader('Content-Type', 'application/data')
@@ -403,7 +409,7 @@ class ToolTests(helper.CPWebCase):
except AttributeError:
pass
else:
- raise AssertionError("Tool.on did not error as it should have.")
+ raise AssertionError('Tool.on did not error as it should have.')
# set
try:
@@ -411,7 +417,24 @@ class ToolTests(helper.CPWebCase):
except AttributeError:
pass
else:
- raise AssertionError("Tool.on did not error as it should have.")
+ raise AssertionError('Tool.on did not error as it should have.')
+
+ def testDecorator(self):
+ @cherrypy.tools.register('on_start_resource')
+ def example():
+ pass
+ self.assertTrue(isinstance(cherrypy.tools.example, cherrypy.Tool))
+ self.assertEqual(cherrypy.tools.example._point, 'on_start_resource')
+
+ @cherrypy.tools.register( # noqa: F811
+ 'before_finalize', name='renamed', priority=60,
+ )
+ def example():
+ pass
+ self.assertTrue(isinstance(cherrypy.tools.renamed, cherrypy.Tool))
+ self.assertEqual(cherrypy.tools.renamed._point, 'before_finalize')
+ self.assertEqual(cherrypy.tools.renamed._name, 'renamed')
+ self.assertEqual(cherrypy.tools.renamed._priority, 60)
class SessionAuthTest(unittest.TestCase):
@@ -423,6 +446,23 @@ class SessionAuthTest(unittest.TestCase):
username and password were unicode.
"""
sa = cherrypy.lib.cptools.SessionAuth()
- res = sa.login_screen(None, username=unicodestr('nobody'),
- password=unicodestr('anypass'))
- self.assertTrue(isinstance(res, bytestr))
+ res = sa.login_screen(None, username=six.text_type('nobody'),
+ password=six.text_type('anypass'))
+ self.assertTrue(isinstance(res, bytes))
+
+
+class TestHooks:
+ def test_priorities(self):
+ """
+ Hooks should sort by priority order.
+ """
+ Hook = cherrypy._cprequest.Hook
+ hooks = [
+ Hook(None, priority=48),
+ Hook(None),
+ Hook(None, priority=49),
+ ]
+ hooks.sort()
+ by_priority = operator.attrgetter('priority')
+ priorities = list(map(by_priority, hooks))
+ assert priorities == [48, 49, 50]
diff --git a/cherrypy/test/test_tutorials.py b/cherrypy/test/test_tutorials.py
index ad89a9ea..efa35b99 100644
--- a/cherrypy/test/test_tutorials.py
+++ b/cherrypy/test/test_tutorials.py
@@ -1,4 +1,9 @@
import sys
+import imp
+import types
+import importlib
+
+import six
import cherrypy
from cherrypy.test import helper
@@ -6,77 +11,74 @@ from cherrypy.test import helper
class TutorialTest(helper.CPWebCase):
+ @classmethod
def setup_server(cls):
-
- conf = cherrypy.config.copy()
-
- def load_tut_module(name):
- """Import or reload tutorial module as needed."""
- cherrypy.config.reset()
- cherrypy.config.update(conf)
-
- target = "cherrypy.tutorial." + name
- if target in sys.modules:
- module = reload(sys.modules[target])
- else:
- module = __import__(target, globals(), locals(), [''])
- # The above import will probably mount a new app at "".
- app = cherrypy.tree.apps[""]
-
- app.root.load_tut_module = load_tut_module
- app.root.sessions = sessions
- app.root.traceback_setting = traceback_setting
-
- cls.supervisor.sync_apps()
- load_tut_module.exposed = True
-
- def sessions():
- cherrypy.config.update({"tools.sessions.on": True})
- sessions.exposed = True
-
- def traceback_setting():
- return repr(cherrypy.request.show_tracebacks)
- traceback_setting.exposed = True
-
+ """
+ Mount something so the engine starts.
+ """
class Dummy:
pass
- root = Dummy()
- root.load_tut_module = load_tut_module
- cherrypy.tree.mount(root)
- setup_server = classmethod(setup_server)
+ cherrypy.tree.mount(Dummy())
+
+ @staticmethod
+ def load_module(name):
+ """
+ Import or reload tutorial module as needed.
+ """
+ target = 'cherrypy.tutorial.' + name
+ if target in sys.modules:
+ module = imp.reload(sys.modules[target])
+ else:
+ module = importlib.import_module(target)
+ return module
+
+ @classmethod
+ def setup_tutorial(cls, name, root_name, config={}):
+ cherrypy.config.reset()
+ module = cls.load_module(name)
+ root = getattr(module, root_name)
+ conf = getattr(module, 'tutconf')
+ class_types = type,
+ if six.PY2:
+ class_types += types.ClassType,
+ if isinstance(root, class_types):
+ root = root()
+ cherrypy.tree.mount(root, config=conf)
+ cherrypy.config.update(config)
def test01HelloWorld(self):
- self.getPage("/load_tut_module/tut01_helloworld")
- self.getPage("/")
+ self.setup_tutorial('tut01_helloworld', 'HelloWorld')
+ self.getPage('/')
self.assertBody('Hello world!')
def test02ExposeMethods(self):
- self.getPage("/load_tut_module/tut02_expose_methods")
- self.getPage("/show_msg")
+ self.setup_tutorial('tut02_expose_methods', 'HelloWorld')
+ self.getPage('/show_msg')
self.assertBody('Hello world!')
def test03GetAndPost(self):
- self.getPage("/load_tut_module/tut03_get_and_post")
+ self.setup_tutorial('tut03_get_and_post', 'WelcomePage')
# Try different GET queries
- self.getPage("/greetUser?name=Bob")
+ self.getPage('/greetUser?name=Bob')
self.assertBody("Hey Bob, what's up?")
- self.getPage("/greetUser")
+ self.getPage('/greetUser')
self.assertBody('Please enter your name <a href="./">here</a>.')
- self.getPage("/greetUser?name=")
+ self.getPage('/greetUser?name=')
self.assertBody('No, really, enter your name <a href="./">here</a>.')
# Try the same with POST
- self.getPage("/greetUser", method="POST", body="name=Bob")
+ self.getPage('/greetUser', method='POST', body='name=Bob')
self.assertBody("Hey Bob, what's up?")
- self.getPage("/greetUser", method="POST", body="name=")
+ self.getPage('/greetUser', method='POST', body='name=')
self.assertBody('No, really, enter your name <a href="./">here</a>.')
def test04ComplexSite(self):
- self.getPage("/load_tut_module/tut04_complex_site")
+ self.setup_tutorial('tut04_complex_site', 'root')
+
msg = '''
<p>Here are some extra useful links:</p>
@@ -86,11 +88,11 @@ class TutorialTest(helper.CPWebCase):
</ul>
<p>[<a href="../">Return to links page</a>]</p>'''
- self.getPage("/links/extra/")
+ self.getPage('/links/extra/')
self.assertBody(msg)
def test05DerivedObjects(self):
- self.getPage("/load_tut_module/tut05_derived_objects")
+ self.setup_tutorial('tut05_derived_objects', 'HomePage')
msg = '''
<html>
<head>
@@ -109,33 +111,32 @@ class TutorialTest(helper.CPWebCase):
# the tutorial has some annoying spaces in otherwise blank lines
msg = msg.replace('</h2>\n\n', '</h2>\n \n')
msg = msg.replace('</p>\n\n', '</p>\n \n')
- self.getPage("/another/")
+ self.getPage('/another/')
self.assertBody(msg)
def test06DefaultMethod(self):
- self.getPage("/load_tut_module/tut06_default_method")
+ self.setup_tutorial('tut06_default_method', 'UsersPage')
self.getPage('/hendrik')
self.assertBody('Hendrik Mans, CherryPy co-developer & crazy German '
'(<a href="./">back</a>)')
def test07Sessions(self):
- self.getPage("/load_tut_module/tut07_sessions")
- self.getPage("/sessions")
+ self.setup_tutorial('tut07_sessions', 'HitCounter')
self.getPage('/')
self.assertBody(
"\n During your current session, you've viewed this"
- "\n page 1 times! Your life is a patio of fun!"
- "\n ")
+ '\n page 1 times! Your life is a patio of fun!'
+ '\n ')
self.getPage('/', self.cookies)
self.assertBody(
"\n During your current session, you've viewed this"
- "\n page 2 times! Your life is a patio of fun!"
- "\n ")
+ '\n page 2 times! Your life is a patio of fun!'
+ '\n ')
def test08GeneratorsAndYield(self):
- self.getPage("/load_tut_module/tut08_generators_and_yield")
+ self.setup_tutorial('tut08_generators_and_yield', 'GeneratorDemo')
self.getPage('/')
self.assertBody('<html><body><h2>Generators rule!</h2>'
'<h3>List of users:</h3>'
@@ -143,19 +144,19 @@ class TutorialTest(helper.CPWebCase):
'</body></html>')
def test09Files(self):
- self.getPage("/load_tut_module/tut09_files")
+ self.setup_tutorial('tut09_files', 'FileDemo')
# Test upload
filesize = 5
- h = [("Content-type", "multipart/form-data; boundary=x"),
- ("Content-Length", str(105 + filesize))]
+ h = [('Content-type', 'multipart/form-data; boundary=x'),
+ ('Content-Length', str(105 + filesize))]
b = ('--x\n'
'Content-Disposition: form-data; name="myFile"; '
'filename="hello.txt"\r\n'
'Content-Type: text/plain\r\n'
'\r\n')
b += 'a' * filesize + '\n' + '--x--\n'
- self.getPage('/upload', h, "POST", b)
+ self.getPage('/upload', h, 'POST', b)
self.assertBody('''<html>
<body>
myFile length: %d<br />
@@ -166,39 +167,44 @@ class TutorialTest(helper.CPWebCase):
# Test download
self.getPage('/download')
- self.assertStatus("200 OK")
- self.assertHeader("Content-Type", "application/x-download")
- self.assertHeader("Content-Disposition",
+ self.assertStatus('200 OK')
+ self.assertHeader('Content-Type', 'application/x-download')
+ self.assertHeader('Content-Disposition',
# Make sure the filename is quoted.
'attachment; filename="pdf_file.pdf"')
self.assertEqual(len(self.body), 85698)
def test10HTTPErrors(self):
- self.getPage("/load_tut_module/tut10_http_errors")
+ self.setup_tutorial('tut10_http_errors', 'HTTPErrorDemo')
- self.getPage("/")
+ @cherrypy.expose
+ def traceback_setting():
+ return repr(cherrypy.request.show_tracebacks)
+ cherrypy.tree.mount(traceback_setting, '/traceback_setting')
+
+ self.getPage('/')
self.assertInBody("""<a href="toggleTracebacks">""")
self.assertInBody("""<a href="/doesNotExist">""")
self.assertInBody("""<a href="/error?code=403">""")
self.assertInBody("""<a href="/error?code=500">""")
self.assertInBody("""<a href="/messageArg">""")
- self.getPage("/traceback_setting")
+ self.getPage('/traceback_setting')
setting = self.body
- self.getPage("/toggleTracebacks")
+ self.getPage('/toggleTracebacks')
self.assertStatus((302, 303))
- self.getPage("/traceback_setting")
+ self.getPage('/traceback_setting')
self.assertBody(str(not eval(setting)))
- self.getPage("/error?code=500")
+ self.getPage('/error?code=500')
self.assertStatus(500)
- self.assertInBody("The server encountered an unexpected condition "
- "which prevented it from fulfilling the request.")
+ self.assertInBody('The server encountered an unexpected condition '
+ 'which prevented it from fulfilling the request.')
- self.getPage("/error?code=403")
+ self.getPage('/error?code=403')
self.assertStatus(403)
self.assertInBody("<h2>You can't do that!</h2>")
- self.getPage("/messageArg")
+ self.getPage('/messageArg')
self.assertStatus(500)
self.assertInBody("If you construct an HTTPError with a 'message'")
diff --git a/cherrypy/test/test_virtualhost.py b/cherrypy/test/test_virtualhost.py
index 7c3d8c71..de88f927 100644
--- a/cherrypy/test/test_virtualhost.py
+++ b/cherrypy/test/test_virtualhost.py
@@ -1,51 +1,53 @@
import os
-curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import cherrypy
from cherrypy.test import helper
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+
class VirtualHostTest(helper.CPWebCase):
+ @staticmethod
def setup_server():
class Root:
+ @cherrypy.expose
def index(self):
- return "Hello, world"
- index.exposed = True
+ return 'Hello, world'
+ @cherrypy.expose
def dom4(self):
- return "Under construction"
- dom4.exposed = True
+ return 'Under construction'
+ @cherrypy.expose
def method(self, value):
- return "You sent %s" % value
- method.exposed = True
+ return 'You sent %s' % value
class VHost:
def __init__(self, sitename):
self.sitename = sitename
+ @cherrypy.expose
def index(self):
- return "Welcome to %s" % self.sitename
- index.exposed = True
+ return 'Welcome to %s' % self.sitename
+ @cherrypy.expose
def vmethod(self, value):
- return "You sent %s" % value
- vmethod.exposed = True
+ return 'You sent %s' % value
+ @cherrypy.expose
def url(self):
- return cherrypy.url("nextpage")
- url.exposed = True
+ return cherrypy.url('nextpage')
# Test static as a handler (section must NOT include vhost prefix)
static = cherrypy.tools.staticdir.handler(
section='/static', dir=curdir)
root = Root()
- root.mydom2 = VHost("Domain 2")
- root.mydom3 = VHost("Domain 3")
+ root.mydom2 = VHost('Domain 2')
+ root.mydom3 = VHost('Domain 3')
hostmap = {'www.mydom2.com': '/mydom2',
'www.mydom3.com': '/mydom3',
'www.mydom4.com': '/dom4',
@@ -62,51 +64,50 @@ class VirtualHostTest(helper.CPWebCase):
'tools.staticdir.index': 'index.html',
},
})
- setup_server = staticmethod(setup_server)
def testVirtualHost(self):
- self.getPage("/", [('Host', 'www.mydom1.com')])
+ self.getPage('/', [('Host', 'www.mydom1.com')])
self.assertBody('Hello, world')
- self.getPage("/mydom2/", [('Host', 'www.mydom1.com')])
+ self.getPage('/mydom2/', [('Host', 'www.mydom1.com')])
self.assertBody('Welcome to Domain 2')
- self.getPage("/", [('Host', 'www.mydom2.com')])
+ self.getPage('/', [('Host', 'www.mydom2.com')])
self.assertBody('Welcome to Domain 2')
- self.getPage("/", [('Host', 'www.mydom3.com')])
+ self.getPage('/', [('Host', 'www.mydom3.com')])
self.assertBody('Welcome to Domain 3')
- self.getPage("/", [('Host', 'www.mydom4.com')])
+ self.getPage('/', [('Host', 'www.mydom4.com')])
self.assertBody('Under construction')
# Test GET, POST, and positional params
- self.getPage("/method?value=root")
- self.assertBody("You sent root")
- self.getPage("/vmethod?value=dom2+GET", [('Host', 'www.mydom2.com')])
- self.assertBody("You sent dom2 GET")
- self.getPage("/vmethod", [('Host', 'www.mydom3.com')], method="POST",
- body="value=dom3+POST")
- self.assertBody("You sent dom3 POST")
- self.getPage("/vmethod/pos", [('Host', 'www.mydom3.com')])
- self.assertBody("You sent pos")
+ self.getPage('/method?value=root')
+ self.assertBody('You sent root')
+ self.getPage('/vmethod?value=dom2+GET', [('Host', 'www.mydom2.com')])
+ self.assertBody('You sent dom2 GET')
+ self.getPage('/vmethod', [('Host', 'www.mydom3.com')], method='POST',
+ body='value=dom3+POST')
+ self.assertBody('You sent dom3 POST')
+ self.getPage('/vmethod/pos', [('Host', 'www.mydom3.com')])
+ self.assertBody('You sent pos')
# Test that cherrypy.url uses the browser url, not the virtual url
- self.getPage("/url", [('Host', 'www.mydom2.com')])
- self.assertBody("%s://www.mydom2.com/nextpage" % self.scheme)
+ self.getPage('/url', [('Host', 'www.mydom2.com')])
+ self.assertBody('%s://www.mydom2.com/nextpage' % self.scheme)
def test_VHost_plus_Static(self):
# Test static as a handler
- self.getPage("/static/style.css", [('Host', 'www.mydom2.com')])
+ self.getPage('/static/style.css', [('Host', 'www.mydom2.com')])
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/css;charset=utf-8')
# Test static in config
- self.getPage("/static2/dirback.jpg", [('Host', 'www.mydom2.com')])
+ self.getPage('/static2/dirback.jpg', [('Host', 'www.mydom2.com')])
self.assertStatus('200 OK')
self.assertHeaderIn('Content-Type', ['image/jpeg', 'image/pjpeg'])
# Test static config with "index" arg
- self.getPage("/static2/", [('Host', 'www.mydom2.com')])
+ self.getPage('/static2/', [('Host', 'www.mydom2.com')])
self.assertStatus('200 OK')
self.assertBody('Hello, world\r\n')
# Since tools.trailing_slash is on by default, this should redirect
- self.getPage("/static2", [('Host', 'www.mydom2.com')])
+ self.getPage('/static2', [('Host', 'www.mydom2.com')])
self.assertStatus(301)
diff --git a/cherrypy/test/test_wsgi_ns.py b/cherrypy/test/test_wsgi_ns.py
index 0df2365b..2a5fedd4 100644
--- a/cherrypy/test/test_wsgi_ns.py
+++ b/cherrypy/test/test_wsgi_ns.py
@@ -5,6 +5,7 @@ from cherrypy.test import helper
class WSGI_Namespace_Test(helper.CPWebCase):
+ @staticmethod
def setup_server():
class WSGIResponse(object):
@@ -23,7 +24,7 @@ class WSGI_Namespace_Test(helper.CPWebCase):
return next(self.iter)
def close(self):
- if hasattr(self.appresults, "close"):
+ if hasattr(self.appresults, 'close'):
self.appresults.close()
class ChangeCase(object):
@@ -70,9 +71,9 @@ class WSGI_Namespace_Test(helper.CPWebCase):
class Root(object):
+ @cherrypy.expose
def index(self):
- return "HellO WoRlD!"
- index.exposed = True
+ return 'HellO WoRlD!'
root_conf = {'wsgi.pipeline': [('replace', Replacer)],
'wsgi.replace.map': {ntob('L'): ntob('X'),
@@ -83,12 +84,11 @@ class WSGI_Namespace_Test(helper.CPWebCase):
app.wsgiapp.pipeline.append(('changecase', ChangeCase))
app.wsgiapp.config['changecase'] = {'to': 'upper'}
cherrypy.tree.mount(app, config={'/': root_conf})
- setup_server = staticmethod(setup_server)
def test_pipeline(self):
if not cherrypy.server.httpserver:
return self.skip()
- self.getPage("/")
+ self.getPage('/')
# If body is "HEXXO WORXD!", the middleware was applied out of order.
- self.assertBody("HERRO WORRD!")
+ self.assertBody('HERRO WORRD!')
diff --git a/cherrypy/test/test_wsgi_unix_socket.py b/cherrypy/test/test_wsgi_unix_socket.py
index 7a829d51..8f1cc00b 100644
--- a/cherrypy/test/test_wsgi_unix_socket.py
+++ b/cherrypy/test/test_wsgi_unix_socket.py
@@ -1,12 +1,15 @@
import os
-import sys
import socket
import atexit
import tempfile
+from six.moves.http_client import HTTPConnection
+
+import pytest
+
import cherrypy
from cherrypy.test import helper
-from cherrypy._cpcompat import HTTPConnection
+
def usocket_path():
fd, path = tempfile.mkstemp('cp_test.sock')
@@ -14,8 +17,10 @@ def usocket_path():
os.remove(path)
return path
+
USOCKET_PATH = usocket_path()
+
class USocketHTTPConnection(HTTPConnection):
"""
HTTPConnection over a unix socket.
@@ -42,21 +47,7 @@ class USocketHTTPConnection(HTTPConnection):
atexit.register(lambda: os.remove(self.path))
-def skip_on_windows(method):
- """
- Decorator to skip the method call if the test is executing on Windows.
- """
- def wrapper(self):
- if sys.platform == "win32":
- return self.skip("No UNIX Socket support in Windows.")
- else:
- return method(self)
- wrapper.__doc__ = method.__doc__
- wrapper.__name__ = method.__name__
- return wrapper
-
-
-
+@pytest.mark.skipif("sys.platform == 'win32'")
class WSGI_UnixSocket_Test(helper.CPWebCase):
"""
Test basic behavior on a cherrypy wsgi server listening
@@ -66,18 +57,17 @@ class WSGI_UnixSocket_Test(helper.CPWebCase):
"""
HTTP_CONN = USocketHTTPConnection(USOCKET_PATH)
-
@staticmethod
def setup_server():
class Root(object):
@cherrypy.expose
def index(self):
- return "Test OK"
+ return 'Test OK'
@cherrypy.expose
def error(self):
- raise Exception("Invalid page")
+ raise Exception('Invalid page')
config = {
'server.socket_file': USOCKET_PATH
@@ -88,19 +78,16 @@ class WSGI_UnixSocket_Test(helper.CPWebCase):
def tearDown(self):
cherrypy.config.update({'server.socket_file': None})
- @skip_on_windows
def test_simple_request(self):
- self.getPage("/")
- self.assertStatus("200 OK")
- self.assertInBody("Test OK")
+ self.getPage('/')
+ self.assertStatus('200 OK')
+ self.assertInBody('Test OK')
- @skip_on_windows
def test_not_found(self):
- self.getPage("/invalid_path")
- self.assertStatus("404 Not Found")
+ self.getPage('/invalid_path')
+ self.assertStatus('404 Not Found')
- @skip_on_windows
def test_internal_error(self):
- self.getPage("/error")
- self.assertStatus("500 Internal Server Error")
- self.assertInBody("Invalid page")
+ self.getPage('/error')
+ self.assertStatus('500 Internal Server Error')
+ self.assertInBody('Invalid page')
diff --git a/cherrypy/test/test_wsgi_vhost.py b/cherrypy/test/test_wsgi_vhost.py
index a36a936c..2b6e5ba9 100644
--- a/cherrypy/test/test_wsgi_vhost.py
+++ b/cherrypy/test/test_wsgi_vhost.py
@@ -4,6 +4,7 @@ from cherrypy.test import helper
class WSGI_VirtualHost_Test(helper.CPWebCase):
+ @staticmethod
def setup_server():
class ClassOfRoot(object):
@@ -11,9 +12,9 @@ class WSGI_VirtualHost_Test(helper.CPWebCase):
def __init__(self, name):
self.name = name
+ @cherrypy.expose
def index(self):
- return "Welcome to the %s website!" % self.name
- index.exposed = True
+ return 'Welcome to the %s website!' % self.name
default = cherrypy.Application(None)
@@ -23,13 +24,12 @@ class WSGI_VirtualHost_Test(helper.CPWebCase):
domains['www.classof%s.example' % year] = app
cherrypy.tree.graft(cherrypy._cpwsgi.VirtualHost(default, domains))
- setup_server = staticmethod(setup_server)
def test_welcome(self):
if not cherrypy.server.using_wsgi:
- return self.skip("skipped (not using WSGI)... ")
+ return self.skip('skipped (not using WSGI)... ')
for year in range(1997, 2008):
self.getPage(
- "/", headers=[('Host', 'www.classof%s.example' % year)])
- self.assertBody("Welcome to the Class of %s website!" % year)
+ '/', headers=[('Host', 'www.classof%s.example' % year)])
+ self.assertBody('Welcome to the Class of %s website!' % year)
diff --git a/cherrypy/test/test_wsgiapps.py b/cherrypy/test/test_wsgiapps.py
index ac65c1eb..fa7f25f7 100644
--- a/cherrypy/test/test_wsgiapps.py
+++ b/cherrypy/test/test_wsgiapps.py
@@ -1,16 +1,14 @@
import sys
+import cherrypy
from cherrypy._cpcompat import ntob
from cherrypy.test import helper
class WSGIGraftTests(helper.CPWebCase):
+ @staticmethod
def setup_server():
- import os
- curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
-
- import cherrypy
def test_app(environ, start_response):
status = '200 OK'
@@ -49,7 +47,7 @@ class WSGIGraftTests(helper.CPWebCase):
return self.iter.next()
def close(self):
- if hasattr(self.appresults, "close"):
+ if hasattr(self.appresults, 'close'):
self.appresults.close()
class ReversingMiddleware(object):
@@ -71,15 +69,15 @@ class WSGIGraftTests(helper.CPWebCase):
def next(this):
line = list(this.iter.next())
line.reverse()
- return "".join(line)
+ return ''.join(line)
return Reverser(results)
class Root:
+ @cherrypy.expose
def index(self):
return ntob("I'm a regular CherryPy page handler!")
- index.exposed = True
cherrypy.tree.mount(Root())
@@ -90,37 +88,33 @@ class WSGIGraftTests(helper.CPWebCase):
# be pulled from the WSGI environ each time.
app = cherrypy.Application(Root(), script_name=None)
cherrypy.tree.graft(ReversingMiddleware(app), '/hosted/app2')
- setup_server = staticmethod(setup_server)
wsgi_output = '''Hello, world!
This is a wsgi app running within CherryPy!'''
def test_01_standard_app(self):
- self.getPage("/")
+ self.getPage('/')
self.assertBody("I'm a regular CherryPy page handler!")
def test_04_pure_wsgi(self):
- import cherrypy
if not cherrypy.server.using_wsgi:
- return self.skip("skipped (not using WSGI)... ")
- self.getPage("/hosted/app1")
- self.assertHeader("Content-Type", "text/plain")
+ return self.skip('skipped (not using WSGI)... ')
+ self.getPage('/hosted/app1')
+ self.assertHeader('Content-Type', 'text/plain')
self.assertInBody(self.wsgi_output)
def test_05_wrapped_cp_app(self):
- import cherrypy
if not cherrypy.server.using_wsgi:
- return self.skip("skipped (not using WSGI)... ")
- self.getPage("/hosted/app2/")
+ return self.skip('skipped (not using WSGI)... ')
+ self.getPage('/hosted/app2/')
body = list("I'm a regular CherryPy page handler!")
body.reverse()
- body = "".join(body)
+ body = ''.join(body)
self.assertInBody(body)
def test_06_empty_string_app(self):
- import cherrypy
if not cherrypy.server.using_wsgi:
- return self.skip("skipped (not using WSGI)... ")
- self.getPage("/hosted/app3")
- self.assertHeader("Content-Type", "text/plain")
+ return self.skip('skipped (not using WSGI)... ')
+ self.getPage('/hosted/app3')
+ self.assertHeader('Content-Type', 'text/plain')
self.assertInBody('Hello world')
diff --git a/cherrypy/test/test_xmlrpc.py b/cherrypy/test/test_xmlrpc.py
index 4beed0a3..ad93b821 100644
--- a/cherrypy/test/test_xmlrpc.py
+++ b/cherrypy/test/test_xmlrpc.py
@@ -1,19 +1,22 @@
import sys
-from cherrypy._cpcompat import py3k
-try:
- from xmlrpclib import DateTime, Fault, ProtocolError, ServerProxy
- from xmlrpclib import SafeTransport
-except ImportError:
- from xmlrpc.client import DateTime, Fault, ProtocolError, ServerProxy
- from xmlrpc.client import SafeTransport
+import six
-if py3k:
+from six.moves.xmlrpc_client import (
+ DateTime, Fault,
+ ProtocolError, ServerProxy, SafeTransport
+)
+
+import cherrypy
+from cherrypy import _cptools
+from cherrypy.test import helper
+
+if six.PY3:
HTTPSTransport = SafeTransport
# Python 3.0's SafeTransport still mistakenly checks for socket.ssl
import socket
- if not hasattr(socket, "ssl"):
+ if not hasattr(socket, 'ssl'):
socket.ssl = True
else:
class HTTPSTransport(SafeTransport):
@@ -47,67 +50,64 @@ else:
return self.parse_response(h.getfile())
-import cherrypy
-
def setup_server():
- from cherrypy import _cptools
class Root:
+ @cherrypy.expose
def index(self):
return "I'm a standard index!"
- index.exposed = True
class XmlRpc(_cptools.XMLRPCController):
+ @cherrypy.expose
def foo(self):
- return "Hello world!"
- foo.exposed = True
+ return 'Hello world!'
+ @cherrypy.expose
def return_single_item_list(self):
return [42]
- return_single_item_list.exposed = True
+ @cherrypy.expose
def return_string(self):
- return "here is a string"
- return_string.exposed = True
+ return 'here is a string'
+ @cherrypy.expose
def return_tuple(self):
return ('here', 'is', 1, 'tuple')
- return_tuple.exposed = True
+ @cherrypy.expose
def return_dict(self):
return dict(a=1, b=2, c=3)
- return_dict.exposed = True
+ @cherrypy.expose
def return_composite(self):
return dict(a=1, z=26), 'hi', ['welcome', 'friend']
- return_composite.exposed = True
+ @cherrypy.expose
def return_int(self):
return 42
- return_int.exposed = True
+ @cherrypy.expose
def return_float(self):
return 3.14
- return_float.exposed = True
+ @cherrypy.expose
def return_datetime(self):
return DateTime((2003, 10, 7, 8, 1, 0, 1, 280, -1))
- return_datetime.exposed = True
+ @cherrypy.expose
def return_boolean(self):
return True
- return_boolean.exposed = True
+ @cherrypy.expose
def test_argument_passing(self, num):
return num * 2
- test_argument_passing.exposed = True
+ @cherrypy.expose
def test_returning_Fault(self):
- return Fault(1, "custom Fault response")
- test_returning_Fault.exposed = True
+ return Fault(1, 'custom Fault response')
root = Root()
root.xmlrpc = XmlRpc()
@@ -117,16 +117,13 @@ def setup_server():
}})
-from cherrypy.test import helper
-
-
class XmlRpcTest(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def testXmlRpc(self):
scheme = self.scheme
- if scheme == "https":
+ if scheme == 'https':
url = 'https://%s:%s/xmlrpc/' % (self.interface(), self.PORT)
proxy = ServerProxy(url, transport=HTTPSTransport())
else:
@@ -134,12 +131,12 @@ class XmlRpcTest(helper.CPWebCase):
proxy = ServerProxy(url)
# begin the tests ...
- self.getPage("/xmlrpc/foo")
- self.assertBody("Hello world!")
+ self.getPage('/xmlrpc/foo')
+ self.assertBody('Hello world!')
self.assertEqual(proxy.return_single_item_list(), [42])
self.assertNotEqual(proxy.return_single_item_list(), 'one bazillion')
- self.assertEqual(proxy.return_string(), "here is a string")
+ self.assertEqual(proxy.return_string(), 'here is a string')
self.assertEqual(proxy.return_tuple(),
list(('here', 'is', 1, 'tuple')))
self.assertEqual(proxy.return_dict(), {'a': 1, 'c': 3, 'b': 2})
@@ -158,10 +155,10 @@ class XmlRpcTest(helper.CPWebCase):
except Exception:
x = sys.exc_info()[1]
self.assertEqual(x.__class__, Fault)
- self.assertEqual(x.faultString, ("unsupported operand type(s) "
+ self.assertEqual(x.faultString, ('unsupported operand type(s) '
"for *: 'dict' and 'int'"))
else:
- self.fail("Expected xmlrpclib.Fault")
+ self.fail('Expected xmlrpclib.Fault')
# https://github.com/cherrypy/cherrypy/issues/533
# if a method is not found, an xmlrpclib.Fault should be raised
@@ -173,7 +170,7 @@ class XmlRpcTest(helper.CPWebCase):
self.assertEqual(x.faultString,
'method "non_method" is not supported')
else:
- self.fail("Expected xmlrpclib.Fault")
+ self.fail('Expected xmlrpclib.Fault')
# Test returning a Fault from the page handler.
try:
@@ -181,6 +178,6 @@ class XmlRpcTest(helper.CPWebCase):
except Exception:
x = sys.exc_info()[1]
self.assertEqual(x.__class__, Fault)
- self.assertEqual(x.faultString, ("custom Fault response"))
+ self.assertEqual(x.faultString, ('custom Fault response'))
else:
- self.fail("Expected xmlrpclib.Fault")
+ self.fail('Expected xmlrpclib.Fault')
diff --git a/cherrypy/test/webtest.py b/cherrypy/test/webtest.py
index 959063f5..c38d4553 100644
--- a/cherrypy/test/webtest.py
+++ b/cherrypy/test/webtest.py
@@ -1,587 +1,11 @@
-"""Extensions to unittest for web frameworks.
+# for compatibility, expose cheroot webtest here
+import warnings
-Use the WebCase.getPage method to request a page from your HTTP server.
+from cheroot.test.webtest import ( # noqa
+ interface, TerseTestResult, TerseTestRunner,
+ ReloadingTestLoader, WebCase, cleanHeaders, shb, openURL,
+ ServerError, server_error,
+)
-Framework Integration
-=====================
-If you have control over your server process, you can handle errors
-in the server-side of the HTTP conversation a bit better. You must run
-both the client (your WebCase tests) and the server in the same process
-(but in separate threads, obviously).
-
-When an error occurs in the framework, call server_error. It will print
-the traceback to stdout, and keep any assertions you have from running
-(the assumption is that, if the server errors, the page output will not
-be of further significance to your tests).
-"""
-
-import pprint
-import re
-import socket
-import sys
-import time
-import traceback
-import types
-
-from unittest import *
-from unittest import _TextTestResult
-
-from cherrypy._cpcompat import basestring, ntob, py3k, HTTPConnection
-from cherrypy._cpcompat import HTTPSConnection, unicodestr
-
-
-def interface(host):
- """Return an IP address for a client connection given the server host.
-
- If the server is listening on '0.0.0.0' (INADDR_ANY)
- or '::' (IN6ADDR_ANY), this will return the proper localhost."""
- if host == '0.0.0.0':
- # INADDR_ANY, which should respond on localhost.
- return "127.0.0.1"
- if host == '::':
- # IN6ADDR_ANY, which should respond on localhost.
- return "::1"
- return host
-
-
-class TerseTestResult(_TextTestResult):
-
- def printErrors(self):
- # Overridden to avoid unnecessary empty line
- if self.errors or self.failures:
- if self.dots or self.showAll:
- self.stream.writeln()
- self.printErrorList('ERROR', self.errors)
- self.printErrorList('FAIL', self.failures)
-
-
-class TerseTestRunner(TextTestRunner):
-
- """A test runner class that displays results in textual form."""
-
- def _makeResult(self):
- return TerseTestResult(self.stream, self.descriptions, self.verbosity)
-
- def run(self, test):
- "Run the given test case or test suite."
- # Overridden to remove unnecessary empty lines and separators
- result = self._makeResult()
- test(result)
- result.printErrors()
- if not result.wasSuccessful():
- self.stream.write("FAILED (")
- failed, errored = list(map(len, (result.failures, result.errors)))
- if failed:
- self.stream.write("failures=%d" % failed)
- if errored:
- if failed:
- self.stream.write(", ")
- self.stream.write("errors=%d" % errored)
- self.stream.writeln(")")
- return result
-
-
-class ReloadingTestLoader(TestLoader):
-
- def loadTestsFromName(self, name, module=None):
- """Return a suite of all tests cases given a string specifier.
-
- The name may resolve either to a module, a test case class, a
- test method within a test case class, or a callable object which
- returns a TestCase or TestSuite instance.
-
- The method optionally resolves the names relative to a given module.
- """
- parts = name.split('.')
- unused_parts = []
- if module is None:
- if not parts:
- raise ValueError("incomplete test name: %s" % name)
- else:
- parts_copy = parts[:]
- while parts_copy:
- target = ".".join(parts_copy)
- if target in sys.modules:
- module = reload(sys.modules[target])
- parts = unused_parts
- break
- else:
- try:
- module = __import__(target)
- parts = unused_parts
- break
- except ImportError:
- unused_parts.insert(0, parts_copy[-1])
- del parts_copy[-1]
- if not parts_copy:
- raise
- parts = parts[1:]
- obj = module
- for part in parts:
- obj = getattr(obj, part)
-
- if isinstance(obj, types.ModuleType):
- return self.loadTestsFromModule(obj)
- elif (((py3k and isinstance(obj, type))
- or isinstance(obj, (type, types.ClassType)))
- and issubclass(obj, TestCase)):
- return self.loadTestsFromTestCase(obj)
- elif isinstance(obj, types.UnboundMethodType):
- if py3k:
- return obj.__self__.__class__(obj.__name__)
- else:
- return obj.im_class(obj.__name__)
- elif hasattr(obj, '__call__'):
- test = obj()
- if not isinstance(test, TestCase) and \
- not isinstance(test, TestSuite):
- raise ValueError("calling %s returned %s, "
- "not a test" % (obj, test))
- return test
- else:
- raise ValueError("do not know how to make test from: %s" % obj)
-
-
-try:
- # Jython support
- if sys.platform[:4] == 'java':
- def getchar():
- # Hopefully this is enough
- return sys.stdin.read(1)
- else:
- # On Windows, msvcrt.getch reads a single char without output.
- import msvcrt
-
- def getchar():
- return msvcrt.getch()
-except ImportError:
- # Unix getchr
- import tty
- import termios
-
- def getchar():
- fd = sys.stdin.fileno()
- old_settings = termios.tcgetattr(fd)
- try:
- tty.setraw(sys.stdin.fileno())
- ch = sys.stdin.read(1)
- finally:
- termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
- return ch
-
-
-class WebCase(TestCase):
- HOST = "127.0.0.1"
- PORT = 8000
- HTTP_CONN = HTTPConnection
- PROTOCOL = "HTTP/1.1"
-
- scheme = "http"
- url = None
-
- status = None
- headers = None
- body = None
-
- encoding = 'utf-8'
-
- time = None
-
- def get_conn(self, auto_open=False):
- """Return a connection to our HTTP server."""
- if self.scheme == "https":
- cls = HTTPSConnection
- else:
- cls = HTTPConnection
- conn = cls(self.interface(), self.PORT)
- # Automatically re-connect?
- conn.auto_open = auto_open
- conn.connect()
- return conn
-
- def set_persistent(self, on=True, auto_open=False):
- """Make our HTTP_CONN persistent (or not).
-
- If the 'on' argument is True (the default), then self.HTTP_CONN
- will be set to an instance of HTTPConnection (or HTTPS
- if self.scheme is "https"). This will then persist across requests.
-
- We only allow for a single open connection, so if you call this
- and we currently have an open connection, it will be closed.
- """
- try:
- self.HTTP_CONN.close()
- except (TypeError, AttributeError):
- pass
-
- if on:
- self.HTTP_CONN = self.get_conn(auto_open=auto_open)
- else:
- if self.scheme == "https":
- self.HTTP_CONN = HTTPSConnection
- else:
- self.HTTP_CONN = HTTPConnection
-
- def _get_persistent(self):
- return hasattr(self.HTTP_CONN, "__class__")
-
- def _set_persistent(self, on):
- self.set_persistent(on)
- persistent = property(_get_persistent, _set_persistent)
-
- def interface(self):
- """Return an IP address for a client connection.
-
- If the server is listening on '0.0.0.0' (INADDR_ANY)
- or '::' (IN6ADDR_ANY), this will return the proper localhost."""
- return interface(self.HOST)
-
- def getPage(self, url, headers=None, method="GET", body=None,
- protocol=None, raise_subcls=None):
- """Open the url with debugging support. Return status, headers, body.
-
- `raise_subcls` must be a tuple with the exceptions classes
- or a single exception class that are not going to be considered
- a socket.error regardless that they were are subclass of a
- socket.error and therefore not considered for a connection retry.
- """
- ServerError.on = False
-
- if isinstance(url, unicodestr):
- url = url.encode('utf-8')
- if isinstance(body, unicodestr):
- body = body.encode('utf-8')
-
- self.url = url
- self.time = None
- start = time.time()
- result = openURL(url, headers, method, body, self.HOST, self.PORT,
- self.HTTP_CONN, protocol or self.PROTOCOL,
- raise_subcls)
- self.time = time.time() - start
- self.status, self.headers, self.body = result
-
- # Build a list of request cookies from the previous response cookies.
- self.cookies = [('Cookie', v) for k, v in self.headers
- if k.lower() == 'set-cookie']
-
- if ServerError.on:
- raise ServerError()
- return result
-
- interactive = True
- console_height = 30
-
- def _handlewebError(self, msg):
- print("")
- print(" ERROR: %s" % msg)
-
- if not self.interactive:
- raise self.failureException(msg)
-
- p = (" Show: "
- "[B]ody [H]eaders [S]tatus [U]RL; "
- "[I]gnore, [R]aise, or sys.e[X]it >> ")
- sys.stdout.write(p)
- sys.stdout.flush()
- while True:
- i = getchar().upper()
- if not isinstance(i, type("")):
- i = i.decode('ascii')
- if i not in "BHSUIRX":
- continue
- print(i.upper()) # Also prints new line
- if i == "B":
- for x, line in enumerate(self.body.splitlines()):
- if (x + 1) % self.console_height == 0:
- # The \r and comma should make the next line overwrite
- sys.stdout.write("<-- More -->\r")
- m = getchar().lower()
- # Erase our "More" prompt
- sys.stdout.write(" \r")
- if m == "q":
- break
- print(line)
- elif i == "H":
- pprint.pprint(self.headers)
- elif i == "S":
- print(self.status)
- elif i == "U":
- print(self.url)
- elif i == "I":
- # return without raising the normal exception
- return
- elif i == "R":
- raise self.failureException(msg)
- elif i == "X":
- self.exit()
- sys.stdout.write(p)
- sys.stdout.flush()
-
- def exit(self):
- sys.exit()
-
- def assertStatus(self, status, msg=None):
- """Fail if self.status != status."""
- if isinstance(status, basestring):
- if not self.status == status:
- if msg is None:
- msg = 'Status (%r) != %r' % (self.status, status)
- self._handlewebError(msg)
- elif isinstance(status, int):
- code = int(self.status[:3])
- if code != status:
- if msg is None:
- msg = 'Status (%r) != %r' % (self.status, status)
- self._handlewebError(msg)
- else:
- # status is a tuple or list.
- match = False
- for s in status:
- if isinstance(s, basestring):
- if self.status == s:
- match = True
- break
- elif int(self.status[:3]) == s:
- match = True
- break
- if not match:
- if msg is None:
- msg = 'Status (%r) not in %r' % (self.status, status)
- self._handlewebError(msg)
-
- def assertHeader(self, key, value=None, msg=None):
- """Fail if (key, [value]) not in self.headers."""
- lowkey = key.lower()
- for k, v in self.headers:
- if k.lower() == lowkey:
- if value is None or str(value) == v:
- return v
-
- if msg is None:
- if value is None:
- msg = '%r not in headers' % key
- else:
- msg = '%r:%r not in headers' % (key, value)
- self._handlewebError(msg)
-
- def assertHeaderIn(self, key, values, msg=None):
- """Fail if header indicated by key doesn't have one of the values."""
- lowkey = key.lower()
- for k, v in self.headers:
- if k.lower() == lowkey:
- matches = [value for value in values if str(value) == v]
- if matches:
- return matches
-
- if msg is None:
- msg = '%(key)r not in %(values)r' % vars()
- self._handlewebError(msg)
-
- def assertHeaderItemValue(self, key, value, msg=None):
- """Fail if the header does not contain the specified value"""
- actual_value = self.assertHeader(key, msg=msg)
- header_values = map(str.strip, actual_value.split(','))
- if value in header_values:
- return value
-
- if msg is None:
- msg = "%r not in %r" % (value, header_values)
- self._handlewebError(msg)
-
- def assertNoHeader(self, key, msg=None):
- """Fail if key in self.headers."""
- lowkey = key.lower()
- matches = [k for k, v in self.headers if k.lower() == lowkey]
- if matches:
- if msg is None:
- msg = '%r in headers' % key
- self._handlewebError(msg)
-
- def assertBody(self, value, msg=None):
- """Fail if value != self.body."""
- if isinstance(value, unicodestr):
- value = value.encode(self.encoding)
- if value != self.body:
- if msg is None:
- msg = 'expected body:\n%r\n\nactual body:\n%r' % (
- value, self.body)
- self._handlewebError(msg)
-
- def assertInBody(self, value, msg=None):
- """Fail if value not in self.body."""
- if isinstance(value, unicodestr):
- value = value.encode(self.encoding)
- if value not in self.body:
- if msg is None:
- msg = '%r not in body: %s' % (value, self.body)
- self._handlewebError(msg)
-
- def assertNotInBody(self, value, msg=None):
- """Fail if value in self.body."""
- if isinstance(value, unicodestr):
- value = value.encode(self.encoding)
- if value in self.body:
- if msg is None:
- msg = '%r found in body' % value
- self._handlewebError(msg)
-
- def assertMatchesBody(self, pattern, msg=None, flags=0):
- """Fail if value (a regex pattern) is not in self.body."""
- if isinstance(pattern, unicodestr):
- pattern = pattern.encode(self.encoding)
- if re.search(pattern, self.body, flags) is None:
- if msg is None:
- msg = 'No match for %r in body' % pattern
- self._handlewebError(msg)
-
-
-methods_with_bodies = ("POST", "PUT")
-
-
-def cleanHeaders(headers, method, body, host, port):
- """Return request headers, with required headers added (if missing)."""
- if headers is None:
- headers = []
-
- # Add the required Host request header if not present.
- # [This specifies the host:port of the server, not the client.]
- found = False
- for k, v in headers:
- if k.lower() == 'host':
- found = True
- break
- if not found:
- if port == 80:
- headers.append(("Host", host))
- else:
- headers.append(("Host", "%s:%s" % (host, port)))
-
- if method in methods_with_bodies:
- # Stick in default type and length headers if not present
- found = False
- for k, v in headers:
- if k.lower() == 'content-type':
- found = True
- break
- if not found:
- headers.append(
- ("Content-Type", "application/x-www-form-urlencoded"))
- headers.append(("Content-Length", str(len(body or ""))))
-
- return headers
-
-
-def shb(response):
- """Return status, headers, body the way we like from a response."""
- if py3k:
- h = response.getheaders()
- else:
- h = []
- key, value = None, None
- for line in response.msg.headers:
- if line:
- if line[0] in " \t":
- value += line.strip()
- else:
- if key and value:
- h.append((key, value))
- key, value = line.split(":", 1)
- key = key.strip()
- value = value.strip()
- if key and value:
- h.append((key, value))
-
- return "%s %s" % (response.status, response.reason), h, response.read()
-
-
-def openURL(url, headers=None, method="GET", body=None,
- host="127.0.0.1", port=8000, http_conn=HTTPConnection,
- protocol="HTTP/1.1", raise_subcls=None):
- """
- Open the given HTTP resource and return status, headers, and body.
-
- `raise_subcls` must be a tuple with the exceptions classes
- or a single exception class that are not going to be considered
- a socket.error regardless that they were are subclass of a
- socket.error and therefore not considered for a connection retry.
- """
- headers = cleanHeaders(headers, method, body, host, port)
-
- # Trying 10 times is simply in case of socket errors.
- # Normal case--it should run once.
- for trial in range(10):
- try:
- # Allow http_conn to be a class or an instance
- if hasattr(http_conn, "host"):
- conn = http_conn
- else:
- conn = http_conn(interface(host), port)
-
- conn._http_vsn_str = protocol
- conn._http_vsn = int("".join([x for x in protocol if x.isdigit()]))
-
- if py3k and isinstance(url, bytes):
- url = url.decode()
- conn.putrequest(method.upper(), url, skip_host=True,
- skip_accept_encoding=True)
-
- for key, value in headers:
- conn.putheader(key, value.encode("Latin-1"))
- conn.endheaders()
-
- if body is not None:
- conn.send(body)
-
- # Handle response
- response = conn.getresponse()
-
- s, h, b = shb(response)
-
- if not hasattr(http_conn, "host"):
- # We made our own conn instance. Close it.
- conn.close()
-
- return s, h, b
- except socket.error as e:
- if raise_subcls is not None and isinstance(e, raise_subcls):
- raise
- else:
- time.sleep(0.5)
- if trial == 9:
- raise
-
-
-
-
-# Add any exceptions which your web framework handles
-# normally (that you don't want server_error to trap).
-ignored_exceptions = []
-
-# You'll want set this to True when you can't guarantee
-# that each response will immediately follow each request;
-# for example, when handling requests via multiple threads.
-ignore_all = False
-
-
-class ServerError(Exception):
- on = False
-
-
-def server_error(exc=None):
- """Server debug hook. Return True if exception handled, False if ignored.
-
- You probably want to wrap this, so you can still handle an error using
- your framework when it's ignored.
- """
- if exc is None:
- exc = sys.exc_info()
-
- if ignore_all or exc[0] in ignored_exceptions:
- return False
- else:
- ServerError.on = True
- print("")
- print("".join(traceback.format_exception(*exc)))
- return True
+warnings.warn('Use cheroot.test.webtest', DeprecationWarning)
diff --git a/cherrypy/tutorial/README.rst b/cherrypy/tutorial/README.rst
new file mode 100644
index 00000000..3c0791bb
--- /dev/null
+++ b/cherrypy/tutorial/README.rst
@@ -0,0 +1,16 @@
+CherryPy Tutorials
+------------------------------------------------------------------------
+
+This is a series of tutorials explaining how to develop dynamic web
+applications using CherryPy. A couple of notes:
+
+
+- Each of these tutorials builds on the ones before it. If you're
+ new to CherryPy, we recommend you start with 01_helloworld.py and
+ work your way upwards. :)
+
+- In most of these tutorials, you will notice that all output is done
+ by returning normal Python strings, often using simple Python
+ variable substitution. In most real-world applications, you will
+ probably want to use a separate template package (like Cheetah,
+ CherryTemplate or XML/XSL).
diff --git a/cherrypy/tutorial/README.txt b/cherrypy/tutorial/README.txt
deleted file mode 100644
index 2b877e1f..00000000
--- a/cherrypy/tutorial/README.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-CherryPy Tutorials
-------------------------------------------------------------------------
-
-This is a series of tutorials explaining how to develop dynamic web
-applications using CherryPy. A couple of notes:
-
- - Each of these tutorials builds on the ones before it. If you're
- new to CherryPy, we recommend you start with 01_helloworld.py and
- work your way upwards. :)
-
- - In most of these tutorials, you will notice that all output is done
- by returning normal Python strings, often using simple Python
- variable substitution. In most real-world applications, you will
- probably want to use a separate template package (like Cheetah,
- CherryTemplate or XML/XSL).
-
diff --git a/cherrypy/tutorial/tut01_helloworld.py b/cherrypy/tutorial/tut01_helloworld.py
index 2fa61afa..e86793c8 100644
--- a/cherrypy/tutorial/tut01_helloworld.py
+++ b/cherrypy/tutorial/tut01_helloworld.py
@@ -4,6 +4,8 @@ Tutorial - Hello World
The most basic (working) CherryPy application possible.
"""
+import os.path
+
# Import CherryPy global namespace
import cherrypy
@@ -12,19 +14,17 @@ class HelloWorld:
""" Sample request handler class. """
+ # Expose the index method through the web. CherryPy will never
+ # publish methods that don't have the exposed attribute set to True.
+ @cherrypy.expose
def index(self):
# CherryPy will call this method for the root URI ("/") and send
# its return value to the client. Because this is tutorial
# lesson number 01, we'll just send something really simple.
# How about...
- return "Hello world!"
+ return 'Hello world!'
- # Expose the index method through the web. CherryPy will never
- # publish methods that don't have the exposed attribute set to True.
- index.exposed = True
-
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -32,6 +32,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HelloWorld(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(HelloWorld(), config=tutconf)
diff --git a/cherrypy/tutorial/tut02_expose_methods.py b/cherrypy/tutorial/tut02_expose_methods.py
index 64a10f26..8afbf7d8 100644
--- a/cherrypy/tutorial/tut02_expose_methods.py
+++ b/cherrypy/tutorial/tut02_expose_methods.py
@@ -5,22 +5,24 @@ This tutorial shows you how to link to other methods of your request
handler.
"""
+import os.path
+
import cherrypy
class HelloWorld:
+ @cherrypy.expose
def index(self):
# Let's link to another method here.
return 'We have an <a href="show_msg">important message</a> for you!'
- index.exposed = True
+ @cherrypy.expose
def show_msg(self):
# Here's the important message!
- return "Hello world!"
- show_msg.exposed = True
+ return 'Hello world!'
+
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -28,6 +30,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HelloWorld(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(HelloWorld(), config=tutconf)
diff --git a/cherrypy/tutorial/tut03_get_and_post.py b/cherrypy/tutorial/tut03_get_and_post.py
index a487a909..0b3d4613 100644
--- a/cherrypy/tutorial/tut03_get_and_post.py
+++ b/cherrypy/tutorial/tut03_get_and_post.py
@@ -4,11 +4,14 @@ Tutorial - Passing variables
This tutorial shows you how to pass GET/POST variables to methods.
"""
+import os.path
+
import cherrypy
class WelcomePage:
+ @cherrypy.expose
def index(self):
# Ask for the user's name.
return '''
@@ -17,8 +20,8 @@ class WelcomePage:
<input type="text" name="name" />
<input type="submit" />
</form>'''
- index.exposed = True
+ @cherrypy.expose
def greetUser(self, name=None):
# CherryPy passes all GET and POST variables as method parameters.
# It doesn't make a difference where the variables come from, how
@@ -37,10 +40,8 @@ class WelcomePage:
return 'Please enter your name <a href="./">here</a>.'
else:
return 'No, really, enter your name <a href="./">here</a>.'
- greetUser.exposed = True
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -48,6 +49,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(WelcomePage(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(WelcomePage(), config=tutconf)
diff --git a/cherrypy/tutorial/tut04_complex_site.py b/cherrypy/tutorial/tut04_complex_site.py
index e0660024..3caa1775 100644
--- a/cherrypy/tutorial/tut04_complex_site.py
+++ b/cherrypy/tutorial/tut04_complex_site.py
@@ -5,11 +5,14 @@ This tutorial shows you how to create a site structure through multiple
possibly nested request handler objects.
"""
+import os.path
+
import cherrypy
class HomePage:
+ @cherrypy.expose
def index(self):
return '''
<p>Hi, this is the home page! Check out the other
@@ -19,17 +22,16 @@ class HomePage:
<li><a href="/joke/">A silly joke</a></li>
<li><a href="/links/">Useful links</a></li>
</ul>'''
- index.exposed = True
class JokePage:
+ @cherrypy.expose
def index(self):
return '''
<p>"In Python, how do you create a string of random
characters?" -- "Read a Perl file!"</p>
<p>[<a href="../">Return</a>]</p>'''
- index.exposed = True
class LinksPage:
@@ -40,6 +42,7 @@ class LinksPage:
# methods!
self.extra = ExtraLinksPage()
+ @cherrypy.expose
def index(self):
# Note the way we link to the extra links page (and back).
# As you can see, this object doesn't really care about its
@@ -62,11 +65,11 @@ class LinksPage:
<p>[<a href="../">Return</a>]</p>
'''
- index.exposed = True
class ExtraLinksPage:
+ @cherrypy.expose
def index(self):
# Note the relative link back to the Links page!
return '''
@@ -78,7 +81,6 @@ class ExtraLinksPage:
</ul>
<p>[<a href="../">Return to links page</a>]</p>'''
- index.exposed = True
# Of course we can also mount request handler objects right here!
@@ -92,7 +94,6 @@ root.links = LinksPage()
# creating all contained request handler objects.
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -100,6 +101,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(root, config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(root, config=tutconf)
diff --git a/cherrypy/tutorial/tut05_derived_objects.py b/cherrypy/tutorial/tut05_derived_objects.py
index 9f4f2c32..f626e03f 100644
--- a/cherrypy/tutorial/tut05_derived_objects.py
+++ b/cherrypy/tutorial/tut05_derived_objects.py
@@ -7,6 +7,8 @@ want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
+import os.path
+
import cherrypy
@@ -45,6 +47,7 @@ class HomePage(Page):
# create a subpage
self.another = AnotherPage()
+ @cherrypy.expose
def index(self):
# Note that we call the header and footer methods inherited
# from the Page class!
@@ -54,22 +57,20 @@ class HomePage(Page):
<a href="./another/">another page</a>, too!
</p>
''' + self.footer()
- index.exposed = True
class AnotherPage(Page):
title = 'Another Page'
+ @cherrypy.expose
def index(self):
return self.header() + '''
<p>
And this is the amazing second page!
</p>
''' + self.footer()
- index.exposed = True
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -77,6 +78,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HomePage(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(HomePage(), config=tutconf)
diff --git a/cherrypy/tutorial/tut06_default_method.py b/cherrypy/tutorial/tut06_default_method.py
index f71c315a..0ce4cabe 100644
--- a/cherrypy/tutorial/tut06_default_method.py
+++ b/cherrypy/tutorial/tut06_default_method.py
@@ -16,11 +16,14 @@ like /users/<username>. Since the <username> bit will not be found (as
there are no matching methods), it is handled by the default method.
"""
+import os.path
+
import cherrypy
class UsersPage:
+ @cherrypy.expose
def index(self):
# Since this is just a stupid little example, we'll simply
# display a list of links to random, made-up users. In a real
@@ -30,27 +33,25 @@ class UsersPage:
<a href="./hendrik">Hendrik Mans</a><br/>
<a href="./lorenzo">Lorenzo Lamas</a><br/>
'''
- index.exposed = True
+ @cherrypy.expose
def default(self, user):
# Here we react depending on the virtualPath -- the part of the
# path that could not be mapped to an object method. In a real
# application, we would probably do some database lookups here
# instead of the silly if/elif/else construct.
if user == 'remi':
- out = "Remi Delon, CherryPy lead developer"
+ out = 'Remi Delon, CherryPy lead developer'
elif user == 'hendrik':
- out = "Hendrik Mans, CherryPy co-developer & crazy German"
+ out = 'Hendrik Mans, CherryPy co-developer & crazy German'
elif user == 'lorenzo':
- out = "Lorenzo Lamas, famous actor and singer!"
+ out = 'Lorenzo Lamas, famous actor and singer!'
else:
- out = "Unknown user. :-("
+ out = 'Unknown user. :-('
return '%s (<a href="./">back</a>)' % out
- default.exposed = True
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -58,6 +59,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(UsersPage(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(UsersPage(), config=tutconf)
diff --git a/cherrypy/tutorial/tut07_sessions.py b/cherrypy/tutorial/tut07_sessions.py
index 62efa440..204322b5 100644
--- a/cherrypy/tutorial/tut07_sessions.py
+++ b/cherrypy/tutorial/tut07_sessions.py
@@ -8,6 +8,8 @@ any kind of object into that dictionary; otherwise, you are limited to
objects that can be pickled.
"""
+import os.path
+
import cherrypy
@@ -15,6 +17,7 @@ class HitCounter:
_cp_config = {'tools.sessions.on': True}
+ @cherrypy.expose
def index(self):
# Increase the silly hit counter
count = cherrypy.session.get('count', 0) + 1
@@ -27,10 +30,8 @@ class HitCounter:
During your current session, you've viewed this
page %s times! Your life is a patio of fun!
''' % count
- index.exposed = True
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -38,6 +39,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HitCounter(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(HitCounter(), config=tutconf)
diff --git a/cherrypy/tutorial/tut08_generators_and_yield.py b/cherrypy/tutorial/tut08_generators_and_yield.py
index 40566e32..18f42f93 100644
--- a/cherrypy/tutorial/tut08_generators_and_yield.py
+++ b/cherrypy/tutorial/tut08_generators_and_yield.py
@@ -7,33 +7,34 @@ in situations where using a template package like CherryPy or Cheetah
would be overkill, and messy string concatenation too uncool. ;-)
"""
+import os.path
+
import cherrypy
class GeneratorDemo:
def header(self):
- return "<html><body><h2>Generators rule!</h2>"
+ return '<html><body><h2>Generators rule!</h2>'
def footer(self):
- return "</body></html>"
+ return '</body></html>'
+ @cherrypy.expose
def index(self):
# Let's make up a list of users for presentation purposes
users = ['Remi', 'Carlos', 'Hendrik', 'Lorenzo Lamas']
# Every yield line adds one part to the total result body.
yield self.header()
- yield "<h3>List of users:</h3>"
+ yield '<h3>List of users:</h3>'
for user in users:
- yield "%s<br/>" % user
+ yield '%s<br/>' % user
yield self.footer()
- index.exposed = True
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -41,6 +42,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(GeneratorDemo(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(GeneratorDemo(), config=tutconf)
diff --git a/cherrypy/tutorial/tut09_files.py b/cherrypy/tutorial/tut09_files.py
index 6a7b4a34..48585cbe 100644
--- a/cherrypy/tutorial/tut09_files.py
+++ b/cherrypy/tutorial/tut09_files.py
@@ -41,15 +41,18 @@ popular browsers.
"""
import os
-localDir = os.path.dirname(__file__)
-absDir = os.path.join(os.getcwd(), localDir)
+import os.path
import cherrypy
from cherrypy.lib import static
+localDir = os.path.dirname(__file__)
+absDir = os.path.join(os.getcwd(), localDir)
+
class FileDemo(object):
+ @cherrypy.expose
def index(self):
return """
<html><body>
@@ -62,8 +65,8 @@ class FileDemo(object):
<a href='download'>This one</a>
</body></html>
"""
- index.exposed = True
+ @cherrypy.expose
def upload(self, myFile):
out = """<html>
<body>
@@ -85,16 +88,14 @@ class FileDemo(object):
size += len(data)
return out % (size, myFile.filename, myFile.content_type)
- upload.exposed = True
+ @cherrypy.expose
def download(self):
- path = os.path.join(absDir, "pdf_file.pdf")
- return static.serve_file(path, "application/x-download",
- "attachment", os.path.basename(path))
- download.exposed = True
+ path = os.path.join(absDir, 'pdf_file.pdf')
+ return static.serve_file(path, 'application/x-download',
+ 'attachment', os.path.basename(path))
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -102,6 +103,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(FileDemo(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(FileDemo(), config=tutconf)
diff --git a/cherrypy/tutorial/tut10_http_errors.py b/cherrypy/tutorial/tut10_http_errors.py
index c0e9893b..18f02fd0 100644
--- a/cherrypy/tutorial/tut10_http_errors.py
+++ b/cherrypy/tutorial/tut10_http_errors.py
@@ -9,18 +9,21 @@ logged, displayed, and formatted.
"""
import os
-localDir = os.path.dirname(__file__)
-curpath = os.path.normpath(os.path.join(os.getcwd(), localDir))
+import os.path
import cherrypy
+localDir = os.path.dirname(__file__)
+curpath = os.path.normpath(os.path.join(os.getcwd(), localDir))
+
class HTTPErrorDemo(object):
# Set a custom response for 403 errors.
_cp_config = {'error_page.403':
- os.path.join(curpath, "custom_error.html")}
+ os.path.join(curpath, 'custom_error.html')}
+ @cherrypy.expose
def index(self):
# display some links that will result in errors
tracebacks = cherrypy.request.show_tracebacks
@@ -49,8 +52,8 @@ class HTTPErrorDemo(object):
when you raise an error.</a></p>
</body></html>
""" % trace
- index.exposed = True
+ @cherrypy.expose
def toggleTracebacks(self):
# simple function to toggle tracebacks on and off
tracebacks = cherrypy.request.show_tracebacks
@@ -58,22 +61,20 @@ class HTTPErrorDemo(object):
# redirect back to the index
raise cherrypy.HTTPRedirect('/')
- toggleTracebacks.exposed = True
+ @cherrypy.expose
def error(self, code):
# raise an error based on the get query
raise cherrypy.HTTPError(status=code)
- error.exposed = True
+ @cherrypy.expose
def messageArg(self):
message = ("If you construct an HTTPError with a 'message' "
- "argument, it wil be placed on the error page "
- "(underneath the status line by default).")
+ 'argument, it wil be placed on the error page '
+ '(underneath the status line by default).')
raise cherrypy.HTTPError(500, message=message)
- messageArg.exposed = True
-import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
@@ -81,6 +82,3 @@ if __name__ == '__main__':
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HTTPErrorDemo(), config=tutconf)
-else:
- # This branch is for the test suite; you can ignore it.
- cherrypy.tree.mount(HTTPErrorDemo(), config=tutconf)
diff --git a/cherrypy/wsgiserver/__init__.py b/cherrypy/wsgiserver/__init__.py
deleted file mode 100644
index ee6190fe..00000000
--- a/cherrypy/wsgiserver/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer',
- 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile',
- 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert',
- 'WorkerThread', 'ThreadPool', 'SSLAdapter',
- 'CherryPyWSGIServer',
- 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0',
- 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class']
-
-import sys
-if sys.version_info < (3, 0):
- from wsgiserver2 import *
-else:
- # Le sigh. Boo for backward-incompatible syntax.
- exec('from .wsgiserver3 import *')
diff --git a/cherrypy/wsgiserver/ssl_builtin.py b/cherrypy/wsgiserver/ssl_builtin.py
deleted file mode 100644
index 2c74ad84..00000000
--- a/cherrypy/wsgiserver/ssl_builtin.py
+++ /dev/null
@@ -1,92 +0,0 @@
-"""A library for integrating Python's builtin ``ssl`` library with CherryPy.
-
-The ssl module must be importable for SSL functionality.
-
-To use this module, set ``CherryPyWSGIServer.ssl_adapter`` to an instance of
-``BuiltinSSLAdapter``.
-"""
-
-try:
- import ssl
-except ImportError:
- ssl = None
-
-try:
- from _pyio import DEFAULT_BUFFER_SIZE
-except ImportError:
- try:
- from io import DEFAULT_BUFFER_SIZE
- except ImportError:
- DEFAULT_BUFFER_SIZE = -1
-
-import sys
-
-from cherrypy import wsgiserver
-
-
-class BuiltinSSLAdapter(wsgiserver.SSLAdapter):
-
- """A wrapper for integrating Python's builtin ssl module with CherryPy."""
-
- certificate = None
- """The filename of the server SSL certificate."""
-
- private_key = None
- """The filename of the server's private key file."""
-
- def __init__(self, certificate, private_key, certificate_chain=None):
- if ssl is None:
- raise ImportError("You must install the ssl module to use HTTPS.")
- self.certificate = certificate
- self.private_key = private_key
- self.certificate_chain = certificate_chain
-
- def bind(self, sock):
- """Wrap and return the given socket."""
- return sock
-
- def wrap(self, sock):
- """Wrap and return the given socket, plus WSGI environ entries."""
- try:
- s = ssl.wrap_socket(sock, do_handshake_on_connect=True,
- server_side=True, certfile=self.certificate,
- keyfile=self.private_key,
- ssl_version=ssl.PROTOCOL_SSLv23)
- except ssl.SSLError:
- e = sys.exc_info()[1]
- if e.errno == ssl.SSL_ERROR_EOF:
- # This is almost certainly due to the cherrypy engine
- # 'pinging' the socket to assert it's connectable;
- # the 'ping' isn't SSL.
- return None, {}
- elif e.errno == ssl.SSL_ERROR_SSL:
- if e.args[1].endswith('http request'):
- # The client is speaking HTTP to an HTTPS server.
- raise wsgiserver.NoSSLError
- elif e.args[1].endswith('unknown protocol'):
- # The client is speaking some non-HTTP protocol.
- # Drop the conn.
- return None, {}
- raise
- return s, self.get_environ(s)
-
- # TODO: fill this out more with mod ssl env
- def get_environ(self, sock):
- """Create WSGI environ entries to be merged into each request."""
- cipher = sock.cipher()
- ssl_environ = {
- "wsgi.url_scheme": "https",
- "HTTPS": "on",
- 'SSL_PROTOCOL': cipher[1],
- 'SSL_CIPHER': cipher[0]
- # SSL_VERSION_INTERFACE string The mod_ssl program version
- # SSL_VERSION_LIBRARY string The OpenSSL program version
- }
- return ssl_environ
-
- if sys.version_info >= (3, 0):
- def makefile(self, sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE):
- return wsgiserver.CP_makefile(sock, mode, bufsize)
- else:
- def makefile(self, sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE):
- return wsgiserver.CP_fileobject(sock, mode, bufsize)
diff --git a/cherrypy/wsgiserver/ssl_pyopenssl.py b/cherrypy/wsgiserver/ssl_pyopenssl.py
deleted file mode 100644
index 62ede265..00000000
--- a/cherrypy/wsgiserver/ssl_pyopenssl.py
+++ /dev/null
@@ -1,253 +0,0 @@
-"""A library for integrating pyOpenSSL with CherryPy.
-
-The OpenSSL module must be importable for SSL functionality.
-You can obtain it from `here <https://launchpad.net/pyopenssl>`_.
-
-To use this module, set CherryPyWSGIServer.ssl_adapter to an instance of
-SSLAdapter. There are two ways to use SSL:
-
-Method One
-----------
-
- * ``ssl_adapter.context``: an instance of SSL.Context.
-
-If this is not None, it is assumed to be an SSL.Context instance,
-and will be passed to SSL.Connection on bind(). The developer is
-responsible for forming a valid Context object. This approach is
-to be preferred for more flexibility, e.g. if the cert and key are
-streams instead of files, or need decryption, or SSL.SSLv3_METHOD
-is desired instead of the default SSL.SSLv23_METHOD, etc. Consult
-the pyOpenSSL documentation for complete options.
-
-Method Two (shortcut)
----------------------
-
- * ``ssl_adapter.certificate``: the filename of the server SSL certificate.
- * ``ssl_adapter.private_key``: the filename of the server's private key file.
-
-Both are None by default. If ssl_adapter.context is None, but .private_key
-and .certificate are both given and valid, they will be read, and the
-context will be automatically created from them.
-"""
-
-import socket
-import threading
-import time
-
-from cherrypy import wsgiserver
-
-try:
- from OpenSSL import SSL
- from OpenSSL import crypto
-except ImportError:
- SSL = None
-
-
-class SSL_fileobject(wsgiserver.CP_fileobject):
-
- """SSL file object attached to a socket object."""
-
- ssl_timeout = 3
- ssl_retry = .01
-
- def _safe_call(self, is_reader, call, *args, **kwargs):
- """Wrap the given call with SSL error-trapping.
-
- is_reader: if False EOF errors will be raised. If True, EOF errors
- will return "" (to emulate normal sockets).
- """
- start = time.time()
- while True:
- try:
- return call(*args, **kwargs)
- except SSL.WantReadError:
- # Sleep and try again. This is dangerous, because it means
- # the rest of the stack has no way of differentiating
- # between a "new handshake" error and "client dropped".
- # Note this isn't an endless loop: there's a timeout below.
- time.sleep(self.ssl_retry)
- except SSL.WantWriteError:
- time.sleep(self.ssl_retry)
- except SSL.SysCallError as e:
- if is_reader and e.args == (-1, 'Unexpected EOF'):
- return ""
-
- errnum = e.args[0]
- if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
- return ""
- raise socket.error(errnum)
- except SSL.Error as e:
- if is_reader and e.args == (-1, 'Unexpected EOF'):
- return ""
-
- thirdarg = None
- try:
- thirdarg = e.args[0][0][2]
- except IndexError:
- pass
-
- if thirdarg == 'http request':
- # The client is talking HTTP to an HTTPS server.
- raise wsgiserver.NoSSLError()
-
- raise wsgiserver.FatalSSLAlert(*e.args)
- except:
- raise
-
- if time.time() - start > self.ssl_timeout:
- raise socket.timeout("timed out")
-
- def recv(self, size):
- return self._safe_call(True, super(SSL_fileobject, self).recv, size)
-
- def sendall(self, *args, **kwargs):
- return self._safe_call(False, super(SSL_fileobject, self).sendall,
- *args, **kwargs)
-
- def send(self, *args, **kwargs):
- return self._safe_call(False, super(SSL_fileobject, self).send,
- *args, **kwargs)
-
-
-class SSLConnection:
-
- """A thread-safe wrapper for an SSL.Connection.
-
- ``*args``: the arguments to create the wrapped ``SSL.Connection(*args)``.
- """
-
- def __init__(self, *args):
- self._ssl_conn = SSL.Connection(*args)
- self._lock = threading.RLock()
-
- for f in ('get_context', 'pending', 'send', 'write', 'recv', 'read',
- 'renegotiate', 'bind', 'listen', 'connect', 'accept',
- 'setblocking', 'fileno', 'close', 'get_cipher_list',
- 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
- 'makefile', 'get_app_data', 'set_app_data', 'state_string',
- 'sock_shutdown', 'get_peer_certificate', 'want_read',
- 'want_write', 'set_connect_state', 'set_accept_state',
- 'connect_ex', 'sendall', 'settimeout', 'gettimeout'):
- exec("""def %s(self, *args):
- self._lock.acquire()
- try:
- return self._ssl_conn.%s(*args)
- finally:
- self._lock.release()
-""" % (f, f))
-
- def shutdown(self, *args):
- self._lock.acquire()
- try:
- # pyOpenSSL.socket.shutdown takes no args
- return self._ssl_conn.shutdown()
- finally:
- self._lock.release()
-
-
-class pyOpenSSLAdapter(wsgiserver.SSLAdapter):
-
- """A wrapper for integrating pyOpenSSL with CherryPy."""
-
- context = None
- """An instance of SSL.Context."""
-
- certificate = None
- """The filename of the server SSL certificate."""
-
- private_key = None
- """The filename of the server's private key file."""
-
- certificate_chain = None
- """Optional. The filename of CA's intermediate certificate bundle.
-
- This is needed for cheaper "chained root" SSL certificates, and should be
- left as None if not required."""
-
- def __init__(self, certificate, private_key, certificate_chain=None):
- if SSL is None:
- raise ImportError("You must install pyOpenSSL to use HTTPS.")
-
- self.context = None
- self.certificate = certificate
- self.private_key = private_key
- self.certificate_chain = certificate_chain
- self._environ = None
-
- def bind(self, sock):
- """Wrap and return the given socket."""
- if self.context is None:
- self.context = self.get_context()
- conn = SSLConnection(self.context, sock)
- self._environ = self.get_environ()
- return conn
-
- def wrap(self, sock):
- """Wrap and return the given socket, plus WSGI environ entries."""
- return sock, self._environ.copy()
-
- def get_context(self):
- """Return an SSL.Context from self attributes."""
- # See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
- c = SSL.Context(SSL.SSLv23_METHOD)
- c.use_privatekey_file(self.private_key)
- if self.certificate_chain:
- c.load_verify_locations(self.certificate_chain)
- c.use_certificate_file(self.certificate)
- return c
-
- def get_environ(self):
- """Return WSGI environ entries to be merged into each request."""
- ssl_environ = {
- "HTTPS": "on",
- # pyOpenSSL doesn't provide access to any of these AFAICT
- # 'SSL_PROTOCOL': 'SSLv2',
- # SSL_CIPHER string The cipher specification name
- # SSL_VERSION_INTERFACE string The mod_ssl program version
- # SSL_VERSION_LIBRARY string The OpenSSL program version
- }
-
- if self.certificate:
- # Server certificate attributes
- cert = open(self.certificate, 'rb').read()
- cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
- ssl_environ.update({
- 'SSL_SERVER_M_VERSION': cert.get_version(),
- 'SSL_SERVER_M_SERIAL': cert.get_serial_number(),
- # 'SSL_SERVER_V_START':
- # Validity of server's certificate (start time),
- # 'SSL_SERVER_V_END':
- # Validity of server's certificate (end time),
- })
-
- for prefix, dn in [("I", cert.get_issuer()),
- ("S", cert.get_subject())]:
- # X509Name objects don't seem to have a way to get the
- # complete DN string. Use str() and slice it instead,
- # because str(dn) == "<X509Name object '/C=US/ST=...'>"
- dnstr = str(dn)[18:-2]
-
- wsgikey = 'SSL_SERVER_%s_DN' % prefix
- ssl_environ[wsgikey] = dnstr
-
- # The DN should be of the form: /k1=v1/k2=v2, but we must allow
- # for any value to contain slashes itself (in a URL).
- while dnstr:
- pos = dnstr.rfind("=")
- dnstr, value = dnstr[:pos], dnstr[pos + 1:]
- pos = dnstr.rfind("/")
- dnstr, key = dnstr[:pos], dnstr[pos + 1:]
- if key and value:
- wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key)
- ssl_environ[wsgikey] = value
-
- return ssl_environ
-
- def makefile(self, sock, mode='r', bufsize=-1):
- if SSL and isinstance(sock, SSL.ConnectionType):
- timeout = sock.gettimeout()
- f = SSL_fileobject(sock, mode, bufsize)
- f.ssl_timeout = timeout
- return f
- else:
- return wsgiserver.CP_fileobject(sock, mode, bufsize)
diff --git a/cherrypy/wsgiserver/wsgiserver2.py b/cherrypy/wsgiserver/wsgiserver2.py
deleted file mode 100644
index f3ae1f9d..00000000
--- a/cherrypy/wsgiserver/wsgiserver2.py
+++ /dev/null
@@ -1,2471 +0,0 @@
-"""A high-speed, production ready, thread pooled, generic HTTP server.
-
-Simplest example on how to use this module directly
-(without using CherryPy's application machinery)::
-
- from cherrypy import wsgiserver
-
- def my_crazy_app(environ, start_response):
- status = '200 OK'
- response_headers = [('Content-type','text/plain')]
- start_response(status, response_headers)
- return ['Hello world!']
-
- server = wsgiserver.CherryPyWSGIServer(
- ('0.0.0.0', 8070), my_crazy_app,
- server_name='www.cherrypy.example')
- server.start()
-
-The CherryPy WSGI server can serve as many WSGI applications
-as you want in one instance by using a WSGIPathInfoDispatcher::
-
- d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
- server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)
-
-Want SSL support? Just set server.ssl_adapter to an SSLAdapter instance.
-
-This won't call the CherryPy engine (application side) at all, only the
-HTTP server, which is independent from the rest of CherryPy. Don't
-let the name "CherryPyWSGIServer" throw you; the name merely reflects
-its origin, not its coupling.
-
-For those of you wanting to understand internals of this module, here's the
-basic call flow. The server's listening thread runs a very tight loop,
-sticking incoming connections onto a Queue::
-
- server = CherryPyWSGIServer(...)
- server.start()
- while True:
- tick()
- # This blocks until a request comes in:
- child = socket.accept()
- conn = HTTPConnection(child, ...)
- server.requests.put(conn)
-
-Worker threads are kept in a pool and poll the Queue, popping off and then
-handling each connection in turn. Each connection can consist of an arbitrary
-number of requests and their responses, so we run a nested loop::
-
- while True:
- conn = server.requests.get()
- conn.communicate()
- -> while True:
- req = HTTPRequest(...)
- req.parse_request()
- -> # Read the Request-Line, e.g. "GET /page HTTP/1.1"
- req.rfile.readline()
- read_headers(req.rfile, req.inheaders)
- req.respond()
- -> response = app(...)
- try:
- for chunk in response:
- if chunk:
- req.write(chunk)
- finally:
- if hasattr(response, "close"):
- response.close()
- if req.close_connection:
- return
-"""
-
-__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer',
- 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile',
- 'CP_fileobject',
- 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert',
- 'WorkerThread', 'ThreadPool', 'SSLAdapter',
- 'CherryPyWSGIServer',
- 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0',
- 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class',
- 'socket_errors_to_ignore']
-
-import os
-try:
- import queue
-except:
- import Queue as queue
-import re
-import email.utils
-import socket
-import sys
-import threading
-import time
-import traceback as traceback_
-import operator
-from urllib import unquote
-import warnings
-import errno
-import logging
-try:
- # prefer slower Python-based io module
- import _pyio as io
-except ImportError:
- # Python 2.6
- import io
-
-try:
- import pkg_resources
-except ImportError:
- pass
-
-if 'win' in sys.platform and hasattr(socket, "AF_INET6"):
- if not hasattr(socket, 'IPPROTO_IPV6'):
- socket.IPPROTO_IPV6 = 41
- if not hasattr(socket, 'IPV6_V6ONLY'):
- socket.IPV6_V6ONLY = 27
-
-
-DEFAULT_BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE
-
-
-try:
- cp_version = pkg_resources.require('cherrypy')[0].version
-except Exception:
- cp_version = 'unknown'
-
-
-class FauxSocket(object):
-
- """Faux socket with the minimal interface required by pypy"""
-
- def _reuse(self):
- pass
-
-_fileobject_uses_str_type = isinstance(
- socket._fileobject(FauxSocket())._rbuf, basestring)
-del FauxSocket # this class is not longer required for anything.
-
-
-if sys.version_info >= (3, 0):
- bytestr = bytes
- unicodestr = str
- basestring = (bytes, str)
-
- def ntob(n, encoding='ISO-8859-1'):
- """Return the given native string as a byte string in the given
- encoding.
- """
- # In Python 3, the native string type is unicode
- return n.encode(encoding)
-else:
- bytestr = str
- unicodestr = unicode
- basestring = basestring
-
- def ntob(n, encoding='ISO-8859-1'):
- """Return the given native string as a byte string in the given
- encoding.
- """
- # In Python 2, the native string type is bytes. Assume it's already
- # in the given encoding, which for ISO-8859-1 is almost always what
- # was intended.
- return n
-
-LF = ntob('\n')
-CRLF = ntob('\r\n')
-TAB = ntob('\t')
-SPACE = ntob(' ')
-COLON = ntob(':')
-SEMICOLON = ntob(';')
-EMPTY = ntob('')
-NUMBER_SIGN = ntob('#')
-QUESTION_MARK = ntob('?')
-ASTERISK = ntob('*')
-FORWARD_SLASH = ntob('/')
-quoted_slash = re.compile(ntob("(?i)%2F"))
-
-
-def plat_specific_errors(*errnames):
- """Return error numbers for all errors in errnames on this platform.
-
- The 'errno' module contains different global constants depending on
- the specific platform (OS). This function will return the list of
- numeric values for a given list of potential names.
- """
- errno_names = dir(errno)
- nums = [getattr(errno, k) for k in errnames if k in errno_names]
- # de-dupe the list
- return list(dict.fromkeys(nums).keys())
-
-socket_error_eintr = plat_specific_errors("EINTR", "WSAEINTR")
-
-socket_errors_to_ignore = plat_specific_errors(
- "EPIPE",
- "EBADF", "WSAEBADF",
- "ENOTSOCK", "WSAENOTSOCK",
- "ETIMEDOUT", "WSAETIMEDOUT",
- "ECONNREFUSED", "WSAECONNREFUSED",
- "ECONNRESET", "WSAECONNRESET",
- "ECONNABORTED", "WSAECONNABORTED",
- "ENETRESET", "WSAENETRESET",
- "EHOSTDOWN", "EHOSTUNREACH",
-)
-socket_errors_to_ignore.append("timed out")
-socket_errors_to_ignore.append("The read operation timed out")
-
-socket_errors_nonblocking = plat_specific_errors(
- 'EAGAIN', 'EWOULDBLOCK', 'WSAEWOULDBLOCK')
-
-comma_separated_headers = [
- ntob(h) for h in
- ['Accept', 'Accept-Charset', 'Accept-Encoding',
- 'Accept-Language', 'Accept-Ranges', 'Allow', 'Cache-Control',
- 'Connection', 'Content-Encoding', 'Content-Language', 'Expect',
- 'If-Match', 'If-None-Match', 'Pragma', 'Proxy-Authenticate', 'TE',
- 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Vary', 'Via', 'Warning',
- 'WWW-Authenticate']
-]
-
-
-if not hasattr(logging, 'statistics'):
- logging.statistics = {}
-
-
-def read_headers(rfile, hdict=None):
- """Read headers from the given stream into the given header dict.
-
- If hdict is None, a new header dict is created. Returns the populated
- header dict.
-
- Headers which are repeated are folded together using a comma if their
- specification so dictates.
-
- This function raises ValueError when the read bytes violate the HTTP spec.
- You should probably return "400 Bad Request" if this happens.
- """
- if hdict is None:
- hdict = {}
-
- while True:
- line = rfile.readline()
- if not line:
- # No more data--illegal end of headers
- raise ValueError("Illegal end of headers.")
-
- if line == CRLF:
- # Normal end of headers
- break
- if not line.endswith(CRLF):
- raise ValueError("HTTP requires CRLF terminators")
-
- if line[0] in (SPACE, TAB):
- # It's a continuation line.
- v = line.strip()
- else:
- try:
- k, v = line.split(COLON, 1)
- except ValueError:
- raise ValueError("Illegal header line.")
- # TODO: what about TE and WWW-Authenticate?
- k = k.strip().title()
- v = v.strip()
- hname = k
-
- if k in comma_separated_headers:
- existing = hdict.get(hname)
- if existing:
- v = ", ".join((existing, v))
- hdict[hname] = v
-
- return hdict
-
-
-class MaxSizeExceeded(Exception):
- pass
-
-
-class SizeCheckWrapper(object):
-
- """Wraps a file-like object, raising MaxSizeExceeded if too large."""
-
- def __init__(self, rfile, maxlen):
- self.rfile = rfile
- self.maxlen = maxlen
- self.bytes_read = 0
-
- def _check_length(self):
- if self.maxlen and self.bytes_read > self.maxlen:
- raise MaxSizeExceeded()
-
- def read(self, size=None):
- data = self.rfile.read(size)
- self.bytes_read += len(data)
- self._check_length()
- return data
-
- def readline(self, size=None):
- if size is not None:
- data = self.rfile.readline(size)
- self.bytes_read += len(data)
- self._check_length()
- return data
-
- # User didn't specify a size ...
- # We read the line in chunks to make sure it's not a 100MB line !
- res = []
- while True:
- data = self.rfile.readline(256)
- self.bytes_read += len(data)
- self._check_length()
- res.append(data)
- # See https://github.com/cherrypy/cherrypy/issues/421
- if len(data) < 256 or data[-1:] == LF:
- return EMPTY.join(res)
-
- def readlines(self, sizehint=0):
- # Shamelessly stolen from StringIO
- total = 0
- lines = []
- line = self.readline()
- while line:
- lines.append(line)
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline()
- return lines
-
- def close(self):
- self.rfile.close()
-
- def __iter__(self):
- return self
-
- def __next__(self):
- data = next(self.rfile)
- self.bytes_read += len(data)
- self._check_length()
- return data
-
- def next(self):
- data = self.rfile.next()
- self.bytes_read += len(data)
- self._check_length()
- return data
-
-
-class KnownLengthRFile(object):
-
- """Wraps a file-like object, returning an empty string when exhausted."""
-
- def __init__(self, rfile, content_length):
- self.rfile = rfile
- self.remaining = content_length
-
- def read(self, size=None):
- if self.remaining == 0:
- return ''
- if size is None:
- size = self.remaining
- else:
- size = min(size, self.remaining)
-
- data = self.rfile.read(size)
- self.remaining -= len(data)
- return data
-
- def readline(self, size=None):
- if self.remaining == 0:
- return ''
- if size is None:
- size = self.remaining
- else:
- size = min(size, self.remaining)
-
- data = self.rfile.readline(size)
- self.remaining -= len(data)
- return data
-
- def readlines(self, sizehint=0):
- # Shamelessly stolen from StringIO
- total = 0
- lines = []
- line = self.readline(sizehint)
- while line:
- lines.append(line)
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline(sizehint)
- return lines
-
- def close(self):
- self.rfile.close()
-
- def __iter__(self):
- return self
-
- def __next__(self):
- data = next(self.rfile)
- self.remaining -= len(data)
- return data
-
-
-class ChunkedRFile(object):
-
- """Wraps a file-like object, returning an empty string when exhausted.
-
- This class is intended to provide a conforming wsgi.input value for
- request entities that have been encoded with the 'chunked' transfer
- encoding.
- """
-
- def __init__(self, rfile, maxlen, bufsize=8192):
- self.rfile = rfile
- self.maxlen = maxlen
- self.bytes_read = 0
- self.buffer = EMPTY
- self.bufsize = bufsize
- self.closed = False
-
- def _fetch(self):
- if self.closed:
- return
-
- line = self.rfile.readline()
- self.bytes_read += len(line)
-
- if self.maxlen and self.bytes_read > self.maxlen:
- raise MaxSizeExceeded("Request Entity Too Large", self.maxlen)
-
- line = line.strip().split(SEMICOLON, 1)
-
- try:
- chunk_size = line.pop(0)
- chunk_size = int(chunk_size, 16)
- except ValueError:
- raise ValueError("Bad chunked transfer size: " + repr(chunk_size))
-
- if chunk_size <= 0:
- self.closed = True
- return
-
-## if line: chunk_extension = line[0]
-
- if self.maxlen and self.bytes_read + chunk_size > self.maxlen:
- raise IOError("Request Entity Too Large")
-
- chunk = self.rfile.read(chunk_size)
- self.bytes_read += len(chunk)
- self.buffer += chunk
-
- crlf = self.rfile.read(2)
- if crlf != CRLF:
- raise ValueError(
- "Bad chunked transfer coding (expected '\\r\\n', "
- "got " + repr(crlf) + ")")
-
- def read(self, size=None):
- data = EMPTY
- while True:
- if size and len(data) >= size:
- return data
-
- if not self.buffer:
- self._fetch()
- if not self.buffer:
- # EOF
- return data
-
- if size:
- remaining = size - len(data)
- data += self.buffer[:remaining]
- self.buffer = self.buffer[remaining:]
- else:
- data += self.buffer
-
- def readline(self, size=None):
- data = EMPTY
- while True:
- if size and len(data) >= size:
- return data
-
- if not self.buffer:
- self._fetch()
- if not self.buffer:
- # EOF
- return data
-
- newline_pos = self.buffer.find(LF)
- if size:
- if newline_pos == -1:
- remaining = size - len(data)
- data += self.buffer[:remaining]
- self.buffer = self.buffer[remaining:]
- else:
- remaining = min(size - len(data), newline_pos)
- data += self.buffer[:remaining]
- self.buffer = self.buffer[remaining:]
- else:
- if newline_pos == -1:
- data += self.buffer
- else:
- data += self.buffer[:newline_pos]
- self.buffer = self.buffer[newline_pos:]
-
- def readlines(self, sizehint=0):
- # Shamelessly stolen from StringIO
- total = 0
- lines = []
- line = self.readline(sizehint)
- while line:
- lines.append(line)
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline(sizehint)
- return lines
-
- def read_trailer_lines(self):
- if not self.closed:
- raise ValueError(
- "Cannot read trailers until the request body has been read.")
-
- while True:
- line = self.rfile.readline()
- if not line:
- # No more data--illegal end of headers
- raise ValueError("Illegal end of headers.")
-
- self.bytes_read += len(line)
- if self.maxlen and self.bytes_read > self.maxlen:
- raise IOError("Request Entity Too Large")
-
- if line == CRLF:
- # Normal end of headers
- break
- if not line.endswith(CRLF):
- raise ValueError("HTTP requires CRLF terminators")
-
- yield line
-
- def close(self):
- self.rfile.close()
-
- def __iter__(self):
- # Shamelessly stolen from StringIO
- total = 0
- line = self.readline(sizehint)
- while line:
- yield line
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline(sizehint)
-
-
-class HTTPRequest(object):
-
- """An HTTP Request (and response).
-
- A single HTTP connection may consist of multiple request/response pairs.
- """
-
- server = None
- """The HTTPServer object which is receiving this request."""
-
- conn = None
- """The HTTPConnection object on which this request connected."""
-
- inheaders = {}
- """A dict of request headers."""
-
- outheaders = []
- """A list of header tuples to write in the response."""
-
- ready = False
- """When True, the request has been parsed and is ready to begin generating
- the response. When False, signals the calling Connection that the response
- should not be generated and the connection should close."""
-
- close_connection = False
- """Signals the calling Connection that the request should close. This does
- not imply an error! The client and/or server may each request that the
- connection be closed."""
-
- chunked_write = False
- """If True, output will be encoded with the "chunked" transfer-coding.
-
- This value is set automatically inside send_headers."""
-
- def __init__(self, server, conn):
- self.server = server
- self.conn = conn
-
- self.ready = False
- self.started_request = False
- self.scheme = ntob("http")
- if self.server.ssl_adapter is not None:
- self.scheme = ntob("https")
- # Use the lowest-common protocol in case read_request_line errors.
- self.response_protocol = 'HTTP/1.0'
- self.inheaders = {}
-
- self.status = ""
- self.outheaders = []
- self.sent_headers = False
- self.close_connection = self.__class__.close_connection
- self.chunked_read = False
- self.chunked_write = self.__class__.chunked_write
-
- def parse_request(self):
- """Parse the next HTTP request start-line and message-headers."""
- self.rfile = SizeCheckWrapper(self.conn.rfile,
- self.server.max_request_header_size)
- try:
- success = self.read_request_line()
- except MaxSizeExceeded:
- self.simple_response(
- "414 Request-URI Too Long",
- "The Request-URI sent with the request exceeds the maximum "
- "allowed bytes.")
- return
- else:
- if not success:
- return
-
- try:
- success = self.read_request_headers()
- except MaxSizeExceeded:
- self.simple_response(
- "413 Request Entity Too Large",
- "The headers sent with the request exceed the maximum "
- "allowed bytes.")
- return
- else:
- if not success:
- return
-
- self.ready = True
-
- def read_request_line(self):
- # HTTP/1.1 connections are persistent by default. If a client
- # requests a page, then idles (leaves the connection open),
- # then rfile.readline() will raise socket.error("timed out").
- # Note that it does this based on the value given to settimeout(),
- # and doesn't need the client to request or acknowledge the close
- # (although your TCP stack might suffer for it: cf Apache's history
- # with FIN_WAIT_2).
- request_line = self.rfile.readline()
-
- # Set started_request to True so communicate() knows to send 408
- # from here on out.
- self.started_request = True
- if not request_line:
- return False
-
- if request_line == CRLF:
- # RFC 2616 sec 4.1: "...if the server is reading the protocol
- # stream at the beginning of a message and receives a CRLF
- # first, it should ignore the CRLF."
- # But only ignore one leading line! else we enable a DoS.
- request_line = self.rfile.readline()
- if not request_line:
- return False
-
- if not request_line.endswith(CRLF):
- self.simple_response(
- "400 Bad Request", "HTTP requires CRLF terminators")
- return False
-
- try:
- method, uri, req_protocol = request_line.strip().split(SPACE, 2)
- rp = int(req_protocol[5]), int(req_protocol[7])
- except (ValueError, IndexError):
- self.simple_response("400 Bad Request", "Malformed Request-Line")
- return False
-
- self.uri = uri
- self.method = method
-
- # uri may be an abs_path (including "http://host.domain.tld");
- scheme, authority, path = self.parse_request_uri(uri)
- if path is None:
- self.simple_response("400 Bad Request",
- "Invalid path in Request-URI.")
- return False
- if NUMBER_SIGN in path:
- self.simple_response("400 Bad Request",
- "Illegal #fragment in Request-URI.")
- return False
-
- if scheme:
- self.scheme = scheme
-
- qs = EMPTY
- if QUESTION_MARK in path:
- path, qs = path.split(QUESTION_MARK, 1)
-
- # Unquote the path+params (e.g. "/this%20path" -> "/this path").
- # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
- #
- # But note that "...a URI must be separated into its components
- # before the escaped characters within those components can be
- # safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2
- # Therefore, "/this%2Fpath" becomes "/this%2Fpath", not "/this/path".
- try:
- atoms = [unquote(x) for x in quoted_slash.split(path)]
- except ValueError:
- ex = sys.exc_info()[1]
- self.simple_response("400 Bad Request", ex.args[0])
- return False
- path = "%2F".join(atoms)
- self.path = path
-
- # Note that, like wsgiref and most other HTTP servers,
- # we "% HEX HEX"-unquote the path but not the query string.
- self.qs = qs
-
- # Compare request and server HTTP protocol versions, in case our
- # server does not support the requested protocol. Limit our output
- # to min(req, server). We want the following output:
- # request server actual written supported response
- # protocol protocol response protocol feature set
- # a 1.0 1.0 1.0 1.0
- # b 1.0 1.1 1.1 1.0
- # c 1.1 1.0 1.0 1.0
- # d 1.1 1.1 1.1 1.1
- # Notice that, in (b), the response will be "HTTP/1.1" even though
- # the client only understands 1.0. RFC 2616 10.5.6 says we should
- # only return 505 if the _major_ version is different.
- sp = int(self.server.protocol[5]), int(self.server.protocol[7])
-
- if sp[0] != rp[0]:
- self.simple_response("505 HTTP Version Not Supported")
- return False
-
- self.request_protocol = req_protocol
- self.response_protocol = "HTTP/%s.%s" % min(rp, sp)
-
- return True
-
- def read_request_headers(self):
- """Read self.rfile into self.inheaders. Return success."""
-
- # then all the http headers
- try:
- read_headers(self.rfile, self.inheaders)
- except ValueError:
- ex = sys.exc_info()[1]
- self.simple_response("400 Bad Request", ex.args[0])
- return False
-
- mrbs = self.server.max_request_body_size
- if mrbs and int(self.inheaders.get("Content-Length", 0)) > mrbs:
- self.simple_response(
- "413 Request Entity Too Large",
- "The entity sent with the request exceeds the maximum "
- "allowed bytes.")
- return False
-
- # Persistent connection support
- if self.response_protocol == "HTTP/1.1":
- # Both server and client are HTTP/1.1
- if self.inheaders.get("Connection", "") == "close":
- self.close_connection = True
- else:
- # Either the server or client (or both) are HTTP/1.0
- if self.inheaders.get("Connection", "") != "Keep-Alive":
- self.close_connection = True
-
- # Transfer-Encoding support
- te = None
- if self.response_protocol == "HTTP/1.1":
- te = self.inheaders.get("Transfer-Encoding")
- if te:
- te = [x.strip().lower() for x in te.split(",") if x.strip()]
-
- self.chunked_read = False
-
- if te:
- for enc in te:
- if enc == "chunked":
- self.chunked_read = True
- else:
- # Note that, even if we see "chunked", we must reject
- # if there is an extension we don't recognize.
- self.simple_response("501 Unimplemented")
- self.close_connection = True
- return False
-
- # From PEP 333:
- # "Servers and gateways that implement HTTP 1.1 must provide
- # transparent support for HTTP 1.1's "expect/continue" mechanism.
- # This may be done in any of several ways:
- # 1. Respond to requests containing an Expect: 100-continue request
- # with an immediate "100 Continue" response, and proceed normally.
- # 2. Proceed with the request normally, but provide the application
- # with a wsgi.input stream that will send the "100 Continue"
- # response if/when the application first attempts to read from
- # the input stream. The read request must then remain blocked
- # until the client responds.
- # 3. Wait until the client decides that the server does not support
- # expect/continue, and sends the request body on its own.
- # (This is suboptimal, and is not recommended.)
- #
- # We used to do 3, but are now doing 1. Maybe we'll do 2 someday,
- # but it seems like it would be a big slowdown for such a rare case.
- if self.inheaders.get("Expect", "") == "100-continue":
- # Don't use simple_response here, because it emits headers
- # we don't want. See
- # https://github.com/cherrypy/cherrypy/issues/951
- msg = self.server.protocol + " 100 Continue\r\n\r\n"
- try:
- self.conn.wfile.sendall(msg)
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- raise
- return True
-
- def parse_request_uri(self, uri):
- """Parse a Request-URI into (scheme, authority, path).
-
- Note that Request-URI's must be one of::
-
- Request-URI = "*" | absoluteURI | abs_path | authority
-
- Therefore, a Request-URI which starts with a double forward-slash
- cannot be a "net_path"::
-
- net_path = "//" authority [ abs_path ]
-
- Instead, it must be interpreted as an "abs_path" with an empty first
- path segment::
-
- abs_path = "/" path_segments
- path_segments = segment *( "/" segment )
- segment = *pchar *( ";" param )
- param = *pchar
- """
- if uri == ASTERISK:
- return None, None, uri
-
- i = uri.find('://')
- if i > 0 and QUESTION_MARK not in uri[:i]:
- # An absoluteURI.
- # If there's a scheme (and it must be http or https), then:
- # http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query
- # ]]
- scheme, remainder = uri[:i].lower(), uri[i + 3:]
- authority, path = remainder.split(FORWARD_SLASH, 1)
- path = FORWARD_SLASH + path
- return scheme, authority, path
-
- if uri.startswith(FORWARD_SLASH):
- # An abs_path.
- return None, None, uri
- else:
- # An authority.
- return None, uri, None
-
- def respond(self):
- """Call the gateway and write its iterable output."""
- mrbs = self.server.max_request_body_size
- if self.chunked_read:
- self.rfile = ChunkedRFile(self.conn.rfile, mrbs)
- else:
- cl = int(self.inheaders.get("Content-Length", 0))
- if mrbs and mrbs < cl:
- if not self.sent_headers:
- self.simple_response(
- "413 Request Entity Too Large",
- "The entity sent with the request exceeds the maximum "
- "allowed bytes.")
- return
- self.rfile = KnownLengthRFile(self.conn.rfile, cl)
-
- self.server.gateway(self).respond()
-
- if (self.ready and not self.sent_headers):
- self.sent_headers = True
- self.send_headers()
- if self.chunked_write:
- self.conn.wfile.sendall("0\r\n\r\n")
-
- def simple_response(self, status, msg=""):
- """Write a simple response back to the client."""
- status = str(status)
- buf = [self.server.protocol + SPACE +
- status + CRLF,
- "Content-Length: %s\r\n" % len(msg),
- "Content-Type: text/plain\r\n"]
-
- if status[:3] in ("413", "414"):
- # Request Entity Too Large / Request-URI Too Long
- self.close_connection = True
- if self.response_protocol == 'HTTP/1.1':
- # This will not be true for 414, since read_request_line
- # usually raises 414 before reading the whole line, and we
- # therefore cannot know the proper response_protocol.
- buf.append("Connection: close\r\n")
- else:
- # HTTP/1.0 had no 413/414 status nor Connection header.
- # Emit 400 instead and trust the message body is enough.
- status = "400 Bad Request"
-
- buf.append(CRLF)
- if msg:
- if isinstance(msg, unicodestr):
- msg = msg.encode("ISO-8859-1")
- buf.append(msg)
-
- try:
- self.conn.wfile.sendall("".join(buf))
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- raise
-
- def write(self, chunk):
- """Write unbuffered data to the client."""
- if self.chunked_write and chunk:
- buf = [hex(len(chunk))[2:], CRLF, chunk, CRLF]
- self.conn.wfile.sendall(EMPTY.join(buf))
- else:
- self.conn.wfile.sendall(chunk)
-
- def send_headers(self):
- """Assert, process, and send the HTTP response message-headers.
-
- You must set self.status, and self.outheaders before calling this.
- """
- hkeys = [key.lower() for key, value in self.outheaders]
- status = int(self.status[:3])
-
- if status == 413:
- # Request Entity Too Large. Close conn to avoid garbage.
- self.close_connection = True
- elif "content-length" not in hkeys:
- # "All 1xx (informational), 204 (no content),
- # and 304 (not modified) responses MUST NOT
- # include a message-body." So no point chunking.
- if status < 200 or status in (204, 205, 304):
- pass
- else:
- if (self.response_protocol == 'HTTP/1.1'
- and self.method != 'HEAD'):
- # Use the chunked transfer-coding
- self.chunked_write = True
- self.outheaders.append(("Transfer-Encoding", "chunked"))
- else:
- # Closing the conn is the only way to determine len.
- self.close_connection = True
-
- if "connection" not in hkeys:
- if self.response_protocol == 'HTTP/1.1':
- # Both server and client are HTTP/1.1 or better
- if self.close_connection:
- self.outheaders.append(("Connection", "close"))
- else:
- # Server and/or client are HTTP/1.0
- if not self.close_connection:
- self.outheaders.append(("Connection", "Keep-Alive"))
-
- if (not self.close_connection) and (not self.chunked_read):
- # Read any remaining request body data on the socket.
- # "If an origin server receives a request that does not include an
- # Expect request-header field with the "100-continue" expectation,
- # the request includes a request body, and the server responds
- # with a final status code before reading the entire request body
- # from the transport connection, then the server SHOULD NOT close
- # the transport connection until it has read the entire request,
- # or until the client closes the connection. Otherwise, the client
- # might not reliably receive the response message. However, this
- # requirement is not be construed as preventing a server from
- # defending itself against denial-of-service attacks, or from
- # badly broken client implementations."
- remaining = getattr(self.rfile, 'remaining', 0)
- if remaining > 0:
- self.rfile.read(remaining)
-
- if "date" not in hkeys:
- self.outheaders.append(("Date", email.utils.formatdate()))
-
- if "server" not in hkeys:
- self.outheaders.append(("Server", self.server.server_name))
-
- buf = [self.server.protocol + SPACE + self.status + CRLF]
- for k, v in self.outheaders:
- buf.append(k + COLON + SPACE + v + CRLF)
- buf.append(CRLF)
- self.conn.wfile.sendall(EMPTY.join(buf))
-
-
-class NoSSLError(Exception):
-
- """Exception raised when a client speaks HTTP to an HTTPS socket."""
- pass
-
-
-class FatalSSLAlert(Exception):
-
- """Exception raised when the SSL implementation signals a fatal alert."""
- pass
-
-
-class CP_fileobject(socket._fileobject):
-
- """Faux file object attached to a socket object."""
-
- def __init__(self, *args, **kwargs):
- self.bytes_read = 0
- self.bytes_written = 0
- socket._fileobject.__init__(self, *args, **kwargs)
-
- def sendall(self, data):
- """Sendall for non-blocking sockets."""
- while data:
- try:
- bytes_sent = self.send(data)
- data = data[bytes_sent:]
- except socket.error, e:
- if e.args[0] not in socket_errors_nonblocking:
- raise
-
- def send(self, data):
- bytes_sent = self._sock.send(data)
- self.bytes_written += bytes_sent
- return bytes_sent
-
- def flush(self):
- if self._wbuf:
- buffer = "".join(self._wbuf)
- self._wbuf = []
- self.sendall(buffer)
-
- def recv(self, size):
- while True:
- try:
- data = self._sock.recv(size)
- self.bytes_read += len(data)
- return data
- except socket.error, e:
- if (e.args[0] not in socket_errors_nonblocking
- and e.args[0] not in socket_error_eintr):
- raise
-
- if not _fileobject_uses_str_type:
- def read(self, size=-1):
- # Use max, disallow tiny reads in a loop as they are very
- # inefficient.
- # We never leave read() with any leftover data from a new recv()
- # call in our internal buffer.
- rbufsize = max(self._rbufsize, self.default_bufsize)
- # Our use of StringIO rather than lists of string objects returned
- # by recv() minimizes memory usage and fragmentation that occurs
- # when rbufsize is large compared to the typical return value of
- # recv().
- buf = self._rbuf
- buf.seek(0, 2) # seek end
- if size < 0:
- # Read until EOF
- # reset _rbuf. we consume it via buf.
- self._rbuf = io.BytesIO()
- while True:
- data = self.recv(rbufsize)
- if not data:
- break
- buf.write(data)
- return buf.getvalue()
- else:
- # Read until size bytes or EOF seen, whichever comes first
- buf_len = buf.tell()
- if buf_len >= size:
- # Already have size bytes in our buffer? Extract and
- # return.
- buf.seek(0)
- rv = buf.read(size)
- self._rbuf = io.BytesIO()
- self._rbuf.write(buf.read())
- return rv
-
- # reset _rbuf. we consume it via buf.
- self._rbuf = io.BytesIO()
- while True:
- left = size - buf_len
- # recv() will malloc the amount of memory given as its
- # parameter even though it often returns much less data
- # than that. The returned data string is short lived
- # as we copy it into a StringIO and free it. This avoids
- # fragmentation issues on many platforms.
- data = self.recv(left)
- if not data:
- break
- n = len(data)
- if n == size and not buf_len:
- # Shortcut. Avoid buffer data copies when:
- # - We have no data in our buffer.
- # AND
- # - Our call to recv returned exactly the
- # number of bytes we were asked to read.
- return data
- if n == left:
- buf.write(data)
- del data # explicit free
- break
- assert n <= left, "recv(%d) returned %d bytes" % (left, n)
- buf.write(data)
- buf_len += n
- del data # explicit free
- #assert buf_len == buf.tell()
- return buf.getvalue()
-
- def readline(self, size=-1):
- buf = self._rbuf
- buf.seek(0, 2) # seek end
- if buf.tell() > 0:
- # check if we already have it in our buffer
- buf.seek(0)
- bline = buf.readline(size)
- if bline.endswith('\n') or len(bline) == size:
- self._rbuf = io.BytesIO()
- self._rbuf.write(buf.read())
- return bline
- del bline
- if size < 0:
- # Read until \n or EOF, whichever comes first
- if self._rbufsize <= 1:
- # Speed up unbuffered case
- buf.seek(0)
- buffers = [buf.read()]
- # reset _rbuf. we consume it via buf.
- self._rbuf = io.BytesIO()
- data = None
- recv = self.recv
- while data != "\n":
- data = recv(1)
- if not data:
- break
- buffers.append(data)
- return "".join(buffers)
-
- buf.seek(0, 2) # seek end
- # reset _rbuf. we consume it via buf.
- self._rbuf = io.BytesIO()
- while True:
- data = self.recv(self._rbufsize)
- if not data:
- break
- nl = data.find('\n')
- if nl >= 0:
- nl += 1
- buf.write(data[:nl])
- self._rbuf.write(data[nl:])
- del data
- break
- buf.write(data)
- return buf.getvalue()
- else:
- # Read until size bytes or \n or EOF seen, whichever comes
- # first
- buf.seek(0, 2) # seek end
- buf_len = buf.tell()
- if buf_len >= size:
- buf.seek(0)
- rv = buf.read(size)
- self._rbuf = io.BytesIO()
- self._rbuf.write(buf.read())
- return rv
- # reset _rbuf. we consume it via buf.
- self._rbuf = io.BytesIO()
- while True:
- data = self.recv(self._rbufsize)
- if not data:
- break
- left = size - buf_len
- # did we just receive a newline?
- nl = data.find('\n', 0, left)
- if nl >= 0:
- nl += 1
- # save the excess data to _rbuf
- self._rbuf.write(data[nl:])
- if buf_len:
- buf.write(data[:nl])
- break
- else:
- # Shortcut. Avoid data copy through buf when
- # returning a substring of our first recv().
- return data[:nl]
- n = len(data)
- if n == size and not buf_len:
- # Shortcut. Avoid data copy through buf when
- # returning exactly all of our first recv().
- return data
- if n >= left:
- buf.write(data[:left])
- self._rbuf.write(data[left:])
- break
- buf.write(data)
- buf_len += n
- #assert buf_len == buf.tell()
- return buf.getvalue()
- else:
- def read(self, size=-1):
- if size < 0:
- # Read until EOF
- buffers = [self._rbuf]
- self._rbuf = ""
- if self._rbufsize <= 1:
- recv_size = self.default_bufsize
- else:
- recv_size = self._rbufsize
-
- while True:
- data = self.recv(recv_size)
- if not data:
- break
- buffers.append(data)
- return "".join(buffers)
- else:
- # Read until size bytes or EOF seen, whichever comes first
- data = self._rbuf
- buf_len = len(data)
- if buf_len >= size:
- self._rbuf = data[size:]
- return data[:size]
- buffers = []
- if data:
- buffers.append(data)
- self._rbuf = ""
- while True:
- left = size - buf_len
- recv_size = max(self._rbufsize, left)
- data = self.recv(recv_size)
- if not data:
- break
- buffers.append(data)
- n = len(data)
- if n >= left:
- self._rbuf = data[left:]
- buffers[-1] = data[:left]
- break
- buf_len += n
- return "".join(buffers)
-
- def readline(self, size=-1):
- data = self._rbuf
- if size < 0:
- # Read until \n or EOF, whichever comes first
- if self._rbufsize <= 1:
- # Speed up unbuffered case
- assert data == ""
- buffers = []
- while data != "\n":
- data = self.recv(1)
- if not data:
- break
- buffers.append(data)
- return "".join(buffers)
- nl = data.find('\n')
- if nl >= 0:
- nl += 1
- self._rbuf = data[nl:]
- return data[:nl]
- buffers = []
- if data:
- buffers.append(data)
- self._rbuf = ""
- while True:
- data = self.recv(self._rbufsize)
- if not data:
- break
- buffers.append(data)
- nl = data.find('\n')
- if nl >= 0:
- nl += 1
- self._rbuf = data[nl:]
- buffers[-1] = data[:nl]
- break
- return "".join(buffers)
- else:
- # Read until size bytes or \n or EOF seen, whichever comes
- # first
- nl = data.find('\n', 0, size)
- if nl >= 0:
- nl += 1
- self._rbuf = data[nl:]
- return data[:nl]
- buf_len = len(data)
- if buf_len >= size:
- self._rbuf = data[size:]
- return data[:size]
- buffers = []
- if data:
- buffers.append(data)
- self._rbuf = ""
- while True:
- data = self.recv(self._rbufsize)
- if not data:
- break
- buffers.append(data)
- left = size - buf_len
- nl = data.find('\n', 0, left)
- if nl >= 0:
- nl += 1
- self._rbuf = data[nl:]
- buffers[-1] = data[:nl]
- break
- n = len(data)
- if n >= left:
- self._rbuf = data[left:]
- buffers[-1] = data[:left]
- break
- buf_len += n
- return "".join(buffers)
-
-
-class HTTPConnection(object):
-
- """An HTTP connection (active socket).
-
- server: the Server object which received this connection.
- socket: the raw socket object (usually TCP) for this connection.
- makefile: a fileobject class for reading from the socket.
- """
-
- remote_addr = None
- remote_port = None
- ssl_env = None
- rbufsize = DEFAULT_BUFFER_SIZE
- wbufsize = DEFAULT_BUFFER_SIZE
- RequestHandlerClass = HTTPRequest
-
- def __init__(self, server, sock, makefile=CP_fileobject):
- self.server = server
- self.socket = sock
- self.rfile = makefile(sock, "rb", self.rbufsize)
- self.wfile = makefile(sock, "wb", self.wbufsize)
- self.requests_seen = 0
-
- def communicate(self):
- """Read each request and respond appropriately."""
- request_seen = False
- try:
- while True:
- # (re)set req to None so that if something goes wrong in
- # the RequestHandlerClass constructor, the error doesn't
- # get written to the previous request.
- req = None
- req = self.RequestHandlerClass(self.server, self)
-
- # This order of operations should guarantee correct pipelining.
- req.parse_request()
- if self.server.stats['Enabled']:
- self.requests_seen += 1
- if not req.ready:
- # Something went wrong in the parsing (and the server has
- # probably already made a simple_response). Return and
- # let the conn close.
- return
-
- request_seen = True
- req.respond()
- if req.close_connection:
- return
- except socket.error:
- e = sys.exc_info()[1]
- errnum = e.args[0]
- # sadly SSL sockets return a different (longer) time out string
- if (
- errnum == 'timed out' or
- errnum == 'The read operation timed out'
- ):
- # Don't error if we're between requests; only error
- # if 1) no request has been started at all, or 2) we're
- # in the middle of a request.
- # See https://github.com/cherrypy/cherrypy/issues/853
- if (not request_seen) or (req and req.started_request):
- # Don't bother writing the 408 if the response
- # has already started being written.
- if req and not req.sent_headers:
- try:
- req.simple_response("408 Request Timeout")
- except FatalSSLAlert:
- # Close the connection.
- return
- elif errnum not in socket_errors_to_ignore:
- self.server.error_log("socket.error %s" % repr(errnum),
- level=logging.WARNING, traceback=True)
- if req and not req.sent_headers:
- try:
- req.simple_response("500 Internal Server Error")
- except FatalSSLAlert:
- # Close the connection.
- return
- return
- except (KeyboardInterrupt, SystemExit):
- raise
- except FatalSSLAlert:
- # Close the connection.
- return
- except NoSSLError:
- if req and not req.sent_headers:
- # Unwrap our wfile
- self.wfile = CP_fileobject(
- self.socket._sock, "wb", self.wbufsize)
- req.simple_response(
- "400 Bad Request",
- "The client sent a plain HTTP request, but "
- "this server only speaks HTTPS on this port.")
- self.linger = True
- except Exception:
- e = sys.exc_info()[1]
- self.server.error_log(repr(e), level=logging.ERROR, traceback=True)
- if req and not req.sent_headers:
- try:
- req.simple_response("500 Internal Server Error")
- except FatalSSLAlert:
- # Close the connection.
- return
-
- linger = False
-
- def close(self):
- """Close the socket underlying this connection."""
- self.rfile.close()
-
- if not self.linger:
- # Python's socket module does NOT call close on the kernel
- # socket when you call socket.close(). We do so manually here
- # because we want this server to send a FIN TCP segment
- # immediately. Note this must be called *before* calling
- # socket.close(), because the latter drops its reference to
- # the kernel socket.
- if hasattr(self.socket, '_sock'):
- self.socket._sock.close()
- self.socket.close()
- else:
- # On the other hand, sometimes we want to hang around for a bit
- # to make sure the client has a chance to read our entire
- # response. Skipping the close() calls here delays the FIN
- # packet until the socket object is garbage-collected later.
- # Someday, perhaps, we'll do the full lingering_close that
- # Apache does, but not today.
- pass
-
-
-class TrueyZero(object):
-
- """An object which equals and does math like the integer 0 but evals True.
- """
-
- def __add__(self, other):
- return other
-
- def __radd__(self, other):
- return other
-trueyzero = TrueyZero()
-
-
-_SHUTDOWNREQUEST = None
-
-
-class WorkerThread(threading.Thread):
-
- """Thread which continuously polls a Queue for Connection objects.
-
- Due to the timing issues of polling a Queue, a WorkerThread does not
- check its own 'ready' flag after it has started. To stop the thread,
- it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue
- (one for each running WorkerThread).
- """
-
- conn = None
- """The current connection pulled off the Queue, or None."""
-
- server = None
- """The HTTP Server which spawned this thread, and which owns the
- Queue and is placing active connections into it."""
-
- ready = False
- """A simple flag for the calling server to know when this thread
- has begun polling the Queue."""
-
- def __init__(self, server):
- self.ready = False
- self.server = server
-
- self.requests_seen = 0
- self.bytes_read = 0
- self.bytes_written = 0
- self.start_time = None
- self.work_time = 0
- self.stats = {
- 'Requests': lambda s: self.requests_seen + (
- (self.start_time is None) and
- trueyzero or
- self.conn.requests_seen
- ),
- 'Bytes Read': lambda s: self.bytes_read + (
- (self.start_time is None) and
- trueyzero or
- self.conn.rfile.bytes_read
- ),
- 'Bytes Written': lambda s: self.bytes_written + (
- (self.start_time is None) and
- trueyzero or
- self.conn.wfile.bytes_written
- ),
- 'Work Time': lambda s: self.work_time + (
- (self.start_time is None) and
- trueyzero or
- time.time() - self.start_time
- ),
- 'Read Throughput': lambda s: s['Bytes Read'](s) / (
- s['Work Time'](s) or 1e-6),
- 'Write Throughput': lambda s: s['Bytes Written'](s) / (
- s['Work Time'](s) or 1e-6),
- }
- threading.Thread.__init__(self)
-
- def run(self):
- self.server.stats['Worker Threads'][self.getName()] = self.stats
- try:
- self.ready = True
- while True:
- conn = self.server.requests.get()
- if conn is _SHUTDOWNREQUEST:
- return
-
- self.conn = conn
- if self.server.stats['Enabled']:
- self.start_time = time.time()
- try:
- conn.communicate()
- finally:
- conn.close()
- if self.server.stats['Enabled']:
- self.requests_seen += self.conn.requests_seen
- self.bytes_read += self.conn.rfile.bytes_read
- self.bytes_written += self.conn.wfile.bytes_written
- self.work_time += time.time() - self.start_time
- self.start_time = None
- self.conn = None
- except (KeyboardInterrupt, SystemExit):
- exc = sys.exc_info()[1]
- self.server.interrupt = exc
-
-
-class ThreadPool(object):
-
- """A Request Queue for an HTTPServer which pools threads.
-
- ThreadPool objects must provide min, get(), put(obj), start()
- and stop(timeout) attributes.
- """
-
- def __init__(self, server, min=10, max=-1,
- accepted_queue_size=-1, accepted_queue_timeout=10):
- self.server = server
- self.min = min
- self.max = max
- self._threads = []
- self._queue = queue.Queue(maxsize=accepted_queue_size)
- self._queue_put_timeout = accepted_queue_timeout
- self.get = self._queue.get
-
- def start(self):
- """Start the pool of threads."""
- for i in range(self.min):
- self._threads.append(WorkerThread(self.server))
- for worker in self._threads:
- worker.setName("CP Server " + worker.getName())
- worker.start()
- for worker in self._threads:
- while not worker.ready:
- time.sleep(.1)
-
- def _get_idle(self):
- """Number of worker threads which are idle. Read-only."""
- return len([t for t in self._threads if t.conn is None])
- idle = property(_get_idle, doc=_get_idle.__doc__)
-
- def put(self, obj):
- self._queue.put(obj, block=True, timeout=self._queue_put_timeout)
- if obj is _SHUTDOWNREQUEST:
- return
-
- def grow(self, amount):
- """Spawn new worker threads (not above self.max)."""
- if self.max > 0:
- budget = max(self.max - len(self._threads), 0)
- else:
- # self.max <= 0 indicates no maximum
- budget = float('inf')
-
- n_new = min(amount, budget)
-
- workers = [self._spawn_worker() for i in range(n_new)]
- while not self._all(operator.attrgetter('ready'), workers):
- time.sleep(.1)
- self._threads.extend(workers)
-
- def _spawn_worker(self):
- worker = WorkerThread(self.server)
- worker.setName("CP Server " + worker.getName())
- worker.start()
- return worker
-
- def _all(func, items):
- results = [func(item) for item in items]
- return reduce(operator.and_, results, True)
- _all = staticmethod(_all)
-
- def shrink(self, amount):
- """Kill off worker threads (not below self.min)."""
- # Grow/shrink the pool if necessary.
- # Remove any dead threads from our list
- for t in self._threads:
- if not t.isAlive():
- self._threads.remove(t)
- amount -= 1
-
- # calculate the number of threads above the minimum
- n_extra = max(len(self._threads) - self.min, 0)
-
- # don't remove more than amount
- n_to_remove = min(amount, n_extra)
-
- # put shutdown requests on the queue equal to the number of threads
- # to remove. As each request is processed by a worker, that worker
- # will terminate and be culled from the list.
- for n in range(n_to_remove):
- self._queue.put(_SHUTDOWNREQUEST)
-
- def stop(self, timeout=5):
- # Must shut down threads here so the code that calls
- # this method can know when all threads are stopped.
- for worker in self._threads:
- self._queue.put(_SHUTDOWNREQUEST)
-
- # Don't join currentThread (when stop is called inside a request).
- current = threading.currentThread()
- if timeout and timeout >= 0:
- endtime = time.time() + timeout
- while self._threads:
- worker = self._threads.pop()
- if worker is not current and worker.isAlive():
- try:
- if timeout is None or timeout < 0:
- worker.join()
- else:
- remaining_time = endtime - time.time()
- if remaining_time > 0:
- worker.join(remaining_time)
- if worker.isAlive():
- # We exhausted the timeout.
- # Forcibly shut down the socket.
- c = worker.conn
- if c and not c.rfile.closed:
- try:
- c.socket.shutdown(socket.SHUT_RD)
- except TypeError:
- # pyOpenSSL sockets don't take an arg
- c.socket.shutdown()
- worker.join()
- except (AssertionError,
- # Ignore repeated Ctrl-C.
- # See
- # https://github.com/cherrypy/cherrypy/issues/691.
- KeyboardInterrupt):
- pass
-
- def _get_qsize(self):
- return self._queue.qsize()
- qsize = property(_get_qsize)
-
-
-try:
- import fcntl
-except ImportError:
- try:
- from ctypes import windll, WinError
- import ctypes.wintypes
- _SetHandleInformation = windll.kernel32.SetHandleInformation
- _SetHandleInformation.argtypes = [
- ctypes.wintypes.HANDLE,
- ctypes.wintypes.DWORD,
- ctypes.wintypes.DWORD,
- ]
- _SetHandleInformation.restype = ctypes.wintypes.BOOL
- except ImportError:
- def prevent_socket_inheritance(sock):
- """Dummy function, since neither fcntl nor ctypes are available."""
- pass
- else:
- def prevent_socket_inheritance(sock):
- """Mark the given socket fd as non-inheritable (Windows)."""
- if not _SetHandleInformation(sock.fileno(), 1, 0):
- raise WinError()
-else:
- def prevent_socket_inheritance(sock):
- """Mark the given socket fd as non-inheritable (POSIX)."""
- fd = sock.fileno()
- old_flags = fcntl.fcntl(fd, fcntl.F_GETFD)
- fcntl.fcntl(fd, fcntl.F_SETFD, old_flags | fcntl.FD_CLOEXEC)
-
-
-class SSLAdapter(object):
-
- """Base class for SSL driver library adapters.
-
- Required methods:
-
- * ``wrap(sock) -> (wrapped socket, ssl environ dict)``
- * ``makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE) ->
- socket file object``
- """
-
- def __init__(self, certificate, private_key, certificate_chain=None):
- self.certificate = certificate
- self.private_key = private_key
- self.certificate_chain = certificate_chain
-
- def wrap(self, sock):
- raise NotImplemented
-
- def makefile(self, sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE):
- raise NotImplemented
-
-
-class HTTPServer(object):
-
- """An HTTP server."""
-
- _bind_addr = "127.0.0.1"
- _interrupt = None
-
- gateway = None
- """A Gateway instance."""
-
- minthreads = None
- """The minimum number of worker threads to create (default 10)."""
-
- maxthreads = None
- """The maximum number of worker threads to create (default -1 = no limit).
- """
-
- server_name = None
- """The name of the server; defaults to socket.gethostname()."""
-
- protocol = "HTTP/1.1"
- """The version string to write in the Status-Line of all HTTP responses.
-
- For example, "HTTP/1.1" is the default. This also limits the supported
- features used in the response."""
-
- request_queue_size = 5
- """The 'backlog' arg to socket.listen(); max queued connections
- (default 5).
- """
-
- shutdown_timeout = 5
- """The total time, in seconds, to wait for worker threads to cleanly exit.
- """
-
- timeout = 10
- """The timeout in seconds for accepted connections (default 10)."""
-
- version = "CherryPy/" + cp_version
- """A version string for the HTTPServer."""
-
- software = None
- """The value to set for the SERVER_SOFTWARE entry in the WSGI environ.
-
- If None, this defaults to ``'%s Server' % self.version``."""
-
- ready = False
- """An internal flag which marks whether the socket is accepting connections
- """
-
- max_request_header_size = 0
- """The maximum size, in bytes, for request headers, or 0 for no limit."""
-
- max_request_body_size = 0
- """The maximum size, in bytes, for request bodies, or 0 for no limit."""
-
- nodelay = True
- """If True (the default since 3.1), sets the TCP_NODELAY socket option."""
-
- ConnectionClass = HTTPConnection
- """The class to use for handling HTTP connections."""
-
- ssl_adapter = None
- """An instance of SSLAdapter (or a subclass).
-
- You must have the corresponding SSL driver library installed."""
-
- def __init__(self, bind_addr, gateway, minthreads=10, maxthreads=-1,
- server_name=None):
- self.bind_addr = bind_addr
- self.gateway = gateway
-
- self.requests = ThreadPool(self, min=minthreads or 1, max=maxthreads)
-
- if not server_name:
- server_name = socket.gethostname()
- self.server_name = server_name
- self.clear_stats()
-
- def clear_stats(self):
- self._start_time = None
- self._run_time = 0
- self.stats = {
- 'Enabled': False,
- 'Bind Address': lambda s: repr(self.bind_addr),
- 'Run time': lambda s: (not s['Enabled']) and -1 or self.runtime(),
- 'Accepts': 0,
- 'Accepts/sec': lambda s: s['Accepts'] / self.runtime(),
- 'Queue': lambda s: getattr(self.requests, "qsize", None),
- 'Threads': lambda s: len(getattr(self.requests, "_threads", [])),
- 'Threads Idle': lambda s: getattr(self.requests, "idle", None),
- 'Socket Errors': 0,
- 'Requests': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Requests'](w) for w in s['Worker Threads'].values()], 0),
- 'Bytes Read': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Read'](w) for w in s['Worker Threads'].values()], 0),
- 'Bytes Written': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Written'](w) for w in s['Worker Threads'].values()],
- 0),
- 'Work Time': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Work Time'](w) for w in s['Worker Threads'].values()], 0),
- 'Read Throughput': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Read'](w) / (w['Work Time'](w) or 1e-6)
- for w in s['Worker Threads'].values()], 0),
- 'Write Throughput': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Written'](w) / (w['Work Time'](w) or 1e-6)
- for w in s['Worker Threads'].values()], 0),
- 'Worker Threads': {},
- }
- logging.statistics["CherryPy HTTPServer %d" % id(self)] = self.stats
-
- def runtime(self):
- if self._start_time is None:
- return self._run_time
- else:
- return self._run_time + (time.time() - self._start_time)
-
- def __str__(self):
- return "%s.%s(%r)" % (self.__module__, self.__class__.__name__,
- self.bind_addr)
-
- def _get_bind_addr(self):
- return self._bind_addr
-
- def _set_bind_addr(self, value):
- if isinstance(value, tuple) and value[0] in ('', None):
- # Despite the socket module docs, using '' does not
- # allow AI_PASSIVE to work. Passing None instead
- # returns '0.0.0.0' like we want. In other words:
- # host AI_PASSIVE result
- # '' Y 192.168.x.y
- # '' N 192.168.x.y
- # None Y 0.0.0.0
- # None N 127.0.0.1
- # But since you can get the same effect with an explicit
- # '0.0.0.0', we deny both the empty string and None as values.
- raise ValueError("Host values of '' or None are not allowed. "
- "Use '0.0.0.0' (IPv4) or '::' (IPv6) instead "
- "to listen on all active interfaces.")
- self._bind_addr = value
- bind_addr = property(
- _get_bind_addr,
- _set_bind_addr,
- doc="""The interface on which to listen for connections.
-
- For TCP sockets, a (host, port) tuple. Host values may be any IPv4
- or IPv6 address, or any valid hostname. The string 'localhost' is a
- synonym for '127.0.0.1' (or '::1', if your hosts file prefers IPv6).
- The string '0.0.0.0' is a special IPv4 entry meaning "any active
- interface" (INADDR_ANY), and '::' is the similar IN6ADDR_ANY for
- IPv6. The empty string or None are not allowed.
-
- For UNIX sockets, supply the filename as a string.""")
-
- def start(self):
- """Run the server forever."""
- # We don't have to trap KeyboardInterrupt or SystemExit here,
- # because cherrpy.server already does so, calling self.stop() for us.
- # If you're using this server with another framework, you should
- # trap those exceptions in whatever code block calls start().
- self._interrupt = None
-
- if self.software is None:
- self.software = "%s Server" % self.version
-
- # Select the appropriate socket
- if isinstance(self.bind_addr, basestring):
- # AF_UNIX socket
-
- # So we can reuse the socket...
- try:
- os.unlink(self.bind_addr)
- except:
- pass
-
- # So everyone can access the socket...
- try:
- os.chmod(self.bind_addr, 0o777)
- except:
- pass
-
- info = [
- (socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)]
- else:
- # AF_INET or AF_INET6 socket
- # Get the correct address family for our host (allows IPv6
- # addresses)
- host, port = self.bind_addr
- try:
- info = socket.getaddrinfo(
- host, port, socket.AF_UNSPEC,
- socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
- except socket.gaierror:
- if ':' in self.bind_addr[0]:
- info = [(socket.AF_INET6, socket.SOCK_STREAM,
- 0, "", self.bind_addr + (0, 0))]
- else:
- info = [(socket.AF_INET, socket.SOCK_STREAM,
- 0, "", self.bind_addr)]
-
- self.socket = None
- msg = "No socket could be created"
- for res in info:
- af, socktype, proto, canonname, sa = res
- try:
- self.bind(af, socktype, proto)
- except socket.error, serr:
- msg = "%s -- (%s: %s)" % (msg, sa, serr)
- if self.socket:
- self.socket.close()
- self.socket = None
- continue
- break
- if not self.socket:
- raise socket.error(msg)
-
- # Timeout so KeyboardInterrupt can be caught on Win32
- self.socket.settimeout(1)
- self.socket.listen(self.request_queue_size)
-
- # Create worker threads
- self.requests.start()
-
- self.ready = True
- self._start_time = time.time()
- while self.ready:
- try:
- self.tick()
- except (KeyboardInterrupt, SystemExit):
- raise
- except:
- self.error_log("Error in HTTPServer.tick", level=logging.ERROR,
- traceback=True)
-
- if self.interrupt:
- while self.interrupt is True:
- # Wait for self.stop() to complete. See _set_interrupt.
- time.sleep(0.1)
- if self.interrupt:
- raise self.interrupt
-
- def error_log(self, msg="", level=20, traceback=False):
- # Override this in subclasses as desired
- sys.stderr.write(msg + '\n')
- sys.stderr.flush()
- if traceback:
- tblines = traceback_.format_exc()
- sys.stderr.write(tblines)
- sys.stderr.flush()
-
- def bind(self, family, type, proto=0):
- """Create (or recreate) the actual socket object."""
- self.socket = socket.socket(family, type, proto)
- prevent_socket_inheritance(self.socket)
- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- if self.nodelay and not isinstance(self.bind_addr, str):
- self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
-
- if self.ssl_adapter is not None:
- self.socket = self.ssl_adapter.bind(self.socket)
-
- # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
- # activate dual-stack. See
- # https://github.com/cherrypy/cherrypy/issues/871.
- if (hasattr(socket, 'AF_INET6') and family == socket.AF_INET6
- and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
- try:
- self.socket.setsockopt(
- socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
- except (AttributeError, socket.error):
- # Apparently, the socket option is not available in
- # this machine's TCP stack
- pass
-
- self.socket.bind(self.bind_addr)
-
- def tick(self):
- """Accept a new connection and put it on the Queue."""
- try:
- s, addr = self.socket.accept()
- if self.stats['Enabled']:
- self.stats['Accepts'] += 1
- if not self.ready:
- return
-
- prevent_socket_inheritance(s)
- if hasattr(s, 'settimeout'):
- s.settimeout(self.timeout)
-
- makefile = CP_fileobject
- ssl_env = {}
- # if ssl cert and key are set, we try to be a secure HTTP server
- if self.ssl_adapter is not None:
- try:
- s, ssl_env = self.ssl_adapter.wrap(s)
- except NoSSLError:
- msg = ("The client sent a plain HTTP request, but "
- "this server only speaks HTTPS on this port.")
- buf = ["%s 400 Bad Request\r\n" % self.protocol,
- "Content-Length: %s\r\n" % len(msg),
- "Content-Type: text/plain\r\n\r\n",
- msg]
-
- wfile = makefile(s._sock, "wb", DEFAULT_BUFFER_SIZE)
- try:
- wfile.sendall("".join(buf))
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- raise
- return
- if not s:
- return
- makefile = self.ssl_adapter.makefile
- # Re-apply our timeout since we may have a new socket object
- if hasattr(s, 'settimeout'):
- s.settimeout(self.timeout)
-
- conn = self.ConnectionClass(self, s, makefile)
-
- if not isinstance(self.bind_addr, basestring):
- # optional values
- # Until we do DNS lookups, omit REMOTE_HOST
- if addr is None: # sometimes this can happen
- # figure out if AF_INET or AF_INET6.
- if len(s.getsockname()) == 2:
- # AF_INET
- addr = ('0.0.0.0', 0)
- else:
- # AF_INET6
- addr = ('::', 0)
- conn.remote_addr = addr[0]
- conn.remote_port = addr[1]
-
- conn.ssl_env = ssl_env
-
- try:
- self.requests.put(conn)
- except queue.Full:
- # Just drop the conn. TODO: write 503 back?
- conn.close()
- return
- except socket.timeout:
- # The only reason for the timeout in start() is so we can
- # notice keyboard interrupts on Win32, which don't interrupt
- # accept() by default
- return
- except socket.error:
- x = sys.exc_info()[1]
- if self.stats['Enabled']:
- self.stats['Socket Errors'] += 1
- if x.args[0] in socket_error_eintr:
- # I *think* this is right. EINTR should occur when a signal
- # is received during the accept() call; all docs say retry
- # the call, and I *think* I'm reading it right that Python
- # will then go ahead and poll for and handle the signal
- # elsewhere. See
- # https://github.com/cherrypy/cherrypy/issues/707.
- return
- if x.args[0] in socket_errors_nonblocking:
- # Just try again. See
- # https://github.com/cherrypy/cherrypy/issues/479.
- return
- if x.args[0] in socket_errors_to_ignore:
- # Our socket was closed.
- # See https://github.com/cherrypy/cherrypy/issues/686.
- return
- raise
-
- def _get_interrupt(self):
- return self._interrupt
-
- def _set_interrupt(self, interrupt):
- self._interrupt = True
- self.stop()
- self._interrupt = interrupt
- interrupt = property(_get_interrupt, _set_interrupt,
- doc="Set this to an Exception instance to "
- "interrupt the server.")
-
- def stop(self):
- """Gracefully shutdown a server that is serving forever."""
- self.ready = False
- if self._start_time is not None:
- self._run_time += (time.time() - self._start_time)
- self._start_time = None
-
- sock = getattr(self, "socket", None)
- if sock:
- if not isinstance(self.bind_addr, basestring):
- # Touch our own socket to make accept() return immediately.
- try:
- host, port = sock.getsockname()[:2]
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- # Changed to use error code and not message
- # See
- # https://github.com/cherrypy/cherrypy/issues/860.
- raise
- else:
- # Note that we're explicitly NOT using AI_PASSIVE,
- # here, because we want an actual IP to touch.
- # localhost won't work if we've bound to a public IP,
- # but it will if we bound to '0.0.0.0' (INADDR_ANY).
- for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
- socket.SOCK_STREAM):
- af, socktype, proto, canonname, sa = res
- s = None
- try:
- s = socket.socket(af, socktype, proto)
- # See
- # http://groups.google.com/group/cherrypy-users/
- # browse_frm/thread/bbfe5eb39c904fe0
- s.settimeout(1.0)
- s.connect((host, port))
- s.close()
- except socket.error:
- if s:
- s.close()
- if hasattr(sock, "close"):
- sock.close()
- self.socket = None
-
- self.requests.stop(self.shutdown_timeout)
-
-
-class Gateway(object):
-
- """A base class to interface HTTPServer with other systems, such as WSGI.
- """
-
- def __init__(self, req):
- self.req = req
-
- def respond(self):
- """Process the current request. Must be overridden in a subclass."""
- raise NotImplemented
-
-
-# These may either be wsgiserver.SSLAdapter subclasses or the string names
-# of such classes (in which case they will be lazily loaded).
-ssl_adapters = {
- 'builtin': 'cherrypy.wsgiserver.ssl_builtin.BuiltinSSLAdapter',
- 'pyopenssl': 'cherrypy.wsgiserver.ssl_pyopenssl.pyOpenSSLAdapter',
-}
-
-
-def get_ssl_adapter_class(name='builtin'):
- """Return an SSL adapter class for the given name."""
- adapter = ssl_adapters[name.lower()]
- if isinstance(adapter, basestring):
- last_dot = adapter.rfind(".")
- attr_name = adapter[last_dot + 1:]
- mod_path = adapter[:last_dot]
-
- try:
- mod = sys.modules[mod_path]
- if mod is None:
- raise KeyError()
- except KeyError:
- # The last [''] is important.
- mod = __import__(mod_path, globals(), locals(), [''])
-
- # Let an AttributeError propagate outward.
- try:
- adapter = getattr(mod, attr_name)
- except AttributeError:
- raise AttributeError("'%s' object has no attribute '%s'"
- % (mod_path, attr_name))
-
- return adapter
-
-# ------------------------------- WSGI Stuff -------------------------------- #
-
-
-class CherryPyWSGIServer(HTTPServer):
-
- """A subclass of HTTPServer which calls a WSGI application."""
-
- wsgi_version = (1, 0)
- """The version of WSGI to produce."""
-
- def __init__(self, bind_addr, wsgi_app, numthreads=10, server_name=None,
- max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5,
- accepted_queue_size=-1, accepted_queue_timeout=10):
- self.requests = ThreadPool(self, min=numthreads or 1, max=max,
- accepted_queue_size=accepted_queue_size,
- accepted_queue_timeout=accepted_queue_timeout)
- self.wsgi_app = wsgi_app
- self.gateway = wsgi_gateways[self.wsgi_version]
-
- self.bind_addr = bind_addr
- if not server_name:
- server_name = socket.gethostname()
- self.server_name = server_name
- self.request_queue_size = request_queue_size
-
- self.timeout = timeout
- self.shutdown_timeout = shutdown_timeout
- self.clear_stats()
-
- def _get_numthreads(self):
- return self.requests.min
-
- def _set_numthreads(self, value):
- self.requests.min = value
- numthreads = property(_get_numthreads, _set_numthreads)
-
-
-class WSGIGateway(Gateway):
-
- """A base class to interface HTTPServer with WSGI."""
-
- def __init__(self, req):
- self.req = req
- self.started_response = False
- self.env = self.get_environ()
- self.remaining_bytes_out = None
-
- def get_environ(self):
- """Return a new environ dict targeting the given wsgi.version"""
- raise NotImplemented
-
- def respond(self):
- """Process the current request."""
- response = self.req.server.wsgi_app(self.env, self.start_response)
- try:
- for chunk in response:
- # "The start_response callable must not actually transmit
- # the response headers. Instead, it must store them for the
- # server or gateway to transmit only after the first
- # iteration of the application return value that yields
- # a NON-EMPTY string, or upon the application's first
- # invocation of the write() callable." (PEP 333)
- if chunk:
- if isinstance(chunk, unicodestr):
- chunk = chunk.encode('ISO-8859-1')
- self.write(chunk)
- finally:
- if hasattr(response, "close"):
- response.close()
-
- def start_response(self, status, headers, exc_info=None):
- """WSGI callable to begin the HTTP response."""
- # "The application may call start_response more than once,
- # if and only if the exc_info argument is provided."
- if self.started_response and not exc_info:
- raise AssertionError("WSGI start_response called a second "
- "time with no exc_info.")
- self.started_response = True
-
- # "if exc_info is provided, and the HTTP headers have already been
- # sent, start_response must raise an error, and should raise the
- # exc_info tuple."
- if self.req.sent_headers:
- try:
- raise exc_info[0], exc_info[1], exc_info[2]
- finally:
- exc_info = None
-
- self.req.status = status
- for k, v in headers:
- if not isinstance(k, str):
- raise TypeError(
- "WSGI response header key %r is not of type str." % k)
- if not isinstance(v, str):
- raise TypeError(
- "WSGI response header value %r is not of type str." % v)
- if k.lower() == 'content-length':
- self.remaining_bytes_out = int(v)
- self.req.outheaders.extend(headers)
-
- return self.write
-
- def write(self, chunk):
- """WSGI callable to write unbuffered data to the client.
-
- This method is also used internally by start_response (to write
- data from the iterable returned by the WSGI application).
- """
- if not self.started_response:
- raise AssertionError("WSGI write called before start_response.")
-
- chunklen = len(chunk)
- rbo = self.remaining_bytes_out
- if rbo is not None and chunklen > rbo:
- if not self.req.sent_headers:
- # Whew. We can send a 500 to the client.
- self.req.simple_response(
- "500 Internal Server Error",
- "The requested resource returned more bytes than the "
- "declared Content-Length.")
- else:
- # Dang. We have probably already sent data. Truncate the chunk
- # to fit (so the client doesn't hang) and raise an error later.
- chunk = chunk[:rbo]
-
- if not self.req.sent_headers:
- self.req.sent_headers = True
- self.req.send_headers()
-
- self.req.write(chunk)
-
- if rbo is not None:
- rbo -= chunklen
- if rbo < 0:
- raise ValueError(
- "Response body exceeds the declared Content-Length.")
-
-
-class WSGIGateway_10(WSGIGateway):
-
- """A Gateway class to interface HTTPServer with WSGI 1.0.x."""
-
- def get_environ(self):
- """Return a new environ dict targeting the given wsgi.version"""
- req = self.req
- env = {
- # set a non-standard environ entry so the WSGI app can know what
- # the *real* server protocol is (and what features to support).
- # See http://www.faqs.org/rfcs/rfc2145.html.
- 'ACTUAL_SERVER_PROTOCOL': req.server.protocol,
- 'PATH_INFO': req.path,
- 'QUERY_STRING': req.qs,
- 'REMOTE_ADDR': req.conn.remote_addr or '',
- 'REMOTE_PORT': str(req.conn.remote_port or ''),
- 'REQUEST_METHOD': req.method,
- 'REQUEST_URI': req.uri,
- 'SCRIPT_NAME': '',
- 'SERVER_NAME': req.server.server_name,
- # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol.
- 'SERVER_PROTOCOL': req.request_protocol,
- 'SERVER_SOFTWARE': req.server.software,
- 'wsgi.errors': sys.stderr,
- 'wsgi.input': req.rfile,
- 'wsgi.multiprocess': False,
- 'wsgi.multithread': True,
- 'wsgi.run_once': False,
- 'wsgi.url_scheme': req.scheme,
- 'wsgi.version': (1, 0),
- }
-
- if isinstance(req.server.bind_addr, basestring):
- # AF_UNIX. This isn't really allowed by WSGI, which doesn't
- # address unix domain sockets. But it's better than nothing.
- env["SERVER_PORT"] = ""
- else:
- env["SERVER_PORT"] = str(req.server.bind_addr[1])
-
- # Request headers
- for k, v in req.inheaders.iteritems():
- env["HTTP_" + k.upper().replace("-", "_")] = v
-
- # CONTENT_TYPE/CONTENT_LENGTH
- ct = env.pop("HTTP_CONTENT_TYPE", None)
- if ct is not None:
- env["CONTENT_TYPE"] = ct
- cl = env.pop("HTTP_CONTENT_LENGTH", None)
- if cl is not None:
- env["CONTENT_LENGTH"] = cl
-
- if req.conn.ssl_env:
- env.update(req.conn.ssl_env)
-
- return env
-
-
-class WSGIGateway_u0(WSGIGateway_10):
-
- """A Gateway class to interface HTTPServer with WSGI u.0.
-
- WSGI u.0 is an experimental protocol, which uses unicode for keys and
- values in both Python 2 and Python 3.
- """
-
- def get_environ(self):
- """Return a new environ dict targeting the given wsgi.version"""
- req = self.req
- env_10 = WSGIGateway_10.get_environ(self)
- env = dict([(k.decode('ISO-8859-1'), v)
- for k, v in env_10.iteritems()])
- env[u'wsgi.version'] = ('u', 0)
-
- # Request-URI
- env.setdefault(u'wsgi.url_encoding', u'utf-8')
- try:
- for key in [u"PATH_INFO", u"SCRIPT_NAME", u"QUERY_STRING"]:
- env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
- except UnicodeDecodeError:
- # Fall back to latin 1 so apps can transcode if needed.
- env[u'wsgi.url_encoding'] = u'ISO-8859-1'
- for key in [u"PATH_INFO", u"SCRIPT_NAME", u"QUERY_STRING"]:
- env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
-
- for k, v in sorted(env.items()):
- if isinstance(v, str) and k not in ('REQUEST_URI', 'wsgi.input'):
- env[k] = v.decode('ISO-8859-1')
-
- return env
-
-wsgi_gateways = {
- (1, 0): WSGIGateway_10,
- ('u', 0): WSGIGateway_u0,
-}
-
-
-class WSGIPathInfoDispatcher(object):
-
- """A WSGI dispatcher for dispatch based on the PATH_INFO.
-
- apps: a dict or list of (path_prefix, app) pairs.
- """
-
- def __init__(self, apps):
- try:
- apps = list(apps.items())
- except AttributeError:
- pass
-
- # Sort the apps by len(path), descending
- apps.sort(cmp=lambda x, y: cmp(len(x[0]), len(y[0])))
- apps.reverse()
-
- # The path_prefix strings must start, but not end, with a slash.
- # Use "" instead of "/".
- self.apps = [(p.rstrip("/"), a) for p, a in apps]
-
- def __call__(self, environ, start_response):
- path = environ["PATH_INFO"] or "/"
- for p, app in self.apps:
- # The apps list should be sorted by length, descending.
- if path.startswith(p + "/") or path == p:
- environ = environ.copy()
- environ["SCRIPT_NAME"] = environ["SCRIPT_NAME"] + p
- environ["PATH_INFO"] = path[len(p):]
- return app(environ, start_response)
-
- start_response('404 Not Found', [('Content-Type', 'text/plain'),
- ('Content-Length', '0')])
- return ['']
diff --git a/cherrypy/wsgiserver/wsgiserver3.py b/cherrypy/wsgiserver/wsgiserver3.py
deleted file mode 100644
index eb169d5e..00000000
--- a/cherrypy/wsgiserver/wsgiserver3.py
+++ /dev/null
@@ -1,2197 +0,0 @@
-"""A high-speed, production ready, thread pooled, generic HTTP server.
-
-Simplest example on how to use this module directly
-(without using CherryPy's application machinery)::
-
- from cherrypy import wsgiserver
-
- def my_crazy_app(environ, start_response):
- status = '200 OK'
- response_headers = [('Content-type','text/plain')]
- start_response(status, response_headers)
- return ['Hello world!']
-
- server = wsgiserver.CherryPyWSGIServer(
- ('0.0.0.0', 8070), my_crazy_app,
- server_name='www.cherrypy.example')
- server.start()
-
-The CherryPy WSGI server can serve as many WSGI applications
-as you want in one instance by using a WSGIPathInfoDispatcher::
-
- d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
- server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)
-
-Want SSL support? Just set server.ssl_adapter to an SSLAdapter instance.
-
-This won't call the CherryPy engine (application side) at all, only the
-HTTP server, which is independent from the rest of CherryPy. Don't
-let the name "CherryPyWSGIServer" throw you; the name merely reflects
-its origin, not its coupling.
-
-For those of you wanting to understand internals of this module, here's the
-basic call flow. The server's listening thread runs a very tight loop,
-sticking incoming connections onto a Queue::
-
- server = CherryPyWSGIServer(...)
- server.start()
- while True:
- tick()
- # This blocks until a request comes in:
- child = socket.accept()
- conn = HTTPConnection(child, ...)
- server.requests.put(conn)
-
-Worker threads are kept in a pool and poll the Queue, popping off and then
-handling each connection in turn. Each connection can consist of an arbitrary
-number of requests and their responses, so we run a nested loop::
-
- while True:
- conn = server.requests.get()
- conn.communicate()
- -> while True:
- req = HTTPRequest(...)
- req.parse_request()
- -> # Read the Request-Line, e.g. "GET /page HTTP/1.1"
- req.rfile.readline()
- read_headers(req.rfile, req.inheaders)
- req.respond()
- -> response = app(...)
- try:
- for chunk in response:
- if chunk:
- req.write(chunk)
- finally:
- if hasattr(response, "close"):
- response.close()
- if req.close_connection:
- return
-"""
-
-__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer',
- 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile',
- 'CP_makefile',
- 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert',
- 'WorkerThread', 'ThreadPool', 'SSLAdapter',
- 'CherryPyWSGIServer',
- 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0',
- 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class',
- 'socket_errors_to_ignore']
-
-import os
-try:
- import queue
-except:
- import Queue as queue
-import re
-import email.utils
-import socket
-import sys
-import threading
-import time
-import traceback as traceback_
-import errno
-import logging
-try:
- # prefer slower Python-based io module
- import _pyio as io
-except ImportError:
- # Python 2.6
- import io
-
-try:
- import pkg_resources
-except ImportError:
- pass
-
-if 'win' in sys.platform and hasattr(socket, "AF_INET6"):
- if not hasattr(socket, 'IPPROTO_IPV6'):
- socket.IPPROTO_IPV6 = 41
- if not hasattr(socket, 'IPV6_V6ONLY'):
- socket.IPV6_V6ONLY = 27
-
-
-DEFAULT_BUFFER_SIZE = io.DEFAULT_BUFFER_SIZE
-
-
-try:
- cp_version = pkg_resources.require('cherrypy')[0].version
-except Exception:
- cp_version = 'unknown'
-
-
-if sys.version_info >= (3, 0):
- bytestr = bytes
- unicodestr = str
- basestring = (bytes, str)
-
- def ntob(n, encoding='ISO-8859-1'):
- """Return the given native string as a byte string in the given
- encoding.
- """
- # In Python 3, the native string type is unicode
- return n.encode(encoding)
-else:
- bytestr = str
- unicodestr = unicode
- basestring = basestring
-
- def ntob(n, encoding='ISO-8859-1'):
- """Return the given native string as a byte string in the given
- encoding.
- """
- # In Python 2, the native string type is bytes. Assume it's already
- # in the given encoding, which for ISO-8859-1 is almost always what
- # was intended.
- return n
-
-LF = ntob('\n')
-CRLF = ntob('\r\n')
-TAB = ntob('\t')
-SPACE = ntob(' ')
-COLON = ntob(':')
-SEMICOLON = ntob(';')
-EMPTY = ntob('')
-NUMBER_SIGN = ntob('#')
-QUESTION_MARK = ntob('?')
-ASTERISK = ntob('*')
-FORWARD_SLASH = ntob('/')
-quoted_slash = re.compile(ntob("(?i)%2F"))
-
-
-def plat_specific_errors(*errnames):
- """Return error numbers for all errors in errnames on this platform.
-
- The 'errno' module contains different global constants depending on
- the specific platform (OS). This function will return the list of
- numeric values for a given list of potential names.
- """
- errno_names = dir(errno)
- nums = [getattr(errno, k) for k in errnames if k in errno_names]
- # de-dupe the list
- return list(dict.fromkeys(nums).keys())
-
-socket_error_eintr = plat_specific_errors("EINTR", "WSAEINTR")
-
-socket_errors_to_ignore = plat_specific_errors(
- "EPIPE",
- "EBADF", "WSAEBADF",
- "ENOTSOCK", "WSAENOTSOCK",
- "ETIMEDOUT", "WSAETIMEDOUT",
- "ECONNREFUSED", "WSAECONNREFUSED",
- "ECONNRESET", "WSAECONNRESET",
- "ECONNABORTED", "WSAECONNABORTED",
- "ENETRESET", "WSAENETRESET",
- "EHOSTDOWN", "EHOSTUNREACH",
-)
-socket_errors_to_ignore.append("timed out")
-socket_errors_to_ignore.append("The read operation timed out")
-
-socket_errors_nonblocking = plat_specific_errors(
- 'EAGAIN', 'EWOULDBLOCK', 'WSAEWOULDBLOCK')
-
-comma_separated_headers = [
- ntob(h) for h in
- ['Accept', 'Accept-Charset', 'Accept-Encoding',
- 'Accept-Language', 'Accept-Ranges', 'Allow', 'Cache-Control',
- 'Connection', 'Content-Encoding', 'Content-Language', 'Expect',
- 'If-Match', 'If-None-Match', 'Pragma', 'Proxy-Authenticate', 'TE',
- 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Vary', 'Via', 'Warning',
- 'WWW-Authenticate']
-]
-
-
-if not hasattr(logging, 'statistics'):
- logging.statistics = {}
-
-
-def read_headers(rfile, hdict=None):
- """Read headers from the given stream into the given header dict.
-
- If hdict is None, a new header dict is created. Returns the populated
- header dict.
-
- Headers which are repeated are folded together using a comma if their
- specification so dictates.
-
- This function raises ValueError when the read bytes violate the HTTP spec.
- You should probably return "400 Bad Request" if this happens.
- """
- if hdict is None:
- hdict = {}
-
- while True:
- line = rfile.readline()
- if not line:
- # No more data--illegal end of headers
- raise ValueError("Illegal end of headers.")
-
- if line == CRLF:
- # Normal end of headers
- break
- if not line.endswith(CRLF):
- raise ValueError("HTTP requires CRLF terminators")
-
- if line[0] in (SPACE, TAB):
- # It's a continuation line.
- v = line.strip()
- else:
- try:
- k, v = line.split(COLON, 1)
- except ValueError:
- raise ValueError("Illegal header line.")
- # TODO: what about TE and WWW-Authenticate?
- k = k.strip().title()
- v = v.strip()
- hname = k
-
- if k in comma_separated_headers:
- existing = hdict.get(hname)
- if existing:
- v = b", ".join((existing, v))
- hdict[hname] = v
-
- return hdict
-
-
-class MaxSizeExceeded(Exception):
- pass
-
-
-class SizeCheckWrapper(object):
-
- """Wraps a file-like object, raising MaxSizeExceeded if too large."""
-
- def __init__(self, rfile, maxlen):
- self.rfile = rfile
- self.maxlen = maxlen
- self.bytes_read = 0
-
- def _check_length(self):
- if self.maxlen and self.bytes_read > self.maxlen:
- raise MaxSizeExceeded()
-
- def read(self, size=None):
- data = self.rfile.read(size)
- self.bytes_read += len(data)
- self._check_length()
- return data
-
- def readline(self, size=None):
- if size is not None:
- data = self.rfile.readline(size)
- self.bytes_read += len(data)
- self._check_length()
- return data
-
- # User didn't specify a size ...
- # We read the line in chunks to make sure it's not a 100MB line !
- res = []
- while True:
- data = self.rfile.readline(256)
- self.bytes_read += len(data)
- self._check_length()
- res.append(data)
- # See https://github.com/cherrypy/cherrypy/issues/421
- if len(data) < 256 or data[-1:] == LF:
- return EMPTY.join(res)
-
- def readlines(self, sizehint=0):
- # Shamelessly stolen from StringIO
- total = 0
- lines = []
- line = self.readline()
- while line:
- lines.append(line)
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline()
- return lines
-
- def close(self):
- self.rfile.close()
-
- def __iter__(self):
- return self
-
- def __next__(self):
- data = next(self.rfile)
- self.bytes_read += len(data)
- self._check_length()
- return data
-
- def next(self):
- data = self.rfile.next()
- self.bytes_read += len(data)
- self._check_length()
- return data
-
-
-class KnownLengthRFile(object):
-
- """Wraps a file-like object, returning an empty string when exhausted."""
-
- def __init__(self, rfile, content_length):
- self.rfile = rfile
- self.remaining = content_length
-
- def read(self, size=None):
- if self.remaining == 0:
- return b''
- if size is None:
- size = self.remaining
- else:
- size = min(size, self.remaining)
-
- data = self.rfile.read(size)
- self.remaining -= len(data)
- return data
-
- def readline(self, size=None):
- if self.remaining == 0:
- return b''
- if size is None:
- size = self.remaining
- else:
- size = min(size, self.remaining)
-
- data = self.rfile.readline(size)
- self.remaining -= len(data)
- return data
-
- def readlines(self, sizehint=0):
- # Shamelessly stolen from StringIO
- total = 0
- lines = []
- line = self.readline(sizehint)
- while line:
- lines.append(line)
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline(sizehint)
- return lines
-
- def close(self):
- self.rfile.close()
-
- def __iter__(self):
- return self
-
- def __next__(self):
- data = next(self.rfile)
- self.remaining -= len(data)
- return data
-
-
-class ChunkedRFile(object):
-
- """Wraps a file-like object, returning an empty string when exhausted.
-
- This class is intended to provide a conforming wsgi.input value for
- request entities that have been encoded with the 'chunked' transfer
- encoding.
- """
-
- def __init__(self, rfile, maxlen, bufsize=8192):
- self.rfile = rfile
- self.maxlen = maxlen
- self.bytes_read = 0
- self.buffer = EMPTY
- self.bufsize = bufsize
- self.closed = False
-
- def _fetch(self):
- if self.closed:
- return
-
- line = self.rfile.readline()
- self.bytes_read += len(line)
-
- if self.maxlen and self.bytes_read > self.maxlen:
- raise MaxSizeExceeded("Request Entity Too Large", self.maxlen)
-
- line = line.strip().split(SEMICOLON, 1)
-
- try:
- chunk_size = line.pop(0)
- chunk_size = int(chunk_size, 16)
- except ValueError:
- raise ValueError("Bad chunked transfer size: " + repr(chunk_size))
-
- if chunk_size <= 0:
- self.closed = True
- return
-
-## if line: chunk_extension = line[0]
-
- if self.maxlen and self.bytes_read + chunk_size > self.maxlen:
- raise IOError("Request Entity Too Large")
-
- chunk = self.rfile.read(chunk_size)
- self.bytes_read += len(chunk)
- self.buffer += chunk
-
- crlf = self.rfile.read(2)
- if crlf != CRLF:
- raise ValueError(
- "Bad chunked transfer coding (expected '\\r\\n', "
- "got " + repr(crlf) + ")")
-
- def read(self, size=None):
- data = EMPTY
- while True:
- if size and len(data) >= size:
- return data
-
- if not self.buffer:
- self._fetch()
- if not self.buffer:
- # EOF
- return data
-
- if size:
- remaining = size - len(data)
- data += self.buffer[:remaining]
- self.buffer = self.buffer[remaining:]
- else:
- data += self.buffer
-
- def readline(self, size=None):
- data = EMPTY
- while True:
- if size and len(data) >= size:
- return data
-
- if not self.buffer:
- self._fetch()
- if not self.buffer:
- # EOF
- return data
-
- newline_pos = self.buffer.find(LF)
- if size:
- if newline_pos == -1:
- remaining = size - len(data)
- data += self.buffer[:remaining]
- self.buffer = self.buffer[remaining:]
- else:
- remaining = min(size - len(data), newline_pos)
- data += self.buffer[:remaining]
- self.buffer = self.buffer[remaining:]
- else:
- if newline_pos == -1:
- data += self.buffer
- else:
- data += self.buffer[:newline_pos]
- self.buffer = self.buffer[newline_pos:]
-
- def readlines(self, sizehint=0):
- # Shamelessly stolen from StringIO
- total = 0
- lines = []
- line = self.readline(sizehint)
- while line:
- lines.append(line)
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline(sizehint)
- return lines
-
- def read_trailer_lines(self):
- if not self.closed:
- raise ValueError(
- "Cannot read trailers until the request body has been read.")
-
- while True:
- line = self.rfile.readline()
- if not line:
- # No more data--illegal end of headers
- raise ValueError("Illegal end of headers.")
-
- self.bytes_read += len(line)
- if self.maxlen and self.bytes_read > self.maxlen:
- raise IOError("Request Entity Too Large")
-
- if line == CRLF:
- # Normal end of headers
- break
- if not line.endswith(CRLF):
- raise ValueError("HTTP requires CRLF terminators")
-
- yield line
-
- def close(self):
- self.rfile.close()
-
- def __iter__(self):
- # Shamelessly stolen from StringIO
- total = 0
- line = self.readline(sizehint)
- while line:
- yield line
- total += len(line)
- if 0 < sizehint <= total:
- break
- line = self.readline(sizehint)
-
-
-class HTTPRequest(object):
-
- """An HTTP Request (and response).
-
- A single HTTP connection may consist of multiple request/response pairs.
- """
-
- server = None
- """The HTTPServer object which is receiving this request."""
-
- conn = None
- """The HTTPConnection object on which this request connected."""
-
- inheaders = {}
- """A dict of request headers."""
-
- outheaders = []
- """A list of header tuples to write in the response."""
-
- ready = False
- """When True, the request has been parsed and is ready to begin generating
- the response. When False, signals the calling Connection that the response
- should not be generated and the connection should close."""
-
- close_connection = False
- """Signals the calling Connection that the request should close. This does
- not imply an error! The client and/or server may each request that the
- connection be closed."""
-
- chunked_write = False
- """If True, output will be encoded with the "chunked" transfer-coding.
-
- This value is set automatically inside send_headers."""
-
- def __init__(self, server, conn):
- self.server = server
- self.conn = conn
-
- self.ready = False
- self.started_request = False
- self.scheme = ntob("http")
- if self.server.ssl_adapter is not None:
- self.scheme = ntob("https")
- # Use the lowest-common protocol in case read_request_line errors.
- self.response_protocol = 'HTTP/1.0'
- self.inheaders = {}
-
- self.status = ""
- self.outheaders = []
- self.sent_headers = False
- self.close_connection = self.__class__.close_connection
- self.chunked_read = False
- self.chunked_write = self.__class__.chunked_write
-
- def parse_request(self):
- """Parse the next HTTP request start-line and message-headers."""
- self.rfile = SizeCheckWrapper(self.conn.rfile,
- self.server.max_request_header_size)
- try:
- success = self.read_request_line()
- except MaxSizeExceeded:
- self.simple_response(
- "414 Request-URI Too Long",
- "The Request-URI sent with the request exceeds the maximum "
- "allowed bytes.")
- return
- else:
- if not success:
- return
-
- try:
- success = self.read_request_headers()
- except MaxSizeExceeded:
- self.simple_response(
- "413 Request Entity Too Large",
- "The headers sent with the request exceed the maximum "
- "allowed bytes.")
- return
- else:
- if not success:
- return
-
- self.ready = True
-
- def read_request_line(self):
- # HTTP/1.1 connections are persistent by default. If a client
- # requests a page, then idles (leaves the connection open),
- # then rfile.readline() will raise socket.error("timed out").
- # Note that it does this based on the value given to settimeout(),
- # and doesn't need the client to request or acknowledge the close
- # (although your TCP stack might suffer for it: cf Apache's history
- # with FIN_WAIT_2).
- request_line = self.rfile.readline()
-
- # Set started_request to True so communicate() knows to send 408
- # from here on out.
- self.started_request = True
- if not request_line:
- return False
-
- if request_line == CRLF:
- # RFC 2616 sec 4.1: "...if the server is reading the protocol
- # stream at the beginning of a message and receives a CRLF
- # first, it should ignore the CRLF."
- # But only ignore one leading line! else we enable a DoS.
- request_line = self.rfile.readline()
- if not request_line:
- return False
-
- if not request_line.endswith(CRLF):
- self.simple_response(
- "400 Bad Request", "HTTP requires CRLF terminators")
- return False
-
- try:
- method, uri, req_protocol = request_line.strip().split(SPACE, 2)
- # The [x:y] slicing is necessary for byte strings to avoid getting
- # ord's
- rp = int(req_protocol[5:6]), int(req_protocol[7:8])
- except ValueError:
- self.simple_response("400 Bad Request", "Malformed Request-Line")
- return False
-
- self.uri = uri
- self.method = method
-
- # uri may be an abs_path (including "http://host.domain.tld");
- scheme, authority, path = self.parse_request_uri(uri)
- if path is None:
- self.simple_response("400 Bad Request",
- "Invalid path in Request-URI.")
- return False
- if NUMBER_SIGN in path:
- self.simple_response("400 Bad Request",
- "Illegal #fragment in Request-URI.")
- return False
-
- if scheme:
- self.scheme = scheme
-
- qs = EMPTY
- if QUESTION_MARK in path:
- path, qs = path.split(QUESTION_MARK, 1)
-
- # Unquote the path+params (e.g. "/this%20path" -> "/this path").
- # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
- #
- # But note that "...a URI must be separated into its components
- # before the escaped characters within those components can be
- # safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2
- # Therefore, "/this%2Fpath" becomes "/this%2Fpath", not "/this/path".
- try:
- atoms = [self.unquote_bytes(x) for x in quoted_slash.split(path)]
- except ValueError:
- ex = sys.exc_info()[1]
- self.simple_response("400 Bad Request", ex.args[0])
- return False
- path = b"%2F".join(atoms)
- self.path = path
-
- # Note that, like wsgiref and most other HTTP servers,
- # we "% HEX HEX"-unquote the path but not the query string.
- self.qs = qs
-
- # Compare request and server HTTP protocol versions, in case our
- # server does not support the requested protocol. Limit our output
- # to min(req, server). We want the following output:
- # request server actual written supported response
- # protocol protocol response protocol feature set
- # a 1.0 1.0 1.0 1.0
- # b 1.0 1.1 1.1 1.0
- # c 1.1 1.0 1.0 1.0
- # d 1.1 1.1 1.1 1.1
- # Notice that, in (b), the response will be "HTTP/1.1" even though
- # the client only understands 1.0. RFC 2616 10.5.6 says we should
- # only return 505 if the _major_ version is different.
- # The [x:y] slicing is necessary for byte strings to avoid getting
- # ord's
- sp = int(self.server.protocol[5:6]), int(self.server.protocol[7:8])
-
- if sp[0] != rp[0]:
- self.simple_response("505 HTTP Version Not Supported")
- return False
-
- self.request_protocol = req_protocol
- self.response_protocol = "HTTP/%s.%s" % min(rp, sp)
- return True
-
- def read_request_headers(self):
- """Read self.rfile into self.inheaders. Return success."""
-
- # then all the http headers
- try:
- read_headers(self.rfile, self.inheaders)
- except ValueError:
- ex = sys.exc_info()[1]
- self.simple_response("400 Bad Request", ex.args[0])
- return False
-
- mrbs = self.server.max_request_body_size
- if mrbs and int(self.inheaders.get(b"Content-Length", 0)) > mrbs:
- self.simple_response(
- "413 Request Entity Too Large",
- "The entity sent with the request exceeds the maximum "
- "allowed bytes.")
- return False
-
- # Persistent connection support
- if self.response_protocol == "HTTP/1.1":
- # Both server and client are HTTP/1.1
- if self.inheaders.get(b"Connection", b"") == b"close":
- self.close_connection = True
- else:
- # Either the server or client (or both) are HTTP/1.0
- if self.inheaders.get(b"Connection", b"") != b"Keep-Alive":
- self.close_connection = True
-
- # Transfer-Encoding support
- te = None
- if self.response_protocol == "HTTP/1.1":
- te = self.inheaders.get(b"Transfer-Encoding")
- if te:
- te = [x.strip().lower() for x in te.split(b",") if x.strip()]
-
- self.chunked_read = False
-
- if te:
- for enc in te:
- if enc == b"chunked":
- self.chunked_read = True
- else:
- # Note that, even if we see "chunked", we must reject
- # if there is an extension we don't recognize.
- self.simple_response("501 Unimplemented")
- self.close_connection = True
- return False
-
- # From PEP 333:
- # "Servers and gateways that implement HTTP 1.1 must provide
- # transparent support for HTTP 1.1's "expect/continue" mechanism.
- # This may be done in any of several ways:
- # 1. Respond to requests containing an Expect: 100-continue request
- # with an immediate "100 Continue" response, and proceed normally.
- # 2. Proceed with the request normally, but provide the application
- # with a wsgi.input stream that will send the "100 Continue"
- # response if/when the application first attempts to read from
- # the input stream. The read request must then remain blocked
- # until the client responds.
- # 3. Wait until the client decides that the server does not support
- # expect/continue, and sends the request body on its own.
- # (This is suboptimal, and is not recommended.)
- #
- # We used to do 3, but are now doing 1. Maybe we'll do 2 someday,
- # but it seems like it would be a big slowdown for such a rare case.
- if self.inheaders.get(b"Expect", b"") == b"100-continue":
- # Don't use simple_response here, because it emits headers
- # we don't want. See
- # https://github.com/cherrypy/cherrypy/issues/951
- msg = self.server.protocol.encode(
- 'ascii') + b" 100 Continue\r\n\r\n"
- try:
- self.conn.wfile.write(msg)
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- raise
- return True
-
- def parse_request_uri(self, uri):
- """Parse a Request-URI into (scheme, authority, path).
-
- Note that Request-URI's must be one of::
-
- Request-URI = "*" | absoluteURI | abs_path | authority
-
- Therefore, a Request-URI which starts with a double forward-slash
- cannot be a "net_path"::
-
- net_path = "//" authority [ abs_path ]
-
- Instead, it must be interpreted as an "abs_path" with an empty first
- path segment::
-
- abs_path = "/" path_segments
- path_segments = segment *( "/" segment )
- segment = *pchar *( ";" param )
- param = *pchar
- """
- if uri == ASTERISK:
- return None, None, uri
-
- scheme, sep, remainder = uri.partition(b'://')
- if sep and QUESTION_MARK not in scheme:
- # An absoluteURI.
- # If there's a scheme (and it must be http or https), then:
- # http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query
- # ]]
- authority, path_a, path_b = remainder.partition(FORWARD_SLASH)
- return scheme.lower(), authority, path_a + path_b
-
- if uri.startswith(FORWARD_SLASH):
- # An abs_path.
- return None, None, uri
- else:
- # An authority.
- return None, uri, None
-
- def unquote_bytes(self, path):
- """takes quoted string and unquotes % encoded values"""
- res = path.split(b'%')
-
- for i in range(1, len(res)):
- item = res[i]
- try:
- res[i] = bytes([int(item[:2], 16)]) + item[2:]
- except ValueError:
- raise
- return b''.join(res)
-
- def respond(self):
- """Call the gateway and write its iterable output."""
- mrbs = self.server.max_request_body_size
- if self.chunked_read:
- self.rfile = ChunkedRFile(self.conn.rfile, mrbs)
- else:
- cl = int(self.inheaders.get(b"Content-Length", 0))
- if mrbs and mrbs < cl:
- if not self.sent_headers:
- self.simple_response(
- "413 Request Entity Too Large",
- "The entity sent with the request exceeds the "
- "maximum allowed bytes.")
- return
- self.rfile = KnownLengthRFile(self.conn.rfile, cl)
-
- self.server.gateway(self).respond()
-
- if (self.ready and not self.sent_headers):
- self.sent_headers = True
- self.send_headers()
- if self.chunked_write:
- self.conn.wfile.write(b"0\r\n\r\n")
-
- def simple_response(self, status, msg=""):
- """Write a simple response back to the client."""
- status = str(status)
- buf = [bytes(self.server.protocol, "ascii") + SPACE +
- bytes(status, "ISO-8859-1") + CRLF,
- bytes("Content-Length: %s\r\n" % len(msg), "ISO-8859-1"),
- b"Content-Type: text/plain\r\n"]
-
- if status[:3] in ("413", "414"):
- # Request Entity Too Large / Request-URI Too Long
- self.close_connection = True
- if self.response_protocol == 'HTTP/1.1':
- # This will not be true for 414, since read_request_line
- # usually raises 414 before reading the whole line, and we
- # therefore cannot know the proper response_protocol.
- buf.append(b"Connection: close\r\n")
- else:
- # HTTP/1.0 had no 413/414 status nor Connection header.
- # Emit 400 instead and trust the message body is enough.
- status = "400 Bad Request"
-
- buf.append(CRLF)
- if msg:
- if isinstance(msg, unicodestr):
- msg = msg.encode("ISO-8859-1")
- buf.append(msg)
-
- try:
- self.conn.wfile.write(b"".join(buf))
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- raise
-
- def write(self, chunk):
- """Write unbuffered data to the client."""
- if self.chunked_write and chunk:
- buf = [bytes(hex(len(chunk)), 'ASCII')[2:], CRLF, chunk, CRLF]
- self.conn.wfile.write(EMPTY.join(buf))
- else:
- self.conn.wfile.write(chunk)
-
- def send_headers(self):
- """Assert, process, and send the HTTP response message-headers.
-
- You must set self.status, and self.outheaders before calling this.
- """
- hkeys = [key.lower() for key, value in self.outheaders]
- status = int(self.status[:3])
-
- if status == 413:
- # Request Entity Too Large. Close conn to avoid garbage.
- self.close_connection = True
- elif b"content-length" not in hkeys:
- # "All 1xx (informational), 204 (no content),
- # and 304 (not modified) responses MUST NOT
- # include a message-body." So no point chunking.
- if status < 200 or status in (204, 205, 304):
- pass
- else:
- if (self.response_protocol == 'HTTP/1.1'
- and self.method != b'HEAD'):
- # Use the chunked transfer-coding
- self.chunked_write = True
- self.outheaders.append((b"Transfer-Encoding", b"chunked"))
- else:
- # Closing the conn is the only way to determine len.
- self.close_connection = True
-
- if b"connection" not in hkeys:
- if self.response_protocol == 'HTTP/1.1':
- # Both server and client are HTTP/1.1 or better
- if self.close_connection:
- self.outheaders.append((b"Connection", b"close"))
- else:
- # Server and/or client are HTTP/1.0
- if not self.close_connection:
- self.outheaders.append((b"Connection", b"Keep-Alive"))
-
- if (not self.close_connection) and (not self.chunked_read):
- # Read any remaining request body data on the socket.
- # "If an origin server receives a request that does not include an
- # Expect request-header field with the "100-continue" expectation,
- # the request includes a request body, and the server responds
- # with a final status code before reading the entire request body
- # from the transport connection, then the server SHOULD NOT close
- # the transport connection until it has read the entire request,
- # or until the client closes the connection. Otherwise, the client
- # might not reliably receive the response message. However, this
- # requirement is not be construed as preventing a server from
- # defending itself against denial-of-service attacks, or from
- # badly broken client implementations."
- remaining = getattr(self.rfile, 'remaining', 0)
- if remaining > 0:
- self.rfile.read(remaining)
-
- if b"date" not in hkeys:
- self.outheaders.append((
- b"Date",
- email.utils.formatdate(usegmt=True).encode('ISO-8859-1')
- ))
-
- if b"server" not in hkeys:
- self.outheaders.append(
- (b"Server", self.server.server_name.encode('ISO-8859-1')))
-
- buf = [self.server.protocol.encode(
- 'ascii') + SPACE + self.status + CRLF]
- for k, v in self.outheaders:
- buf.append(k + COLON + SPACE + v + CRLF)
- buf.append(CRLF)
- self.conn.wfile.write(EMPTY.join(buf))
-
-
-class NoSSLError(Exception):
-
- """Exception raised when a client speaks HTTP to an HTTPS socket."""
- pass
-
-
-class FatalSSLAlert(Exception):
-
- """Exception raised when the SSL implementation signals a fatal alert."""
- pass
-
-
-class CP_BufferedWriter(io.BufferedWriter):
-
- """Faux file object attached to a socket object."""
-
- def write(self, b):
- self._checkClosed()
- if isinstance(b, str):
- raise TypeError("can't write str to binary stream")
-
- with self._write_lock:
- self._write_buf.extend(b)
- self._flush_unlocked()
- return len(b)
-
- def _flush_unlocked(self):
- self._checkClosed("flush of closed file")
- while self._write_buf:
- try:
- # ssl sockets only except 'bytes', not bytearrays
- # so perhaps we should conditionally wrap this for perf?
- n = self.raw.write(bytes(self._write_buf))
- except io.BlockingIOError as e:
- n = e.characters_written
- del self._write_buf[:n]
-
-
-def CP_makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE):
- if 'r' in mode:
- return io.BufferedReader(socket.SocketIO(sock, mode), bufsize)
- else:
- return CP_BufferedWriter(socket.SocketIO(sock, mode), bufsize)
-
-
-class HTTPConnection(object):
-
- """An HTTP connection (active socket).
-
- server: the Server object which received this connection.
- socket: the raw socket object (usually TCP) for this connection.
- makefile: a fileobject class for reading from the socket.
- """
-
- remote_addr = None
- remote_port = None
- ssl_env = None
- rbufsize = DEFAULT_BUFFER_SIZE
- wbufsize = DEFAULT_BUFFER_SIZE
- RequestHandlerClass = HTTPRequest
-
- def __init__(self, server, sock, makefile=CP_makefile):
- self.server = server
- self.socket = sock
- self.rfile = makefile(sock, "rb", self.rbufsize)
- self.wfile = makefile(sock, "wb", self.wbufsize)
- self.requests_seen = 0
-
- def communicate(self):
- """Read each request and respond appropriately."""
- request_seen = False
- try:
- while True:
- # (re)set req to None so that if something goes wrong in
- # the RequestHandlerClass constructor, the error doesn't
- # get written to the previous request.
- req = None
- req = self.RequestHandlerClass(self.server, self)
-
- # This order of operations should guarantee correct pipelining.
- req.parse_request()
- if self.server.stats['Enabled']:
- self.requests_seen += 1
- if not req.ready:
- # Something went wrong in the parsing (and the server has
- # probably already made a simple_response). Return and
- # let the conn close.
- return
-
- request_seen = True
- req.respond()
- if req.close_connection:
- return
- except socket.error:
- e = sys.exc_info()[1]
- errnum = e.args[0]
- # sadly SSL sockets return a different (longer) time out string
- if (
- errnum == 'timed out' or
- errnum == 'The read operation timed out'
- ):
- # Don't error if we're between requests; only error
- # if 1) no request has been started at all, or 2) we're
- # in the middle of a request.
- # See https://github.com/cherrypy/cherrypy/issues/853
- if (not request_seen) or (req and req.started_request):
- # Don't bother writing the 408 if the response
- # has already started being written.
- if req and not req.sent_headers:
- try:
- req.simple_response("408 Request Timeout")
- except FatalSSLAlert:
- # Close the connection.
- return
- elif errnum not in socket_errors_to_ignore:
- self.server.error_log("socket.error %s" % repr(errnum),
- level=logging.WARNING, traceback=True)
- if req and not req.sent_headers:
- try:
- req.simple_response("500 Internal Server Error")
- except FatalSSLAlert:
- # Close the connection.
- return
- return
- except (KeyboardInterrupt, SystemExit):
- raise
- except FatalSSLAlert:
- # Close the connection.
- return
- except NoSSLError:
- if req and not req.sent_headers:
- # Unwrap our wfile
- self.wfile = CP_makefile(
- self.socket._sock, "wb", self.wbufsize)
- req.simple_response(
- "400 Bad Request",
- "The client sent a plain HTTP request, but this server "
- "only speaks HTTPS on this port.")
- self.linger = True
- except Exception:
- e = sys.exc_info()[1]
- self.server.error_log(repr(e), level=logging.ERROR, traceback=True)
- if req and not req.sent_headers:
- try:
- req.simple_response("500 Internal Server Error")
- except FatalSSLAlert:
- # Close the connection.
- return
-
- linger = False
-
- def close(self):
- """Close the socket underlying this connection."""
- self.rfile.close()
-
- if not self.linger:
- # Python's socket module does NOT call close on the kernel
- # socket when you call socket.close(). We do so manually here
- # because we want this server to send a FIN TCP segment
- # immediately. Note this must be called *before* calling
- # socket.close(), because the latter drops its reference to
- # the kernel socket.
- # Python 3 *probably* fixed this with socket._real_close;
- # hard to tell.
-# self.socket._sock.close()
- self.socket.close()
- else:
- # On the other hand, sometimes we want to hang around for a bit
- # to make sure the client has a chance to read our entire
- # response. Skipping the close() calls here delays the FIN
- # packet until the socket object is garbage-collected later.
- # Someday, perhaps, we'll do the full lingering_close that
- # Apache does, but not today.
- pass
-
-
-class TrueyZero(object):
-
- """An object which equals and does math like the integer 0 but evals True.
- """
-
- def __add__(self, other):
- return other
-
- def __radd__(self, other):
- return other
-trueyzero = TrueyZero()
-
-
-_SHUTDOWNREQUEST = None
-
-
-class WorkerThread(threading.Thread):
-
- """Thread which continuously polls a Queue for Connection objects.
-
- Due to the timing issues of polling a Queue, a WorkerThread does not
- check its own 'ready' flag after it has started. To stop the thread,
- it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue
- (one for each running WorkerThread).
- """
-
- conn = None
- """The current connection pulled off the Queue, or None."""
-
- server = None
- """The HTTP Server which spawned this thread, and which owns the
- Queue and is placing active connections into it."""
-
- ready = False
- """A simple flag for the calling server to know when this thread
- has begun polling the Queue."""
-
- def __init__(self, server):
- self.ready = False
- self.server = server
-
- self.requests_seen = 0
- self.bytes_read = 0
- self.bytes_written = 0
- self.start_time = None
- self.work_time = 0
- self.stats = {
- 'Requests': lambda s: self.requests_seen + (
- (self.start_time is None) and
- trueyzero or
- self.conn.requests_seen
- ),
- 'Bytes Read': lambda s: self.bytes_read + (
- (self.start_time is None) and
- trueyzero or
- self.conn.rfile.bytes_read
- ),
- 'Bytes Written': lambda s: self.bytes_written + (
- (self.start_time is None) and
- trueyzero or
- self.conn.wfile.bytes_written
- ),
- 'Work Time': lambda s: self.work_time + (
- (self.start_time is None) and
- trueyzero or
- time.time() - self.start_time
- ),
- 'Read Throughput': lambda s: s['Bytes Read'](s) / (
- s['Work Time'](s) or 1e-6),
- 'Write Throughput': lambda s: s['Bytes Written'](s) / (
- s['Work Time'](s) or 1e-6),
- }
- threading.Thread.__init__(self)
-
- def run(self):
- self.server.stats['Worker Threads'][self.getName()] = self.stats
- try:
- self.ready = True
- while True:
- conn = self.server.requests.get()
- if conn is _SHUTDOWNREQUEST:
- return
-
- self.conn = conn
- if self.server.stats['Enabled']:
- self.start_time = time.time()
- try:
- conn.communicate()
- finally:
- conn.close()
- if self.server.stats['Enabled']:
- self.requests_seen += self.conn.requests_seen
- self.bytes_read += self.conn.rfile.bytes_read
- self.bytes_written += self.conn.wfile.bytes_written
- self.work_time += time.time() - self.start_time
- self.start_time = None
- self.conn = None
- except (KeyboardInterrupt, SystemExit):
- exc = sys.exc_info()[1]
- self.server.interrupt = exc
-
-
-class ThreadPool(object):
-
- """A Request Queue for an HTTPServer which pools threads.
-
- ThreadPool objects must provide min, get(), put(obj), start()
- and stop(timeout) attributes.
- """
-
- def __init__(self, server, min=10, max=-1,
- accepted_queue_size=-1, accepted_queue_timeout=10):
- self.server = server
- self.min = min
- self.max = max
- self._threads = []
- self._queue = queue.Queue(maxsize=accepted_queue_size)
- self._queue_put_timeout = accepted_queue_timeout
- self.get = self._queue.get
-
- def start(self):
- """Start the pool of threads."""
- for i in range(self.min):
- self._threads.append(WorkerThread(self.server))
- for worker in self._threads:
- worker.setName("CP Server " + worker.getName())
- worker.start()
- for worker in self._threads:
- while not worker.ready:
- time.sleep(.1)
-
- def _get_idle(self):
- """Number of worker threads which are idle. Read-only."""
- return len([t for t in self._threads if t.conn is None])
- idle = property(_get_idle, doc=_get_idle.__doc__)
-
- def put(self, obj):
- self._queue.put(obj, block=True, timeout=self._queue_put_timeout)
- if obj is _SHUTDOWNREQUEST:
- return
-
- def grow(self, amount):
- """Spawn new worker threads (not above self.max)."""
- if self.max > 0:
- budget = max(self.max - len(self._threads), 0)
- else:
- # self.max <= 0 indicates no maximum
- budget = float('inf')
-
- n_new = min(amount, budget)
-
- workers = [self._spawn_worker() for i in range(n_new)]
- while not all(worker.ready for worker in workers):
- time.sleep(.1)
- self._threads.extend(workers)
-
- def _spawn_worker(self):
- worker = WorkerThread(self.server)
- worker.setName("CP Server " + worker.getName())
- worker.start()
- return worker
-
- def shrink(self, amount):
- """Kill off worker threads (not below self.min)."""
- # Grow/shrink the pool if necessary.
- # Remove any dead threads from our list
- for t in self._threads:
- if not t.isAlive():
- self._threads.remove(t)
- amount -= 1
-
- # calculate the number of threads above the minimum
- n_extra = max(len(self._threads) - self.min, 0)
-
- # don't remove more than amount
- n_to_remove = min(amount, n_extra)
-
- # put shutdown requests on the queue equal to the number of threads
- # to remove. As each request is processed by a worker, that worker
- # will terminate and be culled from the list.
- for n in range(n_to_remove):
- self._queue.put(_SHUTDOWNREQUEST)
-
- def stop(self, timeout=5):
- # Must shut down threads here so the code that calls
- # this method can know when all threads are stopped.
- for worker in self._threads:
- self._queue.put(_SHUTDOWNREQUEST)
-
- # Don't join currentThread (when stop is called inside a request).
- current = threading.currentThread()
- if timeout and timeout >= 0:
- endtime = time.time() + timeout
- while self._threads:
- worker = self._threads.pop()
- if worker is not current and worker.isAlive():
- try:
- if timeout is None or timeout < 0:
- worker.join()
- else:
- remaining_time = endtime - time.time()
- if remaining_time > 0:
- worker.join(remaining_time)
- if worker.isAlive():
- # We exhausted the timeout.
- # Forcibly shut down the socket.
- c = worker.conn
- if c and not c.rfile.closed:
- try:
- c.socket.shutdown(socket.SHUT_RD)
- except TypeError:
- # pyOpenSSL sockets don't take an arg
- c.socket.shutdown()
- worker.join()
- except (AssertionError,
- # Ignore repeated Ctrl-C.
- # See
- # https://github.com/cherrypy/cherrypy/issues/691.
- KeyboardInterrupt):
- pass
-
- def _get_qsize(self):
- return self._queue.qsize()
- qsize = property(_get_qsize)
-
-
-try:
- import fcntl
-except ImportError:
- try:
- from ctypes import windll, WinError
- import ctypes.wintypes
- _SetHandleInformation = windll.kernel32.SetHandleInformation
- _SetHandleInformation.argtypes = [
- ctypes.wintypes.HANDLE,
- ctypes.wintypes.DWORD,
- ctypes.wintypes.DWORD,
- ]
- _SetHandleInformation.restype = ctypes.wintypes.BOOL
- except ImportError:
- def prevent_socket_inheritance(sock):
- """Dummy function, since neither fcntl nor ctypes are available."""
- pass
- else:
- def prevent_socket_inheritance(sock):
- """Mark the given socket fd as non-inheritable (Windows)."""
- if not _SetHandleInformation(sock.fileno(), 1, 0):
- raise WinError()
-else:
- def prevent_socket_inheritance(sock):
- """Mark the given socket fd as non-inheritable (POSIX)."""
- fd = sock.fileno()
- old_flags = fcntl.fcntl(fd, fcntl.F_GETFD)
- fcntl.fcntl(fd, fcntl.F_SETFD, old_flags | fcntl.FD_CLOEXEC)
-
-
-class SSLAdapter(object):
-
- """Base class for SSL driver library adapters.
-
- Required methods:
-
- * ``wrap(sock) -> (wrapped socket, ssl environ dict)``
- * ``makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE) ->
- socket file object``
- """
-
- def __init__(self, certificate, private_key, certificate_chain=None):
- self.certificate = certificate
- self.private_key = private_key
- self.certificate_chain = certificate_chain
-
- def wrap(self, sock):
- raise NotImplemented
-
- def makefile(self, sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE):
- raise NotImplemented
-
-
-class HTTPServer(object):
-
- """An HTTP server."""
-
- _bind_addr = "127.0.0.1"
- _interrupt = None
-
- gateway = None
- """A Gateway instance."""
-
- minthreads = None
- """The minimum number of worker threads to create (default 10)."""
-
- maxthreads = None
- """The maximum number of worker threads to create (default -1 = no limit).
- """
-
- server_name = None
- """The name of the server; defaults to socket.gethostname()."""
-
- protocol = "HTTP/1.1"
- """The version string to write in the Status-Line of all HTTP responses.
-
- For example, "HTTP/1.1" is the default. This also limits the supported
- features used in the response."""
-
- request_queue_size = 5
- """The 'backlog' arg to socket.listen(); max queued connections
- (default 5).
- """
-
- shutdown_timeout = 5
- """The total time, in seconds, to wait for worker threads to cleanly exit.
- """
-
- timeout = 10
- """The timeout in seconds for accepted connections (default 10)."""
-
- version = "CherryPy/" + cp_version
- """A version string for the HTTPServer."""
-
- software = None
- """The value to set for the SERVER_SOFTWARE entry in the WSGI environ.
-
- If None, this defaults to ``'%s Server' % self.version``."""
-
- ready = False
- """An internal flag which marks whether the socket is accepting
- connections.
- """
-
- max_request_header_size = 0
- """The maximum size, in bytes, for request headers, or 0 for no limit."""
-
- max_request_body_size = 0
- """The maximum size, in bytes, for request bodies, or 0 for no limit."""
-
- nodelay = True
- """If True (the default since 3.1), sets the TCP_NODELAY socket option."""
-
- ConnectionClass = HTTPConnection
- """The class to use for handling HTTP connections."""
-
- ssl_adapter = None
- """An instance of SSLAdapter (or a subclass).
-
- You must have the corresponding SSL driver library installed."""
-
- def __init__(self, bind_addr, gateway, minthreads=10, maxthreads=-1,
- server_name=None):
- self.bind_addr = bind_addr
- self.gateway = gateway
-
- self.requests = ThreadPool(self, min=minthreads or 1, max=maxthreads)
-
- if not server_name:
- server_name = socket.gethostname()
- self.server_name = server_name
- self.clear_stats()
-
- def clear_stats(self):
- self._start_time = None
- self._run_time = 0
- self.stats = {
- 'Enabled': False,
- 'Bind Address': lambda s: repr(self.bind_addr),
- 'Run time': lambda s: (not s['Enabled']) and -1 or self.runtime(),
- 'Accepts': 0,
- 'Accepts/sec': lambda s: s['Accepts'] / self.runtime(),
- 'Queue': lambda s: getattr(self.requests, "qsize", None),
- 'Threads': lambda s: len(getattr(self.requests, "_threads", [])),
- 'Threads Idle': lambda s: getattr(self.requests, "idle", None),
- 'Socket Errors': 0,
- 'Requests': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Requests'](w) for w in s['Worker Threads'].values()], 0),
- 'Bytes Read': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Read'](w) for w in s['Worker Threads'].values()], 0),
- 'Bytes Written': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Written'](w) for w in s['Worker Threads'].values()],
- 0),
- 'Work Time': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Work Time'](w) for w in s['Worker Threads'].values()], 0),
- 'Read Throughput': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Read'](w) / (w['Work Time'](w) or 1e-6)
- for w in s['Worker Threads'].values()], 0),
- 'Write Throughput': lambda s: (not s['Enabled']) and -1 or sum(
- [w['Bytes Written'](w) / (w['Work Time'](w) or 1e-6)
- for w in s['Worker Threads'].values()], 0),
- 'Worker Threads': {},
- }
- logging.statistics["CherryPy HTTPServer %d" % id(self)] = self.stats
-
- def runtime(self):
- if self._start_time is None:
- return self._run_time
- else:
- return self._run_time + (time.time() - self._start_time)
-
- def __str__(self):
- return "%s.%s(%r)" % (self.__module__, self.__class__.__name__,
- self.bind_addr)
-
- def _get_bind_addr(self):
- return self._bind_addr
-
- def _set_bind_addr(self, value):
- if isinstance(value, tuple) and value[0] in ('', None):
- # Despite the socket module docs, using '' does not
- # allow AI_PASSIVE to work. Passing None instead
- # returns '0.0.0.0' like we want. In other words:
- # host AI_PASSIVE result
- # '' Y 192.168.x.y
- # '' N 192.168.x.y
- # None Y 0.0.0.0
- # None N 127.0.0.1
- # But since you can get the same effect with an explicit
- # '0.0.0.0', we deny both the empty string and None as values.
- raise ValueError("Host values of '' or None are not allowed. "
- "Use '0.0.0.0' (IPv4) or '::' (IPv6) instead "
- "to listen on all active interfaces.")
- self._bind_addr = value
- bind_addr = property(
- _get_bind_addr,
- _set_bind_addr,
- doc="""The interface on which to listen for connections.
-
- For TCP sockets, a (host, port) tuple. Host values may be any IPv4
- or IPv6 address, or any valid hostname. The string 'localhost' is a
- synonym for '127.0.0.1' (or '::1', if your hosts file prefers IPv6).
- The string '0.0.0.0' is a special IPv4 entry meaning "any active
- interface" (INADDR_ANY), and '::' is the similar IN6ADDR_ANY for
- IPv6. The empty string or None are not allowed.
-
- For UNIX sockets, supply the filename as a string.""")
-
- def start(self):
- """Run the server forever."""
- # We don't have to trap KeyboardInterrupt or SystemExit here,
- # because cherrpy.server already does so, calling self.stop() for us.
- # If you're using this server with another framework, you should
- # trap those exceptions in whatever code block calls start().
- self._interrupt = None
-
- if self.software is None:
- self.software = "%s Server" % self.version
-
- # Select the appropriate socket
- if isinstance(self.bind_addr, basestring):
- # AF_UNIX socket
-
- # So we can reuse the socket...
- try:
- os.unlink(self.bind_addr)
- except:
- pass
-
- # So everyone can access the socket...
- try:
- os.chmod(self.bind_addr, 0o777)
- except:
- pass
-
- info = [
- (socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)]
- else:
- # AF_INET or AF_INET6 socket
- # Get the correct address family for our host (allows IPv6
- # addresses)
- host, port = self.bind_addr
- try:
- info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
- socket.SOCK_STREAM, 0,
- socket.AI_PASSIVE)
- except socket.gaierror:
- if ':' in self.bind_addr[0]:
- info = [(socket.AF_INET6, socket.SOCK_STREAM,
- 0, "", self.bind_addr + (0, 0))]
- else:
- info = [(socket.AF_INET, socket.SOCK_STREAM,
- 0, "", self.bind_addr)]
-
- self.socket = None
- msg = "No socket could be created"
- for res in info:
- af, socktype, proto, canonname, sa = res
- try:
- self.bind(af, socktype, proto)
- except socket.error as serr:
- msg = "%s -- (%s: %s)" % (msg, sa, serr)
- if self.socket:
- self.socket.close()
- self.socket = None
- continue
- break
- if not self.socket:
- raise socket.error(msg)
-
- # Timeout so KeyboardInterrupt can be caught on Win32
- self.socket.settimeout(1)
- self.socket.listen(self.request_queue_size)
-
- # Create worker threads
- self.requests.start()
-
- self.ready = True
- self._start_time = time.time()
- while self.ready:
- try:
- self.tick()
- except (KeyboardInterrupt, SystemExit):
- raise
- except:
- self.error_log("Error in HTTPServer.tick", level=logging.ERROR,
- traceback=True)
- if self.interrupt:
- while self.interrupt is True:
- # Wait for self.stop() to complete. See _set_interrupt.
- time.sleep(0.1)
- if self.interrupt:
- raise self.interrupt
-
- def error_log(self, msg="", level=20, traceback=False):
- # Override this in subclasses as desired
- sys.stderr.write(msg + '\n')
- sys.stderr.flush()
- if traceback:
- tblines = traceback_.format_exc()
- sys.stderr.write(tblines)
- sys.stderr.flush()
-
- def bind(self, family, type, proto=0):
- """Create (or recreate) the actual socket object."""
- self.socket = socket.socket(family, type, proto)
- prevent_socket_inheritance(self.socket)
- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- if self.nodelay and not isinstance(self.bind_addr, str):
- self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
-
- if self.ssl_adapter is not None:
- self.socket = self.ssl_adapter.bind(self.socket)
-
- # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
- # activate dual-stack. See
- # https://github.com/cherrypy/cherrypy/issues/871.
- if (hasattr(socket, 'AF_INET6') and family == socket.AF_INET6
- and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
- try:
- self.socket.setsockopt(
- socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
- except (AttributeError, socket.error):
- # Apparently, the socket option is not available in
- # this machine's TCP stack
- pass
-
- self.socket.bind(self.bind_addr)
-
- def tick(self):
- """Accept a new connection and put it on the Queue."""
- try:
- s, addr = self.socket.accept()
- if self.stats['Enabled']:
- self.stats['Accepts'] += 1
- if not self.ready:
- return
-
- prevent_socket_inheritance(s)
- if hasattr(s, 'settimeout'):
- s.settimeout(self.timeout)
-
- makefile = CP_makefile
- ssl_env = {}
- # if ssl cert and key are set, we try to be a secure HTTP server
- if self.ssl_adapter is not None:
- try:
- s, ssl_env = self.ssl_adapter.wrap(s)
- except NoSSLError:
- msg = ("The client sent a plain HTTP request, but "
- "this server only speaks HTTPS on this port.")
- buf = ["%s 400 Bad Request\r\n" % self.protocol,
- "Content-Length: %s\r\n" % len(msg),
- "Content-Type: text/plain\r\n\r\n",
- msg]
-
- wfile = makefile(s, "wb", DEFAULT_BUFFER_SIZE)
- try:
- wfile.write("".join(buf).encode('ISO-8859-1'))
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- raise
- return
- if not s:
- return
- makefile = self.ssl_adapter.makefile
- # Re-apply our timeout since we may have a new socket object
- if hasattr(s, 'settimeout'):
- s.settimeout(self.timeout)
-
- conn = self.ConnectionClass(self, s, makefile)
-
- if not isinstance(self.bind_addr, basestring):
- # optional values
- # Until we do DNS lookups, omit REMOTE_HOST
- if addr is None: # sometimes this can happen
- # figure out if AF_INET or AF_INET6.
- if len(s.getsockname()) == 2:
- # AF_INET
- addr = ('0.0.0.0', 0)
- else:
- # AF_INET6
- addr = ('::', 0)
- conn.remote_addr = addr[0]
- conn.remote_port = addr[1]
-
- conn.ssl_env = ssl_env
-
- try:
- self.requests.put(conn)
- except queue.Full:
- # Just drop the conn. TODO: write 503 back?
- conn.close()
- return
- except socket.timeout:
- # The only reason for the timeout in start() is so we can
- # notice keyboard interrupts on Win32, which don't interrupt
- # accept() by default
- return
- except socket.error:
- x = sys.exc_info()[1]
- if self.stats['Enabled']:
- self.stats['Socket Errors'] += 1
- if x.args[0] in socket_error_eintr:
- # I *think* this is right. EINTR should occur when a signal
- # is received during the accept() call; all docs say retry
- # the call, and I *think* I'm reading it right that Python
- # will then go ahead and poll for and handle the signal
- # elsewhere. See
- # https://github.com/cherrypy/cherrypy/issues/707.
- return
- if x.args[0] in socket_errors_nonblocking:
- # Just try again. See
- # https://github.com/cherrypy/cherrypy/issues/479.
- return
- if x.args[0] in socket_errors_to_ignore:
- # Our socket was closed.
- # See https://github.com/cherrypy/cherrypy/issues/686.
- return
- raise
-
- def _get_interrupt(self):
- return self._interrupt
-
- def _set_interrupt(self, interrupt):
- self._interrupt = True
- self.stop()
- self._interrupt = interrupt
- interrupt = property(_get_interrupt, _set_interrupt,
- doc="Set this to an Exception instance to "
- "interrupt the server.")
-
- def stop(self):
- """Gracefully shutdown a server that is serving forever."""
- self.ready = False
- if self._start_time is not None:
- self._run_time += (time.time() - self._start_time)
- self._start_time = None
-
- sock = getattr(self, "socket", None)
- if sock:
- if not isinstance(self.bind_addr, basestring):
- # Touch our own socket to make accept() return immediately.
- try:
- host, port = sock.getsockname()[:2]
- except socket.error:
- x = sys.exc_info()[1]
- if x.args[0] not in socket_errors_to_ignore:
- # Changed to use error code and not message
- # See
- # https://github.com/cherrypy/cherrypy/issues/860.
- raise
- else:
- # Note that we're explicitly NOT using AI_PASSIVE,
- # here, because we want an actual IP to touch.
- # localhost won't work if we've bound to a public IP,
- # but it will if we bound to '0.0.0.0' (INADDR_ANY).
- for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
- socket.SOCK_STREAM):
- af, socktype, proto, canonname, sa = res
- s = None
- try:
- s = socket.socket(af, socktype, proto)
- # See
- # http://groups.google.com/group/cherrypy-users/
- # browse_frm/thread/bbfe5eb39c904fe0
- s.settimeout(1.0)
- s.connect((host, port))
- s.close()
- except socket.error:
- if s:
- s.close()
- if hasattr(sock, "close"):
- sock.close()
- self.socket = None
-
- self.requests.stop(self.shutdown_timeout)
-
-
-class Gateway(object):
-
- """A base class to interface HTTPServer with other systems, such as WSGI.
- """
-
- def __init__(self, req):
- self.req = req
-
- def respond(self):
- """Process the current request. Must be overridden in a subclass."""
- raise NotImplemented
-
-
-# These may either be wsgiserver.SSLAdapter subclasses or the string names
-# of such classes (in which case they will be lazily loaded).
-ssl_adapters = {
- 'builtin': 'cherrypy.wsgiserver.ssl_builtin.BuiltinSSLAdapter',
- 'pyopenssl': 'cherrypy.wsgiserver.ssl_pyopenssl.pyOpenSSLAdapter',
-}
-
-
-def get_ssl_adapter_class(name='builtin'):
- """Return an SSL adapter class for the given name."""
- adapter = ssl_adapters[name.lower()]
- if isinstance(adapter, basestring):
- last_dot = adapter.rfind(".")
- attr_name = adapter[last_dot + 1:]
- mod_path = adapter[:last_dot]
-
- try:
- mod = sys.modules[mod_path]
- if mod is None:
- raise KeyError()
- except KeyError:
- # The last [''] is important.
- mod = __import__(mod_path, globals(), locals(), [''])
-
- # Let an AttributeError propagate outward.
- try:
- adapter = getattr(mod, attr_name)
- except AttributeError:
- raise AttributeError("'%s' object has no attribute '%s'"
- % (mod_path, attr_name))
-
- return adapter
-
-# ------------------------------- WSGI Stuff -------------------------------- #
-
-
-class CherryPyWSGIServer(HTTPServer):
-
- """A subclass of HTTPServer which calls a WSGI application."""
-
- wsgi_version = (1, 0)
- """The version of WSGI to produce."""
-
- def __init__(self, bind_addr, wsgi_app, numthreads=10, server_name=None,
- max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5,
- accepted_queue_size=-1, accepted_queue_timeout=10):
- self.requests = ThreadPool(self, min=numthreads or 1, max=max,
- accepted_queue_size=accepted_queue_size,
- accepted_queue_timeout=accepted_queue_timeout)
- self.wsgi_app = wsgi_app
- self.gateway = wsgi_gateways[self.wsgi_version]
-
- self.bind_addr = bind_addr
- if not server_name:
- server_name = socket.gethostname()
- self.server_name = server_name
- self.request_queue_size = request_queue_size
-
- self.timeout = timeout
- self.shutdown_timeout = shutdown_timeout
- self.clear_stats()
-
- def _get_numthreads(self):
- return self.requests.min
-
- def _set_numthreads(self, value):
- self.requests.min = value
- numthreads = property(_get_numthreads, _set_numthreads)
-
-
-class WSGIGateway(Gateway):
-
- """A base class to interface HTTPServer with WSGI."""
-
- def __init__(self, req):
- self.req = req
- self.started_response = False
- self.env = self.get_environ()
- self.remaining_bytes_out = None
-
- def get_environ(self):
- """Return a new environ dict targeting the given wsgi.version"""
- raise NotImplemented
-
- def respond(self):
- """Process the current request."""
- response = self.req.server.wsgi_app(self.env, self.start_response)
- try:
- for chunk in response:
- # "The start_response callable must not actually transmit
- # the response headers. Instead, it must store them for the
- # server or gateway to transmit only after the first
- # iteration of the application return value that yields
- # a NON-EMPTY string, or upon the application's first
- # invocation of the write() callable." (PEP 333)
- if chunk:
- if isinstance(chunk, unicodestr):
- chunk = chunk.encode('ISO-8859-1')
- self.write(chunk)
- finally:
- if hasattr(response, "close"):
- response.close()
-
- def start_response(self, status, headers, exc_info=None):
- """WSGI callable to begin the HTTP response."""
- # "The application may call start_response more than once,
- # if and only if the exc_info argument is provided."
- if self.started_response and not exc_info:
- raise AssertionError("WSGI start_response called a second "
- "time with no exc_info.")
- self.started_response = True
-
- # "if exc_info is provided, and the HTTP headers have already been
- # sent, start_response must raise an error, and should raise the
- # exc_info tuple."
- if self.req.sent_headers:
- try:
- raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
- finally:
- exc_info = None
-
- # According to PEP 3333, when using Python 3, the response status
- # and headers must be bytes masquerading as unicode; that is, they
- # must be of type "str" but are restricted to code points in the
- # "latin-1" set.
- if not isinstance(status, str):
- raise TypeError("WSGI response status is not of type str.")
- self.req.status = status.encode('ISO-8859-1')
-
- for k, v in headers:
- if not isinstance(k, str):
- raise TypeError(
- "WSGI response header key %r is not of type str." % k)
- if not isinstance(v, str):
- raise TypeError(
- "WSGI response header value %r is not of type str." % v)
- if k.lower() == 'content-length':
- self.remaining_bytes_out = int(v)
- self.req.outheaders.append(
- (k.encode('ISO-8859-1'), v.encode('ISO-8859-1')))
-
- return self.write
-
- def write(self, chunk):
- """WSGI callable to write unbuffered data to the client.
-
- This method is also used internally by start_response (to write
- data from the iterable returned by the WSGI application).
- """
- if not self.started_response:
- raise AssertionError("WSGI write called before start_response.")
-
- chunklen = len(chunk)
- rbo = self.remaining_bytes_out
- if rbo is not None and chunklen > rbo:
- if not self.req.sent_headers:
- # Whew. We can send a 500 to the client.
- self.req.simple_response("500 Internal Server Error",
- "The requested resource returned "
- "more bytes than the declared "
- "Content-Length.")
- else:
- # Dang. We have probably already sent data. Truncate the chunk
- # to fit (so the client doesn't hang) and raise an error later.
- chunk = chunk[:rbo]
-
- if not self.req.sent_headers:
- self.req.sent_headers = True
- self.req.send_headers()
-
- self.req.write(chunk)
-
- if rbo is not None:
- rbo -= chunklen
- if rbo < 0:
- raise ValueError(
- "Response body exceeds the declared Content-Length.")
-
-
-class WSGIGateway_10(WSGIGateway):
-
- """A Gateway class to interface HTTPServer with WSGI 1.0.x."""
-
- def get_environ(self):
- """Return a new environ dict targeting the given wsgi.version"""
- req = self.req
- env = {
- # set a non-standard environ entry so the WSGI app can know what
- # the *real* server protocol is (and what features to support).
- # See http://www.faqs.org/rfcs/rfc2145.html.
- 'ACTUAL_SERVER_PROTOCOL': req.server.protocol,
- 'PATH_INFO': req.path.decode('ISO-8859-1'),
- 'QUERY_STRING': req.qs.decode('ISO-8859-1'),
- 'REMOTE_ADDR': req.conn.remote_addr or '',
- 'REMOTE_PORT': str(req.conn.remote_port or ''),
- 'REQUEST_METHOD': req.method.decode('ISO-8859-1'),
- 'REQUEST_URI': req.uri.decode('ISO-8859-1'),
- 'SCRIPT_NAME': '',
- 'SERVER_NAME': req.server.server_name,
- # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol.
- 'SERVER_PROTOCOL': req.request_protocol.decode('ISO-8859-1'),
- 'SERVER_SOFTWARE': req.server.software,
- 'wsgi.errors': sys.stderr,
- 'wsgi.input': req.rfile,
- 'wsgi.multiprocess': False,
- 'wsgi.multithread': True,
- 'wsgi.run_once': False,
- 'wsgi.url_scheme': req.scheme.decode('ISO-8859-1'),
- 'wsgi.version': (1, 0),
- }
- if isinstance(req.server.bind_addr, basestring):
- # AF_UNIX. This isn't really allowed by WSGI, which doesn't
- # address unix domain sockets. But it's better than nothing.
- env["SERVER_PORT"] = ""
- else:
- env["SERVER_PORT"] = str(req.server.bind_addr[1])
-
- # Request headers
- for k, v in req.inheaders.items():
- k = k.decode('ISO-8859-1').upper().replace("-", "_")
- env["HTTP_" + k] = v.decode('ISO-8859-1')
-
- # CONTENT_TYPE/CONTENT_LENGTH
- ct = env.pop("HTTP_CONTENT_TYPE", None)
- if ct is not None:
- env["CONTENT_TYPE"] = ct
- cl = env.pop("HTTP_CONTENT_LENGTH", None)
- if cl is not None:
- env["CONTENT_LENGTH"] = cl
-
- if req.conn.ssl_env:
- env.update(req.conn.ssl_env)
-
- return env
-
-
-class WSGIGateway_u0(WSGIGateway_10):
-
- """A Gateway class to interface HTTPServer with WSGI u.0.
-
- WSGI u.0 is an experimental protocol, which uses unicode for keys
- and values in both Python 2 and Python 3.
- """
-
- def get_environ(self):
- """Return a new environ dict targeting the given wsgi.version"""
- req = self.req
- env_10 = WSGIGateway_10.get_environ(self)
- env = env_10.copy()
- env['wsgi.version'] = ('u', 0)
-
- # Request-URI
- env.setdefault('wsgi.url_encoding', 'utf-8')
- try:
- # SCRIPT_NAME is the empty string, who cares what encoding it is?
- env["PATH_INFO"] = req.path.decode(env['wsgi.url_encoding'])
- env["QUERY_STRING"] = req.qs.decode(env['wsgi.url_encoding'])
- except UnicodeDecodeError:
- # Fall back to latin 1 so apps can transcode if needed.
- env['wsgi.url_encoding'] = 'ISO-8859-1'
- env["PATH_INFO"] = env_10["PATH_INFO"]
- env["QUERY_STRING"] = env_10["QUERY_STRING"]
-
- return env
-
-wsgi_gateways = {
- (1, 0): WSGIGateway_10,
- ('u', 0): WSGIGateway_u0,
-}
-
-
-class WSGIPathInfoDispatcher(object):
-
- """A WSGI dispatcher for dispatch based on the PATH_INFO.
-
- apps: a dict or list of (path_prefix, app) pairs.
- """
-
- def __init__(self, apps):
- try:
- apps = list(apps.items())
- except AttributeError:
- pass
-
- # Sort the apps by len(path), descending
- apps.sort()
- apps.reverse()
-
- # The path_prefix strings must start, but not end, with a slash.
- # Use "" instead of "/".
- self.apps = [(p.rstrip("/"), a) for p, a in apps]
-
- def __call__(self, environ, start_response):
- path = environ["PATH_INFO"] or "/"
- for p, app in self.apps:
- # The apps list should be sorted by length, descending.
- if path.startswith(p + "/") or path == p:
- environ = environ.copy()
- environ["SCRIPT_NAME"] = environ["SCRIPT_NAME"] + p
- environ["PATH_INFO"] = path[len(p):]
- return app(environ, start_response)
-
- start_response('404 Not Found', [('Content-Type', 'text/plain'),
- ('Content-Length', '0')])
- return ['']
diff --git a/docs/.gitignore b/docs/.gitignore
new file mode 100644
index 00000000..796b96d1
--- /dev/null
+++ b/docs/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/docs/_static/bgsides.png b/docs/_static/bgsides.png
index 27c305fa..5e224435 100644
--- a/docs/_static/bgsides.png
+++ b/docs/_static/bgsides.png
Binary files differ
diff --git a/docs/_static/cpdocmain.css b/docs/_static/cpdocmain.css
index 4414d472..e2c6ab11 100644
--- a/docs/_static/cpdocmain.css
+++ b/docs/_static/cpdocmain.css
@@ -231,4 +231,4 @@ table.docutils td {
div.sphinxsidebarwrapper {
padding: 10px 5px 0 25px;
-} \ No newline at end of file
+}
diff --git a/docs/_static/images/cherrypy_logo_big.png b/docs/_static/images/cherrypy_logo_big.png
new file mode 100644
index 00000000..aba0020e
--- /dev/null
+++ b/docs/_static/images/cherrypy_logo_big.png
Binary files differ
diff --git a/docs/_static/images/cpreturn.gif b/docs/_static/images/cpreturn.gif
index 074ea3cd..bd30508f 100644
--- a/docs/_static/images/cpreturn.gif
+++ b/docs/_static/images/cpreturn.gif
Binary files differ
diff --git a/docs/_static/images/cpyield.gif b/docs/_static/images/cpyield.gif
index e07c50aa..b1257ff6 100644
--- a/docs/_static/images/cpyield.gif
+++ b/docs/_static/images/cpyield.gif
Binary files differ
diff --git a/docs/_static/images/sushibelt.JPG b/docs/_static/images/sushibelt.JPG
index 8f379b73..a8fb896e 100644
--- a/docs/_static/images/sushibelt.JPG
+++ b/docs/_static/images/sushibelt.JPG
Binary files differ
diff --git a/docs/_templates/python_2_eol.html b/docs/_templates/python_2_eol.html
new file mode 100644
index 00000000..21ae4333
--- /dev/null
+++ b/docs/_templates/python_2_eol.html
@@ -0,0 +1,49 @@
+<!-- Based on https://github.com/kennethreitz/python-guide/commit/7a58e5c03ab1a21f07367937454c966505ca8af7 -->
+<aside id="python27eol">
+ <a href="https://pythonclock.org/" target="_blank" title="Python 2.7 EOL Countdown">
+ Python 3, the new best practice, is here to stay.
+ Python 2 will retire in only <time></time>!
+ </a>
+</aside>
+
+<!-- Python 2 EOL Clock -->
+<style type="text/css">
+ body {
+ margin-top: 4em;
+ }
+
+ #python27eol {
+ position: fixed;
+ top: 0;
+ left: 0; right: 0;
+ height: auto;
+ text-align: center;
+ color: white;
+ background-color: black;
+ font-size: larger;
+ line-height: 3;
+ }
+
+ #python27eol>* {
+ color: white;
+ background-color: black;
+ }
+
+ #python27eol>a {
+ display: block;
+ }
+</style>
+
+<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
+<script src="//cdnjs.cloudflare.com/ajax/libs/countdown/2.6.0/countdown.min.js"></script>
+<script src="//cdn.rawgit.com/icambron/moment-countdown/master/dist/moment-countdown.min.js"></script>
+
+<script>
+ var py2_death = moment('2020-04-12').toDate()
+
+ countdown(py2_death, update_time_left)
+
+ function update_time_left(moments_left, timer_id) {
+ document.querySelector('#python27eol time').innerHTML = moments_left.toHTML("em")
+ }
+</script>
diff --git a/docs/advanced.rst b/docs/advanced.rst
index 731fa1bb..3def3437 100644
--- a/docs/advanced.rst
+++ b/docs/advanced.rst
@@ -14,7 +14,7 @@ will describe.
Set aliases to page handlers
############################
-A fairly unknown, yet useful, feature provided by the :func:`cherrypy.expose`
+A fairly unknown, yet useful, feature provided by the :func:`cherrypy.expose`
decorator is to support aliases.
Let's use the template provided by :ref:`tutorial 03 <tut03>`:
@@ -23,14 +23,14 @@ Let's use the template provided by :ref:`tutorial 03 <tut03>`:
import random
import string
-
+
import cherrypy
class StringGenerator(object):
@cherrypy.expose(['generer', 'generar'])
def generate(self, length=8):
return ''.join(random.sample(string.hexdigits, int(length)))
-
+
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())
@@ -42,14 +42,14 @@ accessible via:
- /generer (French)
- /generar (Spanish)
-Obviously, your aliases may be whatever suits your needs.
+Obviously, your aliases may be whatever suits your needs.
.. note::
The alias may be a single string or a list of them.
.. _restful:
-
+
RESTful-style dispatching
#########################
@@ -59,25 +59,25 @@ that nicely map to the entities an application exposes.
.. important::
We will not enter the debate around what is restful or not but we will
- showcase two mechanisms to implement the usual idea in your
+ showcase two mechanisms to implement the usual idea in your
CherryPy application.
Let's assume you wish to create an application that exposes
music bands and their records. Your application will probably have
the following URLs:
-- http://hostname/<bandname>/
-- http://hostname/<bandname>/albums/<recordname>/
+- http://hostname/<artist>/
+- http://hostname/<artist>/albums/<album_title>/
It's quite clear you would not create a page handler named after
every possible band in the world. This means you will need a page handler
that acts as a proxy for all of them.
The default dispatcher cannot deal with that scenario on its own
-because it expects page handlers to be explicitely declared in your
+because it expects page handlers to be explicitly declared in your
source code. Luckily, CherryPy provides ways to support those use cases.
-.. seealso::
+.. seealso::
This section extends from this `stackoverflow response <http://stackoverflow.com/a/15789415/1363905>`_.
@@ -85,8 +85,8 @@ The special _cp_dispatch method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``_cp_dispatch`` is a special method you declare in any of your :term:`controller`
-to massage the remaining segments before CherryPy gets to process them.
-This offers you the capacity to remove, add or otherwise handle any segment
+to massage the remaining segments before CherryPy gets to process them.
+This offers you the capacity to remove, add or otherwise handle any segment
you wish and, even, entirely change the remaining parts.
.. code-block:: python
@@ -126,7 +126,7 @@ Notice how the controller defines `_cp_dispatch`, it takes
a single argument, the URL path info broken into its segments.
The method can inspect and manipulate the list of segments,
-removing any or adding new segments at any position. The new list of
+removing any or adding new segments at any position. The new list of
segments is then sent to the dispatcher which will use it
to locate the appropriate resource.
@@ -146,7 +146,7 @@ In this case, we take the dynamic segments in the URL (band and record names),
we inject them into the request parameters and we remove them
from the segment lists as if they had never been there in the first place.
-In other words, `_cp_dispatch` makes it as if we were
+In other words, `_cp_dispatch` makes it as if we were
working on the following URLs:
- http://localhost:8080/?artist=nirvana
@@ -155,29 +155,30 @@ working on the following URLs:
The popargs decorator
^^^^^^^^^^^^^^^^^^^^^
-:func:`cherrypy.popargs` is more straightforward as it gives a name to any segment
-that CherryPy wouldn't be able to interpret otherwise. This makes the
-matching of segments with page handler signatures easier and helps CherryPy
+
+:func:`cherrypy.popargs` is more straightforward as it gives a name to any segment
+that CherryPy wouldn't be able to interpret otherwise. This makes the
+matching of segments with page handler signatures easier and helps CherryPy
understand the structure of your URL.
.. code-block:: python
import cherrypy
- @cherrypy.popargs('name')
+ @cherrypy.popargs('band_name')
class Band(object):
def __init__(self):
self.albums = Album()
@cherrypy.expose
- def index(self, name):
- return 'About %s...' % name
+ def index(self, band_name):
+ return 'About %s...' % band_name
- @cherrypy.popargs('title')
+ @cherrypy.popargs('album_title')
class Album(object):
@cherrypy.expose
- def index(self, name, title):
- return 'About %s by %s...' % (title, name)
+ def index(self, band_name, album_title):
+ return 'About %s by %s...' % (album_title, band_name)
if __name__ == '__main__':
cherrypy.quickstart(Band())
@@ -185,24 +186,24 @@ understand the structure of your URL.
This works similarly to `_cp_dispatch` but, as said above, is more
explicit and localized. It says:
-- take the first segment and store it into a parameter name `band`
-- take again the first segment (since we removed the previous first)
- and store it into a parameter named `title`
+- take the first segment and store it into a parameter named `band_name`
+- take again the first segment (since we removed the previous first)
+ and store it into a parameter named `album_title`
Note that the decorator accepts more than a single binding. For instance:
.. code-block:: python
- @cherrypy.popargs('title')
+ @cherrypy.popargs('album_title')
class Album(object):
- def __init__(self):
- self.tracks = Track()
+ def __init__(self):
+ self.tracks = Track()
- @cherrypy.popargs('num', 'track')
+ @cherrypy.popargs('track_num', 'track_title')
class Track(object):
@cherrypy.expose
- def index(self, name, title, num, track):
- ...
+ def index(self, band_name, album_title, track_num, track_title):
+ ...
This would handle the following URL:
@@ -211,6 +212,34 @@ This would handle the following URL:
Notice finally how the whole stack of segments is passed to each
page handler so that you have the full context.
+Error handling
+##############
+CherryPy's ``HTTPError`` class supports raising immediate responses in the case of
+errors.
+
+.. code-block:: python
+
+ class Root:
+ @cherrypy.expose
+ def thing(self, path):
+ if not authorized():
+ raise cherrypy.HTTPError(401, 'Unauthorized')
+ try:
+ file = open(path)
+ except FileNotFoundError:
+ raise cherrypy.HTTPError(404)
+
+``HTTPError.handle`` is a context manager which supports translating exceptions
+raised in the app into an appropriate HTTP response, as in the second example.
+
+.. code-block:: python
+
+ class Root:
+ @cherrypy.expose
+ def thing(self, path):
+ with cherrypy.HTTPError.handle(FileNotFoundError, 404):
+ file = open(path)
+
Streaming the response body
###########################
@@ -296,55 +325,12 @@ the client. Because of the issues outlined above, **it is usually better to
flatten (buffer) content rather than stream content**. Do otherwise only when
the benefits of streaming outweigh the risks.
-Response timeouts
-#################
+Response timing
+###############
-CherryPy responses include 3 attributes related to time:
+CherryPy responses include an attribute:
* ``response.time``: the :func:`time.time` at which the response began
- * ``response.timeout``: the number of seconds to allow responses to run
- * ``response.timed_out``: a boolean indicating whether the response has
- timed out (default False).
-
-The request processing logic inspects the value of ``response.timed_out`` at
-various stages; if it is ever True, then :class:`TimeoutError` is raised.
-You are free to do the same within your own code.
-
-Rather than calculate the difference by hand, you can call
-``response.check_timeout`` to set ``timed_out`` for you.
-
-.. note::
-
- The default response timeout is 300 seconds.
-
-.. _timeoutmonitor:
-
-Timeout Monitor
-^^^^^^^^^^^^^^^
-
-In addition, CherryPy includes a ``cherrypy.engine.timeout_monitor`` which
-monitors all active requests in a separate thread; periodically, it calls
-``check_timeout`` on them all. It is subscribed by default. To turn it off:
-
-.. code-block:: ini
-
- [global]
- engine.timeout_monitor.on: False
-
-or:
-
-.. code-block:: python
-
- cherrypy.engine.timeout_monitor.unsubscribe()
-
-You can also change the interval (in seconds) at which the timeout monitor runs:
-
-.. code-block:: ini
-
- [global]
- engine.timeout_monitor.frequency: 60 * 60
-
-The default is once per minute. The above example changes that to once per hour.
Deal with signals
#################
@@ -373,9 +359,10 @@ Windows Console Events
^^^^^^^^^^^^^^^^^^^^^^
Microsoft Windows uses console events to communicate some signals, like Ctrl-C.
-When deploying CherryPy on Windows platforms, you should obtain the
-`Python for Windows Extensions <http://sourceforge.net/projects/pywin32/>`_;
-once you have them installed, CherryPy will handle Ctrl-C and other
+Deploying CherryPy on Windows platforms requires `Python for Windows Extensions
+<http://sourceforge.net/projects/pywin32/>`_, which are installed automatically,
+being provided an extra dependency with environment marker. With that
+installed, CherryPy will handle Ctrl-C and other
console events (CTRL_C_EVENT, CTRL_LOGOFF_EVENT, CTRL_BREAK_EVENT,
CTRL_SHUTDOWN_EVENT, and CTRL_CLOSE_EVENT) automatically, shutting down the
bus in preparation for process exit.
@@ -404,23 +391,22 @@ There are several settings that can be enabled to make CherryPy pages more secur
#. Enable XSS Protection
#. Set the Content Security Policy
-An easy way to accomplish this is to set headers with a tool
+An easy way to accomplish this is to set headers with a tool
and wrap your entire CherryPy application with it:
.. code-block:: python
-
+
import cherrypy
+ # set the priority according to your needs if you are hooking something
+ # else on the 'before_finalize' hook point.
+ @cherrypy.tools.register('before_finalize', priority=60)
def secureheaders():
headers = cherrypy.response.headers
headers['X-Frame-Options'] = 'DENY'
headers['X-XSS-Protection'] = '1; mode=block'
headers['Content-Security-Policy'] = "default-src='self'"
- # set the priority according to your needs if you are hooking something
- # else on the 'before_finalize' hook point.
- cherrypy.tools.secureheaders = cherrypy.Tool('before_finalize', secureheaders, priority=60)
-
.. note::
Read more about `those headers <https://www.owasp.org/index.php/List_of_useful_HTTP_headers>`_.
@@ -454,7 +440,7 @@ If you use SSL you can also enable Strict Transport Security:
# conveyed over non-secure transport"
# http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-7.2
if (cherrypy.server.ssl_certificate != None and cherrypy.server.ssl_private_key != None):
- headers['Strict-Transport-Security'] = 'max-age=31536000' # one year
+ headers['Strict-Transport-Security'] = 'max-age=31536000' # one year
Next, you should probably use :ref:`SSL <ssl>`.
@@ -473,7 +459,7 @@ on more than a single port. This is easily achieved:
server.subscribe()
You can create as many :class:`server <cherrypy._cpserver.Server>`
-server instances as you need, once :ref:`subscribed <busplugins>`,
+server instances as you need, once :ref:`subscribed <busplugins>`,
they will follow the CherryPy engine's life-cycle.
WSGI support
@@ -519,7 +505,7 @@ facility.
.. important::
You cannot use tools with a foreign WSGI application.
- However, you can still benefit from the
+ However, you can still benefit from the
:ref:`CherryPy bus <buspattern>`.
@@ -535,7 +521,7 @@ a slight performance increase.
.. code-block:: python
import cherrypy
-
+
class Root(object):
@cherrypy.expose
def index(self):
@@ -549,14 +535,14 @@ a slight performance increase.
.. important::
- Using the native server, you will not be able to
+ Using the native server, you will not be able to
graft a WSGI application as shown in the previous section.
Doing so will result in a server error at runtime.
WebSocket support
#################
-`WebSocket <http://tools.ietf.org/html/rfc6455>`_
+`WebSocket <http://tools.ietf.org/html/rfc6455>`_
is a recent application protocol that came to life
from the HTML5 working-group in response to the needs for
bi-directional communication. Various hacks had been proposed
@@ -569,7 +555,7 @@ Instead, both connected endpoints may use the socket
to push data to the other end.
CherryPy itself does not support WebSocket, but the feature
-is provided by an external library called
+is provided by an external library called
`ws4py <https://github.com/Lawouach/WebSocket-for-Python>`_.
Database support
@@ -579,11 +565,11 @@ CherryPy does not bundle any database access but its architecture
makes it easy to integrate common database interfaces such as
the DB-API specified in :pep:`249`. Alternatively, you can also
use an `ORM <en.wikipedia.org/wiki/Object-relational_mapping>`_
-such as `SQLAlchemy <http://sqlalchemy.readthedocs.org>`_
+such as `SQLAlchemy <http://sqlalchemy.readthedocs.org>`_
or `SQLObject <https://pypi.python.org/pypi/SQLObject/>`_.
You will find `here <https://bitbucket.org/Lawouach/cherrypy-recipes/src/tip/web/database/sql_alchemy/>`_
-a recipe on how integrating SQLAlchemy using a mix of
+a recipe on how integrating SQLAlchemy using a mix of
:ref:`plugins <busplugins>` and :ref:`tools <tools>`.
HTML Templating support
@@ -601,8 +587,8 @@ Testing your application
########################
Web applications, like any other kind of code, must be tested. CherryPy provides
-a :class:`helper class <cherrypy.test.helper.CPWebCase>` to ease writing
-functional tests.
+a :class:`helper class <cherrypy.test.helper.CPWebCase>` to ease writing
+functional tests.
Here is a simple example for a basic echo application:
@@ -642,10 +628,10 @@ Here is a simple example for a basic echo application:
)
self.assertStatus('404 Not Found')
-As you can see the, test inherits from that helper class. You should
+As you can see the, test inherits from that helper class. You should
setup your application and mount it as per-usual. Then, define your various
tests and call the helper :meth:`~cherrypy.test.helper.CPWebCase.getPage`
-method to perform a request. Simply use the various specialized
+method to perform a request. Simply use the various specialized
assert* methods to validate your workflow and data.
You can then run the test using `py.test <http://pytest.org/latest/>`_ as follows:
@@ -658,9 +644,9 @@ The ``-s`` is necessary because the CherryPy class also wraps stdin and stdout.
.. note::
- Although they are written using the typical pattern the
- :mod:`unittest` module supports, they are not bare unit tests.
- Indeed, a whole CherryPy stack is started for you and runs your application.
+ Although they are written using the typical pattern the
+ :mod:`unittest` module supports, they are not bare unit tests.
+ Indeed, a whole CherryPy stack is started for you and runs your application.
If you want to really unit test your CherryPy application, meaning without
- having to start a server, you may want to have a look at
+ having to start a server, you may want to have a look at
this `recipe <https://bitbucket.org/Lawouach/cherrypy-recipes/src/tip/testing/unit/serverless/>`_.
diff --git a/docs/basics.rst b/docs/basics.rst
index b1896f22..1d2ff290 100644
--- a/docs/basics.rst
+++ b/docs/basics.rst
@@ -177,7 +177,7 @@ You can also log an exception:
try:
...
- except:
+ except Exception:
cherrypy.log("kaboom!", traceback=True)
Both logs are writing to files identified by the following keys
@@ -307,7 +307,7 @@ example on setting it up.
cherrypy.config.update({'log.screen': False,
'log.access_file': '',
'log.error_file': ''})
- cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files)
+ cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files)
logging.config.dictConfig(LOG_CONF)
cherrypy.quickstart(Root())
@@ -568,8 +568,8 @@ the given directory.
[/]
tools.sessions.on: True
- tools.sessions.storage_type = "file"
- tools.sessions.storage_path = "/some/directorys"
+ tools.sessions.storage_class = cherrypy.lib.sessions.FileSession
+ tools.sessions.storage_path = "/some/directory"
Memcached backend
^^^^^^^^^^^^^^^^^
@@ -578,14 +578,26 @@ Memcached backend
it is distributed and a good choice if you want to
share sessions outside of the process running CherryPy.
+Requires that the Python
+`memcached <https://pypi.org/project/memcached>`_
+package is installed, which may be indicated by installing
+``cherrypy[memcached_session]``.
+
.. code-block:: ini
[/]
tools.sessions.on: True
- tools.sessions.storage_type = "memcached"
+ tools.sessions.storage_class = cherrypy.lib.sessions.MemcachedSession
.. _staticontent:
+Other backends
+^^^^^^^^^^^^^^
+
+Any other library may implement a session backend. Simply subclass
+``cherrypy.lib.sessions.Session`` and indicate that subclass as
+``tools.sessions.storage_class``.
+
Static content serving
######################
@@ -654,7 +666,7 @@ CherryPy will automatically respond to URLs such as
Specifying an index file
^^^^^^^^^^^^^^^^^^^^^^^^^
-By default, CherryPy will repsond to the root of a static
+By default, CherryPy will respond to the root of a static
directory with an 404 error indicating the path '/' was not found.
To specify an index file, you can use the following:
diff --git a/docs/conf.py b/docs/conf.py
index 77e53587..c3e83ce4 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,3 +1,4 @@
+"""CherryPy sphinx doc configuration module."""
# -*- coding: utf-8 -*-
#
# CherryPy documentation build configuration file, created by
@@ -12,14 +13,22 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
+import importlib
+import pkg_resources
import sys
-import os
-try:
- import sphinx_rtd_theme
- WITH_RTD_THEME = True
-except ImportError:
- WITH_RTD_THEME = False
+assert sys.version_info > (3,), 'Python 3 required to build docs'
+
+
+def try_import(mod_name):
+ """Attempt importing module and suppress failure of doing this."""
+ try:
+ return importlib.import_module(mod_name)
+ except ImportError:
+ pass
+
+
+custom_sphinx_theme = try_import('alabaster')
# 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
@@ -30,9 +39,19 @@ except ImportError:
# 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.todo', 'sphinx.ext.intersphinx']
-intersphinx_mapping = {'http://docs.python.org/2/': None}
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.todo',
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.napoleon',
+ 'rst.linker',
+ 'jaraco.packaging.sphinx',
+]
+
+intersphinx_mapping = {
+ 'https://docs.python.org/3/': None,
+}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@@ -40,74 +59,24 @@ templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
-# The encoding of source files.
-#source_encoding = 'utf-8'
-
# The master toctree document.
master_doc = 'index'
-# General information about the project.
-project = u'CherryPy'
-copyright = u'2001-2015, CherryPy Team'
-
-# 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.
-sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
-import cherrypy
-version = cherrypy.__version__
-# The full version, including alpha/beta/rc tags.
-release = cherrypy.__version__
-
-# 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 documents that shouldn't be included in the build.
-#unused_docs = []
+project = pkg_resources.get_distribution('cherrypy').project_name
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []
-# 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. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
-if WITH_RTD_THEME:
- html_theme = "sphinx_rtd_theme"
-else:
- html_theme = 'default'
+html_theme = getattr(custom_sphinx_theme, '__name__', 'default')
# 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
@@ -126,27 +95,18 @@ else:
# "footertextcolor": "white",
# "codebgcolor": "#FFEEEE",
# }
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-if WITH_RTD_THEME:
- html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# "<project> v<release> 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
+html_theme_options = {
+ 'logo': 'images/cherrypy_logo_big.png',
+ 'github_user': project.lower(),
+ 'github_repo': project.lower(),
+ 'github_button': True,
+ 'github_banner': True,
+ 'github_type': 'watch',
+ 'github_count': True,
+ 'travis_button': True,
+ 'codecov_button': True,
+ # 'analytics_id': ...,
+}
# 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,
@@ -155,40 +115,15 @@ html_static_path = ['_static']
# html_style = 'cpdocmain.css'
-# 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_use_modindex = 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, an OpenSearch description file will be output, and all pages will
-# contain a <link> tag referring to it. The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = ''
+html_sidebars = {
+ 'index': [
+ 'about.html', 'searchbox.html', 'navigation.html', 'python_2_eol.html',
+ ],
+ '**': [
+ 'about.html', 'searchbox.html', 'navigation.html', 'python_2_eol.html',
+ ],
+}
# Output file base name for HTML help builder.
htmlhelp_basename = 'CherryPydoc'
@@ -196,67 +131,69 @@ htmlhelp_basename = 'CherryPydoc'
# -- Options for LaTeX output --------------------------------------------
-# The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
-
-# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
-
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author,
# documentclass [howto/manual]).
latex_documents = [
- ('index', 'CherryPy.tex', u'CherryPy Documentation',
- u'CherryPy Team', 'manual'),
+ (
+ 'index',
+ 'CherryPy.tex',
+ 'CherryPy Documentation',
+ 'CherryPy Team',
+ '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
-
-# Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-#latex_use_modindex = True
-
-import os
-
-on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
-if on_rtd:
- # so that ReadTheDocs can generate the docs properly
- # even the PDF version. Since ReadTheDocs runs on Linux,
- # it can't import pywin32. See:
- # http://read-the-docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
- import sys
-
- class Mock(object):
- def __init__(self, *args, **kwargs):
- pass
+def mock_pywin32():
+ """Mock pywin32 module.
- def __call__(self, *args, **kwargs):
- return Mock()
+ Resulting in Linux hosts, including ReadTheDocs,
+ and other environments that don't have pywin32 can generate the docs
+ properly including the PDF version.
+ See:
+ http://read-the-docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
+ """
+ if try_import('win32api'):
+ return
- @classmethod
- def __getattr__(cls, name):
- if name in ('__file__', '__path__'):
- return '/dev/null'
- elif name[0] == name[0].upper():
- mockType = type(name, (), {})
- mockType.__module__ = __name__
- return mockType
- else:
- return Mock()
+ from unittest import mock
- MOCK_MODULES = ['win32api', 'win32con', 'win32event',
- 'win32service', 'win32serviceutil']
+ MOCK_MODULES = [
+ 'win32api', 'win32con', 'win32event', 'win32service',
+ 'win32serviceutil',
+ ]
for mod_name in MOCK_MODULES:
- sys.modules[mod_name] = Mock()
+ sys.modules[mod_name] = mock.MagicMock()
+
+
+mock_pywin32()
+
+link_files = {
+ '../CHANGES.rst': dict(
+ using=dict(
+ GH='https://github.com',
+ ),
+ replace=[
+ dict(
+ pattern=r'((Issue|PR)\s?)?#(?P<issue_or_pr>\d+)',
+ url='{GH}/cherrypy/{project}/issues/{issue_or_pr}',
+ ),
+ dict(
+ pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n',
+ with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
+ ),
+ dict(
+ pattern=r'PEP[- ](?P<pep_number>\d+)',
+ url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
+ ),
+ dict(
+ # FIXME: currently this puts #v1.2.3 style version
+ # into URL, but it should be v1-2-3
+ pattern=r'cheroot v?(?P<cheroot_version>\d+(\.\d+){1,2})',
+ url='https://cheroot.readthedocs.io'
+ '/en/latest/history.html#v{cheroot_version}',
+ ),
+ ],
+ ),
+}
diff --git a/docs/config.rst b/docs/config.rst
index a4eb3acc..2f31352e 100644
--- a/docs/config.rst
+++ b/docs/config.rst
@@ -84,7 +84,7 @@ or, in python code:
.. code-block:: python
- config = {'/':
+ config = {'/':
{
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.trailing_slash.on': False,
@@ -237,9 +237,9 @@ that bit of config directly on the page handler:
.. code-block:: python
+ @cherrypy.expose
def page(self):
return "Hello, world!"
- page.exposed = True
page._cp_config = {"request.methods_with_bodies": ("POST", "PUT", "PROPPATCH")}
``_cp_config`` is a reserved attribute which the dispatcher looks for at
@@ -258,9 +258,9 @@ attached that config to a class which contains the page method:
_cp_config = {"request.methods_with_bodies": ("POST", "PUT", "PROPPATCH")}
+ @cherrypy.expose
def page(self):
return "Hullo, Werld!"
- page.exposed = True
.. note::
@@ -441,7 +441,7 @@ will call ``db_namespace('connstring', 'Oracle:host=1.10.100.200;sid=TEST')``.
The point at which your namespace handler is called depends on where you add it:
=========== ============================================================================= ===================================
-Scope Namespace dict Handler is called in
+Scope Namespace dict Handler is called in
----------- ----------------------------------------------------------------------------- -----------------------------------
Global :attr:`cherrypy.config.namespaces <cherrypy._cpconfig.Config.namespaces>` cherrypy.config.update
Application :attr:`app.namespaces <cherrypy._cptree.Application.namespaces>` Application.merge (which is called by cherrypy.tree.mount)
@@ -466,7 +466,7 @@ It only applies to the global config, and only when you use
entry *imports* other config entries from the following template stored in
``cherrypy._cpconfig.environments[environment]``.
-.. literalinclude:: ../../../cherrypy/_cpconfig.py
+.. literalinclude:: ../cherrypy/_cpconfig.py
:start-after: Sphinx begin config.environments
:end-before: Sphinx end config.environments
@@ -481,4 +481,3 @@ limiting or just plain wrong, feel free to extend them or add new environments:
'tools.encode.encoding': 'ISO-8859-7',
'tools.decode.encoding': 'ISO-8859-7',
}
-
diff --git a/docs/contribute.rst b/docs/contribute.rst
index 94bdf2c0..16301d2a 100644
--- a/docs/contribute.rst
+++ b/docs/contribute.rst
@@ -1,6 +1,58 @@
-
Contribute
----------
+CherryPy is a community-maintained, open-source project hosted at Github.
+The project active encourages aspiring and experienced users to dive
+in and add their best contribution to the project.
+
+How can you contribute? Well, first search the `docs
+<https://docs.cherrypy.org>`_ and the `project page
+<https://github.com/cherrypy/cherrypy>`_ to see if someone
+has already reported your issue.
+
+StackOverflow
+=============
+
+On `StackOverflow <https://stackoverflow.com>`_, there are questions
+tagged with 'cherrypy'. Answer unanswered questions, add an improved
+answer, clarify an answer with a comment, or ask more meaningful
+questions there. Earn reputation and share experience.
+
+CherryPy also maintains a `StackOverflow Wiki
+<http://stackoverflow.com/documentation/cherrypy/topics>`_ where
+anyone can publish tricks and techniques and refine others.
+
+Filing Bug Reports
+==================
+
+If you find a bug, an issue where the product doesn't behave as you
+expect, you may file a bug report at `the project page
+<https://github.com/cherrypy/cherrypy>`_. Be sure to include
+what your expectation was, what happened instead, details about
+your system that might be relevant, and steps that someone else
+could take to replicate your finding. The more detailed and exact
+your description, the better one of the volunteers on the project may
+be able to help resolve your issue.
+
+Fixing Bugs
+===========
+
+CherryPy has a number of open, reported `issues
+<https://github.com/cherrypy/cherrypy/issues>`_. Some of them are
+complicated and difficult, but others are more straightforward and
+shovel-ready. Feel free to find one that you think you can solve or
+introduce yourself and ask for guidance in `our gitter channel
+<https://gitter.im/cherrypy/cherrypy>`_.
+
+As you work through the issue and commit changes to your clone
+of the repository, be sure to add issue references to your changes
+(like "Fixes #999" or "Ref #999") so your changes link to the
+issue and vice-versa.
+
+Writing Pull Requests
+=====================
-To be done.
+To contribute, first read `How to write the perfect pull request
+<http://blog.jaraco.com/how-to-write-perfect-pull-request/>`_
+and file your contribution with the `CherryPy Project page
+<https://github.com/cherrypy/cherrypy>`_.
diff --git a/docs/deploy.rst b/docs/deploy.rst
index b7bab85e..db607c6c 100644
--- a/docs/deploy.rst
+++ b/docs/deploy.rst
@@ -8,7 +8,7 @@ it is not uncommon to run CherryPy behind a reverse proxy
or use other servers to host the application.
.. note::
-
+
CherryPy's server has proven reliable and fast enough
for years now. If the volume of traffic you receive is
average, it will do well enough on its own. Nonetheless,
@@ -84,12 +84,25 @@ provide a 'pidfile' argument, preferably an absolute path:
PIDFile(cherrypy.engine, '/var/run/myapp.pid').subscribe()
+Systemd socket activation
+#########################
+
+Socket Activation is a systemd feature that allows to setup a system so that
+the systemd will sit on a port and start services 'on demand' (a little bit
+like inetd and xinetd used to do).
+
+CherryPy has built-in socket activation support, if run from a systemd
+service file it will detect the `LISTEN_PID` environment variable to know that
+it should consider fd 3 to be the passed socket.
+
+To read more about socket activation:
+http://0pointer.de/blog/projects/socket-activation.html
Control via Supervisord
#######################
-`Supervisord <http://supervisord.org>`_ is a powerful process control
-and management tool that can perform a lot of tasks around process monitoring.
+`Supervisord <http://supervisord.org>`_ is a powerful process control
+and management tool that can perform a lot of tasks around process monitoring.
Below is a simple supervisor configuration for your CherryPy
application.
@@ -97,7 +110,7 @@ application.
.. code-block:: ini
[unix_http_server]
- file=/tmp/supervisor.sock
+ file=/tmp/supervisor.sock
[supervisord]
logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log)
@@ -108,16 +121,16 @@ application.
nodaemon=false ; (start in foreground if true;default false)
minfds=1024 ; (min. avail startup file descriptors;default 1024)
minprocs=200 ; (min. avail process descriptors;default 200)
-
+
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
-
+
[supervisorctl]
serverurl=unix:///tmp/supervisor.sock
[program:myapp]
command=python server.py
- environment=PYTHONPATH=.
+ environment=PYTHONPATH=.
directory=.
This could control your server via the ``server.py`` module as
@@ -126,15 +139,15 @@ the application entry point.
.. code-block:: python
import cherrypy
-
+
class Root(object):
@cherrypy.expose
def index(self):
return "Hello World!"
-
+
cherrypy.config.update({'server.socket_port': 8090,
- 'engine.autoreload_on': False,
+ 'engine.autoreload.on': False,
'log.access_file': './access.log',
'log.error_file': './error.log'})
cherrypy.quickstart(Root())
@@ -179,7 +192,7 @@ CherryPy can encrypt connections using SSL to create an https connection. This k
You can create either a key that requires a password to use, or one without a password. Protecting your private key with a password is much more secure, but requires that you enter the password every time you use the key. For example, you may have to enter the password when you start or restart your CherryPy server. This may or may not be feasible, depending on your setup.
-If you want to require a password, add one of the ``-aes128``, ``-aes192`` or ``-aes256`` switches to the command above. You should not use any of the DES, 3DES, or SEED algoritms to protect your password, as they are insecure.
+If you want to require a password, add one of the ``-aes128``, ``-aes192`` or ``-aes256`` switches to the command above. You should not use any of the DES, 3DES, or SEED algorithms to protect your password, as they are insecure.
SSL Labs recommends using 2048-bit RSA keys for security (see references section at the end).
@@ -209,7 +222,7 @@ openssl will then ask you a series of questions. You can enter whatever values a
4. Add the following lines in your CherryPy config to point to your certificate files:
-
+
.. code-block:: python
cherrypy.server.ssl_certificate = "cert.pem"
@@ -230,7 +243,7 @@ Embedding into another WSGI framework
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Though CherryPy comes with a very reliable and fast enough HTTP server,
-you may wish to integrate your CherryPy application within a
+you may wish to integrate your CherryPy application within a
different framework. To do so, we will benefit from the WSGI
interface defined in :pep:`333` and :pep:`3333`.
@@ -248,7 +261,7 @@ in a third-party WSGI server:
cherrypy.engine.start()
-- Stop the CherryPy's engine when you terminate. This will publish
+- Stop the CherryPy's engine when you terminate. This will publish
to the `"stop"` channel of the bus.
.. code-block:: python
@@ -274,13 +287,13 @@ in a third-party WSGI server:
on how the other framework handles them.
.. code-block:: python
-
+
cherrypy.engine.signals.subscribe()
- Use the ``"embedded"`` environment configuration scheme.
.. code-block:: python
-
+
cherrypy.config.update({'environment': 'embedded'})
Essentially this will disable the following:
@@ -296,7 +309,7 @@ in a third-party WSGI server:
Tornado
^^^^^^^
-You can use `tornado <http://www.tornadoweb.org/>`_ HTTP server as
+You can use `tornado <http://www.tornadoweb.org/>`_ HTTP server as
follow:
.. code-block:: python
@@ -316,7 +329,7 @@ follow:
# our WSGI application
wsgiapp = cherrypy.tree.mount(Root())
- # Disable the autoreload which won't play well
+ # Disable the autoreload which won't play well
cherrypy.config.update({'engine.autoreload.on': False})
# let's not start the CherryPy HTTP server
@@ -344,7 +357,7 @@ follow:
Twisted
^^^^^^^
-You can use `Twisted <https://twistedmatrix.com/>`_ HTTP server as
+You can use `Twisted <https://twistedmatrix.com/>`_ HTTP server as
follow:
.. code-block:: python
@@ -365,7 +378,7 @@ follow:
wsgiapp = cherrypy.tree.mount(Root())
# Configure the CherryPy's app server
- # Disable the autoreload which won't play well
+ # Disable the autoreload which won't play well
cherrypy.config.update({'engine.autoreload.on': False})
# We will be using Twisted HTTP server so let's
@@ -384,7 +397,7 @@ follow:
reactor.addSystemEventTrigger('after', 'startup', cherrypy.engine.start)
reactor.addSystemEventTrigger('before', 'shutdown', cherrypy.engine.exit)
resource = WSGIResource(reactor, reactor.getThreadPool(), wsgiapp)
-
+
Notice how we attach the bus methods to the Twisted's own lifecycle.
Save that code into a module named `cptw.py` and run it as follows:
@@ -397,7 +410,7 @@ Save that code into a module named `cptw.py` and run it as follows:
uwsgi
^^^^^
-You can use `uwsgi <http://projects.unbit.it/uwsgi/>`_ HTTP server as
+You can use `uwsgi <http://projects.unbit.it/uwsgi/>`_ HTTP server as
follow:
.. code-block:: python
@@ -470,8 +483,8 @@ In this example, we declare two domains and their ports:
- company.com:8080
- home.net:8080
-Thanks to the :class:`cherrypy.dispatch.VirtualHost` dispatcher,
-we tell CherryPy which application to dispatch to when a request
+Thanks to the :class:`cherrypy.dispatch.VirtualHost` dispatcher,
+we tell CherryPy which application to dispatch to when a request
arrives. The dispatcher looks up the requested domain and
call the according application.
@@ -542,7 +555,7 @@ be a good starting point.
}
}
-Edit this configuration to match your own paths. Then, save this configuration
+Edit this configuration to match your own paths. Then, save this configuration
into a file under ``/etc/nginx/conf.d/`` (assuming Ubuntu).
The filename is irrelevant. Then run the following commands:
@@ -582,7 +595,7 @@ Now, let's see our application:
if __name__ == '__main__':
cherrypy.config.update({
- 'server.socket_port': 8080,
+ 'server.socket_port': 8080,
'tools.proxy.on': True,
'tools.proxy.base': 'http://www.example.com'
})
diff --git a/docs/development.rst b/docs/development.rst
new file mode 100644
index 00000000..d52d76e9
--- /dev/null
+++ b/docs/development.rst
@@ -0,0 +1,20 @@
+Testing
+-------
+
+- To run the regression tests, first install tox:
+
+ .. code:: sh
+
+ pip install 'tox>=2.5'
+
+ then run it
+
+ .. code:: sh
+
+ tox
+
+- To run individual tests type:
+
+ .. code:: sh
+
+ tox -- -k test_foo
diff --git a/docs/extend.rst b/docs/extend.rst
index ef8bf8b5..56eb9859 100644
--- a/docs/extend.rst
+++ b/docs/extend.rst
@@ -17,7 +17,7 @@ Server-wide functions
CherryPy can be considered both as a HTTP library
as much as a web application framework. In that latter case,
its architecture provides mechanisms to support operations
-accross the whole server instance. This offers a powerful
+across the whole server instance. This offers a powerful
canvas to perform persistent operations as server-wide
functions live outside the request processing itself. They
are available to the whole process as long as the bus lives.
@@ -35,8 +35,8 @@ Publish/Subscribe pattern
^^^^^^^^^^^^^^^^^^^^^^^^^
CherryPy's backbone consists of a bus system implementing
-a simple `publish/subscribe messaging pattern <http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern>`_.
-Simply put, in CherryPy everything is controlled via that bus.
+a simple `publish/subscribe messaging pattern <http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern>`_.
+Simply put, in CherryPy everything is controlled via that bus.
One can easily picture the bus as a sushi restaurant's belt as in
the picture below.
@@ -44,10 +44,10 @@ the picture below.
:target: http://en.wikipedia.org/wiki/YO!_Sushi
-You can subscribe and publish to channels on a bus. A channel is
+You can subscribe and publish to channels on a bus. A channel is
bit like a unique identifier within the bus. When a message is
published to a channel, the bus will dispatch the message to
-all subscribers for that channel.
+all subscribers for that channel.
One interesting aspect of a pubsub pattern is that it promotes
decoupling between a caller and the callee. A published message
@@ -70,7 +70,7 @@ Let's take the following dummy application:
.. code-block:: python
import cherrypy
-
+
class ECommerce(object):
def __init__(self, db):
self.mydb = db
@@ -78,14 +78,14 @@ Let's take the following dummy application:
@cherrypy.expose
def save_kart(self, cart_data):
cart = Cart(cart_data)
- self.mydb.save(cart)
+ self.mydb.save(cart)
if __name__ == '__main__':
cherrypy.quickstart(ECommerce(), '/')
The application has a reference to the database but
this creates a fairly strong coupling between the
-database provider and the application.
+database provider and the application.
Another approach to work around the coupling is by
using a pubsub workflow:
@@ -93,12 +93,12 @@ using a pubsub workflow:
.. code-block:: python
import cherrypy
-
+
class ECommerce(object):
@cherrypy.expose
def save_kart(self, cart_data):
cart = Cart(cart_data)
- cherrypy.engine.publish('db-save', cart)
+ cherrypy.engine.publish('db-save', cart)
if __name__ == '__main__':
cherrypy.quickstart(ECommerce(), '/')
@@ -110,8 +110,8 @@ have to know about them.
.. note::
- This approach is not mandatory and it's up to you to
- decide how to design your entities interaction.
+ This approach is not mandatory and it's up to you to
+ decide how to design your entities interaction.
Implementation details
@@ -119,16 +119,16 @@ Implementation details
CherryPy's bus implementation is simplistic as it registers
functions to channels. Whenever a message is published to
-a channel, each registered function is applied with that
-message passas as a parameter.
+a channel, each registered function is applied with that
+message passed as a parameter.
The whole behaviour happens synchronously and, in that sense,
if a subscriber takes too long to process a message, the
remaining subscribers will be delayed.
CherryPy's bus is not an advanced pubsub messaging broker
-system such as provided by `zeromq <http://zeromq.org/>`_ or
-`RabbitMQ <https://www.rabbitmq.com/>`_.
+system such as provided by `zeromq <http://zeromq.org/>`_ or
+`RabbitMQ <https://www.rabbitmq.com/>`_.
Use it with the understanding that it may have a cost.
.. _cpengine:
@@ -181,7 +181,7 @@ to the transition changes of the `engine`.
In addition, a few other channels are also published to during
the request processing.
-- `**"before_request"**: right before the request is processed by CherryPy
+- **"before_request"**: right before the request is processed by CherryPy
- **"after_request"**: right after it has been processed
Also, from the :class:`cherrypy.process.plugins.ThreadManager` plugin:
@@ -197,8 +197,8 @@ Bus API
In order to work with the bus, the implementation
provides the following simple API:
-- :meth:`cherrypy.engine.publish(channel, *args) <cherrypy.process.wspbus.Bus.publish>`:
- - The `channel` parameter is a string identifying the channel to
+- :meth:`cherrypy.engine.publish(channel, *args) <cherrypy.process.wspbus.Bus.publish>`:
+ - The `channel` parameter is a string identifying the channel to
which the message should be sent to
- `*args` is the message and may contain any valid Python values or
objects.
@@ -224,7 +224,7 @@ publishing or subscribing to channels, usually both at the same time.
Plugins are extremely useful whenever you have functionalities:
- - Available accross the whole application server
+ - Available across the whole application server
- Associated to the application's life-cycle
- You want to avoid being strongly coupled to the application
@@ -241,16 +241,16 @@ A typical plugin looks like this:
class DatabasePlugin(plugins.SimplePlugin):
def __init__(self, bus, db_klass):
plugins.SimplePlugin.__init__(self, bus)
- self.db = db_klass()
-
+ self.db = db_klass()
+
def start(self):
self.bus.log('Starting up DB access')
self.bus.subscribe("db-save", self.save_it)
-
+
def stop(self):
self.bus.log('Stopping down DB access')
self.bus.unsubscribe("db-save", self.save_it)
-
+
def save_it(self, entity):
self.db.save(entity)
@@ -261,13 +261,13 @@ your `start` and `stop` methods to the related channels.
When the `start` and `stop` channels are published on, those
methods are called accordingly.
-Notice then how our plugin subscribes to the `db-save`
+Notice then how our plugin subscribes to the `db-save`
channel so that the bus can dispatch messages to the plugin.
Enable a plugin
~~~~~~~~~~~~~~~
-To enable the plugin, it has to be registered to the the
+To enable the plugin, it has to be registered to the the
bus as follows:
.. code-block:: python
@@ -299,7 +299,7 @@ Let's see an example using this default application:
.. code-block:: python
import cherrypy
-
+
class Root(object):
@cherrypy.expose
def index(self):
@@ -318,7 +318,6 @@ this application:
[27/Apr/2014:13:04:07] ENGINE Listening for SIGUSR1.
[27/Apr/2014:13:04:07] ENGINE Bus STARTING
[27/Apr/2014:13:04:07] ENGINE Started monitor thread 'Autoreloader'.
- [27/Apr/2014:13:04:07] ENGINE Started monitor thread '_TimeoutMonitor'.
[27/Apr/2014:13:04:08] ENGINE Serving on http://127.0.0.1:8080
[27/Apr/2014:13:04:08] ENGINE Bus STARTED
@@ -327,7 +326,7 @@ Now let's unsubscribe the HTTP server:
.. code-block:: python
import cherrypy
-
+
class Root(object):
@cherrypy.expose
def index(self):
@@ -346,7 +345,6 @@ This is what we get:
[27/Apr/2014:13:08:06] ENGINE Listening for SIGUSR1.
[27/Apr/2014:13:08:06] ENGINE Bus STARTING
[27/Apr/2014:13:08:06] ENGINE Started monitor thread 'Autoreloader'.
- [27/Apr/2014:13:08:06] ENGINE Started monitor thread '_TimeoutMonitor'.
[27/Apr/2014:13:08:06] ENGINE Bus STARTED
As you can see, the server is not started. The missing:
@@ -362,9 +360,9 @@ One of the most common task in a web application development
is to tailor the request's processing to the runtime context.
Within CherryPy, this is performed via what are called `tools`.
-If you are familiar with Django or WSGI middlewares,
-CherryPy tools are similar in spirit.
-They add functions that are applied during the
+If you are familiar with Django or WSGI middlewares,
+CherryPy tools are similar in spirit.
+They add functions that are applied during the
request/response processing.
.. _hookpoint:
@@ -405,18 +403,24 @@ Tools
^^^^^
A tool is a simple callable object (function, method, object
-implementing a `__call__` method) that is attached to a
-:ref:`hook point <hookpoint>`.
+implementing a `__call__` method) that is attached to a
+:ref:`hook point <hookpoint>`.
Below is a simple tool that is attached to the `before_finalize`
hook point, hence after the page handler was called:
.. code-block:: python
- def log_it():
+ @cherrypy.tools.register('before_finalize')
+ def logit():
print(cherrypy.request.remote.ip)
-
- cherrypy.tools.logit = cherrypy.Tool('before_finalize', log_it)
+
+Tools can also be created and assigned manually.
+The decorator registration is equivalent to:
+
+.. code-block:: python
+
+ cherrypy.tools.logit = cherrypy.Tool('before_finalize', logit)
Using that tool is as simple as follows:
@@ -428,12 +432,12 @@ Using that tool is as simple as follows:
def index(self):
return "hello world"
-Obviously the tool may be declared the
+Obviously the tool may be declared the
:ref:`other usual ways <perappconf>`.
.. note::
- The name of the tool, technically the attribute set to `cherrypy.tools`,
+ The name of the tool, technically the attribute set to `cherrypy.tools`,
does not have to match the name of the callable. However, it is
that name that will be used in the configuration to refer to that
tool.
@@ -483,10 +487,10 @@ right after the handler returned its result.
The import bits is that the :class:`cherrypy.Tool <cherrypy._cptools.Tool>` constructor
allows you to register to a hook point but, to attach the
-same tool to a different hook point, you must use the
-:meth:`cherrypy.request.hooks.attach <cherrypy._cprequest.HookMap.attach>` method.
-The :meth:`cherrypy.Tool._setup <cherrypy._cptools.Tool._setup>`
-method is automatically called by CherryPy when the tool
+same tool to a different hook point, you must use the
+:meth:`cherrypy.request.hooks.attach <cherrypy._cprequest.HookMap.attach>` method.
+The :meth:`cherrypy.Tool._setup <cherrypy._cptools.Tool._setup>`
+method is automatically called by CherryPy when the tool
is applied to the request.
Next, let's see how to use our tool:
@@ -533,10 +537,10 @@ could benefit (hint, hint). Creating a new Toolbox is as simple as:
newauthtools = cherrypy._cptools.Toolbox("newauth")
# Add a Tool to our new Toolbox.
+ @newauthtools.register('before_request_body')
def check_access(default=False):
if not getattr(cherrypy.request, "userid", default):
raise cherrypy.HTTPError(401)
- newauthtools.check_access = cherrypy.Tool('before_request_body', check_access)
Then, in your application, use it just like you would use ``cherrypy.tools``,
with the additional step of registering your toolbox with your app.
@@ -554,7 +558,7 @@ you can see the config entries in action below:
conf = {
'/demo': {
- 'newauth.check_access.on': True,
+ 'newauth.check_access.on': True,
'newauth.check_access.default': True,
}
}
@@ -589,18 +593,18 @@ page handler instead of the user id.
def load(self):
req = cherrypy.request
- # let's assume we have a db session
+ # let's assume we have a db session
# attached to the request somehow
- db = req.db
+ db = req.db
# retrieve the user id and remove it
# from the request parameters
- user_id = req.params.pop('user_id')
+ user_id = req.params.pop('user_id')
req.params['user'] = db.get(int(user_id))
cherrypy.tools.user = UserManager()
-
+
class Root(object):
@cherrypy.expose
@cherrypy.tools.user()
@@ -620,8 +624,8 @@ Tailored dispatchers
####################
Dispatching is the art of locating the appropriate page handler
-for a given request. Usually, dispatching is based on the
-request's URL, the query-string and, sometimes, the request's method
+for a given request. Usually, dispatching is based on the
+request's URL, the query-string and, sometimes, the request's method
(GET, POST, etc.).
Based on this, CherryPy comes with various dispatchers already.
@@ -655,7 +659,7 @@ to a lower-case page handler.
}
cherrypy.quickstart(StringGenerator(), '/', conf)
-Once you run this snipper, go to:
+Once you run this snippet, go to:
- http://localhost:8080/generate?length=8
- http://localhost:8080/GENerAte?length=8
@@ -672,10 +676,10 @@ a tool can be called is always after the page handler has been found.
In our example, it would be already too late as the default dispatcher
would have not even found a match for `/GENerAte`.
-A dispatcher exists mostly to determine the best page
+A dispatcher exists mostly to determine the best page
handler to serve the requested resource.
-On ther other hand, tools are there to adapt the request's processing
+On the other hand, tools are there to adapt the request's processing
to the runtime context of the application and the request's content.
Usually, you will have to write a dispatcher only if you
diff --git a/docs/glossary.rst b/docs/glossary.rst
index cfeb0966..2be2a5f9 100644
--- a/docs/glossary.rst
+++ b/docs/glossary.rst
@@ -2,7 +2,7 @@
Glossary
--------
-.. glossary::
+.. glossary::
application
A CherryPy application is simply a class instance containing
@@ -13,22 +13,22 @@ Glossary
exposed
A Python function or method which has an attribute called `exposed`
- set to `True`. This attribute can be set directly or via the
+ set to `True`. This attribute can be set directly or via the
:func:`cherrypy.expose()` decorator.
.. code-block:: python
-
+
@cherrypy.expose
- def method(...):
- ...
+ def method(...):
+ ...
is equivalent to:
.. code-block:: python
-
- def method(...):
- ...
+
+ def method(...):
+ ...
method.exposed = True
-
+
page handler
Name commonly given to an exposed method
diff --git a/docs/history.rst b/docs/history.rst
new file mode 100644
index 00000000..1817ba07
--- /dev/null
+++ b/docs/history.rst
@@ -0,0 +1,6 @@
+:tocdepth: 1
+
+History
+=======
+
+.. include:: ../CHANGES (links).rst
diff --git a/docs/index.rst b/docs/index.rst
index 0ccc48aa..0b6f6319 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -1,4 +1,4 @@
-
+
CherryPy - A Minimalist Python Web Framework
============================================
@@ -13,17 +13,21 @@ CherryPy - A Minimalist Python Web Framework
config.rst
extend.rst
deploy.rst
+ support.rst
contribute.rst
+ development.rst
glossary.rst
+ history.rst
+ pkg/modules.rst
`CherryPy <http://www.cherrypy.org>`_ is a pythonic, object-oriented web framework.
-CherryPy allows developers to build web applications in much the
-same way they would build any other object-oriented Python program.
+CherryPy allows developers to build web applications in much the
+same way they would build any other object-oriented Python program.
This results in smaller source code developed in less time.
-CherryPy is now more than ten years old and it is has proven to
-be fast and reliable. It is being used in production by many
+CherryPy is now more than ten years old and it is has proven to
+be fast and reliable. It is being used in production by many
sites, from the simplest to the most demanding.
A CherryPy application typically looks like this:
@@ -31,7 +35,7 @@ A CherryPy application typically looks like this:
.. code-block:: python
import cherrypy
-
+
class HelloWorld(object):
@cherrypy.expose
def index(self):
@@ -41,11 +45,11 @@ A CherryPy application typically looks like this:
In order to make the most of CherryPy, you should start
with the :ref:`tutorials <tutorials>` that will lead you through the most common
-aspects of the framework. Once done, you will probably want to
-browse through the :ref:`basics <basics>` and :ref:`advanced <advanced>`
-sections that will demonstrate how to implement certain operations.
-Finally, you will want to carefully read the configuration and
-:ref:`extend <extend>` sections that go in-depth regarding the
+aspects of the framework. Once done, you will probably want to
+browse through the :ref:`basics <basics>` and :ref:`advanced <advanced>`
+sections that will demonstrate how to implement certain operations.
+Finally, you will want to carefully read the configuration and
+:ref:`extend <extend>` sections that go in-depth regarding the
powerful features provided by the framework.
Above all, have fun with your application!
diff --git a/docs/install.rst b/docs/install.rst
index dec9c007..c558ac0f 100644
--- a/docs/install.rst
+++ b/docs/install.rst
@@ -16,19 +16,23 @@ Requirements
############
CherryPy does not have any mandatory requirements. However certain features it comes with
-will require you install certain packages.
+will require you install certain packages. To simplify installing additional
+dependencies CherryPy enables you to specify extras in your requirements (e.g.
+``cherrypy[json,routes_dispatcher,ssl]``):
+
+- doc -- for documentation related stuff
+- json -- for custom `JSON processing library <https://github.com/simplejson/simplejson>`_
+- routes_dispatcher -- `routes <http://routes.readthedocs.org/en/latest/>`_ for declarative URL mapping dispatcher
+- ssl -- for `OpenSSL bindings <https://github.com/pyca/pyopenssl>`_, useful in Python environments not having the builtin :mod:`ssl` module
+- testing
+- memcached_session -- enables `memcached <https://github.com/linsomniac/python-memcached>`_ backend session
+- xcgi
-- `routes <http://routes.readthedocs.org/en/latest/>`_ for declarative URL mapping dispatcher
-- `psycopg2 <http://pythonhosted.org//psycopg2/>`_ for PostgreSQL backend session
-- `pywin32 <http://sourceforge.net/projects/pywin32/>`_ for Windows services
-- `python-memcached <https://github.com/linsomniac/python-memcached>`_ for memcached backend session
-- `simplejson <https://github.com/simplejson/simplejson>`_ for a better JSON support
-- `pyOpenSSL <https://github.com/pyca/pyopenssl>`_ if your Python environment does not have the builtin :mod:`ssl` module
Supported python version
########################
-CherryPy supports Python 2.3 through to 3.4.
+CherryPy supports Python 2.7 through to 3.5.
Installing
@@ -74,7 +78,6 @@ Once started the above command shows the following logs:
[15/Feb/2014:21:51:22] ENGINE Listening for SIGUSR1.
[15/Feb/2014:21:51:22] ENGINE Bus STARTING
[15/Feb/2014:21:51:22] ENGINE Started monitor thread 'Autoreloader'.
- [15/Feb/2014:21:51:22] ENGINE Started monitor thread '_TimeoutMonitor'.
[15/Feb/2014:21:51:22] ENGINE Serving on http://127.0.0.1:8080
[15/Feb/2014:21:51:23] ENGINE Bus STARTED
@@ -153,4 +156,3 @@ Command-Line Options
.. cmdoption:: -P, --Path
Add the given paths to sys.path
-
diff --git a/docs/intro.rst b/docs/intro.rst
index 72af26d3..500bb256 100644
--- a/docs/intro.rst
+++ b/docs/intro.rst
@@ -4,15 +4,15 @@ Foreword
Why CherryPy?
#############
-CherryPy is among the oldest web framework available for Python, yet many people aren't aware of its existence.
+CherryPy is among the oldest web framework available for Python, yet many people aren't aware of its existence.
One of the reason for this is that CherryPy is not a complete stack with built-in support for a multi-tier architecture.
It doesn't provide frontend utilities nor will it tell you how to speak with your storage. Instead, CherryPy's take
-is to let the developer make those decisions. This is a contrasting position compared to other well-known frameworks.
+is to let the developer make those decisions. This is a contrasting position compared to other well-known frameworks.
CherryPy has a clean interface and does its best to stay out of your way whilst providing
a reliable scaffolding for you to build from.
-Typical use-cases for CherryPy go from regular web application with user frontends
+Typical use-cases for CherryPy go from regular web application with user frontends
(think blogging, CMS, portals, ecommerce) to web-services only.
Here are some reasons you would want to choose CherryPy:
@@ -34,14 +34,14 @@ Here are some reasons you would want to choose CherryPy:
CherryPy also provides :ref:`tools <tools>` and :ref:`plugins <busplugins>`, which are powerful extension points needed to develop world-class web applications.
3. Maturity
-
+
Maturity is extremely important when developing a real-world application. Unlike many other web frameworks, CherryPy has had many final, stable releases. It is fully bugtested, optimized, and proven reliable for real-world use. The API will not suddenly change and break backwards compatibility, so your applications are assured to continue working even through subsequent updates in the current version series.
CherryPy is also a “3.0” project: the first edition of CherryPy set the tone, the second edition made it work, and the third edition makes it beautiful. Each version built on lessons learned from the previous, bringing the developer a superior tool for the job.
4. Community
-
- CherryPy has an devoted community that develops deployed CherryPy applications and are willing and ready to assist you on the CherryPy mailing list or IRC (#cherrypy on OFTC). The developers also frequent the list and often answer questions and implement features requested by the end-users.
+
+ CherryPy has an devoted community that develops deployed CherryPy applications and are willing and ready to assist you on the CherryPy mailing list or Gitter. The developers also frequent the list and often answer questions and implement features requested by the end-users.
5. Deployability
@@ -71,7 +71,7 @@ using it, or simply check out products or application running it.
If you would like to have your CherryPy powered website or product listed here,
contact us via our `mailing list <http://groups.google.com/group/cherrypy-users>`_
-or IRC (#cherrypy on `OFTC <http://www.oftc.net/oftc/>`_).
+or `Gitter <https://gitter.im/cherrypy/cherrypy>`_.
Websites running atop CherryPy
@@ -117,7 +117,7 @@ Communication training company. Built on CherryPy 3.2.0 and Python 2.7.3, with
`Almad's Homepage <http://www.almad.net>`_ - Simple homepage with blog.
-`Fight.Watch <http://fight.watch>`_ - Twitch.tv web portal for fighting games.
+`Fight.Watch <http://fight.watch>`_ - Twitch.tv web portal for fighting games.
Built on CherryPy 3.3.0 and Python 2.7.3 with Jinja 2.7.2 and SQLAlchemy 0.9.4.
Products based on CherryPy
diff --git a/docs/pkg/cherrypy.lib.rst b/docs/pkg/cherrypy.lib.rst
index b43db26a..c8dc6d9b 100644
--- a/docs/pkg/cherrypy.lib.rst
+++ b/docs/pkg/cherrypy.lib.rst
@@ -76,14 +76,6 @@ cherrypy.lib.gctools module
:undoc-members:
:show-inheritance:
-cherrypy.lib.http module
-------------------------
-
-.. automodule:: cherrypy.lib.http
- :members:
- :undoc-members:
- :show-inheritance:
-
cherrypy.lib.httpauth module
----------------------------
@@ -116,6 +108,14 @@ cherrypy.lib.lockfile module
:undoc-members:
:show-inheritance:
+cherrypy.lib.locking module
+---------------------------
+
+.. automodule:: cherrypy.lib.locking
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
cherrypy.lib.profiler module
----------------------------
diff --git a/docs/pkg/cherrypy.rst b/docs/pkg/cherrypy.rst
index e9287331..38599fa1 100644
--- a/docs/pkg/cherrypy.rst
+++ b/docs/pkg/cherrypy.rst
@@ -11,143 +11,14 @@ Subpackages
cherrypy.scaffold
cherrypy.test
cherrypy.tutorial
- cherrypy.wsgiserver
Submodules
----------
-cherrypy._cpchecker module
---------------------------
+cherrypy.daemon module
+----------------------
-.. automodule:: cherrypy._cpchecker
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpcompat module
--------------------------
-
-.. automodule:: cherrypy._cpcompat
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpcompat_subprocess module
-------------------------------------
-
-.. automodule:: cherrypy._cpcompat_subprocess
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpconfig module
--------------------------
-
-.. automodule:: cherrypy._cpconfig
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpdispatch module
----------------------------
-
-.. automodule:: cherrypy._cpdispatch
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cperror module
-------------------------
-
-.. automodule:: cherrypy._cperror
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cplogging module
---------------------------
-
-.. automodule:: cherrypy._cplogging
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpmodpy module
-------------------------
-
-.. automodule:: cherrypy._cpmodpy
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpnative_server module
---------------------------------
-
-.. automodule:: cherrypy._cpnative_server
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpreqbody module
---------------------------
-
-.. automodule:: cherrypy._cpreqbody
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cprequest module
---------------------------
-
-.. automodule:: cherrypy._cprequest
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpserver module
--------------------------
-
-.. automodule:: cherrypy._cpserver
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpthreadinglocal module
----------------------------------
-
-.. automodule:: cherrypy._cpthreadinglocal
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cptools module
-------------------------
-
-.. automodule:: cherrypy._cptools
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cptree module
------------------------
-
-.. automodule:: cherrypy._cptree
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpwsgi module
------------------------
-
-.. automodule:: cherrypy._cpwsgi
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy._cpwsgi_server module
-------------------------------
-
-.. automodule:: cherrypy._cpwsgi_server
+.. automodule:: cherrypy.daemon
:members:
:undoc-members:
:show-inheritance:
diff --git a/docs/pkg/cherrypy.test.rst b/docs/pkg/cherrypy.test.rst
index 88f1d68a..0d5e22f3 100644
--- a/docs/pkg/cherrypy.test.rst
+++ b/docs/pkg/cherrypy.test.rst
@@ -4,22 +4,6 @@ cherrypy.test package
Submodules
----------
-cherrypy.test._test_decorators module
--------------------------------------
-
-.. automodule:: cherrypy.test._test_decorators
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy.test._test_states_demo module
---------------------------------------
-
-.. automodule:: cherrypy.test._test_states_demo
- :members:
- :undoc-members:
- :show-inheritance:
-
cherrypy.test.benchmark module
------------------------------
@@ -212,6 +196,14 @@ cherrypy.test.test_httplib module
:undoc-members:
:show-inheritance:
+cherrypy.test.test_iterator module
+----------------------------------
+
+.. automodule:: cherrypy.test.test_iterator
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
cherrypy.test.test_json module
------------------------------
@@ -252,6 +244,14 @@ cherrypy.test.test_objectmapping module
:undoc-members:
:show-inheritance:
+cherrypy.test.test_params module
+--------------------------------
+
+.. automodule:: cherrypy.test.test_params
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
cherrypy.test.test_proxy module
-------------------------------
@@ -348,6 +348,14 @@ cherrypy.test.test_wsgi_ns module
:undoc-members:
:show-inheritance:
+cherrypy.test.test_wsgi_unix_socket module
+------------------------------------------
+
+.. automodule:: cherrypy.test.test_wsgi_unix_socket
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
cherrypy.test.test_wsgi_vhost module
------------------------------------
diff --git a/docs/pkg/cherrypy.wsgiserver.rst b/docs/pkg/cherrypy.wsgiserver.rst
deleted file mode 100644
index 9e91f631..00000000
--- a/docs/pkg/cherrypy.wsgiserver.rst
+++ /dev/null
@@ -1,46 +0,0 @@
-cherrypy.wsgiserver package
-===========================
-
-Submodules
-----------
-
-cherrypy.wsgiserver.ssl_builtin module
---------------------------------------
-
-.. automodule:: cherrypy.wsgiserver.ssl_builtin
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy.wsgiserver.ssl_pyopenssl module
-----------------------------------------
-
-.. automodule:: cherrypy.wsgiserver.ssl_pyopenssl
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy.wsgiserver.wsgiserver2 module
---------------------------------------
-
-.. automodule:: cherrypy.wsgiserver.wsgiserver2
- :members:
- :undoc-members:
- :show-inheritance:
-
-cherrypy.wsgiserver.wsgiserver3 module
---------------------------------------
-
-.. automodule:: cherrypy.wsgiserver.wsgiserver3
- :members:
- :undoc-members:
- :show-inheritance:
-
-
-Module contents
----------------
-
-.. automodule:: cherrypy.wsgiserver
- :members:
- :undoc-members:
- :show-inheritance:
diff --git a/docs/pkg/modules.rst b/docs/pkg/modules.rst
index fe45a992..9c68b63a 100644
--- a/docs/pkg/modules.rst
+++ b/docs/pkg/modules.rst
@@ -1,5 +1,5 @@
-cherrypy
-========
+Modules
+=======
.. toctree::
:maxdepth: 4
diff --git a/docs/requirements.txt b/docs/requirements.txt
new file mode 100644
index 00000000..01fb021e
--- /dev/null
+++ b/docs/requirements.txt
@@ -0,0 +1 @@
+.[docs,testing]
diff --git a/docs/support.rst b/docs/support.rst
new file mode 100644
index 00000000..1c31c242
--- /dev/null
+++ b/docs/support.rst
@@ -0,0 +1,51 @@
+Support
+=======
+
+You've read the documentation and you've brushed up on the basics of
+Python and web development, but you still could use some help. Users
+have several options.
+
+I have a question
+-----------------
+
+If you have a question and cannot find an answer for it in issues or the
+the `documentation <http://docs.cherrypy.org/en/latest/>`__, `please
+create an issue <https://github.com/cherrypy/cherrypy/issues/new>`__.
+
+Questions and their answers have great value for the community, and a
+tip is to really put the effort in and write a good explanation, you
+will get better and quicker answers. Examples are strongly encouraged.
+
+I have found a bug
+------------------
+
+If no one have already, `create an
+issue <https://github.com/cherrypy/cherrypy/issues/new>`__. Be sure to
+provide ample information, remember that any help won't be better than
+your explanation.
+
+Unless something is very obviously wrong, you are likely to be asked to
+provide a working example, displaying the erroneous behaviour.
+
+Note: While this might feel troublesome, a tip is to always make a
+separate example that have the same dependencies as your project. It is
+great for troubleshooting those annoying problems where you don't know
+if the problem is at your end or the components. Also, you can then
+easily fork and provide as an example. You will get answers and
+resolutions way quicker. Also, many other open source projects require
+it.
+
+I have a feature request
+------------------------
+
+`Good stuff! Please create an
+issue! <https://github.com/cherrypy/cherrypy/issues/new>`__\ Note:
+Features are more likely to be added the more users they seem to
+benefit.
+
+I want to converse
+------------------
+
+`The gitter page <https://gitter.im/cherrypy/cherrypy>`__ is good for
+when you want to discuss in real time or get pointed in the right
+direction.
diff --git a/docs/tutorials.rst b/docs/tutorials.rst
index e50fa1dd..c25cf747 100644
--- a/docs/tutorials.rst
+++ b/docs/tutorials.rst
@@ -23,13 +23,15 @@ http://127.0.0.1:8080/
import cherrypy
+
class HelloWorld(object):
@cherrypy.expose
def index(self):
- return "Hello world!"
+ return "Hello world!"
+
if __name__ == '__main__':
- cherrypy.quickstart(HelloWorld())
+ cherrypy.quickstart(HelloWorld())
Store this code snippet into a file named `tut01.py` and
execute it as follows:
@@ -49,14 +51,13 @@ This will display something along the following:
[24/Feb/2014:21:01:46] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.
-
+
[24/Feb/2014:21:01:46] ENGINE Started monitor thread 'Autoreloader'.
- [24/Feb/2014:21:01:46] ENGINE Started monitor thread '_TimeoutMonitor'.
[24/Feb/2014:21:01:46] ENGINE Serving on http://127.0.0.1:8080
[24/Feb/2014:21:01:46] ENGINE Bus STARTED
This tells you several things. The first three lines indicate
-the server will handle :mod:`signal` for you. The next line tells you
+the server will handle :mod:`signal` for you. The next line tells you
the current state of the server, as that
point it is in `STARTING` stage. Then, you are notified your
application has no specific configuration set to it.
@@ -78,8 +79,8 @@ understand how to set the configuration.
Tutorial 2: Different URLs lead to different functions
######################################################
-Your applications will obviously handle more than a single URL.
-Let's imagine you have an application that generates a random
+Your applications will obviously handle more than a single URL.
+Let's imagine you have an application that generates a random
string each time it is called:
.. code-block:: python
@@ -87,18 +88,20 @@ string each time it is called:
import random
import string
-
+
import cherrypy
+
class StringGenerator(object):
@cherrypy.expose
def index(self):
- return "Hello world!"
+ return "Hello world!"
@cherrypy.expose
def generate(self):
return ''.join(random.sample(string.hexdigits, 8))
-
+
+
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())
@@ -109,7 +112,7 @@ Save this into a file named `tut02.py` and run it as follows:
$ python tut02.py
Go now to http://localhost:8080/generate and your browser
-will display a random string.
+will display a random string.
Let's take a minute to decompose what's happening here. This is the
URL that you have typed into your browser: http://localhost:8080/generate
@@ -138,18 +141,20 @@ to indicate the length of that string dynamically.
import random
import string
-
+
import cherrypy
+
class StringGenerator(object):
@cherrypy.expose
def index(self):
- return "Hello world!"
+ return "Hello world!"
@cherrypy.expose
def generate(self, length=8):
return ''.join(random.sample(string.hexdigits, int(length)))
-
+
+
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())
@@ -161,18 +166,18 @@ Save this into a file named `tut03.py` and run it as follows:
Go now to http://localhost:8080/generate?length=16 and your browser
will display a generated string of length 16. Notice how
-we benefit from Python's default arguments' values to support
+we benefit from Python's default arguments' values to support
URLs such as http://localhost:8080/generate still.
-In a URL such as this one, the section after `?` is called a
-query-string. Traditionally, the query-string is used to
+In a URL such as this one, the section after `?` is called a
+query-string. Traditionally, the query-string is used to
contextualize the URL by passing a set of (key, value) pairs. The
format for those pairs is `key=value`. Each pair being
separated by a `&` character.
Notice how we have to convert the given `length` value to
-and integer. Indeed, values are sent out from the client
-to our server as strings.
+an integer. Indeed, values are sent out from the client
+to our server as strings.
Much like CherryPy maps URL path segments to exposed functions,
query-string keys are mapped to those exposed function parameters.
@@ -194,26 +199,28 @@ example.
import random
import string
-
+
import cherrypy
+
class StringGenerator(object):
@cherrypy.expose
def index(self):
- return """<html>
+ return """<html>
<head></head>
- <body>
- <form method="get" action="generate">
- <input type="text" value="8" name="length" />
+ <body>
+ <form method="get" action="generate">
+ <input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
- </form>
- </body>
- </html>"""
+ </form>
+ </body>
+ </html>"""
@cherrypy.expose
def generate(self, length=8):
return ''.join(random.sample(string.hexdigits, int(length)))
-
+
+
if __name__ == '__main__':
cherrypy.quickstart(StringGenerator())
@@ -227,9 +234,9 @@ Go now to http://localhost:8080/ and your browser and this will
display a simple input field to indicate the length of the string
you want to generate.
-Notice that in this example, the form uses the `GET` method and
+Notice that in this example, the form uses the `GET` method and
when you pressed the `Give it now!` button, the form is sent using the
-same URL as in the :ref:`previous <tut03>` tutorial. HTML forms also support the
+same URL as in the :ref:`previous <tut03>` tutorial. HTML forms also support the
`POST` method, in that case the query-string is not appended to the
URL but it sent as the body of the client's request to the server.
However, this would not change your application's exposed method because
@@ -244,29 +251,30 @@ Tutorial 5: Track my end-user's activity
It's not uncommon that an application needs to follow the
user's activity for a while. The usual mechanism is to use
a `session identifier <http://en.wikipedia.org/wiki/Session_(computer_science)#HTTP_session_token>`_
-that is carried during the conversation between the user and
-your application.
+that is carried during the conversation between the user and
+your application.
.. code-block:: python
:linenos:
- import random
- import string
+ import random
+ import string
+
+ import cherrypy
- import cherrypy
- class StringGenerator(object):
+ class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head></head>
- <body>
- <form method="get" action="generate">
- <input type="text" value="8" name="length" />
+ <body>
+ <form method="get" action="generate">
+ <input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
- </form>
- </body>
- </html>"""
+ </form>
+ </body>
+ </html>"""
@cherrypy.expose
def generate(self, length=8):
@@ -278,13 +286,14 @@ your application.
def display(self):
return cherrypy.session['mystring']
- if __name__ == '__main__':
- conf = {
- '/': {
- 'tools.sessions.on': True
- }
- }
- cherrypy.quickstart(StringGenerator(), '/', conf)
+
+ if __name__ == '__main__':
+ conf = {
+ '/': {
+ 'tools.sessions.on': True
+ }
+ }
+ cherrypy.quickstart(StringGenerator(), '/', conf)
Save this into a file named `tut05.py` and run it as follows:
@@ -292,11 +301,11 @@ Save this into a file named `tut05.py` and run it as follows:
$ python tut05.py
-In this example, we generate the string as in the
+In this example, we generate the string as in the
:ref:`previous <tut04>` tutorial but also store it in the current
session. If you go to http://localhost:8080/, generate a
random string, then go to http://localhost:8080/display, you
-will see the string you just generated.
+will see the string you just generated.
The lines 30-34 show you how to enable the session support
in your CherryPy application. By default, CherryPy will save
@@ -319,9 +328,9 @@ and stored into a local directory `public/css`.
.. code-block:: css
:linenos:
- body {
- background-color: blue;
- }
+ body {
+ background-color: blue;
+ }
Now let's update the HTML code so that we link to the stylesheet
using the http://localhost:8080/static/css/style.css URL.
@@ -329,26 +338,27 @@ using the http://localhost:8080/static/css/style.css URL.
.. code-block:: python
:linenos:
- import os, os.path
- import random
- import string
+ import os, os.path
+ import random
+ import string
- import cherrypy
+ import cherrypy
- class StringGenerator(object):
+
+ class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head>
<link href="/static/css/style.css" rel="stylesheet">
</head>
- <body>
- <form method="get" action="generate">
- <input type="text" value="8" name="length" />
+ <body>
+ <form method="get" action="generate">
+ <input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
- </form>
- </body>
- </html>"""
+ </form>
+ </body>
+ </html>"""
@cherrypy.expose
def generate(self, length=8):
@@ -360,18 +370,20 @@ using the http://localhost:8080/static/css/style.css URL.
def display(self):
return cherrypy.session['mystring']
- if __name__ == '__main__':
- conf = {
- '/': {
- 'tools.sessions.on': True,
- 'tools.staticdir.root': os.path.abspath(os.getcwd())
- },
- '/static': {
- 'tools.staticdir.on': True,
- 'tools.staticdir.dir': './public'
- }
- }
- cherrypy.quickstart(StringGenerator(), '/', conf)
+
+ if __name__ == '__main__':
+ conf = {
+ '/': {
+ 'tools.sessions.on': True,
+ 'tools.staticdir.root': os.path.abspath(os.getcwd())
+ },
+ '/static': {
+ 'tools.staticdir.on': True,
+ 'tools.staticdir.dir': './public'
+ }
+ }
+ cherrypy.quickstart(StringGenerator(), '/', conf)
+
Save this into a file named `tut06.py` and run it as follows:
@@ -409,7 +421,7 @@ Roughly speaking, it assumes that you can identify a resource
and that you can address that resource through that identifier.
"What for?" you may ask. Well, mostly, these principles are there
-to ensure that you decouple, as best as you can, the entities
+to ensure that you decouple, as best as you can, the entities
your application expose from the way they are manipulated or
consumed. To embrace this point of view, developers will
usually design a web API that expose pairs of `(URL, HTTP method, data, constraints)`.
@@ -428,39 +440,41 @@ mildly following REST principles.
.. code-block:: python
:linenos:
- import random
- import string
+ import random
+ import string
+
+ import cherrypy
+
- import cherrypy
+ @cherrypy.expose
+ class StringGeneratorWebService(object):
- class StringGeneratorWebService(object):
- exposed = True
+ @cherrypy.tools.accept(media='text/plain')
+ def GET(self):
+ return cherrypy.session['mystring']
- @cherrypy.tools.accept(media='text/plain')
- def GET(self):
- return cherrypy.session['mystring']
+ def POST(self, length=8):
+ some_string = ''.join(random.sample(string.hexdigits, int(length)))
+ cherrypy.session['mystring'] = some_string
+ return some_string
- def POST(self, length=8):
- some_string = ''.join(random.sample(string.hexdigits, int(length)))
- cherrypy.session['mystring'] = some_string
- return some_string
+ def PUT(self, another_string):
+ cherrypy.session['mystring'] = another_string
- def PUT(self, another_string):
- cherrypy.session['mystring'] = another_string
+ def DELETE(self):
+ cherrypy.session.pop('mystring', None)
- def DELETE(self):
- cherrypy.session.pop('mystring', None)
- if __name__ == '__main__':
- conf = {
- '/': {
- 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
- 'tools.sessions.on': True,
- 'tools.response_headers.on': True,
- 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
- }
- }
- cherrypy.quickstart(StringGeneratorWebService(), '/', conf)
+ if __name__ == '__main__':
+ conf = {
+ '/': {
+ 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
+ 'tools.sessions.on': True,
+ 'tools.response_headers.on': True,
+ 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
+ }
+ }
+ cherrypy.quickstart(StringGeneratorWebService(), '/', conf)
Save this into a file named `tut07.py` and run it as follows:
@@ -472,18 +486,18 @@ Save this into a file named `tut07.py` and run it as follows:
Before we see it in action, let's explain a few things. Until now,
CherryPy was creating a tree of exposed methods that were used to
match URLs. In the case of our web API, we want to stress the role
-played by the actual requests' HTTP methods. So we created
+played by the actual requests' HTTP methods. So we created
methods that are named after them and they are all exposed at once
-through the `exposed = True` attribute of the class itself.
+by decorating the class itself with `cherrypy.expose`.
However, we must then switch from the default mechanism of matching
URLs to method for one that is aware of the whole HTTP method
-shenanigan. This is what goes on line 27 where we create
+shenanigan. This is what goes on line 27 where we create
a :class:`~cherrypy.dispatch.MethodDispatcher` instance.
Then we force the responses `content-type` to be `text/plain` and
we finally ensure that `GET` requests will only be responded to clients
-that accept that `content-type` by having a `Accept: text/plain`
+that accept that `content-type` by having a `Accept: text/plain`
header set in their request. However, we do this only for that
HTTP method as it wouldn't have much meaning on the other methods.
@@ -533,7 +547,7 @@ on the latter case, that it doesn't exist after we've deleted it.
Lines 12-14 show you how the application reacted when our client requested
the generated string as a JSON format. Since we configured the
-web API to only support plain text, it returns the appropriate
+web API to only support plain text, it returns the appropriate
`HTTP error code <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7>`_.
@@ -547,7 +561,7 @@ web API to only support plain text, it returns the appropriate
.. important::
It's all about RESTful URLs these days, isn't it?
-
+
It is likely your URL will be made of dynamic parts that you
will not be able to match to page handlers. For example,
``/library/12/book/15`` cannot be directly handled by the
@@ -558,7 +572,7 @@ web API to only support plain text, it returns the appropriate
explained in the :ref:`advanced section <restful>`.
-
+
.. _tut08:
@@ -566,11 +580,11 @@ Tutorial 8: Make it smoother with Ajax
######################################
In the recent years, web applications have moved away from the
-simple pattern of "HTML forms + refresh the whole page". This
+simple pattern of "HTML forms + refresh the whole page". This
traditional scheme still works very well but users have become used
-to web applications that don't refresh the entire page.
-Broadly speaking, web applications carry code performed
-client-side that can speak with the backend without having to
+to web applications that don't refresh the entire page.
+Broadly speaking, web applications carry code performed
+client-side that can speak with the backend without having to
refresh the whole page.
This tutorial will involve a little more code this time around. First,
@@ -579,11 +593,11 @@ let's see our CSS stylesheet located in `public/css/style.css`.
.. code-block:: css
:linenos:
- body {
+ body {
background-color: blue;
}
- #the-string {
+ #the-string {
display: none;
}
@@ -596,56 +610,56 @@ Save the following HTML code into a file named `index.html`.
<!DOCTYPE html>
<html>
- <head>
- <link href="/static/css/style.css" rel="stylesheet">
- <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function() {
-
- $("#generate-string").click(function(e) {
- $.post("/generator", {"length": $("input[name='length']").val()})
- .done(function(string) {
- $("#the-string").show();
- $("#the-string input").val(string);
- });
- e.preventDefault();
- });
-
- $("#replace-string").click(function(e) {
- $.ajax({
- type: "PUT",
- url: "/generator",
- data: {"another_string": $("#the-string input").val()}
- })
- .done(function() {
- alert("Replaced!");
- });
- e.preventDefault();
- });
-
- $("#delete-string").click(function(e) {
- $.ajax({
- type: "DELETE",
- url: "/generator"
- })
- .done(function() {
- $("#the-string").hide();
- });
- e.preventDefault();
- });
-
- });
- </script>
- </head>
- <body>
- <input type="text" value="8" name="length" />
- <button id="generate-string">Give it now!</button>
- <div id="the-string">
- <input type="text" />
- <button id="replace-string">Replace</button>
- <button id="delete-string">Delete it</button>
- </div>
- </body>
+ <head>
+ <link href="/static/css/style.css" rel="stylesheet">
+ <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
+ <script type="text/javascript">
+ $(document).ready(function() {
+
+ $("#generate-string").click(function(e) {
+ $.post("/generator", {"length": $("input[name='length']").val()})
+ .done(function(string) {
+ $("#the-string").show();
+ $("#the-string input").val(string);
+ });
+ e.preventDefault();
+ });
+
+ $("#replace-string").click(function(e) {
+ $.ajax({
+ type: "PUT",
+ url: "/generator",
+ data: {"another_string": $("#the-string input").val()}
+ })
+ .done(function() {
+ alert("Replaced!");
+ });
+ e.preventDefault();
+ });
+
+ $("#delete-string").click(function(e) {
+ $.ajax({
+ type: "DELETE",
+ url: "/generator"
+ })
+ .done(function() {
+ $("#the-string").hide();
+ });
+ e.preventDefault();
+ });
+
+ });
+ </script>
+ </head>
+ <body>
+ <input type="text" value="8" name="length"/>
+ <button id="generate-string">Give it now!</button>
+ <div id="the-string">
+ <input type="text" />
+ <button id="replace-string">Replace</button>
+ <button id="delete-string">Delete it</button>
+ </div>
+ </body>
</html>
We'll be using the `jQuery framework <http://jquery.com/>`_
@@ -662,55 +676,57 @@ Both are hosted by the same application server.
.. code-block:: python
:linenos:
- import os, os.path
- import random
- import string
+ import os, os.path
+ import random
+ import string
+
+ import cherrypy
- import cherrypy
- class StringGenerator(object):
+ class StringGenerator(object):
@cherrypy.expose
def index(self):
return open('index.html')
- class StringGeneratorWebService(object):
- exposed = True
-
- @cherrypy.tools.accept(media='text/plain')
- def GET(self):
- return cherrypy.session['mystring']
-
- def POST(self, length=8):
- some_string = ''.join(random.sample(string.hexdigits, int(length)))
- cherrypy.session['mystring'] = some_string
- return some_string
-
- def PUT(self, another_string):
- cherrypy.session['mystring'] = another_string
-
- def DELETE(self):
- cherrypy.session.pop('mystring', None)
-
- if __name__ == '__main__':
- conf = {
- '/': {
- 'tools.sessions.on': True,
- 'tools.staticdir.root': os.path.abspath(os.getcwd())
- },
- '/generator': {
- 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
- 'tools.response_headers.on': True,
- 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
- },
- '/static': {
- 'tools.staticdir.on': True,
- 'tools.staticdir.dir': './public'
- }
- }
- webapp = StringGenerator()
- webapp.generator = StringGeneratorWebService()
- cherrypy.quickstart(webapp, '/', conf)
+ @cherrypy.expose
+ class StringGeneratorWebService(object):
+
+ @cherrypy.tools.accept(media='text/plain')
+ def GET(self):
+ return cherrypy.session['mystring']
+
+ def POST(self, length=8):
+ some_string = ''.join(random.sample(string.hexdigits, int(length)))
+ cherrypy.session['mystring'] = some_string
+ return some_string
+
+ def PUT(self, another_string):
+ cherrypy.session['mystring'] = another_string
+
+ def DELETE(self):
+ cherrypy.session.pop('mystring', None)
+
+
+ if __name__ == '__main__':
+ conf = {
+ '/': {
+ 'tools.sessions.on': True,
+ 'tools.staticdir.root': os.path.abspath(os.getcwd())
+ },
+ '/generator': {
+ 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
+ 'tools.response_headers.on': True,
+ 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
+ },
+ '/static': {
+ 'tools.staticdir.on': True,
+ 'tools.staticdir.dir': './public'
+ }
+ }
+ webapp = StringGenerator()
+ webapp.generator = StringGeneratorWebService()
+ cherrypy.quickstart(webapp, '/', conf)
Save this into a file named `tut08.py` and run it as follows:
@@ -718,7 +734,7 @@ Save this into a file named `tut08.py` and run it as follows:
$ python tut08.py
-Go to http://127.0.0.1:8080/ and play with the input and buttons
+Go to http://127.0.0.1:8080/ and play with the input and buttons
to generate, replace or delete the strings. Notice how the page
isn't refreshed, simply part of its content.
@@ -731,10 +747,10 @@ could easily be used by non-HTML clients.
Tutorial 9: Data is all my life
###############################
-Until now, all the generated strings were saved in the
+Until now, all the generated strings were saved in the
session, which by default is stored in the process memory. Though,
you can persist sessions on disk or in a distributed memory store,
-this is not the right way of keeping your data on the long run.
+this is not the right way of keeping your data on the long run.
Sessions are there to identify your user and carry as little
amount of data as necessary for the operation carried by the user.
@@ -748,11 +764,11 @@ There exist many to choose from with various paradigm support:
- graph-oriented: neo4j
Let's focus on the relational ones since they are the most common
-and probably what you will want to learn first.
+and probably what you will want to learn first.
For the sake of reducing the number of dependencies for these
tutorials, we will go for the :mod:`sqlite` database which
-is directly supported by Python.
+is directly supported by Python.
Our application will replace the storage of the generated
string from the session to a SQLite database. The application
@@ -762,93 +778,97 @@ So let's simply focus on the application code itself:
.. code-block:: python
:linenos:
- import os, os.path
- import random
- import sqlite3
- import string
- import time
+ import os, os.path
+ import random
+ import sqlite3
+ import string
+ import time
+
+ import cherrypy
- import cherrypy
+ DB_STRING = "my.db"
- DB_STRING = "my.db"
- class StringGenerator(object):
+ class StringGenerator(object):
@cherrypy.expose
def index(self):
- return file('index.html')
-
- class StringGeneratorWebService(object):
- exposed = True
-
- @cherrypy.tools.accept(media='text/plain')
- def GET(self):
- with sqlite3.connect(DB_STRING) as c:
- cherrypy.session['ts'] = time.time()
- r = c.execute("SELECT value FROM user_string WHERE session_id=?",
- [cherrypy.session.id])
- return r.fetchone()
-
- def POST(self, length=8):
- some_string = ''.join(random.sample(string.hexdigits, int(length)))
- with sqlite3.connect(DB_STRING) as c:
- cherrypy.session['ts'] = time.time()
- c.execute("INSERT INTO user_string VALUES (?, ?)",
- [cherrypy.session.id, some_string])
- return some_string
-
- def PUT(self, another_string):
- with sqlite3.connect(DB_STRING) as c:
- cherrypy.session['ts'] = time.time()
- c.execute("UPDATE user_string SET value=? WHERE session_id=?",
- [another_string, cherrypy.session.id])
-
- def DELETE(self):
- cherrypy.session.pop('ts', None)
- with sqlite3.connect(DB_STRING) as c:
- c.execute("DELETE FROM user_string WHERE session_id=?",
- [cherrypy.session.id])
-
- def setup_database():
- """
- Create the `user_string` table in the database
- on server startup
- """
- with sqlite3.connect(DB_STRING) as con:
- con.execute("CREATE TABLE user_string (session_id, value)")
-
- def cleanup_database():
- """
- Destroy the `user_string` table from the database
- on server shutdown.
- """
- with sqlite3.connect(DB_STRING) as con:
- con.execute("DROP TABLE user_string")
-
- if __name__ == '__main__':
- conf = {
- '/': {
- 'tools.sessions.on': True,
- 'tools.staticdir.root': os.path.abspath(os.getcwd())
- },
- '/generator': {
- 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
- 'tools.response_headers.on': True,
- 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
- },
- '/static': {
- 'tools.staticdir.on': True,
- 'tools.staticdir.dir': './public'
- }
- }
-
- cherrypy.engine.subscribe('start', setup_database)
- cherrypy.engine.subscribe('stop', cleanup_database)
-
- webapp = StringGenerator()
- webapp.generator = StringGeneratorWebService()
- cherrypy.quickstart(webapp, '/', conf)
+ return open('index.html')
+
+
+ @cherrypy.expose
+ class StringGeneratorWebService(object):
+
+ @cherrypy.tools.accept(media='text/plain')
+ def GET(self):
+ with sqlite3.connect(DB_STRING) as c:
+ cherrypy.session['ts'] = time.time()
+ r = c.execute("SELECT value FROM user_string WHERE session_id=?",
+ [cherrypy.session.id])
+ return r.fetchone()
+
+ def POST(self, length=8):
+ some_string = ''.join(random.sample(string.hexdigits, int(length)))
+ with sqlite3.connect(DB_STRING) as c:
+ cherrypy.session['ts'] = time.time()
+ c.execute("INSERT INTO user_string VALUES (?, ?)",
+ [cherrypy.session.id, some_string])
+ return some_string
+
+ def PUT(self, another_string):
+ with sqlite3.connect(DB_STRING) as c:
+ cherrypy.session['ts'] = time.time()
+ c.execute("UPDATE user_string SET value=? WHERE session_id=?",
+ [another_string, cherrypy.session.id])
+
+ def DELETE(self):
+ cherrypy.session.pop('ts', None)
+ with sqlite3.connect(DB_STRING) as c:
+ c.execute("DELETE FROM user_string WHERE session_id=?",
+ [cherrypy.session.id])
+ def setup_database():
+ """
+ Create the `user_string` table in the database
+ on server startup
+ """
+ with sqlite3.connect(DB_STRING) as con:
+ con.execute("CREATE TABLE user_string (session_id, value)")
+
+
+ def cleanup_database():
+ """
+ Destroy the `user_string` table from the database
+ on server shutdown.
+ """
+ with sqlite3.connect(DB_STRING) as con:
+ con.execute("DROP TABLE user_string")
+
+
+ if __name__ == '__main__':
+ conf = {
+ '/': {
+ 'tools.sessions.on': True,
+ 'tools.staticdir.root': os.path.abspath(os.getcwd())
+ },
+ '/generator': {
+ 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
+ 'tools.response_headers.on': True,
+ 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
+ },
+ '/static': {
+ 'tools.staticdir.on': True,
+ 'tools.staticdir.dir': './public'
+ }
+ }
+
+ cherrypy.engine.subscribe('start', setup_database)
+ cherrypy.engine.subscribe('stop', cleanup_database)
+
+ webapp = StringGenerator()
+ webapp.generator = StringGeneratorWebService()
+ cherrypy.quickstart(webapp, '/', conf)
+
Save this into a file named `tut09.py` and run it as follows:
.. code-block:: bash
@@ -857,14 +877,14 @@ Save this into a file named `tut09.py` and run it as follows:
Let's first see how we create two functions that create
and destroy the table within our database. These functions
-are registered to the CherryPy's server on lines 76-77,
+are registered to the CherryPy's server on lines 85-86,
so that they are called when the server starts and stops.
Next, notice how we replaced all the session code with calls
to the database. We use the session id to identify the
user's string within our database. Since the session will go
away after a while, it's probably not the right approach.
-A better idea would be to associate the user's login or
+A better idea would be to associate the user's login or
more resilient unique identifier. For the sake of our
demo, this should do.
@@ -879,17 +899,17 @@ demo, this should do.
.. note::
Unfortunately, sqlite in Python forbids us
- to share a connection between threads. Since CherryPy is a
+ to share a connection between threads. Since CherryPy is a
multi-threaded server, this would be an issue. This is the
reason why we open and close a connection to the database
on each call. This is clearly not really production friendly,
and it is probably advisable to either use a more capable
- database engine or a higher level library, such as
+ database engine or a higher level library, such as
`SQLAlchemy <http://sqlalchemy.readthedocs.org>`_, to better
support your application's needs.
.. _tut10:
-
+
Tutorial 10: Make it a modern single-page application with React.js
###################################################################
@@ -915,14 +935,15 @@ First, let's see how our HTML code has changed:
<link href="/static/css/style.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="generator"></div>
- <script type="text/javascript" src="static/js/gen.js"></script>
+ <script type="text/babel" src="static/js/gen.js"></script>
</body>
</html>
-Basically, we have remove the entire Javascript code that was using jQuery.
+Basically, we have removed the entire Javascript code that was using jQuery.
Instead, we load the React.js library as well as a new, local,
Javascript module, named ``gen.js`` and located in the ``public/js``
directory:
@@ -930,164 +951,163 @@ directory:
.. code-block:: javascript
:linenos:
- var StringGeneratorBox = React.createClass({
- handleGenerate: function() {
- var length = this.state.length;
- this.setState(function() {
- $.ajax({
- url: this.props.url,
- dataType: 'text',
- type: 'POST',
- data: {
- "length": length
- },
- success: function(data) {
- this.setState({
- length: length,
- string: data,
- mode: "edit"
- });
- }.bind(this),
- error: function(xhr, status, err) {
- console.error(this.props.url,
- status, err.toString()
- );
- }.bind(this)
- });
- });
- },
- handleEdit: function() {
- var new_string = this.state.string;
- this.setState(function() {
- $.ajax({
- url: this.props.url,
- type: 'PUT',
- data: {
- "another_string": new_string
- },
- success: function() {
- this.setState({
- length: new_string.length,
- string: new_string,
- mode: "edit"
- });
- }.bind(this),
- error: function(xhr, status, err) {
- console.error(this.props.url,
- status, err.toString()
- );
- }.bind(this)
- });
- });
- },
- handleDelete: function() {
- this.setState(function() {
- $.ajax({
- url: this.props.url,
- type: 'DELETE',
- success: function() {
- this.setState({
- length: "8",
- string: "",
- mode: "create"
- });
- }.bind(this),
- error: function(xhr, status, err) {
- console.error(this.props.url,
- status, err.toString()
- );
- }.bind(this)
- });
- });
- },
- handleLengthChange: function(length) {
- this.setState({
- length: length,
- string: "",
- mode: "create"
- });
- },
- handleStringChange: function(new_string) {
- this.setState({
- length: new_string.length,
- string: new_string,
- mode: "edit"
- });
- },
- getInitialState: function() {
- return {
- length: "8",
- string: "",
- mode: "create"
- };
- },
- render: function() {
- return (
- <div className="stringGenBox">
- <StringGeneratorForm onCreateString={this.handleGenerate}
- onReplaceString={this.handleEdit}
- onDeleteString={this.handleDelete}
- onLengthChange={this.handleLengthChange}
- onStringChange={this.handleStringChange}
- mode={this.state.mode}
- length={this.state.length}
- string={this.state.string}/>
- </div>
- );
- }
- });
-
- var StringGeneratorForm = React.createClass({
- handleCreate: function(e) {
- e.preventDefault();
- this.props.onCreateString();
- },
- handleReplace: function(e) {
- e.preventDefault();
- this.props.onReplaceString();
- },
- handleDelete: function(e) {
- e.preventDefault();
- this.props.onDeleteString();
- },
- handleLengthChange: function(e) {
- e.preventDefault();
- var length = React.findDOMNode(this.refs.length).value.trim();
- this.props.onLengthChange(length);
- },
- handleStringChange: function(e) {
- e.preventDefault();
- var string = React.findDOMNode(this.refs.string).value.trim();
- this.props.onStringChange(string);
- },
- render: function() {
- if (this.props.mode == "create") {
- return (
- <div>
- <input type="text" ref="length" defaultValue="8" value={this.props.length} onChange={this.handleLengthChange} />
- <button onClick={this.handleCreate}>Give it now!</button>
- </div>
- );
- } else if (this.props.mode == "edit") {
- return (
- <div>
- <input type="text" ref="string" value={this.props.string} onChange={this.handleStringChange} />
- <button onClick={this.handleReplace}>Replace</button>
- <button onClick={this.handleDelete}>Delete it</button>
- </div>
- );
- }
-
- return null;
- }
- });
-
- React.render(
- <StringGeneratorBox url="/generator" />,
- document.getElementById('generator')
- );
-
-
+ var StringGeneratorBox = React.createClass({
+ handleGenerate: function() {
+ var length = this.state.length;
+ this.setState(function() {
+ $.ajax({
+ url: this.props.url,
+ dataType: 'text',
+ type: 'POST',
+ data: {
+ "length": length
+ },
+ success: function(data) {
+ this.setState({
+ length: length,
+ string: data,
+ mode: "edit"
+ });
+ }.bind(this),
+ error: function(xhr, status, err) {
+ console.error(this.props.url,
+ status, err.toString()
+ );
+ }.bind(this)
+ });
+ });
+ },
+ handleEdit: function() {
+ var new_string = this.state.string;
+ this.setState(function() {
+ $.ajax({
+ url: this.props.url,
+ type: 'PUT',
+ data: {
+ "another_string": new_string
+ },
+ success: function() {
+ this.setState({
+ length: new_string.length,
+ string: new_string,
+ mode: "edit"
+ });
+ }.bind(this),
+ error: function(xhr, status, err) {
+ console.error(this.props.url,
+ status, err.toString()
+ );
+ }.bind(this)
+ });
+ });
+ },
+ handleDelete: function() {
+ this.setState(function() {
+ $.ajax({
+ url: this.props.url,
+ type: 'DELETE',
+ success: function() {
+ this.setState({
+ length: "8",
+ string: "",
+ mode: "create"
+ });
+ }.bind(this),
+ error: function(xhr, status, err) {
+ console.error(this.props.url,
+ status, err.toString()
+ );
+ }.bind(this)
+ });
+ });
+ },
+ handleLengthChange: function(length) {
+ this.setState({
+ length: length,
+ string: "",
+ mode: "create"
+ });
+ },
+ handleStringChange: function(new_string) {
+ this.setState({
+ length: new_string.length,
+ string: new_string,
+ mode: "edit"
+ });
+ },
+ getInitialState: function() {
+ return {
+ length: "8",
+ string: "",
+ mode: "create"
+ };
+ },
+ render: function() {
+ return (
+ <div className="stringGenBox">
+ <StringGeneratorForm onCreateString={this.handleGenerate}
+ onReplaceString={this.handleEdit}
+ onDeleteString={this.handleDelete}
+ onLengthChange={this.handleLengthChange}
+ onStringChange={this.handleStringChange}
+ mode={this.state.mode}
+ length={this.state.length}
+ string={this.state.string}/>
+ </div>
+ );
+ }
+ });
+
+ var StringGeneratorForm = React.createClass({
+ handleCreate: function(e) {
+ e.preventDefault();
+ this.props.onCreateString();
+ },
+ handleReplace: function(e) {
+ e.preventDefault();
+ this.props.onReplaceString();
+ },
+ handleDelete: function(e) {
+ e.preventDefault();
+ this.props.onDeleteString();
+ },
+ handleLengthChange: function(e) {
+ e.preventDefault();
+ var length = React.findDOMNode(this.refs.length).value.trim();
+ this.props.onLengthChange(length);
+ },
+ handleStringChange: function(e) {
+ e.preventDefault();
+ var string = React.findDOMNode(this.refs.string).value.trim();
+ this.props.onStringChange(string);
+ },
+ render: function() {
+ if (this.props.mode == "create") {
+ return (
+ <div>
+ <input type="text" ref="length" defaultValue="8" value={this.props.length} onChange={this.handleLengthChange} />
+ <button onClick={this.handleCreate}>Give it now!</button>
+ </div>
+ );
+ } else if (this.props.mode == "edit") {
+ return (
+ <div>
+ <input type="text" ref="string" value={this.props.string} onChange={this.handleStringChange} />
+ <button onClick={this.handleReplace}>Replace</button>
+ <button onClick={this.handleDelete}>Delete it</button>
+ </div>
+ );
+ }
+
+ return null;
+ }
+ });
+
+ React.render(
+ <StringGeneratorBox url="/generator" />,
+ document.getElementById('generator')
+ );
+
Wow! What a lot of code for something so simple, isn't it?
The entry point is the last few lines where we indicate that we
want to render the HTML code of the ``StringGeneratorBox`` React.js
@@ -1114,7 +1134,7 @@ Tutorial 11: Organize my code
CherryPy comes with a powerful architecture
that helps you organizing your code in a way that should make
-it easier to maintain and more flexible.
+it easier to maintain and more flexible.
Several mechanisms are at your disposal, this tutorial will focus
on the three main ones:
@@ -1131,7 +1151,7 @@ In order to understand them, let's imagine you are at a superstore:
to make sure sections are always in order (this is your backend)
In spite of being really simplistic, this is not far from how your
-application behaves. CherryPy helps you structure your application
+application behaves. CherryPy helps you structure your application
in a way that mirrors these high-level ideas.
Dispatchers
@@ -1160,7 +1180,7 @@ only for a specific category of customers. CherryPy will deal
with such use case via a mechanism called a :ref:`tool <tools>`.
A tool is a piece of code that runs on a per-request
-basis in order to perform additional work. Usually a tool is a
+basis in order to perform additional work. Usually a tool is a
simple Python function that is executed at a given point during
the process of the request by CherryPy.
@@ -1173,10 +1193,8 @@ the stock and deal with any customers' expectation.
In the CherryPy world, this translates into having functions
that run outside of any request life-cycle. These functions should
take care of background tasks, long lived connections (such as
-those to a database for instance), etc.
+those to a database for instance), etc.
-:ref:`Plugins <busplugins>` are called that way because
-they work along with the CherryPy :ref:`engine <cpengine>`
+:ref:`Plugins <busplugins>` are called that way because
+they work along with the CherryPy :ref:`engine <cpengine>`
and extend it with your operations.
-
-
diff --git a/docs/util/convert-trac.py b/docs/util/convert-trac.py
deleted file mode 100644
index ebb77d42..00000000
--- a/docs/util/convert-trac.py
+++ /dev/null
@@ -1,134 +0,0 @@
-#!python
-
-"""
-%prog <filename>
-
-A utility script for performing some commonly-encountered patterns in
-Trac Wiki format into reStructuredText (rst).
-
-filename is the name of the text file to be saved. If -U is not used,
-the file is converted in-place and filename is also the name of the
-source.
-"""
-
-from __future__ import print_function
-import sys
-import re
-import inspect
-import optparse
-import shutil
-import urllib2
-from StringIO import StringIO
-
-
-def get_options():
- global options
- parser = optparse.OptionParser(usage=inspect.cleandoc(__doc__))
- parser.add_option('-U', '--url',
- help="Trac URL from which to retrieve source")
- options, args = parser.parse_args()
- try:
- options.filename = args.pop()
- except IndexError:
- parser.error("Filename required")
-
-# each of the replacement functions should have a docstring
-# which is a regular expression to be matched.
-
-
-def replace_external_link(matcher):
- r"\[(?P<href>(?P<scheme>\w+)\://.+?) (?P<name>.+?)\]"
- return '`{name} <{href}>`_'.format(**matcher.groupdict())
-
-
-def replace_wiki_link(matcher):
- r"\[wiki\:(?P<ref>.+?) (?P<name>.+?)\]"
- return '`{name} <TODO-fix wiki target {ref}>`_'.format(
- **matcher.groupdict()
- )
-
-# character array indexed by level for characters
-heading_characters = [None, '*', '=', '-', '^']
-
-
-def replace_headings(matcher):
- r"^(?P<level>=+) (?P<name>.*) (?P=level)$"
- level = len(matcher.groupdict()['level'])
- char = heading_characters[level]
- name = matcher.groupdict()['name']
- lines = [name, char * len(name)]
- if level == 1:
- lines.insert(0, char * len(name))
- return '\n'.join(lines)
-
-
-def indent(block):
- add_indent = lambda s: ' ' + s
- lines = StringIO(block)
- i_lines = map(add_indent, lines)
- return ''.join(i_lines)
-
-
-def replace_inline_code(matcher):
- r"\{\{\{(?P<code>[^\n]*?)\}\}\}"
- return '``{code}``'.format(**matcher.groupdict())
-
-
-def replace_code_block(matcher):
- r"\{\{\{\n(?P<code>(.|\n)*?)^\}\}\}"
- return '::\n\n' + indent(matcher.groupdict()['code'])
-
-
-def replace_page_outline(matcher):
- r"\[\[PageOutline\]\]\n"
- return ''
-
-
-def replace_bang_symbols(matcher):
- r"!(?P<symbol>\w+)"
- return matcher.groupdict()['symbol']
-
-# a number of the files end in
-"""{{{
-#!html
-<h2 class='compatibility'>Older versions</h2>
-}}}""" # and everything after is garbage, so just remove it.
-
-
-def remove_2x_compat_notes(matcher):
- r"\{\{\{\n#!html\n<h2(.|\n)*"
- return ''
-
-replacements = [remove_2x_compat_notes] + \
- [func for name,
- func in globals().items() if name.startswith('replace_')]
-
-
-def normalize_linebreaks(text):
- return text.replace('\r\n', '\n')
-
-
-def convert_file():
- filename = options.filename
- if options.url:
- text = urllib2.urlopen(options.url).read()
- text = normalize_linebreaks(text)
- else:
- shutil.copy(filename, filename + '.bak')
- text = open(filename).read()
- # iterate over each of the replacements and execute it
- new_text = text
- for repl in replacements:
- pattern = re.compile(inspect.getdoc(repl), re.MULTILINE)
- new_text = pattern.sub(repl, new_text)
-
- open(filename, 'w').write(new_text)
- print("done")
-
-
-def handle_command_line():
- get_options()
- convert_file()
-
-if __name__ == '__main__':
- handle_command_line()
diff --git a/docs/util/test-doc.py b/docs/util/test-doc.py
deleted file mode 100644
index 3d06da99..00000000
--- a/docs/util/test-doc.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from __future__ import print_function
-import sys
-import inspect
-import docutils.utils
-import docutils.parsers.rst
-from StringIO import StringIO
-
-
-def print_with_line_numbers(block):
- stream = StringIO(block)
- for number, line in enumerate(stream):
- number += 1
- print(number, line.rstrip())
-
-target_class_spec = sys.argv[1]
-import cherrypy
-target_class = eval(target_class_spec)
-source = inspect.getdoc(target_class)
-print_with_line_numbers(source)
-parser = docutils.parsers.rst.Parser()
-settings = None # ?
-document = docutils.utils.new_document(source, settings)
-parser.parse(source, document)
diff --git a/make-sdist b/make-sdist
deleted file mode 100644
index 0d2f57e4..00000000
--- a/make-sdist
+++ /dev/null
@@ -1,2 +0,0 @@
-rm MANIFEST
-python setup.py sdist
diff --git a/man/cherryd.1 b/man/cherryd.1
index cf27a360..1811660a 100644
--- a/man/cherryd.1
+++ b/man/cherryd.1
@@ -108,7 +108,7 @@ server.socket_host = "0.0.0.0"
.br
server.socket_port = 8008
.br
-engine.autoreload_on = False
+engine.autoreload.on = False
.br
.UNINDENT
@@ -184,7 +184,7 @@ These are the built\-in environment configurations:
.INDENT 0.0
.INDENT 3.5
-\'engine.autoreload_on\': False,
+\'engine.autoreload.on\': False,
.br
\'checker.on\': False,
.br
@@ -260,4 +260,4 @@ cherrypy.org
This man page is placed in the public domain
.\" Generated by docutils manpage writer on 2009-06-15 15:07.
-.\"
+.\"
diff --git a/pytest.ini b/pytest.ini
new file mode 100644
index 00000000..09493bf6
--- /dev/null
+++ b/pytest.ini
@@ -0,0 +1,4 @@
+[pytest]
+norecursedirs=dist build .tox
+addopts=-v -rxs --junitxml=junit-test-results.xml --cov=cherrypy --cov-report term-missing:skip-covered --cov-report xml
+doctest_optionflags=ALLOW_UNICODE ELLIPSIS
diff --git a/setup.cfg b/setup.cfg
index 13afd86f..f34fe3d2 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,24 +1,9 @@
-[bumpversion]
-current_version = 5.2.0
-commit = True
-tag = True
-
[aliases]
-clean_egg_info = egg_info -RDb ''
-release = clean_egg_info sdist bdist_wheel
-
-[sdist]
-formats = gztar,zip
-
-[nosetests]
-where = cherrypy
-logging-filter = cherrypy
-verbosity = 2
-nocapture = True
-
-[egg_info]
-tag_build = .post
-tag_date = 1
+release = sdist bdist_wheel
+test = pytest
-[bumpversion:file:setup.py]
+[metadata]
+license_file = LICENSE.md
+[wheel]
+universal = 1
diff --git a/setup.py b/setup.py
index d4267e09..b3ab3cb6 100644..100755
--- a/setup.py
+++ b/setup.py
@@ -1,135 +1,106 @@
-"""Installs CherryPy using distutils
+#! /usr/bin/env python
+"""CherryPy package setuptools installer."""
-Run:
- python setup.py install
+import io
-to install this package.
-"""
-
-try:
- from setuptools import setup
-except ImportError:
- from distutils.core import setup
-
-from distutils.command.install import INSTALL_SCHEMES
-from distutils.command.build_py import build_py
-import sys
-import re
-
-
-class cherrypy_build_py(build_py):
- """Custom version of build_py that excludes Python-specific modules"""
-
- def build_module(self, module, module_file, package):
- python3 = sys.version_info >= (3,)
- if python3:
- exclude_pattern = re.compile('wsgiserver2|ssl_pyopenssl|'
- '_cpcompat_subprocess')
- else:
- exclude_pattern = re.compile('wsgiserver3')
- if exclude_pattern.match(module):
- return # skip it
- return build_py.build_module(self, module, module_file, package)
+import setuptools
###############################################################################
# arguments for the setup command
###############################################################################
-name = "CherryPy"
-version = "5.2.0"
-desc = "Object-Oriented HTTP framework"
-long_desc = "CherryPy is a pythonic, object-oriented HTTP framework"
+name = 'CherryPy'
+desc = 'Object-Oriented HTTP framework'
+
+with io.open('README.rst', encoding='utf-8') as strm:
+ long_desc = strm.read()
+
classifiers = [
- "Development Status :: 5 - Production/Stable",
- "Environment :: Web Environment",
- "Intended Audience :: Developers",
- "License :: Freely Distributable",
- "Operating System :: OS Independent",
- "Framework :: CherryPy",
- "License :: OSI Approved :: BSD License",
- "Programming Language :: Python",
- "Programming Language :: Python :: 2",
- "Programming Language :: Python :: 2.6",
- "Programming Language :: Python :: 2.7",
- "Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.1",
- "Programming Language :: Python :: 3.2",
- "Programming Language :: Python :: 3.3",
- "Programming Language :: Python :: 3.4",
- "Programming Language :: Python :: 3.5",
- "Programming Language :: Python :: Implementation",
- "Programming Language :: Python :: Implementation :: CPython",
- "Programming Language :: Python :: Implementation :: Jython",
- "Programming Language :: Python :: Implementation :: PyPy",
- "Topic :: Internet :: WWW/HTTP",
- "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
- "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
- "Topic :: Internet :: WWW/HTTP :: WSGI",
- "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
- "Topic :: Internet :: WWW/HTTP :: WSGI :: Server",
- "Topic :: Software Development :: Libraries :: Application Frameworks",
+ 'Development Status :: 5 - Production/Stable',
+ 'Environment :: Web Environment',
+ 'Intended Audience :: Developers',
+ 'License :: Freely Distributable',
+ 'Operating System :: OS Independent',
+ 'Framework :: CherryPy',
+ 'License :: OSI Approved :: BSD License',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: Implementation',
+ 'Programming Language :: Python :: Implementation :: CPython',
+ 'Programming Language :: Python :: Implementation :: Jython',
+ 'Programming Language :: Python :: Implementation :: PyPy',
+ 'Topic :: Internet :: WWW/HTTP',
+ 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
+ 'Topic :: Internet :: WWW/HTTP :: HTTP Servers',
+ 'Topic :: Internet :: WWW/HTTP :: WSGI',
+ 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
+ 'Topic :: Internet :: WWW/HTTP :: WSGI :: Server',
+ 'Topic :: Software Development :: Libraries :: Application Frameworks',
]
-author = "CherryPy Team"
-author_email = "team@cherrypy.org"
-url = "http://www.cherrypy.org"
-cp_license = "BSD"
+author = 'CherryPy Team'
+author_email = 'team@cherrypy.org'
+url = 'http://www.cherrypy.org'
+cp_license = 'BSD'
packages = [
- "cherrypy", "cherrypy.lib",
- "cherrypy.tutorial", "cherrypy.test",
- "cherrypy.process",
- "cherrypy.scaffold",
- "cherrypy.wsgiserver",
+ 'cherrypy', 'cherrypy.lib',
+ 'cherrypy.tutorial', 'cherrypy.test',
+ 'cherrypy.process',
+ 'cherrypy.scaffold',
]
-data_files = [
- ('cherrypy', ['cherrypy/cherryd',
- 'cherrypy/favicon.ico',
- 'cherrypy/LICENSE.txt',
- ]),
- ('cherrypy/process', []),
- ('cherrypy/scaffold', ['cherrypy/scaffold/example.conf',
- 'cherrypy/scaffold/site.conf',
- ]),
- ('cherrypy/scaffold/static', [
- 'cherrypy/scaffold/static/made_with_cherrypy_small.png']),
- ('cherrypy/test', ['cherrypy/test/style.css',
- 'cherrypy/test/test.pem',
- ]),
- ('cherrypy/test/static', ['cherrypy/test/static/index.html',
- 'cherrypy/test/static/dirback.jpg', ]),
- ('cherrypy/tutorial',
- [
- 'cherrypy/tutorial/tutorial.conf',
- 'cherrypy/tutorial/README.txt',
- 'cherrypy/tutorial/pdf_file.pdf',
- 'cherrypy/tutorial/custom_error.html',
- ]
- ),
-]
-scripts = ["cherrypy/cherryd"]
-cmd_class = dict(
- build_py=cherrypy_build_py,
-)
+# install requirements must not contain namespace
+# packages. See #1673
+install_requires = [
+ 'six>=1.11.0',
+ 'cheroot>=5.9.1',
+ 'portend>=2.1.1',
+]
-if sys.version_info >= (3, 0):
- required_python_version = '3.1'
-else:
- required_python_version = '2.6'
+extras_require = {
+ 'docs': [
+ 'sphinx',
+ 'docutils',
+ 'alabaster',
+ 'rst.linker>=1.9',
+ 'jaraco.packaging>=3.2',
+ ],
+ 'json': ['simplejson'],
+ 'routes_dispatcher': ['routes>=2.3.1'],
+ 'ssl': ['pyOpenSSL'],
+ 'testing': [
+ 'coverage', # inspects tests coverage
+ 'codecov', # sends tests coverage to codecov.io
+
+ # cherrypy.lib.gctools
+ 'objgraph',
+
+ 'pytest>=2.8',
+ 'pytest-cov',
+ 'pytest-sugar',
+ 'backports.unittest_mock',
+ 'path.py',
+ ],
+ # Enables memcached session support via `cherrypy[memcached_session]`:
+ 'memcached_session': ['python-memcached>=1.58'],
+ 'xcgi': ['flup'],
+
+ # http://docs.cherrypy.org/en/latest/advanced.html?highlight=windows#windows-console-events
+ ':sys_platform == "win32"': ['pypiwin32'],
+}
+"""Feature flags end-users can use in dependencies"""
###############################################################################
# end arguments for setup
###############################################################################
-# wininst may install data_files in Python/x.y instead of the cherrypy package.
-# Django's solution is at http://code.djangoproject.com/changeset/8313
-# See also
-# http://mail.python.org/pipermail/distutils-sig/2004-August/004134.html
-if 'bdist_wininst' in sys.argv or '--format=wininst' in sys.argv:
- data_files = [(r'\PURELIB\%s' % path, files) for path, files in data_files]
-
setup_params = dict(
name=name,
- version=version,
+ use_scm_version=True,
description=desc,
long_description=long_desc,
classifiers=classifiers,
@@ -138,23 +109,21 @@ setup_params = dict(
url=url,
license=cp_license,
packages=packages,
- data_files=data_files,
- scripts=scripts,
- cmdclass=cmd_class,
+ entry_points={'console_scripts': ['cherryd = cherrypy.__main__:run']},
+ include_package_data=True,
+ install_requires=install_requires,
+ extras_require=extras_require,
+ setup_requires=[
+ 'setuptools_scm',
+ ],
+ python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*',
)
-def main():
- if sys.version < required_python_version:
- s = "I'm sorry, but %s %s requires Python %s or later."
- print(s % (name, version, required_python_version))
- sys.exit(1)
- # set default location for "data_files" to
- # platform specific "site-packages" location
- for scheme in list(INSTALL_SCHEMES.values()):
- scheme['data'] = scheme['purelib']
- setup(**setup_params)
+def main():
+ """Package installation entry point."""
+ setuptools.setup(**setup_params)
-if __name__ == "__main__":
+if __name__ == '__main__':
main()
diff --git a/tests/dist-check.py b/tests/dist-check.py
new file mode 100644
index 00000000..e4d614f0
--- /dev/null
+++ b/tests/dist-check.py
@@ -0,0 +1,59 @@
+"""
+Integration test to check the integrity of the
+distribution.
+
+This file is explicitly not named 'test_' to avoid
+being collected by pytest, but must instead be
+invoked explicitly (i.e. pytest tests/dist-check.py).
+
+This test cannot be invoked as part of the normal
+test suite nor can it be included in the normal test
+suite because it must import cherrypy late (after
+removing sys.path[0]).
+"""
+
+import os
+import sys
+
+import pytest
+
+
+@pytest.fixture(params=[
+ 'favicon.ico',
+ 'scaffold/static/made_with_cherrypy_small.png',
+ 'tutorial/tutorial.conf',
+ 'tutorial/custom_error.html',
+])
+def data_file_path(request):
+ 'generates data file paths expected to be found in the package'
+ return request.param
+
+
+@pytest.fixture(autouse=True, scope='session')
+def remove_sys_path_0():
+ 'pytest adds cwd to sys.path[0]'
+ print('removing', sys.path[0])
+ del sys.path[0]
+ assert 'cherrypy' not in sys.modules
+
+
+def test_data_files_installed(data_file_path):
+ """
+ Ensure that data file paths are available in the
+ installed package as expected.
+ """
+ import cherrypy
+ root = os.path.dirname(cherrypy.__file__)
+ fn = os.path.join(root, data_file_path)
+ assert os.path.exists(fn), fn
+ # make sure the file isn't in the local checkout
+ assert not os.path.samefile(fn, os.path.join('cherrypy', data_file_path))
+
+
+def test_sanity():
+ """
+ Test the test to show that it does fail when a file
+ is missing.
+ """
+ with pytest.raises(Exception):
+ test_data_files_installed('does not exist')
diff --git a/tox.ini b/tox.ini
index 2baa1fbd..b7331730 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,9 +1,45 @@
[tox]
-envlist = py26, py27, py32, py33, py34, py35, pypy
+envlist = python
[testenv]
-deps = nose
- mock
- Routes
+usedevelop = True
commands =
- nosetests -s []
+ pytest {posargs}
+ codecov -f coverage.xml -X gcov
+passenv =
+ WEBTEST_INTERACTIVE
+ CI
+ TRAVIS
+ TRAVIS_*
+ APPVEYOR
+ APPVEYOR_*
+setenv =
+ WEBTEST_INTERACTIVE=false
+extras =
+ testing
+ routes_dispatcher
+
+[testenv:cheroot-master]
+deps = git+git://github.com/cherrypy/cheroot.git@master#egg=cheroot
+
+[testenv:pre-commit]
+deps = pre-commit
+commands = pre-commit run --all-files {posargs}
+
+[testenv:pre-commit-pep257]
+deps = pre-commit
+commands =
+ pre-commit run --config .pre-commit-config-pep257.yaml --all-files {posargs}
+
+[testenv:dist-check]
+# ensure that package artifacts are installed as expected
+usedevelop = False
+commands =
+ pytest tests/dist-check.py {posargs}
+
+[testenv:setup-check]
+extras =
+ docs
+usedevelop = False
+commands =
+ python -m setup check --metadata --restructuredtext --strict --verbose
diff --git a/visuals/cherrypy_logo_big.png b/visuals/cherrypy_logo_big.png
index dc358119..aba0020e 100644
--- a/visuals/cherrypy_logo_big.png
+++ b/visuals/cherrypy_logo_big.png
Binary files differ
diff --git a/visuals/cherrypy_logo_small.jpg b/visuals/cherrypy_logo_small.jpg
index 744233a0..50b7362f 100644
--- a/visuals/cherrypy_logo_small.jpg
+++ b/visuals/cherrypy_logo_small.jpg
Binary files differ
diff --git a/visuals/made_with_cherrypy_big.png b/visuals/made_with_cherrypy_big.png
index d093a613..48f7703d 100644
--- a/visuals/made_with_cherrypy_big.png
+++ b/visuals/made_with_cherrypy_big.png
Binary files differ
diff --git a/visuals/made_with_cherrypy_small.png b/visuals/made_with_cherrypy_small.png
index c3aafeed..724f9d72 100644
--- a/visuals/made_with_cherrypy_small.png
+++ b/visuals/made_with_cherrypy_small.png
Binary files differ