2016-12-05 67 views
0

我想弄清楚如何自定義用cherrypy提供的靜態內容。用CherryPy自定義靜態內容

目標是當路徑以/ pub開始時按照正常方式提供文件,但當路徑以其他任何內容開始時,我想添加首先檢查訪問的自定義函數。

該文檔給我足夠的。這是我到目前爲止...

import cherrypy 
from cherrypy.lib.static import serve_file 
class Root(object): 
    # Somehow turn this into a handler for all files 
    def page(self): 
     if authorized(): # Check whether authenticated user may access the requested path 
      file_location = .... # Work out file location from request 
      print("Serving file from %s" % file_location) 
      return serve_file(file_location) 
     else: 
      return "Not Authorized" 

if __name__ == '__main__': 
    serve_conf = {'/': {'tools.gzip.on': True}, 
        '/pub': { 
         'tools.staticdir.on': True, 
         'tools.staticdir.dir': "/data/public", 
         'tools.staticdir.debug': True, 
         'log.screen': True 
         }, 
        '/secure': { "PROBABLY CONFIGURE THE HANDLER HERE" } 
        } 
    cherrypy.quickstart(Root(), config=serve_conf) 

回答

0

我有或多或少的痛苦的嘗試和錯誤。這是我的第一個「工具」

from os.path import basename 

import cherrypy 
import os 

from cherrypy import Tool 
from validator.util import validate_bearer_header 

# Returns the "signing secret" file from the handler application 
def get_signing_secret(*args): 
    signing_secret = cherrypy.request.app.cdn_signing_secret 
    return signing_secret 

# A tool that can be used to "protect" resources that requires authentication 
def protect(*args): 
    subject_resource = basename(cherrypy.request.path_info) 
    supplied_auth = cherrypy.request.headers.get("Authorization", None) 
    if not supplied_auth: 
     raise cherrypy.HTTPError("401 Not Authenticated") 
    token_test_result = validate_bearer_header(supplied_auth, get_signing_secret()) 
    if not token_test_result: 
     raise cherrypy.HTTPError("401 Not Authenticated") 
    if not token_test_result.get("sub") == subject_resource: 
     raise cherrypy.HTTPError("403 Unauthorized") 


class Root(object): 

    def __init__(self): 
     try: 
      with open(cherrypy.config["cdn_signingkey.filename"], 'r') as secretfile: 
       self.cdn_signing_secret = secretfile.read().replace('\n', '') 
      print("CDN signing secret obtained") 
     except: 
      print("ERROR reading CDN signing secret file") 
      raise 
     cherrypy.tools.protect = Tool('before_handler', protect) 

    # TODO Add exposed handlers to allow automated master/slave CDN file replication 


if __name__ == '__main__': 
    conf_file = os.path.join(os.path.dirname(__file__), 'cdn_server.conf') 
    cherrypy.config.update(conf_file) 
    cherrypy.quickstart(Root(), config=conf_file) 

,涉及到的應用程序在我的配置文件中的條目是:

[/] 
tools.gzip.on = True 

[/pub] 
tools.staticdir.on = True 
tools.staticdir.dir = "/data/cdn/public" 
tools.staticdir.debug = True 
log.screen = True 

[/secure]: 
tools.staticdir.on = True 
tools.staticdir.dir = "/data/cdn/secure" 
tools.staticdir.debug = True 
log.screen = True 
tools.protect.on = True 

我寧願定義get_signing_secret作爲應用類的成員,然後訪問self.cdn_signing_secret而不是上面的方法,但我無法弄清楚如何處理傳遞給工具的「自我」。

+0

請看[auth工具的例子](https://github.com/GDG-Ukraine/gdg.org.ua/blob/master/src/GDGUkraine/lib/tools/authorize.py),它使用類「cherrypy.Tool」和[正在通過簡單賦值註冊](https://github.com/GDG-Ukraine/gdg.org.ua/blob/master/src/GDGUkraine/lib/tools/__init__。 PY#L7)。我希望這會幫助你將你的代碼包裝到一個類中。 – webKnjaZ