Skip to content

ENH: Add headers paramater to read_json and read_csv #36754

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

Closed
wants to merge 7 commits into from
Closed
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
7 changes: 4 additions & 3 deletions pandas/io/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,9 @@ def urlopen(*args, **kwargs):
Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of
the stdlib.
"""
import urllib.request
from urllib.request import Request, urlopen as _urlopen
Copy link
Member

Choose a reason for hiding this comment

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

Why was this changed?

Copy link
Author

Choose a reason for hiding this comment

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

I find it makes the code more concise, but if you think the old way is better I can change it back.


return urllib.request.urlopen(*args, **kwargs)
return _urlopen(Request(*args, **kwargs))


def is_fsspec_url(url: FilePathOrBuffer) -> bool:
Expand All @@ -176,6 +176,7 @@ def get_filepath_or_buffer(
compression: CompressionOptions = None,
mode: ModeVar = None, # type: ignore[assignment]
storage_options: StorageOptions = None,
headers: Dict[str, Any] = {},
) -> IOargs[ModeVar, EncodingVar]:
"""
If the filepath_or_buffer is a url, translate and return the buffer.
Expand Down Expand Up @@ -251,7 +252,7 @@ def get_filepath_or_buffer(
raise ValueError(
"storage_options passed with file object or non-fsspec file path"
)
req = urlopen(filepath_or_buffer)
req = urlopen(filepath_or_buffer, headers=headers)
content_encoding = req.headers.get("Content-Encoding", None)
if content_encoding == "gzip":
# Override compression based on Content-Encoding header
Expand Down
8 changes: 7 additions & 1 deletion pandas/io/json/_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from io import BytesIO, StringIO
from itertools import islice
import os
from typing import IO, Any, Callable, List, Optional, Type
from typing import IO, Any, Callable, Dict, List, Optional, Type

import numpy as np

Expand Down Expand Up @@ -377,6 +377,7 @@ def read_json(
compression: CompressionOptions = "infer",
nrows: Optional[int] = None,
storage_options: StorageOptions = None,
headers: Dict[str, Any] = {},
):
"""
Convert a JSON string to pandas object.
Expand Down Expand Up @@ -527,6 +528,10 @@ def read_json(
a file-like buffer. See the fsspec and backend storage implementation
docs for the set of allowed keys and values.

headers : dict, optional
HTTP headers that are passed to urlopen. Allows to specify the User-Agent
in case the urllib User-Agent is blocked for example

.. versionadded:: 1.2.0

Returns
Expand Down Expand Up @@ -614,6 +619,7 @@ def read_json(
encoding=encoding,
compression=compression,
storage_options=storage_options,
headers=headers,
)

json_reader = JsonReader(
Expand Down
13 changes: 12 additions & 1 deletion pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,10 @@
a file-like buffer. See the fsspec and backend storage implementation
docs for the set of allowed keys and values.

headers : dict, optional
HTTP headers that are passed to urlopen. Allows to specify the User-Agent
in case the urllib User-Agent is blocked for example

.. versionadded:: 1.2

Returns
Expand Down Expand Up @@ -432,9 +436,14 @@ def _read(filepath_or_buffer: FilePathOrBuffer, kwds):
encoding = re.sub("_", "-", encoding).lower()
kwds["encoding"] = encoding
compression = kwds.get("compression", "infer")
headers = kwds.get("headers", {})

ioargs = get_filepath_or_buffer(
filepath_or_buffer, encoding, compression, storage_options=storage_options
filepath_or_buffer,
encoding,
compression,
storage_options=storage_options,
headers=headers,
)
kwds["compression"] = ioargs.compression

Expand Down Expand Up @@ -599,6 +608,7 @@ def read_csv(
memory_map=False,
float_precision=None,
storage_options: StorageOptions = None,
headers: Dict[str, Any] = {},
):
# gh-23761
#
Expand Down Expand Up @@ -686,6 +696,7 @@ def read_csv(
infer_datetime_format=infer_datetime_format,
skip_blank_lines=skip_blank_lines,
storage_options=storage_options,
headers=headers,
)

return _read(filepath_or_buffer, kwds)
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/io/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,3 +417,11 @@ def test_is_fsspec_url():
assert not icom.is_fsspec_url("random:pandas/somethingelse.com")
assert not icom.is_fsspec_url("/local/path")
assert not icom.is_fsspec_url("relative/local/path")


def test_urlopen_headers():
headers = {"User-Agent": "Pandas 1.1.0"}
# this returns the User-Agent
url = "http://ifconfig.me/ua"
r = icom.urlopen(url, headers=headers)
assert r.read().decode("utf-8") == headers["User-Agent"]