def __call__(self, request): if self.location == "authorization": credentials = self.credentials auth = requests.auth.HTTPBasicAuth( credentials["app_id"], credentials["app_key"]) return auth(request) return super().__call__(request)
def search_helper(q): try: results = requests.get( f"{SPOTIFY_ENDPOINT}search/?q={q}&type=playlist&limit=25", headers=auth()).json()['playlists']['items'] return [playlist for playlist in results] except KeyError: return
def auth(): """Authenticates the user through reddit's API""" try: client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET) username = raw_input("Username: "******"Password: "******"grant_type": "password", "username": username, "password": password} headers = {"User-Agent": APP_NAME} url = "https://www.reddit.com/api/v1/access_token" response = requests.post(url, auth=client_auth, data=post_data, headers=headers) except KeyError: print "Invalid login. Please try again." auth() data = {} data['access_token'] = response.json()['access_token'] access_file = open("access.json", "w+") json.dump(data, access_file) access_file.close() start()
def get_tracks(playlist_id): try: tracks = requests.get( f"{SPOTIFY_ENDPOINT}playlists/{playlist_id}/tracks", headers=auth()).json() return [ f"{track['track']['name']} by {track['track']['artists'][0]['name']}" for track in tracks['items'] ] except KeyError: return
def start(): """Main menu function""" try: access_file = open("access.json") access = json.load(access_file) access_token = access['access_token'] access_file.close() headers = {"Authorization": "bearer {}".format(access_token), "User-Agent": APP_NAME} url = "https://oauth.reddit.com/api/v1/me" response = requests.get(url, headers=headers) username = response.json()['name'] link_karma = response.json()['link_karma'] comment_karma = response.json()['comment_karma'] links = ("{} link karma").format(link_karma) comments = ("{} comment karma").format(comment_karma) print "Logged in as {} [{} | {}]".format(username, links, comments) except (IOError, KeyError): print """1. Log In 0. Quit""" userinput = raw_input("> ") if userinput == "1": print "Logging in..." auth() elif userinput == "0": sys.exit() else: print """1. View Profile 2. Moderation List 3. Log Out 0. Quit""" userinput = raw_input("> ") if userinput == "1": profile() elif userinput == "2": modlist() elif userinput == "3": os.remove("access.json") start() elif userinput == "0": sys.exit()
def brute(ip): window.append(str(ip)) for pair in pairs: window.progress(None) print("DEBUG") res = auth(ip, *pair) if res: print("Found for ip =", ip, ";", *pair, file=fout) window.statusbar.showMessage("Found!") window.append("Found for " + ip + " " + pair[0] + " " + pair[1]) return True elif res == None: return False print("Not found for ip =", ip, file=fout) return False
def __call__(self, request): credentials = self.credentials if self.location == "authorization": credentials = credentials.values() auth = requests.auth.HTTPBasicAuth(*credentials) return auth(request) if self.location == "headers": request.prepare_headers(credentials) elif self.location == "query": request.prepare_url(request.url, credentials) else: raise ValueError("Unknown credentials location '%s'" % self.location) return request
def __init__( self, url, processes=None, converters=None, username=None, password=None, headers=None, auth=None, verify=True, cert=None, verbose=False, progress=False, version=WPS_DEFAULT_VERSION, caps_xml=None, desc_xml=None, language=None, ): """ Args: url (str): Link to WPS provider. config (Config): an instance processes: Specify a subset of processes to bind. Defaults to all processes. converters (dict): Correspondence of {mimetype: class} to convert this mimetype to a python object. username (str): passed to :class:`owslib.wps.WebProcessingService` password (str): passed to :class:`owslib.wps.WebProcessingService` headers (str): passed to :class:`owslib.wps.WebProcessingService` auth (requests.auth.AuthBase): requests-style auth class to authenticate, see https://2.python-requests.org/en/master/user/authentication/ verify (bool): passed to :class:`owslib.wps.WebProcessingService` cert (str): passed to :class:`owslib.wps.WebProcessingService` verbose (str): passed to :class:`owslib.wps.WebProcessingService` progress (bool): If True, enable interactive user mode. version (str): WPS version to use. language (str): passed to :class:`owslib.wps.WebProcessingService` ex: 'fr-CA', 'en_US'. """ self._converters = converters self._interactive = progress self._mode = ASYNC if progress else SYNC self._notebook = notebook.is_notebook() self._inputs = {} self._outputs = {} if not verify: import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) if headers is None: headers = {} if auth is not None: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = requests.auth.HTTPBasicAuth(*auth) # We only need some headers from the requests.auth.AuthBase implementation # We prepare a dummy request, call the auth object with it, and get its headers dummy_request = requests.Request("get", "http://localhost") r = auth(dummy_request.prepare()) auth_headers = ["Authorization", "Proxy-Authorization", "Cookie"] headers.update( {h: r.headers[h] for h in auth_headers if h in r.headers}) self._wps = WebProcessingService(url, version=version, username=username, password=password, verbose=verbose, headers=headers, verify=verify, cert=cert, skip_caps=True, language=language) try: self._wps.getcapabilities(xml=caps_xml) except ServiceException as e: if "AccessForbidden" in str(e): raise UnauthorizedException( "You are not authorized to do a request of type: GetCapabilities" ) raise self._processes = self._get_process_description(processes, xml=desc_xml) # Build the methods for pid in self._processes: setattr(self, sanitize(pid), types.MethodType(self._method_factory(pid), self)) self.logger = logging.getLogger('WPSClient') if progress: self._setup_logging() self.__doc__ = utils.build_wps_client_doc(self._wps, self._processes)
def __call__(self, request): if self.location == "authorization": auth = requests.auth.HTTPBasicAuth(next(iter(self.credentials.values())), "") return auth(request) return super().__call__(request)