2016-12-05 5 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

나는 고통스런 시행 착오로 그것을 다소 해결했습니다.

[/] 
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 정의 선호 것이다 : 이것은 내 최초의 "도구"

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) 

응용 프로그램에 관한 내 config 파일의 항목입니다 위의 방법 대신 self.cdn_signing_secret에 액세스하십시오. 그러나 도구에 전달 된 "self"를 처리하는 방법을 이해할 수 없습니다.

+0

[인증 도구 예] (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