def parse_qs(): # Parse query string to GET dict GET = {} if "QUERY_STRING" in os.environ: GET = _parse_qs(os.environ["QUERY_STRING"]) GET = {k: v[0] for k, v in GET.items()} return GET
def _parse_query_string(self): query_vars = dict() query_string = None if self.method == "GET": query_string = self._env["QUERY_STRING"] elif self.method == "POST": content_type = self._env["CONTENT_TYPE"] assert content_type == "application/x-www-form-urlencoded" length = int(self._env["CONTENT_LENGTH"]) query_string = self._env["wsgi.input"].read(length) if not query_string: return query_vars try: items = _parse_qs(query_string, False, True) except ValueError: raise RequestError("Failed to parse query string") query_vars.update(items) return query_vars
def parse_qs(): """ Parse the request's query string into a dict """ GET = {} if "QUERY_STRING" in os.environ: GET = _parse_qs(os.environ["QUERY_STRING"]) GET = {k: v[0] if len(v) == 1 else v for k, v in GET.items()} return GET
def parse_response(query_params): """解析远程模拟提交后返回的信息 <param name="strText">要解析的字符串</param> <returns>解析结果</returns> """ params = _parse_qs(query_params, True) if "res_data" in params: if Settings.SIGN_TYPE == "0001": # TODO RSA 解密 params["res_data"] = "<r>解密结果</r>" tree = Etree.fromstring(params["res_data"][0]) token = tree.find("request_token").text params.update({"request_token": token}) return params
def parse_response(query_params, sign_type="MD5"): """解析远程模拟提交后返回的信息 <param name="strText">要解析的字符串</param> <returns>解析结果</returns> """ params = _parse_qs(query_params, True) if params["res_data"]: if sign_type == "0001": # TO DO RSA 解密 params["res_data"] = "<r>解密结果</r>" tree = etree.fromstring(params["res_data"][0]) token = tree.find("request_token").text params.update({"request_token": token}) return params
def parse_qs_bytes(qs, keep_blank_values=False, strict_parsing=False): """Parses a query string like urlparse.parse_qs, but returns the values as byte strings. Keys still become type str (interpreted as latin1 in python3!) because it's too painful to keep them as byte strings in python3 and in practice they're nearly always ascii anyway. """ # This is gross, but python3 doesn't give us another way. # Latin1 is the universal donor of character encodings. result = _parse_qs(qs, keep_blank_values, strict_parsing, encoding="latin1", errors="strict") encoded = {} for k, v in result.items(): encoded[k] = [i.encode("latin1") for i in v] return encoded
def parse_response(query_params, sign_type="MD5"): """解析远程模拟提交后返回的信息 <param name="strText">要解析的字符串</param> <returns>解析结果</returns> """ params = _parse_qs(query_params, True) if params["res_data"]: if sign_type == "0001": # TODO RSA 解密 params["res_data"] = "<r>解密结果</r>" tree = etree.fromstring(params["res_data"][0]) token = tree.find("request_token").text params.update({"request_token": token}) return params
def parse_qs_bytes(qs, keep_blank_values=False, strict_parsing=False): """Parses a query string like urlparse.parse_qs, but returns the values as byte strings. :param qs: quotes :param keep_blank_values: whether need keep bland values :param strict_parsing: whether need strict parsing :return: quotes bytes """ # This is gross, but python3 doesn't give us another way. # Latin1 is the universal donor of character encodings. result = _parse_qs(qs, keep_blank_values, strict_parsing, encoding='latin1', errors='strict') encoded = {} for k, v in result.items(): encoded[k] = [i.encode('latin1') for i in v] return encoded
def parse_qs_bytes(qs, keep_blank_values=False, strict_parsing=False): """Parses a query string like urlparse.parse_qs, but returns the values as byte strings. Keys still become type str (interpreted as latin1 in python3!) because it's too painful to keep them as byte strings in python3 and in practice they're nearly always ascii anyway. """ # This is gross, but python3 doesn't give us another way. # Latin1 is the universal donor of character encodings. result = _parse_qs(qs, keep_blank_values, strict_parsing, encoding='latin1', errors='strict') encoded = {} for k, v in result.items(): encoded[k] = [i.encode('latin1') for i in v] return encoded
def parse_qs(query_string, keep_blank_values=True): """parse_qs(query_string) -> dict Build a params dictionary from a query_string. If keep_blank_values is True (the default), keep values that are blank. """ if image_map_pattern.match(query_string): # Server-side image map. Map the coords to "x" and "y" # (like CGI::Request does). pm = query_string.split(",") return {"x": int(pm[0]), "y": int(pm[1])} else: pm = _parse_qs(query_string, keep_blank_values) return dict((k, v[0]) for k, v in pm.items() if v)
def parse_qs(query_string): """ Parses a query parameter string according to the OAuth spec. Use only with OAuth query strings. :see: Parameter Sources (http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1) :param query_string: Query string to parse. If ``query_string`` starts with a ``?`` character it will be ignored for convenience. """ query_string = to_utf8_if_unicode(query_string) or "" if query_string.startswith("?"): logging.warning("Ignoring `?` query string prefix -- `%r`" % query_string) query_string = query_string[1:] return _parse_qs(query_string, keep_blank_values=True)
def __init__(self, string): parts = urllib.parse.urlsplit(urllib.parse.unquote(string)) if parts[0] != 'http' and parts[0] != 'https': raise ValueError('Invalid url: %s.' % string) if "@" in parts[1]: host = parts[1].split('@').pop() else: host = parts[1] self.hostname = host if parts[0] == 'http': self.port = 80 else: self.port = 443 if ":" in host: try: self.hostname, self.port = host.split(':') except: raise ValueError('Invalid url: %s.' % string) self.port = int(self.port) self.uri = "%s://%s" % (parts[0], host) if parts[2]: self.path = parts[2] else: self.path = '' if parts[3]: self.query = _parse_qs(parts[3]) else: self.query = {} self.username = parts.username self.password = parts.password
def parse_qs(qs, encoding): return _parse_qs(qs, keep_blank_values=True)
def parse_qs(_path): path = _path.split("?")[1] return _parse_qs(path)
def parse_url(self): self.url = _urlparse(self.path) self.queries = _parse_qs(self.url.query)
def send_password(self, url, username=None, password=None, otpcode=None, remember_password=True, remember_device=None, dryrun=None): """Send a password and one-time code to the supplied login url""" if not remember_password: remember_device = False # the login URL is http[s]://something.com?id=XXXX/YY.YY.YY.YY # where XXXX is the service_uid of the service we should # connect with, and YY.YY.YY.YY is the short_uid of the login try: from urllib.parse import urlparse as _urlparse from urllib.parse import parse_qs as _parse_qs idcode = _parse_qs(_urlparse(url).query)["id"][0] except Exception as e: from Acquire.Client import LoginError raise LoginError( "Cannot identify the session or service information from " "the login URL '%s'. This should have id=XX-XX/YY.YY.YY.YY " "as a query parameter. <%s> %s" % (url, e.__class__.__name__, str(e))) try: (service_uid, short_uid) = idcode.split("/") except: from Acquire.Client import LoginError raise LoginError( "Cannot extract the service_uid and short_uid from the " "login ID code '%s'. This should be in the format " "XX-XX/YY.YY.YY.YY" % idcode) # now get the service try: service = self.get_service(service_uid=service_uid) except Exception as e: from Acquire.Client import LoginError raise LoginError( "Cannot find the service with UID %s: <%s> %s" % (service_uid, e.__class__.__name__, str(e))) if not service.can_identify_users(): from Acquire.Client import LoginError raise LoginError( "Service '%s' is unable to identify users! " "You cannot log into something that is not " "a valid identity service!" % (service)) userinfo = self._find_userinfo(username=username, password=password, service_uid=service_uid) if username is None: username = userinfo["username"] if "user_uid" in userinfo: user_uid = userinfo["user_uid"] else: user_uid = None _output("Logging in using username '%s'" % username) try: device_uid = userinfo["device_uid"] except: device_uid = None if password is None: password = self._get_user_password(userinfo=userinfo) if otpcode is None: otpcode = self._get_otpcode(userinfo=userinfo) else: # user is providing the primary OTP, so this is not a device device_uid = None _output("\nLogging in to '%s', session '%s'..." % ( service.canonical_url(), short_uid), end="") _flush_output() if dryrun: print("Calling %s with username=%s, password=%s, otpcode=%s, " "remember_device=%s, device_uid=%s, short_uid=%s " "user_uid=%s" % (service.canonical_url(), username, password, otpcode, remember_device, device_uid, short_uid, user_uid)) return try: from Acquire.Client import Credentials as _Credentials creds = _Credentials(username=username, password=password, otpcode=otpcode, short_uid=short_uid, device_uid=device_uid) args = {"credentials": creds.to_data(identity_uid=service.uid()), "user_uid": user_uid, "remember_device": remember_device, "short_uid": short_uid} response = service.call_function(function="login", args=args) _output("SUCCEEDED!") _flush_output() except Exception as e: _output("FAILED!") _flush_output() from Acquire.Client import LoginError raise LoginError("Failed to log in. %s" % e.args) if not remember_password: return try: returned_user_uid = response["user_uid"] if returned_user_uid != user_uid: # change of user? userinfo = {} user_uid = returned_user_uid except: # no user_uid, so nothing to save return if user_uid is None: # can't save anything return userinfo["username"] = username userinfo["password"] = password try: userinfo["device_uid"] = response["device_uid"] except: pass try: userinfo["otpsecret"] = response["otpsecret"] except: pass self._set_userinfo(userinfo=userinfo, user_uid=user_uid, service_uid=service.uid())