python - 我应该在 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
或者必须为每个单独的请求创建会话?
解决方案
推荐阅读
- javascript - 用 webpack 中的字段值替换带有静态字段的对象
- json - React Native:将 console.log 输出记录为 JSON 发送到服务器
- sql - SQL - 从多个表中选择,其中一个没有结果
- linux - 更新环境变量linux后无法识别anaconda
- math - Divmod:一个 Elixir 函数中除法的商和余数
- java - 使用 XSLT 将 xml 转换为 csv 时,将逗号 ',' 替换为一个值
- android - ionic3 应用程序启动画面前的空白屏幕
- botframework - LUIS 无法理解不同的实体 [已编辑]
- python - Pandas 从现有数据框创建新数据框
- javascript - 插值中的 Angular 2 连接变量