Skip to content

Instantly share code, notes, and snippets.

@zdk123
Created November 17, 2019 19:52
Show Gist options
  • Save zdk123/8322353ca25fff14a66954e4c4991a0e to your computer and use it in GitHub Desktop.
Save zdk123/8322353ca25fff14a66954e4c4991a0e to your computer and use it in GitHub Desktop.
A requests session for public google drive links
from requests import Session
from urllib.parse import urlparse, parse_qs, urlencode
class GDriveSession(Session):
"""
A Session for handling requests to public google drive URLs
"""
def __init__(self):
super().__init__()
def _get_confirm_token(self, response):
for key, value in response.cookies.items():
if key.startswith("download_warning"):
return value
return None
def _get_from_google_drive(self, id, url, **kwargs): # destination,
stream = kwargs.pop("stream")
response = super().get(url, params={"id": id}, stream=True, **kwargs)
token = self._get_confirm_token(response)
if token:
kwargs["stream"] = stream
params = {"id": id, "confirm": token}
response = super().get(url, params=params, **kwargs)
return response
def _parse_id_fromurl(self, url):
parsed = urlparse(url)
query = parse_qs(parsed.query)
id = query.pop("id")[0]
parsed = parsed._replace(query=urlencode(query, True))
return id, parsed.geturl()
def get(self, url, **kwargs):
"""
A get method for downloading public objects from google drive accounts
"""
## Pop the id from the query string of a google drive url
try:
id, newurl = self._parse_id_fromurl(url)
return self._get_from_google_drive(id, newurl, **kwargs)
except KeyError:
return super().get(url, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment