Service

PyPtt.Service.__init__(self, pyptt_init_config: dict | None = None, call_interval: float = 0)

這是一個可以在多執行緒中使用的 PyPtt API 服務。

請注意:這僅僅只是 Thread Safe 的實作,對效能並不會有實質上的幫助。
如果你需要更好的效能,請在每一個線程都使用一個 PyPtt.API 物件。
參數:
  • pyptt_init_config (dict) -- PyPtt 初始化設定,請參考 初始化設定

  • call_interval (float) -- API 呼叫之間的最小時間間隔(秒),預設為 0(不限制)。

回傳:

None

範例:

from PyPtt import Service

def api_test(thread_id, service):

    result = service.call('get_time')
    print(f'thread id {thread_id}', 'get_time', result)

    result = service.call('get_aid_from_url', {'url': 'https://www.ptt.cc/bbs/Python/M.1565335521.A.880.html'})
    print(f'thread id {thread_id}', 'get_aid_from_url', result)

    result = service.call('get_newest_index', {'index_type': PyPtt.NewIndex.BOARD, 'board': 'Python'})
    print(f'thread id {thread_id}', 'get_newest_index', result)

if __name__ == '__main__':
    pyptt_init_config = {
        # 'language': PyPtt.Language.ENGLISH,
    }

    service = Service(pyptt_init_config, call_interval=0.5)

    try:
        service.call('login', {'ptt_id': 'YOUR_PTT_ID', 'ptt_pw': 'YOUR_PTT_PW'})

        pool = []
        for i in range(10):
            t = threading.Thread(target=api_test, args=(i, service))
            t.start()
            pool.append(t)

        for t in pool:
            t.join()

        service.call('logout')
    finally:
        service.close()
PyPtt.Service.set_call_interval(self, call_interval: float)

設定 API 呼叫之間的最小時間間隔。

參數:

call_interval (float) -- 最小時間間隔(秒),必須 >= 0。

回傳:

None