mirror of
https://github.com/eternnoir/pyTelegramBotAPI.git
synced 2023-08-10 21:12:57 +03:00
Merge pull request #374 from the31k/per_thread_requests_sessions
Per-thread requests sessions
This commit is contained in:
commit
cb60a1256f
@ -18,7 +18,6 @@ from telebot import types
|
||||
from telebot import util
|
||||
|
||||
logger = telebot.logger
|
||||
req_session = requests.session()
|
||||
proxy = None
|
||||
|
||||
API_URL = "https://api.telegram.org/bot{0}/{1}"
|
||||
@ -28,6 +27,10 @@ CONNECT_TIMEOUT = 3.5
|
||||
READ_TIMEOUT = 9999
|
||||
|
||||
|
||||
def _get_req_session():
|
||||
return util.per_thread('req_session', lambda: requests.session())
|
||||
|
||||
|
||||
def _make_request(token, method_name, method='get', params=None, files=None, base_url=API_URL):
|
||||
"""
|
||||
Makes a request to the Telegram API.
|
||||
@ -47,7 +50,7 @@ def _make_request(token, method_name, method='get', params=None, files=None, bas
|
||||
if params:
|
||||
if 'timeout' in params: read_timeout = params['timeout'] + 10
|
||||
if 'connect-timeout' in params: connect_timeout = params['connect-timeout'] + 10
|
||||
result = req_session.request(method, request_url, params=params, files=files,
|
||||
result = _get_req_session().request(method, request_url, params=params, files=files,
|
||||
timeout=(connect_timeout, read_timeout), proxies=proxy)
|
||||
logger.debug("The server returned: '{0}'".format(result.text.encode('utf8')))
|
||||
return _check_result(method_name, result)['result']
|
||||
@ -97,7 +100,7 @@ def get_file(token, file_id):
|
||||
|
||||
def download_file(token, file_path):
|
||||
url = FILE_URL.format(token, file_path)
|
||||
result = req_session.get(url)
|
||||
result = _get_req_session().get(url)
|
||||
if result.status_code != 200:
|
||||
msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]' \
|
||||
.format(result.status_code, result.reason, result.text)
|
||||
|
@ -17,6 +17,9 @@ except ImportError:
|
||||
from telebot import logger
|
||||
|
||||
|
||||
thread_local = threading.local()
|
||||
|
||||
|
||||
class WorkerThread(threading.Thread):
|
||||
count = 0
|
||||
|
||||
@ -242,3 +245,12 @@ def extract_arguments(text):
|
||||
regexp = re.compile("\/\w*(@\w*)*\s*([\s\S]*)",re.IGNORECASE)
|
||||
result = regexp.match(text)
|
||||
return result.group(2) if is_command(text) else None
|
||||
|
||||
|
||||
def per_thread(key, construct_value):
|
||||
try:
|
||||
return getattr(thread_local, key)
|
||||
except AttributeError:
|
||||
value = construct_value()
|
||||
setattr(thread_local, key, value)
|
||||
return value
|
||||
|
Loading…
Reference in New Issue
Block a user