首页 > 解决方案 > 我应该在 Python 的 http 请求中使用共享会话吗?

问题描述

我正在调用其他人托管的 http 服务,我的代码如下:

def process_text(text):
    session = requests.Session()
    retry = Retry(connect=3, backoff_factor=0.5)
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)

    try:
        r = session.get(HTTP_URL, params={'text': text})
       
        r_json = r.json()
    except Exception as e:
        logger.error('Failed to request from http service: {}'.format(str(e)))
        return None

我有一个包含很多句子的文本文件,对于每个句子,我需要为每个句子调用“process_text”函数。我的问题是,我可以只在 process_text 之外创建一个“会话”对象,如下所示:

class Processor(object):
   def __init__(self):
        self.session = requests.Session()
        retry = Retry(connect=3, backoff_factor=0.5)
        adapter = HTTPAdapter(max_retries=retry)
        self.session.mount('http://', adapter)
        self.session.mount('https://', adapter)

   def process_text(self.text):
       
    
        try:
            r = self.session.get(HTTP_URL, params={'text': text})
           
            r_json = r.json()
        except Exception as e:
            logger.error('Failed to request from http service: {}'.format(str(e)))
            return None

或者必须为每个单独的请求创建会话?

标签: pythonhttppython-requests

解决方案


推荐阅读