CherryPy server name tag

后端 未结 3 2054
一向
一向 2021-01-12 08:42

When running a CherryPy app it will send server name tag something like CherryPy/version. Is it possible to rename/overwrite that from the app without modifying CherryPy so

3条回答
  •  孤独总比滥情好
    2021-01-12 09:18

    This string appears to be being set in the CherrPy Response class:

    def __init__(self):
      self.status = None
      self.header_list = None
      self._body = []
      self.time = time.time()
    
      self.headers = http.HeaderMap()
      # 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": http.HTTPDate(self.time),
      })
    

    So when you're creating your Response object, you can update the "Server" header to display your desired string. From the CherrPy Response Object documentation:

    headers

    A dictionary containing the headers of the response. You may set values in this dict anytime before the finalize phase, after which CherryPy switches to using header_list ...

    EDIT: To avoid needing to make this change with every response object you create, one simple way to get around this is to wrap the Response object. For example, you can create your own Response object that inherits from CherryPy's Response and updates the headers key after initializing:

    class MyResponse(Response):
    
        def __init__(self):
            Response.__init__(self)
            dict.update(self.headers, {
                "Server": "MyServer/1.0",
            })
    
    RespObject = MyResponse()
    print RespObject.headers["Server"]
    

    Then you can can call your object for uses where you need to create a Response object, and it will always have the Server header set to your desired string.

提交回复
热议问题