當前位置: 首頁>>代碼示例>>Python>>正文


Python parse.urlencode方法代碼示例

本文整理匯總了Python中future.moves.urllib.parse.urlencode方法的典型用法代碼示例。如果您正苦於以下問題:Python parse.urlencode方法的具體用法?Python parse.urlencode怎麽用?Python parse.urlencode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在future.moves.urllib.parse的用法示例。


在下文中一共展示了parse.urlencode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_authorization_url

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def get_authorization_url(self, scopes, state_token=None):
        """Generates authorization url using scopes specified where user is redirected to
        
        :param scopes: Scopes for OAuth/OpenId flow
        :type scopes: list of enum, `intuitlib.enums.Scopes`
        :param state_token: CSRF token, defaults to None
        :return: Authorization url
        """

        state = state_token or self.state_token 
        if state is None:
            state = generate_token()
        self.state_token = state

        url_params = {
            'client_id': self.client_id,
            'response_type': 'code',
            'scope': scopes_to_string(scopes),
            'redirect_uri': self.redirect_uri,
            'state': self.state_token 
        }

        return '?'.join([self.auth_endpoint, urlencode(url_params)]) 
開發者ID:intuit,項目名稱:oauth-pythonclient,代碼行數:25,代碼來源:client.py

示例2: get_bearer_token

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def get_bearer_token(self, auth_code, realm_id=None):
        """Gets access_token and refresh_token using authorization code
        
        :param auth_code: Authorization code received from redirect_uri
        :param realm_id: Realm ID/Company ID of the QBO company
        :raises `intuitlib.exceptions.AuthClientError`: if response status != 200
        """

        realm = realm_id or self.realm_id
        if realm is not None:
            self.realm_id = realm
        
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': get_auth_header(self.client_id, self.client_secret)
        }

        body = {
            'grant_type': 'authorization_code',
            'code': auth_code,
            'redirect_uri': self.redirect_uri
        }

        send_request('POST', self.token_endpoint, headers, self, body=urlencode(body), session=self) 
開發者ID:intuit,項目名稱:oauth-pythonclient,代碼行數:26,代碼來源:client.py

示例3: refresh

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def refresh(self, refresh_token=None):
        """Gets fresh access_token and refresh_token 
        
        :param refresh_token: Refresh Token
        :raises ValueError: if Refresh Token value not specified
        :raises `intuitlib.exceptions.AuthClientError`: if response status != 200
        """

        token = refresh_token or self.refresh_token
        if token is None:
            raise ValueError('Refresh token not specified')

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': get_auth_header(self.client_id, self.client_secret)
        }

        body = {
            'grant_type': 'refresh_token',
            'refresh_token': token
        }

        send_request('POST', self.token_endpoint, headers, self, body=urlencode(body), session=self) 
開發者ID:intuit,項目名稱:oauth-pythonclient,代碼行數:25,代碼來源:client.py

示例4: mutex_loop

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def mutex_loop(self):
        def do(args):
            # Requests a mutex from the server.
            call = dht_msg_endpoint + "?call=get_mutex&"
            call += urlencode({"node_id": self.node_id}) + "&"
            call += urlencode({"password": self.password})

            # Make API call.
            ret = requests.get(call, timeout=5).text
            if "1" in ret or "2" in ret:
                self.has_mutex = int(ret)
            self.is_mutex_ready.set()

            return 0

        self.retry_in_thread(do, check_interval=MUTEX_TIMEOUT) 
開發者ID:StorjOld,項目名稱:pyp2p,代碼行數:18,代碼來源:dht_msg.py

示例5: add_query_params

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def add_query_params(url, params):
    scheme, netloc, path, query_string, fragment = urlsplit(url)
    query_params = parse_qs(query_string)

    for name, value in iteritems(params):
        if value:
            query_params[name] = [value]

    new_query_string = urlencode(query_params, doseq=True)

    return urlunsplit((scheme, netloc, path, new_query_string, fragment)) 
開發者ID:Mendeley,項目名稱:mendeley-python-sdk,代碼行數:13,代碼來源:base.py

示例6: get_update_url

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def get_update_url(url, data):
    """
    獲取更新後的url
    :param url:
    :param data:
    :return:
    """
    result = urlparse(url)
    query_payload = dict(parse_qsl(result.query), **data)
    query_param = urlencode(query_payload)
    return urlunparse((result.scheme, result.netloc, result.path, result.params, query_param, result.fragment)) 
開發者ID:zhanghe06,項目名稱:news_spider,代碼行數:13,代碼來源:url.py

示例7: send

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def send(self, data):
        request = Request(
            self.endpoint + '?' + urlencode(self.fixUTF8(data)).encode('utf-8'),
            headers={
                'User-Agent': self.user_agent
            }
        )
        self.open(request) 
開發者ID:Tautulli,項目名稱:Tautulli,代碼行數:10,代碼來源:Tracker.py

示例8: _sendhttp

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def _sendhttp(self, host, command):
        url_command = urlencode(command)
        url = host + '/xbmcCmds/xbmcHttp/?' + url_command

        if self.config['password']:
            return request.request_content(url, auth=(self.config['username'], self.config['password']))
        else:
            return request.request_content(url) 
開發者ID:Tautulli,項目名稱:Tautulli,代碼行數:10,代碼來源:notifiers.py

示例9: page

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def page(endpoint, *args, **kwargs):
    endpoints = {
        'pms_image_proxy': pms_image_proxy,
        'info': info_page,
        'library': library_page,
        'user': user_page
    }

    params = {}

    if endpoint in endpoints:
        params = endpoints[endpoint](*args, **kwargs)

    return endpoint + '?' + urlencode(params) 
開發者ID:Tautulli,項目名稱:Tautulli,代碼行數:16,代碼來源:helpers.py

示例10: alive_loop

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def alive_loop(self):
        def do(args):
            # Requests a mutex from the server.
            call = dht_msg_endpoint + "?call=last_alive&"
            call += urlencode({"node_id": self.node_id}) + "&"
            call += urlencode({"password": self.password})

            # Make API call.
            ret = requests.get(call, timeout=5)

            return 0

        self.retry_in_thread(do, check_interval=ALIVE_TIMEOUT) 
開發者ID:StorjOld,項目名稱:pyp2p,代碼行數:15,代碼來源:dht_msg.py

示例11: find_neighbours_loop

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def find_neighbours_loop(self):
        def do(args):
            # Requests a mutex from the server.
            call = dht_msg_endpoint + "?call=find_neighbours&"
            call += urlencode({"node_id": self.node_id}) + "&"
            call += urlencode({"password": self.password}) + "&"
            call += urlencode({"network_id": self.network_id})

            # Make API call.
            ret = requests.get(call, timeout=5).text
            ret = json.loads(ret)
            if type(ret) == dict:
                ret = [ret]

            # Convert to kademlia neighbours.
            neighbours = []
            for neighbour in ret:
                if not is_ip_valid(neighbour["ip"]):
                    continue

                neighbour["port"] = int(neighbour["port"])
                if not is_valid_port(neighbour["port"]):
                    continue

                knode = KadNode(
                    id=binascii.unhexlify(neighbour["id"].encode("ascii")),
                    ip=neighbour["ip"],
                    port=neighbour["port"],
                    can_test=int(neighbour["can_test"])
                )

                neighbours.append(knode)

            self.neighbours = neighbours
            self.is_neighbours_ready.set()

            return 0

        self.retry_in_thread(do, check_interval=ALIVE_TIMEOUT) 
開發者ID:StorjOld,項目名稱:pyp2p,代碼行數:41,代碼來源:dht_msg.py

示例12: register

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def register(self, node_id, password):
        def do(node_id, password):
            try:
                # Registers a new node to receive messages.
                call = dht_msg_endpoint + "?call=register&"
                call += urlencode({"node_id": node_id}) + "&"
                call += urlencode({"password": password}) + "&"
                call += urlencode({"port": self.port}) + "&"
                call += urlencode({"network_id": self.network_id})
                if self.ip is not None:
                   call += "&" + urlencode({"ip": self.ip})

                # Make API call.
                ret = requests.get(call, timeout=5)
                self.handles.append(ret)
                if "success" not in ret.text:
                    return 0
                self.is_registered.set()
                return 1
            except Exception as e:
                print(e)
                self.debug_print("Register timed out in DHT msg")

            self.debug_print("DHT REGISTER FAILED")
            return 0

        mappings = {
            "node_id": node_id,
            "password": password
        }
        self.retry_in_thread(do, mappings) 
開發者ID:StorjOld,項目名稱:pyp2p,代碼行數:33,代碼來源:dht_msg.py

示例13: put

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def put(self, node_id, msg, list_pop=1):
        def do(node_id, msg):
            if node_id in self.relay_links:
                relay_link = self.relay_links[node_id]
                msg = self.build_dht_response(self.serialize_message(msg))
                relay_link.protocol.messages_received.put_nowait(msg)
                return 1

            try:
                # Send a message directly to a node in the "DHT"
                call = dht_msg_endpoint + "?call=put&"
                call += urlencode({"dest_node_id": node_id}) + "&"
                msg = self.serialize_message(msg)
                call += urlencode({"msg": msg}) + "&"
                call += urlencode({"node_id": self.node_id}) + "&"
                call += urlencode({"password": self.password}) + "&"
                call += urlencode({"list_pop": list_pop})

                # Make API call.
                ret = requests.get(call, timeout=5)
                self.handles.append(ret)
                if "success" not in ret.text:
                    return 0

                return 1

            except Exception as e:
                # Reschedule call.
                self.debug_print("DHT PUT TIMED OUT")
                self.debug_print(e)
                self.debug_print("Rescheduling DHT PUT")

            self.debug_print("PUT FAILED")
            return 0

        mappings = {
            "node_id": node_id,
            "msg": msg
        }
        return self.retry_in_thread(do, mappings) 
開發者ID:StorjOld,項目名稱:pyp2p,代碼行數:42,代碼來源:dht_msg.py

示例14: request

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def request(self, path, params=None, returns_json=True,
                method='POST', api_version=API_VERSION):
        '''Process a request using the OAuth client's request method.

        :param str path: Path fragment to the API endpoint, e.g. "resource/ID"
        :param dict params: Parameters to pass to request
        :param str method: Optional HTTP method, normally POST for Instapaper
        :param str api_version: Optional alternative API version
        :returns: response headers and body
        :retval: dict
        '''
        time.sleep(REQUEST_DELAY_SECS)
        full_path = '/'.join([BASE_URL, 'api/%s' % api_version, path])
        params = urlencode(params) if params else None
        log.debug('URL: %s', full_path)
        request_kwargs = {'method': method}
        if params:
            request_kwargs['body'] = params
        response, content = self.oauth_client.request(
            full_path, **request_kwargs)
        log.debug('CONTENT: %s ...', content[:50])
        if returns_json:
            try:
                data = json.loads(content)
                if isinstance(data, list) and len(data) == 1:
                    # ugly -- API always returns a list even when you expect
                    # only one item
                    if data[0]['type'] == 'error':
                        raise Exception('Instapaper error %d: %s' % (
                            data[0]['error_code'],
                            data[0]['message'])
                        )
                    # TODO: PyInstapaperException custom class?
            except ValueError:
                # Instapaper API can be unpredictable/inconsistent, e.g.
                # bookmarks/get_text doesn't return JSON
                data = content
        else:
            data = content
        return {
            'response': response,
            'data': data
        } 
開發者ID:mdorn,項目名稱:pyinstapaper,代碼行數:45,代碼來源:instapaper.py

示例15: granule_download

# 需要導入模塊: from future.moves.urllib import parse [as 別名]
# 或者: from future.moves.urllib.parse import urlencode [as 別名]
def granule_download(self, query_string, path=''):
        ''' Granule Download service submits a job to subset and download. Upon a successful request,\
            token will be returned which can be used to check status.

            :param query_string: data collection query json as a string.
            :type query_string: :mod:`string`

            :param path: path to a directory where you want the subsetted \
                dataset to be stored.
            :type path: :mod:`string`

            :returns: a zip file downloaded and extracted in the destination\
                directory path provided.
        '''
        params = urlencode({'query': query_string})
        headers = {
            "Content-type": "application/x-www-form-urlencoded", "Accept": "*"}
        connection = HTTPSConnection("podaac-tools.jpl.nasa.gov")
        connection.request("POST", "/l2ss-services/l2ss/subset/submit",
                           params, headers)
        response = connection.getresponse()
        data = response.read().decode('utf-8')
        result = json.loads(data)
        token = result['token']
        connection.close()

        flag = 0
        while flag == 0:
            url = url = self.URL + "subset/status?token=" + token
            subset_response = requests.get(url).text
            subset_response_json = json.loads(subset_response)
            status = subset_response_json['status']
            if status == "done":
                flag = 1
            if status == "error":
                raise Exception(
                    "Unexpected error occured for the subset job you have requested")
            if status == "partial error":
                raise Exception(
                    "The job was done but with some errors, please submit the job again")
            time.sleep(1)

        print("Done! downloading the dataset zip .....")
        download_url = subset_response_json['resultURLs'][0]
        split = download_url.split('/')
        length = len(split)
        zip_file_name = split[length - 1]
        if path == '':
            path = os.path.join(os.path.dirname(__file__), zip_file_name)
        else:
            path = path + zip_file_name
        response = urlretrieve(download_url, path)
        zip_content = zipfile.ZipFile(path)
        zip_content.extractall()
        os.remove(path) 
開發者ID:nasa,項目名稱:podaacpy,代碼行數:57,代碼來源:l2ss.py


注:本文中的future.moves.urllib.parse.urlencode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。