本文整理汇总了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)])
示例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)
示例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)
示例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)
示例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))
示例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))
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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
}
示例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)