Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for uploading files as a list #403

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions atests/http_server/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,16 @@ def get_files():

files = dict()

for k, v in request.files.items():
content_type = request.files[k].content_type or 'application/octet-stream'
val = json_safe(v.read(), content_type)
if files.get(k):
if not isinstance(files[k], list):
files[k] = [files[k]]
files[k].append(val)
else:
files[k] = val
for k in request.files.keys():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you also had to fix httpbin?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, as this only returned one item the way it was written. According to what I found out, you need to use the getlist(key) method to get all files for one key.

for v in request.files.getlist(k):
content_type = v.content_type or 'application/octet-stream'
val = json_safe(v.read(), content_type)
if files.get(k):
if not isinstance(files[k], list):
files[k] = [files[k]]
files[k].append(val)
else:
files[k] = val

return files

Expand Down
18 changes: 17 additions & 1 deletion atests/test_post_multipart.robot
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Library RequestsLibrary


*** Test Cases ***
Test Post On Session Multipart
Test Post Dictionary On Session Multipart
${file_1}= Get File For Streaming Upload atests/randombytes.bin
${file_2}= Get File For Streaming Upload atests/randombytes.bin
${files}= Create Dictionary randombytes1 ${file_1} randombytes2 ${file_2}
Expand All @@ -14,3 +14,19 @@ Test Post On Session Multipart
Should Contain ${resp.json()}[headers][Content-Length] 480
Should Contain ${resp.json()}[files] randombytes1
Should Contain ${resp.json()}[files] randombytes2

Test Post List On Session Multipart
${file_1}= Get File For Streaming Upload atests/randombytes.bin
${file_2}= Get File For Streaming Upload atests/randombytes.bin
${file_1_tuple}= Create List file1.bin ${file_1}
${file_2_tuple}= Create List file2.bin ${file_2}
${file_1_upload}= Create List randombytes ${file_1_tuple}
${file_2_upload}= Create List randombytes ${file_2_tuple}
${files}= Create List ${file_1_upload} ${file_2_upload}

${resp}= POST On Session ${GLOBAL_SESSION} /anything files=${files}

Should Contain ${resp.json()}[headers][Content-Type] multipart/form-data; boundary=
Should Contain ${resp.json()}[headers][Content-Length] 466
Should Contain ${resp.json()}[files] randombytes
Length Should Be ${resp.json()}[files][randombytes] 2
4 changes: 2 additions & 2 deletions doc/RequestsLibrary.html

Large diffs are not rendered by default.

16 changes: 12 additions & 4 deletions src/RequestsLibrary/RequestsKeywords.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from RequestsLibrary import log
from RequestsLibrary.compat import urljoin
from RequestsLibrary.utils import (
is_list_or_tuple,
is_file_descriptor,
warn_if_equal_symbol_in_url_session_less,
)
Expand Down Expand Up @@ -48,9 +49,16 @@ def _common_request(self, method, session, uri, **kwargs):

files = kwargs.get("files", {}) or {}
data = kwargs.get("data", []) or []
files_descriptor_to_close = filter(
is_file_descriptor, list(files.values()) + [data]
)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

at this point I would extract the logic to close file descriptor in a dedicated function and try to cleanup this part

if is_list_or_tuple(files):
files_descriptor_to_close = filter(
is_file_descriptor, [file[1][1] for file in files] + [data]
)
else:
files_descriptor_to_close = filter(
is_file_descriptor, list(files.values()) + [data]
)

for file_descriptor in files_descriptor_to_close:
file_descriptor.close()

Expand Down Expand Up @@ -176,7 +184,7 @@ def session_less_get(
| ``json`` | A JSON serializable Python object to send in the body of the request. |
| ``headers`` | Dictionary of HTTP Headers to send with the request. |
| ``cookies`` | Dict or CookieJar object to send with the request. |
| ``files`` | Dictionary of file-like-objects (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. |
| ``files`` | Dictionary of file-like-objects (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. List or tuple of ``('key': file-tuple)`` allows uploading multiple files with the same key, resulting in a list of files on the receiving end. |
| ``auth`` | Auth tuple to enable Basic/Digest/Custom HTTP Auth. |
| ``timeout`` | How many seconds to wait for the server to send data before giving up, as a float, or a ``(connect timeout, read timeout)`` tuple. |
| ``allow_redirects`` | Boolean. Enable/disable (values ``${True}`` or ``${False}``). Only for HEAD method keywords allow_redirection defaults to ``${False}``, all others ``${True}``. |
Expand Down
2 changes: 2 additions & 0 deletions src/RequestsLibrary/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ def is_string_type(data):
def is_file_descriptor(fd):
return isinstance(fd, io.IOBase)

def is_list_or_tuple(data):
return isinstance(data, (list, tuple))

def utf8_urlencode(data):
if is_string_type(data):
Expand Down
Loading