Skip to content

Commit f728dc9

Browse files
author
Pietro Albini
committed
Reuse existing connections to Telegram when possible
botogram communicates with the Bot API a lot, and creating new HTTPS connections is all but cheap in terms of speed. By reusing existing connections (thanks to Keep-Alive), it's possible to make botogram faster than before.
1 parent cfc2740 commit f728dc9

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

botogram/api.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
Released under the MIT license
77
"""
88

9+
import os
10+
911
import requests
1012

1113

@@ -76,10 +78,23 @@ def __init__(self, api_key, endpoint=None):
7678
self._api_key = api_key
7779
self._endpoint = endpoint
7880

81+
self._session_cache = None
82+
self._session_pid = -1
83+
84+
def _session(self):
85+
"""Get the current requests session"""
86+
# Ensure a new session is created if the PID changes. This is because
87+
# sessions behaves badly if you use them after fork()
88+
if self._session_pid != os.getpid() or self._session_cache is None:
89+
self._session_cache = requests.Session()
90+
self._session_pid = os.getpid()
91+
92+
return self._session_cache
93+
7994
def call(self, method, params=None, files=None, expect=None):
8095
"""Call a method of the API"""
8196
url = self._endpoint + "bot%s/%s" % (self._api_key, method)
82-
response = requests.get(url, params=params, files=files)
97+
response = self._session().get(url, params=params, files=files)
8398
content = response.json()
8499

85100
if not content["ok"]:

docs/changelog/0.4.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
.. Copyright (c) 2016 Pietro Albini <[email protected]>
2+
Released under the MIT license
3+
4+
===========================
5+
Changelog of botogram 0.4.x
6+
===========================
7+
8+
Here you can find all the changes in the botogram 0.4.x releases.
9+
10+
.. _changelog-0.4:
11+
12+
botogram 0.4
13+
============
14+
15+
*Alpha release, not yet released.*
16+
17+
Release description not yet written.
18+
19+
Performance improvements
20+
------------------------
21+
22+
* botogram now tries to reuse existing connections to Telegram when possible

docs/changelog/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ Here you can see what changed in every botogram release.
1212
.. toctree::
1313
:maxdepth: 2
1414

15+
0.4
1516
0.3
1617
0.2
1718
0.1

0 commit comments

Comments
 (0)