CherryPy对静态文件的访问限制

0 投票
1 回答
1101 浏览
提问于 2025-04-18 09:04

我有一个CherryPy服务器,它可以在/foosball这个路径下提供一些静态的HTML、JS等文件,同时通过REST API在根路径/下提供一些JSON数据。

import cherrypy

config = {
    'global': {
        'server.socket_host': '0.0.0.0',
        'server.socket_port': # my port here,
        'tools.json_in.on': True
    },
    '/foosball': {
        'tools.staticdir.on': True,
        'tools.staticdir.root': '/var/www/html',
        'tools.staticdir.dir': 'foosball',
        'tools.staticdir.index': 'index.html'
    }
}

@cherrypy.popargs('player_id')
class RESTClient_Player(object):
    # stuff

class RESTClient_Game(object):
    # stuff

class RESTClient:
    players = RESTClient_Player()
    games = RESTClient_Game()

    @cherrypy.expose
    def index(self):
        http_method = getattr(self, cherrypy.request.method)
        return (http_method)()

cherrypy.quickstart(RESTClient(), '/', config)

我还想对这些页面进行基本的访问限制保护,所以我在研究CherryPy提供的优秀教程

问题是,这份文档主要是针对那些动态生成的页面,也就是通过def语句明确声明的页面。我尝试过将文档中的内容应用到/foosball中的文件上,但没有成功。每次访问/foosball时,都会直接加载,而没有任何身份验证的请求。

我该怎么做才能给静态文件增加一些访问限制的功能呢?

谢谢!


编辑:有人建议我使用auth_tool。通过下面的配置块,我成功地给REST API部分加上了登录界面,但/foosball中的所有静态文件仍然可以自由访问:

def check_login_and_password(login, password):
    cherrypy.log(login)
    cherrypy.log(password)

    return

config = {
    'global': {
        'server.socket_host': '0.0.0.0',
        'server.socket_port': # my port here,
        'tools.json_in.on': True,
        'tools.sessions.on': True,
        'tools.session_auth.on': True,
        'tools.session_auth.check_username_and_password': check_login_and_password
    },
    '/foosball': {
        'tools.staticdir.on': True,
        'tools.staticdir.root': '/var/www/html',
        'tools.staticdir.dir': 'foosball',
        'tools.staticdir.index': 'index.html',
        'tools.sessions.on': True,
        'tools.session_auth.on': True,
        'tools.session_auth.check_username_and_password': check_login_and_password
    }
}

1 个回答

2

与其在你的配置中使用“staticdir”,不如在你的类里创建一个函数来返回静态文件。这样做的话,你就可以在这个函数周围加上身份验证。

import cherrypy
from cherrypy.lib.static import serve_file
import os

class Hello(object):
    @cherrypy.expose
    def index(self):
        return "Hello World"

    @cherrypy.expose
    def static(self, page):
        return serve_file(os.path.join(current_dir, 'static', page), content_type='text/html')


if __name__ == '__main__':
    current_dir = os.path.dirname(os.path.abspath(__file__))
    cherrypy.quickstart(Hello())

撰写回答