summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarcel Hellkamp <marcel.hellkamp@gwdg.de>2022-08-03 09:44:52 +0200
committerMarcel Hellkamp <marcel.hellkamp@gwdg.de>2022-08-03 09:44:52 +0200
commitd21be50c20fbd926a06becd51dbb382a537c1647 (patch)
tree1e48c69fcaebf45e80b795f7151771a2f344b28e
parent1677de087ee6517eb3f09a4cffe6f91758ef07ba (diff)
downloadbottle-d21be50c20fbd926a06becd51dbb382a537c1647.tar.gz
docs: Improve hooks/CORS recipe
-rwxr-xr-xdocs/recipes.rst42
1 files changed, 24 insertions, 18 deletions
diff --git a/docs/recipes.rst b/docs/recipes.rst
index 34315a6..dbd86bf 100755
--- a/docs/recipes.rst
+++ b/docs/recipes.rst
@@ -232,29 +232,35 @@ Supporting Gzip compression is not a straightforward proposition, due to a numbe
Because of these requirements, it is the recommendation of the Bottle project that Gzip compression is best handled by the WSGI server Bottle runs on top of. WSGI servers such as cherrypy_ provide a GzipFilter_ middleware that can be used to accomplish this.
-Using the hooks plugin
-----------------------
-
-For example, if you want to allow Cross-Origin Resource Sharing for
-the content returned by all of your URL, you can use the hook
-decorator and setup a callback function::
+Using hooks to handle CORS
+--------------------------
- from bottle import hook, response, route
+Hooks are useful to unconditionally do something before or after each
+request. For example, if you want to allow Cross-Origin requests for your
+entire application, instead of writing a :doc:`plugin <plugin>` you can
+use hooks to add the appropiate headers::
- @hook('after_request')
- def enable_cors():
- response.headers['Access-Control-Allow-Origin'] = '*'
+ from bottle import hook, response, HTTPResponse
- @route('/foo')
- def say_foo():
- return 'foo!'
+ cors_headers = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
+ # 'Access-Control-Allow-Headers': 'X-Token, ...',
+ # 'Access-Control-Expose-Headers': 'X-My-Custom-Header, ...',
+ # 'Access-Control-Max-Age': '86400',
+ # 'Access-Control-Allow-Credentials': 'true',
+ }
- @route('/bar')
- def say_bar():
- return {'type': 'friendly', 'content': 'Hi!'}
+ @hook('before_request')
+ def handle_options():
+ if request.method == 'OPTIONS':
+ # Bypass request routing and immediately return a response
+ raise HTTPResponse(headers=cors_headers)
-You can also use the ``before_request`` to take an action before
-every function gets called.
+ @hook('after_request')
+ def enable_cors():
+ for key, value in cors_headers.items():
+ response.set_header(key, value)
Using Bottle with Heroku