-
-
Save VoidSec/cde179f4eeae3372b90c70d66870dc9d to your computer and use it in GitHub Desktop.
Reusable class for Python requests library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://docs.python-requests.org/en/master/api/ | |
import requests | |
class RequestsApi: | |
def __init__(self, base_url, **kwargs): | |
self.base_url = base_url | |
self.session = requests.Session() | |
for arg in kwargs: | |
if isinstance(kwargs[arg], dict): | |
kwargs[arg] = self.__deep_merge(getattr(self.session, arg), kwargs[arg]) | |
setattr(self.session, arg, kwargs[arg]) | |
def request(self, method, url, **kwargs): | |
return self.session.request(method, self.base_url+url, **kwargs) | |
def head(self, url, **kwargs): | |
return self.session.head(self.base_url+url, **kwargs) | |
def get(self, url, **kwargs): | |
return self.session.get(self.base_url+url, **kwargs) | |
def post(self, url, **kwargs): | |
return self.session.post(self.base_url+url, **kwargs) | |
def put(self, url, **kwargs): | |
return self.session.put(self.base_url+url, **kwargs) | |
def patch(self, url, **kwargs): | |
return self.session.patch(self.base_url+url, **kwargs) | |
def delete(self, url, **kwargs): | |
return self.session.delete(self.base_url+url, **kwargs) | |
@staticmethod | |
def __deep_merge(source, destination): | |
for key, value in source.items(): | |
if isinstance(value, dict): | |
node = destination.setdefault(key, {}) | |
RequestsApi.__deep_merge(value, node) | |
else: | |
destination[key] = value | |
return destination |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from requests_api import RequestsApi | |
github = RequestsApi("https://api.github.com") | |
r = github.get("/gists/96b655f1512d1ce9d570e008dbe122d3") | |
print(r.json()) | |
github = RequestsApi("https://api.github.com", headers={"Authorization": "token abcdef"}) | |
r = github.get("/user", headers={"Accept": "application/json"}) | |
print(r.text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment