Beispiel #1
0
 def testUnicodeBugInDefaultUnicode(self):
     self.assertEquals('a=a%3Fp', urllib_urlencode({'a': u'a?p'}))
     self.assertEquals('a=3', urllib_urlencode({'a': 3}))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': 'a\xc3\xa1p'}))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': 'aáp'}))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': u'aáp'}))
     self.assertEquals('a=a%3Fp', urllib_urlencode({'a': u'a?p'}, doseq=True))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': 'a\xc3\xa1p'}, doseq=True))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': 'aáp'}, doseq=True))
     # Bug in unicode characters and us of doseq=True
     self.assertEquals('a=a%3Fp', urllib_urlencode({'a': u'aáp'}, doseq=True))
Beispiel #2
0
def get_emailage_url(method, url, consumer_key, consumer_secret, query=None):
    """Generate the oauth url for emailAge
    :param query:
    :param method:
    :param url:
    :param consumer_key:
    :param consumer_secret:
    :return:
    """
    if not method:
        method = "GET"

    nonce, timestamp = generate_nonce_timestamp()

    # URL encode credential params
    cred_params = [('format', 'json'), ('oauth_consumer_key', consumer_key), ('oauth_nonce', nonce),
                   ('oauth_signature_method', 'HMAC-SHA1'), ('oauth_timestamp', timestamp), ('oauth_version', '1.0')]
    if method == 'GET':
        cred_params.append(('query', query))
    cred_params = urllib_urlencode(cred_params)
    """ivar: credential parameters required in the payload."""

    query_str = cred_params

    sig_url = method.upper() + "&" + urllib_quote(url, "") + "&" + urllib_quote(query_str, "")

    sig = get_signature(consumer_secret, sig_url)
    """ivar: signature based on consumer secret to validate request."""

    oauth_url = url + "?" + query_str + "&oauth_signature=" + urllib_quote(sig.decode(), "")

    return oauth_url
Beispiel #3
0
 def __new__(cls, action, structured_data=()):
     """
     string action -- action to perform
     list structured_data -- list of tuples, data to send with specified
         action
     """
     return super(RequestData,
                  cls).__new__(cls, action, structured_data,
                               urllib_urlencode(structured_data))
 def testUnicodeBugInDefaultUnicode(self):
     self.assertEquals('a=a%3Fp', urllib_urlencode({'a': u'a?p'}))
     self.assertEquals('a=3', urllib_urlencode({'a': 3}))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': 'a\xc3\xa1p'}))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': 'aáp'}))
     self.assertEquals('a=a%C3%A1p', urllib_urlencode({'a': u'aáp'}))
     self.assertEquals('a=a%3Fp', urllib_urlencode({'a': u'a?p'},
                                                   doseq=True))
     self.assertEquals('a=a%C3%A1p',
                       urllib_urlencode({'a': 'a\xc3\xa1p'}, doseq=True))
     self.assertEquals('a=a%C3%A1p',
                       urllib_urlencode({'a': 'aáp'}, doseq=True))
     # Bug in unicode characters and us of doseq=True
     self.assertEquals('a=a%3Fp', urllib_urlencode({'a': u'aáp'},
                                                   doseq=True))
Beispiel #5
0
 def handshake(self):
     print("[LastFMScrobbler] try logging into lastfm-submission-server")
     url = "http://" + self.host + ":" + str(
         self.port) + "?" + urllib_urlencode({
             "hs": "true",
             "p": "1.1",
             "c": self.client,
             "v": self.version,
             "u": self.user
         })
     getPage(url).addCallback(self.handshakeCB).addErrback(
         self.handshakeCBError)
Beispiel #6
0
    def call(self, url, p, data = False):
        """Calls the given url with the params urlencoded
        """
        if not self.access_token:
            self.access_token = self.get_access_token()
        final_url = "%s?%s" % (url, urllib_urlencode(p))
        headers={'Content-Type' : 'text/xml', 'Authorization': 'Bearer %s' % self.access_token}

        if data :
            r = requests.post(url, headers = headers, data = data, timeout=30)
        else :
            r = requests.get(final_url, headers = headers, timeout=30)

        response = r.text

        if response.count("ArgumentOutOfRangeException"):
            raise ArgumentOutOfRangeException(response)

        if response.count("ArgumentException"):
            raise ArgumentException(response)

        if response.count("TranslateApiException"):
            raise TranslateApiException(response)

        response = xmlstring = re.sub(' xmlns="[^"]+"', '', response, count=1)
        root = etree.ElementTree.fromstring(response.decode("utf-8-sig"))
        rv = []

        for child in root :
            result = {}
            for part in child :
                name = part.tag
                if name in ["TranslatedText", "From"] :
                    mverbose("Setting: " + name + " = " + str(part.text))
                    result[name] = part.text
                else :
                    for number in part :
                        mverbose("Setting: " + name + " = " + str(number.text))
                        result[name] = number.text
            rv.append(result)

        if len(rv) > 0 and self.test :
            rvc = deepcopy(rv)
            for idx in range(0, len(rvc)) : 
                mwarn("RVC idx: " + str(idx) + " is " + str(type(rvc[idx])) + ", " + str(rvc))
                rvc[idx]["TranslatedText"] = rvc[idx]["TranslatedText"].encode("utf-8")

            # Log the results of microsoft for unit testing.
            test_log(self.test, exchange = dict(inp = {'texts' : str(p["texts"]), 'from' : p['from'], 'options' : p['options'], 'to' : p['to']}, outp = rvc))
        return rv
    def sendRequest(self, urlString, data_=None):
        try:
            if data_ is not None:
                data = urllib_urlencode(data_)
                request = urllib_request.Request(
                    urlString, data, headers=self.headers)
            else:
                request = urllib_request.Request(urlString, headers=self.headers)

            response = urllib_request.urlopen(request)
        except Exception as e:
            raise AfricasTalkingGatewayException(str(e))
        else:
            self.responseCode = response.getcode()
            response = response.read().decode('utf-8')
            if self.Debug:
                print(response)
            return response
Beispiel #8
0
    def sendRequest(self, urlString, data_=None):
        try:
            if data_ is not None:
                data = urllib_urlencode(data_)
                request = urllib_request.Request(urlString,
                                                 data,
                                                 headers=self.headers)
            else:
                request = urllib_request.Request(urlString,
                                                 headers=self.headers)

            response = urllib_request.urlopen(request)
        except Exception as e:
            raise AfricasTalkingGatewayException(str(e))
        else:
            self.responseCode = response.getcode()
            response = response.read().decode('utf-8')
            if self.Debug:
                print(response)
            return response
Beispiel #9
0
def authenticate(username, password, auth_url):
    try:
        output_dict = jabber_crypt.dumps({"username": username, "password": password})
        url = auth_url + "/auth"
        log.write("URL: " + url + "\n")

        up = {"exchange": myquote(output_dict)}
        req = urllib2_Request(url, urllib_urlencode(up))
        res = jabber_crypt.loads(urllib2_unquote(urllib2_urlopen(req).read().encode("utf-8")))

        if res == "good":
            return 1, False
        elif res == "bad":
            return 0, "Unauthorized"
        else:
            return 0, "error"

    except urllib2_HTTPError, e:
        if e.code == 401:
            return 0, _("Invalid credentials. Please try again") + "."
        error = "(HTTP code: " + str(e.code) + ")"
Beispiel #10
0
def get_emailage_url(method, url, consumer_key, consumer_secret, query=None):
    """Generate the oauth url for emailAge
    :param query:
    :param method:
    :param url:
    :param consumer_key:
    :param consumer_secret:
    :return:
    """
    if not method:
        method = "GET"

    nonce, timestamp = generate_nonce_timestamp()

    # URL encode credential params
    cred_params = [('format', 'json'), ('oauth_consumer_key', consumer_key),
                   ('oauth_nonce', nonce),
                   ('oauth_signature_method', 'HMAC-SHA1'),
                   ('oauth_timestamp', timestamp), ('oauth_version', '1.0')]
    if method == 'GET':
        cred_params.append(('query', query))
    cred_params = urllib_urlencode(cred_params)
    """ivar: credential parameters required in the payload."""

    query_str = cred_params

    sig_url = method.upper() + "&" + urllib_quote(
        url, "") + "&" + urllib_quote(query_str, "")

    sig = get_signature(consumer_secret, sig_url)
    """ivar: signature based on consumer secret to validate request."""

    oauth_url = url + "?" + query_str + "&oauth_signature=" + urllib_quote(
        sig.decode(), "")

    return oauth_url
Beispiel #11
0
def encodeUrlParams(dParams):
    """
    See urllib.urlencode().
    """
    return urllib_urlencode(dParams, doseq=True)
def encodeUrlParams(dParams):
    """
    See urllib.urlencode().
    """
    return urllib_urlencode(dParams, doseq=True)
Beispiel #13
0
 def format_data_dict(cls, data):
     """
     Encode data for transport (only plain dict is supported)
     """
     return urllib_urlencode(data)
Beispiel #14
0
 def format_data_dict(cls, data):
     """
     Encode data for transport (only plain dict is supported)
     """
     return urllib_urlencode(data)