From d21be50c20fbd926a06becd51dbb382a537c1647 Mon Sep 17 00:00:00 2001 From: Marcel Hellkamp Date: Wed, 3 Aug 2022 09:44:52 +0200 Subject: docs: Improve hooks/CORS recipe --- docs/recipes.rst | 42 ++++++++++++++++++++++++------------------ 1 file 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 ` 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 -- cgit v1.2.1