Search code examples
python-3.xbottle

Bottle: HEAD always falls back to GET, thus functions always executed twice?


I'm using Bottle to implement a web interface for a simple database system. As documented, Bottle handles HTTP HEAD requests by falling back to the corresponding GET route and cutting off the response body. However, in my experience, it means that the function attached to the GET route is executed both times in response to a GET request. This can be problematic if that function performs an operation that side-effects, such as a database operation.

Is there a way to prevent this double execution from happening? Or should I define a fake HEAD route for every GET route?


Solution

  • Update: It sounds like Bottle is working as designed (calling the function only once per request). Your browser is the apparent source of the HEAD requests.


    On HEAD requests, Bottle calls the method once, not twice. Can you demonstrate some code that shows the behaviour you're describing? When I run the following code, I see the "Called" line only once:

    from bottle import Bottle, request
    
    app = Bottle()
    
    @app.get("/")
    def home():
        print(f"Called: {request.method}")
        return "Some text\n"
    
    app.run()
    

    Output:

    $ curl --head http://127.0.0.1:8080/
    Called: HEAD
    HTTP/1.0 200 OK
    127.0.0.1 - - [13/Jan/2021 08:28:02] "HEAD / HTTP/1.1" 200 0
    Date: Wed, 13 Jan 2021 13:28:02 GMT
    Server: WSGIServer/0.2 CPython/3.8.6
    Content-Length: 10
    Content-Type: text/html; charset=UTF-8