class Session(requests.Session): """ Session for making API requests and interacting with the filesystem """ def __init__(self): super(Session, self).__init__() self.trust_env = False cookie_file = os.path.expanduser('~/.danabox/cookies.txt') cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.danabox dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, 0700) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load() self.cookies.clear_expired_cookies() def clear(self): """Clear cookies""" try: self.cookies.clear() self.cookies.save() except KeyError: pass def git_root(self): """ Return the absolute path from the git repository root If no git repository exists, raise an EnvironmentError """ try: git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel'], stderr=subprocess.PIPE).strip('\n') except subprocess.CalledProcessError: raise EnvironmentError('Current directory is not a git repository') return git_root def get_app(self): """ Return the application name for the current directory The application is determined by parsing `git remote -v` output for the origin remote. Because Danabox only allows deployment of public Github repos we can create unique app names from a combination of the Github user's name and the repo name. Eg; '[email protected]:opdemand/example-ruby-sinatra.git' becomes 'opdemand-example--ruby--sinatra' If no application is found, raise an EnvironmentError. """ git_root = self.git_root() remotes = subprocess.check_output(['git', 'remote', '-v'], cwd=git_root) if remotes is None: raise EnvironmentError('No git remotes found.') for remote in remotes.splitlines(): if 'github.com' in remote: url = remote.split()[1] break if url is None: raise EnvironmentError('No Github remotes found.') pieces = url.split('/') owner = pieces[-2].split(':')[-1] repo = pieces[-1].replace('.git', '') app_raw = owner + '/' + repo app_name = app_raw.replace('-', '--').replace('/', '-') return app_name app = property(get_app) def request(self, *args, **kwargs): """ Issue an HTTP request with proper cookie handling including `Django CSRF tokens <https://docs.djangoproject.com/en/dev/ref/contrib/csrf/>` """ for cookie in self.cookies: if cookie.name == 'csrftoken': if 'headers' in kwargs: kwargs['headers']['X-CSRFToken'] = cookie.value else: kwargs['headers'] = {'X-CSRFToken': cookie.value} break response = super(Session, self).request(*args, **kwargs) self.cookies.save() return response
class Session(requests.Session): """ Session for making API requests and interacting with the filesystem """ def __init__(self): super(Session, self).__init__() self.trust_env = False cookie_file = os.path.expanduser('~/.deis/cookies.txt') cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.deis dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, 0700) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load() self.cookies.clear_expired_cookies() def git_root(self): """ Return the absolute path from the git repository root If no git repository exists, raise an EnvironmentError """ try: git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel'], stderr=subprocess.PIPE).strip('\n') except subprocess.CalledProcessError: raise EnvironmentError('Current directory is not a git repository') return git_root def get_formation(self): """ Return the formation name for the current directory The formation is determined by parsing `git remote -v` output. If no formation is found, raise an EnvironmentError. """ git_root = self.git_root() # try to match a deis remote remotes = subprocess.check_output(['git', 'remote', '-v'], cwd=git_root) m = re.match(r'^deis\W+(?P<url>\S+)\W+\(', remotes, re.MULTILINE) if not m: raise EnvironmentError( 'Could not find deis remote in `git remote -v`') url = m.groupdict()['url'] m = re.match('\S+:(?P<formation>[a-z0-9-]+)(.git)?', url) if not m: raise EnvironmentError("Could not parse: {url}".format(**locals())) return m.groupdict()['formation'] formation = property(get_formation) def request(self, *args, **kwargs): """ Issue an HTTP request with proper cookie handling including `Django CSRF tokens <https://docs.djangoproject.com/en/dev/ref/contrib/csrf/>` """ for cookie in self.cookies: if cookie.name == 'csrftoken': if 'headers' in kwargs: kwargs['headers']['X-CSRFToken'] = cookie.value else: kwargs['headers'] = {'X-CSRFToken': cookie.value} break response = super(Session, self).request(*args, **kwargs) self.cookies.save() return response
class Session(requests.Session): """ Session for making API requests and interacting with the filesystem """ def __init__(self): super(Session, self).__init__() self.trust_env = False cookie_file = os.path.expanduser('~/.danabox/cookies.txt') cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.danabox dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, 0700) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load() self.cookies.clear_expired_cookies() def clear(self): """Clear cookies""" try: self.cookies.clear() self.cookies.save() except KeyError: pass def git_root(self): """ Return the absolute path from the git repository root If no git repository exists, raise an EnvironmentError """ try: git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel'], stderr=subprocess.PIPE).strip('\n') except subprocess.CalledProcessError: raise EnvironmentError('Current directory is not a git repository') return git_root def get_app(self): """ Return the application name for the current directory The application is determined by parsing `git remote -v` output for the origin remote. Because Danabox only allows deployment of public Github repos we can create unique app names from a combination of the Github user's name and the repo name. Eg; '[email protected]:opdemand/example-ruby-sinatra.git' becomes 'opdemand-example--ruby--sinatra' If no application is found, raise an EnvironmentError. """ git_root = self.git_root() remotes = subprocess.check_output(['git', 'remote', '-v'], cwd=git_root) if remotes is None: raise EnvironmentError('No git remotes found.') for remote in remotes.splitlines(): if 'github.com' in remote: url = remote.split()[1] break if url is None: raise EnvironmentError('No Github remotes found.') pieces = url.split('/') owner = pieces[-2].split(':')[-1] repo = pieces[-1].replace('.git', '') app_raw = owner + '/' + repo app_name = app_raw.replace('-', '--').replace('/', '-') return app_name app = property(get_app) def request(self, *args, **kwargs): """ Issue an HTTP request with proper cookie handling including `Django CSRF tokens <https://docs.djangoproject.com/en/dev/ref/contrib/csrf/>` """ for cookie in self.cookies: if cookie.name == 'csrftoken': if 'headers' in kwargs: kwargs['headers']['X-CSRFToken'] = cookie.value else: kwargs['headers'] = {'X-CSRFToken': cookie.value} break response = super(Session, self).request(*args, **kwargs) self.cookies.save() return response