Skip to content

Commit 4abcff7

Browse files
committed
Refactor InputFile to use urllib3 (python-telegram-bot#328)
1 parent 71fd795 commit 4abcff7

File tree

2 files changed

+6
-48
lines changed

2 files changed

+6
-48
lines changed

telegram/inputfile.py

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
import imghdr
3030
import mimetypes
3131
import os
32-
import sys
3332

3433
from telegram import TelegramError
3534

@@ -102,51 +101,6 @@ def content_type(self):
102101
"""
103102
return 'multipart/form-data; boundary=%s' % self.boundary
104103

105-
def to_form(self):
106-
"""
107-
Returns:
108-
str:
109-
"""
110-
form = []
111-
form_boundary = '--' + self.boundary
112-
113-
# Add data fields
114-
for name in iter(self.data):
115-
value = self.data[name]
116-
form.extend([
117-
form_boundary, 'Content-Disposition: form-data; name="%s"' % name, '', str(value)
118-
])
119-
120-
# Add input_file to upload
121-
form.extend([
122-
form_boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' %
123-
(self.input_name,
124-
self.filename), 'Content-Type: %s' % self.mimetype, '', self.input_file_content
125-
])
126-
127-
form.append('--' + self.boundary + '--')
128-
form.append('')
129-
130-
return self._parse(form)
131-
132-
@staticmethod
133-
def _parse(form):
134-
"""
135-
Returns:
136-
str:
137-
"""
138-
if sys.version_info > (3,):
139-
# on Python 3 form needs to be byte encoded
140-
encoded_form = []
141-
for item in form:
142-
try:
143-
encoded_form.append(item.encode())
144-
except AttributeError:
145-
encoded_form.append(item)
146-
147-
return b'\r\n'.join(encoded_form)
148-
return '\r\n'.join(form)
149-
150104
@staticmethod
151105
def is_image(stream):
152106
"""Check if the content file is an image by analyzing its headers.

telegram/utils/request.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from urllib3.connection import HTTPConnection
3232
from urllib3.util.timeout import Timeout
3333

34-
from telegram import (InputFile, TelegramError)
34+
from telegram import InputFile, TelegramError
3535
from telegram.error import (Unauthorized, NetworkError, TimedOut, BadRequest, ChatMigrated,
3636
RetryAfter, InvalidToken)
3737

@@ -223,7 +223,11 @@ def post(self, url, data, timeout=None):
223223
if InputFile.is_inputfile(data):
224224
data = InputFile(data)
225225
result = self._request_wrapper(
226-
'POST', url, body=data.to_form(), headers=data.headers, **urlopen_kwargs)
226+
'POST',
227+
url,
228+
body=data.input_file_content,
229+
headers={'Content-Type': data.mimetype},
230+
**urlopen_kwargs)
227231
else:
228232
data = json.dumps(data)
229233
result = self._request_wrapper(

0 commit comments

Comments
 (0)