requests icon indicating copy to clipboard operation
requests copied to clipboard

Non-string form field names raise AttributeError when files are attached

Open jbrown9513 opened this issue 1 month ago • 12 comments

While testing an experimental version of Perch, we found the following and figured it was worth a report.

A non-string key in data works for a urlencoded body, but the same data fails once files is added and the body becomes multipart. A non-string key in files fails the same way.

Expected Result

The request prepares in both cases (the urlencoded path already accepts {1: "a"} and sends 1=a), or a TypeError that names the field.

Actual Result

AttributeError: 'int' object has no attribute 'translate'

raised from inside urllib3. _encode_files passes the field name straight to RequestField(name=k, ...) (models.py:245), which expects a str. Values are converted with str() a few lines earlier; names aren't.

Reproduction Steps

import requests

requests.Request("POST", "http://x", data={1: "a"}).prepare()
# works

requests.Request("POST", "http://x", data={1: "a"}, files={"f": b"x"}).prepare()
# AttributeError: 'int' object has no attribute 'translate'

requests.Request("POST", "http://x", files={1: b"x"}).prepare()
# AttributeError: 'int' object has no attribute 'translate'

System Information

$ python -m requests.help
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.5.2"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.20"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.14.2"
  },
  "platform": {
    "release": "25.2.0",
    "system": "Darwin"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.34.2"
  },
  "system_ssl": {
    "version": "30500040"
  },
  "urllib3": {
    "version": "2.8.0"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}

jbrown9513 avatar Oct 12 '26 00:10 jbrown9513

Hi, I'd like to work on this. I'll submit a PR shortly.

nightcityblade avatar Oct 12 '26 03:10 nightcityblade

I’m stepping back after reading the repository’s AI policy, so this issue is available for another contributor.

nightcityblade avatar Oct 12 '26 03:10 nightcityblade

Reproduced on 2.34.2 (current master), and the asymmetry is exactly as described. Scouting the fix site:

The multipart path at src/requests/models.py:245 (RequestField(name=k, ...)) passes the key through untouched, while the values two loops above are normalized (str(v) for non-bytes, field.decode("utf-8") for bytes keys in the data loop). The urlencoded path never crashes because urlencode stringifies keys on the way out. So data={1: "a"} works, and the moment files flips the encoder to multipart, the raw int reaches urllib3's escape → .translate → AttributeError.

The minimal, consistent fix is to normalize the name the same way the surrounding code normalizes everything else, at the same one place:

rf = RequestField(
    name=k.decode("utf-8") if isinstance(k, bytes) else str(k),
    data=fdata, filename=fn, headers=fh,
)

Notes for review:

  • str(k) matches the value behavior five lines above (values are already str()-coerced) and the urlencoded path's eventual urlencode stringification — so files={1: b"x"} would send a 1 field name, same as data={1: "a"} sends 1=a. Consistency argues for coercion, not TypeError.
  • The isinstance(k, bytes) branch mirrors the data-field loop's field.decode("utf-8") (bytes keys crash at the identical site today, with the same AttributeError).
  • Same file, same function, one statement — no behavior change for str keys, which is the entire existing test corpus.
  • Test sketch: prepare() a multipart request with data={1: "a"}, files={"f": b"x"} and with files={1: b"x"}, assert prepare().body contains name="1"; assert bytes key b"field" yields name="field".

Happy to open a PR for this if nobody's claimed it.

heyuhe2003 avatar Oct 12 '26 20:10 heyuhe2003

Withdrawing my offer to open a PR: .github/AI_POLICY.md explicitly excludes agentic tools from submitting, and a patch authored under agent control can't certify the authorship clause. Leaving the analysis above for whoever picks this up — the one-line normalization at models.py:245 (str-coerce, decode bytes keys) keeps the name behavior consistent with the value normalization already in the same function.

heyuhe2003 avatar Oct 12 '26 23:10 heyuhe2003

The issue can be reproduced locally. When a non-string field name is used in a request with file attachments, it raises an AttributeError. Before working on a fix, I would like to clarify the intended behavior. Would it be preferable to convert non-string field names to strings for consistency, or to raise a TypeError for invalid field names?

PranithaBoddu avatar Oct 13 '26 18:10 PranithaBoddu

If we take the approach of casting non-string field names to strings, where do we draw the line on acceptable input types for field names? The field names are passed as keys to a dict in the examples in the report, which allows all hashable types, which then includes types like functions, classes and modules, tuples, floats, bools, None - none of which seem to me to translate meaningfully into parameters in an http request.

Checking the docs shows that the dict format is one of many supported types for the data parameter - data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request

I think the real issue here is that the urlencoded code path is blindly accepting/converting int keys to strings, and the lack of input validation on either the urlencoded code path or the multipart encoded code path then exposes inconsistent behavior.

To my mind, the right approach is likely to only accept string-like types in all cases and consistently raise a TypeError rather than depending on the behavior of downstream encoding functions. That would, however, be a breaking change. We already have one example of code that currently "works" and wouldn't anymore if we introduce that change. It also seems likely, given the documented supported input types, that there's a fair bit of complexity involved to do this "correctly".

I don't have an authoritative answer, I'd love to hear other opinions on the best course here.

bernardgardner avatar Oct 15 '26 21:10 bernardgardner

The proposed solutions are incorrect. files explicitly only supports str keys. The case of non-string keys in data and string keys in files not working is a defect spawned from overly permissive data input in the original implementation.

Keys should be strings, they can't be emitted without being strings. Us doing the normalization in data originally was arguably wrong.

nateprewitt avatar Oct 15 '26 21:10 nateprewitt

So how about:

  • File field names: raise a clear TypeError for non-string names. They’re passed to urllib3 as-is and already fail; replacing its AttributeError with an intentional, useful error is a bug fix.
  • Multipart data field names: likewise, reject unsupported non-string names. Bytes are already decoded as UTF-8 here, so preserve that behavior (I think bytes are considered supported).
  • URL-encoded data field names: warn when accepting non-string keys, since that path currently stringifies them. A later release can turn that warning into a TypeError when appropriate to introduce the breaking change.

There's also some documentation related stuff: In src/requests/_types.py, FilesType is typed as Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] | None, so file field names are declared as strings. The documentation describes files as a dictionary of names to file objects or tuples, but doesn’t clearly say the keys must be strings.

For example:

  • Request docs say “dictionary of {filename: fileobject}.”
  • request docs say "Dictionary of 'name': 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."

I feel like the user docs imply stringiness by always using a string as the example, but should probably explicitly state the requirement that the provided value should be stringy.

bernardgardner avatar Oct 16 '26 02:10 bernardgardner

Also - in _types.py should those str types on line 133 be _FileName instead?

bernardgardner avatar Oct 16 '26 02:10 bernardgardner

I am working on a focused fix for multipart field names in #7634, with regression coverage for integer and non-string keys.

masyarakatai avatar Oct 22 '26 01:10 masyarakatai

The fix and regression tests are ready on my fork, but GitHub does not allow my account to create pull requests against psf/requests. Compare URL: https://github.com/psf/requests/compare/main...masyarakatai:fix/multipart-field-names-7634

masyarakatai avatar Oct 22 '26 01:10 masyarakatai

Here is the cause and a fix for this:

Cause

In _encode_files (src/requests/models.py), values in fields are converted to strings with str(v) if not bytes, but the keys (field) are left unconverted if not bytes. When non-string keys (like integers) are passed, tuples like (1, b'...') are passed to urllib3's RequestField.from_tuples(), which expects str and calls translate(), raising AttributeError. Similarly in files, non-string field names and filenames are passed unconverted to RequestField(name=k, ..., filename=fn).

Fix

Convert non-bytes keys and filenames to str:

  1. In fields: field.decode("utf-8") if isinstance(field, bytes) else str(field).
  2. In files: k = k.decode("utf-8") if isinstance(k, bytes) else str(k), and fn = fn.decode("utf-8") if isinstance(fn, bytes) else str(fn) (if fn is not None).

I've tested this with unit tests on branch: https://github.com/X6M-Work/requests/tree/fix-encode-files-non-str-keys

Full diff comparison against main: https://github.com/psf/requests/compare/main...X6M-Work:requests:fix-encode-files-non-str-keys

(Since PR creation is restricted to collaborators on this repository, feel free to cherry-pick from the branch or let me know if you'd like an invite to submit the PR directly!)

X6M-Work avatar Nov 06 '26 13:11 X6M-Work