在pywb中重写函数而不更改代码源

2024-06-13 16:30:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python开发的新手,我正在使用PYWB库来重放web档案(warc文件)。你知道吗

我想修改pywb/warcserver/index中的函数,但不修改源代码。你知道吗

其思想是在保留原始代码源的同时修改一些特性。在不丢失更改的情况下更新代码源代码将非常有用。你知道吗

在pywb和python中如何实现这一点。你知道吗

要在indexsource.py文件中重写的函数是load_index

谢谢


Tags: 文件函数代码webindex源代码情况档案
1条回答
网友
1楼 · 发布于 2024-06-13 16:30:53

load_indexFileIndexSource类的方法。您可以在实例级别修改方法,而无需更改库的源代码。例如:

from pywb.utils.binsearch import iter_range
from pywb.utils.wbexception import NotFoundException
from pywb.warcserver.index.cdxobject import CDXObject
from pywb.utils.format import res_template

def modified_load_index(self, params):

    filename = res_template(self.filename_template, params)

    try:
        fh = open(filename, 'rb')
    except IOError:
        raise NotFoundException(filename)

    def do_load(fh):
        with fh:
            gen = iter_range(fh, params['key'], params['end_key'])
            for line in gen:
                yield CDXObject(line)

    # (... some modification on this method)
    return do_load(fh)

# Change the "load_index" method on the instance of FileIndexSource
my_file_index_source.load_index = modified_load_index

因此,每次在my_file_index_source上调用方法load_index,都将运行修改后的方法。你知道吗

另一种选择是创建一个新类,该类从FileIndexSource继承并覆盖load_index方法。你知道吗

相关问题 更多 >