summaryrefslogtreecommitdiff
path: root/docs/recipes.rst
diff options
context:
space:
mode:
Diffstat (limited to 'docs/recipes.rst')
-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