-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathhttp.py
More file actions
69 lines (53 loc) · 2.03 KB
/
http.py
File metadata and controls
69 lines (53 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import requests
from .exceptions import (
HTTPError,
HTTPConnectionError,
TimeoutError,
)
from .__version__ import __version__
class HTTPClient:
"""This class handles outgoing HTTP requests to SerpApi.com."""
BASE_DOMAIN = "https://serpapi.com"
USER_AGENT = f"serpapi-python, v{__version__}"
def __init__(self, *, api_key=None, timeout=None):
# Used to authenticate requests.
# TODO: do we want to support the environment variable? Seems like a security risk.
self.api_key = api_key
self.timeout = timeout
self.session = requests.Session()
def request(self, method, path, params, *, assert_200=True, **kwargs):
# Inject the API Key into the params.
if "api_key" not in params:
params["api_key"] = self.api_key
# Build the URL, as needed.
if not path.startswith("http"):
url = self.BASE_DOMAIN + path
else:
url = path
# Make the HTTP request.
try:
headers = {"User-Agent": self.USER_AGENT}
# Use the default timeout if one was provided to the client.
if self.timeout and "timeout" not in kwargs:
kwargs["timeout"] = self.timeout
r = self.session.request(
method=method, url=url, params=params, headers=headers, **kwargs
)
except requests.exceptions.ConnectionError as e:
raise HTTPConnectionError(e)
except requests.exceptions.Timeout as e:
raise TimeoutError(e)
# Raise an exception if the status code is not 200.
if assert_200:
try:
raise_for_status(r)
except requests.exceptions.HTTPError as e:
raise HTTPError(e)
return r
def raise_for_status(r):
"""Raise an exception if the status code is not 200."""
# TODO: put custom behavior in here for various status codes.
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise HTTPError(e)