Skip to content

Commit ac04cfc

Browse files
author
Laurynas Butkus
committed
Add upload IO
1 parent c7d52a8 commit ac04cfc

File tree

4 files changed

+34
-10
lines changed

4 files changed

+34
-10
lines changed

convertapi/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from .exceptions import *
44
from .client import Client
5+
from .upload_io import UploadIO
56
from .api import convert
67

78
# configuration

convertapi/file_param.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
11
import os
2-
import convertapi
32

43
from .result_file import ResultFile
4+
from .upload_io import UploadIO
55

66
def build(resource):
77
if isinstance(resource, ResultFile):
88
return resource.url
99

10+
if isinstance(resource, UploadIO):
11+
return resource.upload()
12+
1013
if os.path.isfile(resource):
11-
return __upload_file(resource)
14+
io = open(resource, 'rb')
15+
return UploadIO(io).upload()
1216

1317
return resource
14-
15-
def __upload_file(file):
16-
filename = os.path.basename(file)
17-
18-
with open(file, 'rb') as f:
19-
result = convertapi.client.upload(f, filename)
20-
return result['FileId']

convertapi/upload_io.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import convertapi
2+
import os.path
3+
4+
class UploadIO:
5+
def __init__(self, io, filename = None):
6+
self.io = io
7+
self.__filename = filename
8+
9+
def upload(self):
10+
result = convertapi.client.upload(self.io, self.filename)
11+
return result['FileId']
12+
13+
@property
14+
def filename(self):
15+
if self.__filename:
16+
return self.__filename
17+
18+
if 'name' in dir(self.io):
19+
return os.path.basename(self.io.name)
20+
21+
raise 'Filename must be provided for non File resources'

tests/test_convertapi.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import convertapi
22
import os
3+
import io
34
import tempfile
45

56
from . import utils
@@ -25,4 +26,8 @@ def test_convert_url(self):
2526
result = convertapi.convert('pdf', { 'Url': 'http://convertapi.com' }, 'web')
2627
assert result.conversion_cost > 0
2728

28-
29+
def test_upload_io(self):
30+
string_io = io.StringIO(u'test')
31+
upload_io = convertapi.UploadIO(string_io, 'test.txt')
32+
result = convertapi.convert('pdf', { 'File': upload_io }, 'txt')
33+
assert result.conversion_cost > 0

0 commit comments

Comments
 (0)