本文整理汇总了Python中requests.compat.urlencode函数的典型用法代码示例。如果您正苦于以下问题:Python urlencode函数的具体用法?Python urlencode怎么用?Python urlencode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了urlencode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: query_hph
def query_hph( method='get', **argvs):
data = OrderedDict(sorted(argvs.items(), key=lambda t: t[0]))
time_s = int(time.time())
data_str = unquote(urlencode(data))
hash_str = 'private_key={0}&ts={1}&{2}'.format(private_key,
time_s,
data_str)
sign = hashlib.md5(hash_str.encode('utf-8')).hexdigest()
data.update({'sign': sign, 'ts': str(time_s)})
par_str = unquote(urlencode(data))
url = build_url(url=URL, qs=par_str)
try:
response = requests.get(url)
response_dict = response.json()
except requests.RequestException as e:
return False
response_code = response_dict.get('code')
if response_code == 0:
return response_dict['data']
else:
print('no info')
return False
示例2: rtmp_publish_url
def rtmp_publish_url(self, stream_id, app_name=None):
if app_name is None:
app_name = self._app_name
url_path = '/' + urljoin(quote_plus(app_name)+'/', quote_plus(stream_id))
query = {'vhost': self._play_domain}
if not self._auth_type:
return 'rtmp://' + self._publish_domain + url_path + '?' + urlencode(query)
elif self._auth_type == self.AUTH_TYPE_A:
query['auth_key'] = self._calc_auth_token(url_path)
return 'rtmp://' + self._publish_domain + url_path + '?' + urlencode(query)
else:
raise IVRError('Unknown auth type {0}'.format(self._auth_type))
示例3: reply
def reply(self, url, special_reply_content=None):
"""
:param special_reply_content: will use this reply instead of self.replies
:return: if success return True, else return False
"""
assert self.logged, 'Did not login successfully!'
assert self._reply_contents or special_reply_content, 'No reply text!'
resp = self.get(url)
followup_value = self.pat_followup_value.search(resp.text).group(1).strip(r'\"')
# 为什么不用parse_qs? 因为cc98 url上的boardid有些大写有些小写,不是统一的,
# cc98 is too SB
# 为什么不用lower降成小写?因为我写完上面那句话才想起来的,为了保留上面那句话
# I is too SB
qs_list = parse_qsl(urlparse(url).query)
boardid = qs_list[0][1]
rootid = qs_list[1][1]
reply_url = self.REPLY_BASE_URL + '?' + urlencode((('method', 'fastreply'), ('BoardID', boardid)))
cookies_password = parse_qs(resp.request.headers['cookie']).get('password')[0]
post_reply = special_reply_content if special_reply_content else random.choice(self._reply_contents)
post_form = {
'followup': followup_value,
'RootID': rootid,
'star': '1',
'UserName': self.username,
'passwd': cookies_password,
'Expression': 'face7.gif',
'Content': post_reply,
'signflag': 'yes',
}
self._reply_resp = self.post(reply_url, data=post_form)
return self._reply_resp.ok
示例4: _encode_params
def _encode_params(data):
"""Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
if data is None:
return ''
elif isinstance(data, basestring):
return data
elif hasattr(data, 'read'):
return data
elif hasattr(data, '__iter__'):
result = []
for k, vs in sorted(CaseInsensitiveDict(data).lower_items()):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
return urlencode(result, doseq=True)
else:
return data
示例5: _get_auth
def _get_auth(self):
self.url = 'https://api.put.io/login'
self.session.headers['Accept'] = 'application/json'
next_params = {
'client_id': self.client_id,
'response_type': 'token',
'redirect_uri': self.redirect_uri
}
post_data = {
'name': self.username,
'password': self.password,
'next': '/v2/oauth2/authenticate?' + urlencode(next_params)
}
try:
response = self.session.post(self.url, data=post_data,
allow_redirects=False)
response.raise_for_status()
response = self.session.get(response.headers['location'],
allow_redirects=False)
response.raise_for_status()
resulting_uri = '{redirect_uri}#access_token=(.*)'.format(
redirect_uri=re.escape(self.redirect_uri))
self.auth = re.search(resulting_uri, response.headers['location']).group(1)
except Exception as error:
helpers.handle_requests_exception(error)
self.auth = None
return self.auth
示例6: _send
def _send(self):
"""POST the user's question and all required information to the
Cleverbot service
Cleverbot obfuscates how it generates the 'icognocheck' token. The token
is currently the md5 checksum of the 10th through 36th characters of the
encoded data. This may change in the future.
"""
# Set data as appropriate
if self.conversation:
linecount = 1
for line in reversed(self.conversation):
linecount += 1
self.data['vText' + str(linecount)] = line
if linecount == 8:
break
# Generate the token
enc_data = urlencode(self.data)
digest_txt = enc_data[9:35]
token = hashlib.md5(digest_txt.encode('utf-8')).hexdigest()
self.data['icognocheck'] = token
# POST the data to Cleverbot and return
return self.session.post(self.SERVICE_URL,
data=self.data,
headers=self.headers)
示例7: authentication_url
def authentication_url(self):
params = {
'client_id': self.client_id,
'response_type': 'token',
'redirect_uri': self.redirect_uri
}
return self.auth_path + "?" + urlencode(params)
示例8: updateCache
def updateCache(self):
# check if we should update
if not self.shouldUpdate():
return
# clear cache
self._clearCache()
# set updated
self.setLastUpdate()
cl = []
for group in ["alt.binaries.hdtv", "alt.binaries.hdtv.x264", "alt.binaries.tv", "alt.binaries.tvseries", "alt.binaries.teevee"]:
urlArgs = {"max": 50, "g": group}
url = self.provider.urls['rss'] + "?" + urlencode(urlArgs)
logger.log("Cache update URL: {}".format(url), logger.DEBUG)
for item in self.getRSSFeed(url)["entries"] or []:
ci = self._parseItem(item)
if ci:
cl.append(ci)
if len(cl) > 0:
cache_db_con = self._getDB()
cache_db_con.mass_action(cl)
示例9: scrape_attachments_page
def scrape_attachments_page(self, agenda_item_id, attachments_page_url):
print("scrape Attachment " + attachments_page_url)
html = requests.get(attachments_page_url).text
soup = BeautifulSoup(html)
txt = soup.get_text()
if "Auf die Anlage konnte nicht zugegriffen werden oder Sie existiert nicht mehr." in txt:
print("Zu TOP " + agenda_item_id + " fehlt mindestens eine Anlage")
yield ('404', {'agenda_item_id': agenda_item_id,
'attachmentsPageURL': attachments_page_url})
else:
for forms in soup.find_all('form'):
title = forms.get_text()
parameters = {form['name']: form['value']
for form
in forms.find_all('input', {'type': 'hidden'})}
file_with_parameters = '?'.join((forms['action'],
urlencode(parameters)))
url = self.base_url + file_with_parameters
yield ('OK', {'sid': self.meeting_id,
'agenda_item_id': agenda_item_id,
'attachment_title': title,
'attachment_file_url': url})
示例10: _send
def _send(self):
"""POST the user's question and all required information to the
Cleverbot API
Cleverbot tries to prevent unauthorized access to its API by
obfuscating how it generates the 'icognocheck' token. The token is
currently the md5 checksum of the 10th through 36th characters of the
encoded data. This may change in the future.
TODO: Order is not guaranteed when urlencoding dicts. This hasn't been
a problem yet, but let's look into ordered dicts or tuples instead.
"""
# Set data as appropriate
if self.conversation:
linecount = 1
for line in reversed(self.conversation):
linecount += 1
self.data['vText' + str(linecount)] = line
if linecount == 8:
break
# Generate the token
enc_data = urlencode(self.data)
digest_txt = enc_data[9:35]
token = hashlib.md5(digest_txt.encode('utf-8')).hexdigest()
self.data['icognocheck'] = token
# POST the data to Cleverbot's API and return
return self.session.post(Cleverbot.API_URL,
data=self.data,
headers=Cleverbot.headers)
示例11: get_url_from_form
def get_url_from_form(self, td):
parameters = {tag['name']: tag['value']
for tag in td.form.find_all('input', {'type': 'hidden'})}
file_with_parameters = '?'.join((td.form['action'], urlencode(parameters)))
return urljoin(self.base_url, file_with_parameters)
示例12: _get
def _get(self, method, format, params=None, headers=None, raw=False):
"""Performs GET request"""
from requests.compat import urlencode
url = self._build_url(method, format)
if params:
url = "{0}?{1}".format(url, urlencode(params, True))
return self._request(url, None, headers, format, raw)
示例13: params
def params(self):
return urlencode(OrderedDict([
('cbtt', self.getvalue('station')),
('interval', 'instant'),
('format', 2),
('back', 360)
]))
示例14: search
def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals
results = []
if self.show and not self.show.is_anime:
return results
for mode in search_strings:
items = []
logger.log(u"Search Mode: {}".format(mode), logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS':
logger.log(u"Search string: {}".format(search_string.decode("utf-8")),
logger.DEBUG)
params = {
"page": 'rss',
"cats": '1_0', # All anime
"sort": 2, # Sort Descending By Seeders
"order": 1
}
if mode != 'RSS':
params["term"] = search_string
search_url = self.url + '?' + urlencode(params)
logger.log(u"Search URL: %s" % search_url, logger.DEBUG)
summary_regex = ur"(\d+) seeder\(s\), (\d+) leecher\(s\), \d+ download\(s\) - (\d+.?\d* [KMGT]iB)(.*)"
s = re.compile(summary_regex, re.DOTALL)
results = []
for curItem in self.cache.getRSSFeed(search_url)['entries'] or []:
title = curItem['title']
download_url = curItem['link']
if not all([title, download_url]):
continue
seeders, leechers, torrent_size, verified = s.findall(curItem['summary'])[0]
size = convert_size(torrent_size) or -1
# Filter unseeded torrent
if seeders < self.minseed or leechers < self.minleech:
if mode != 'RSS':
logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {} (S:{} L:{})".format
(title, seeders, leechers), logger.DEBUG)
continue
if self.confirmed and not verified and mode != 'RSS':
logger.log(u"Found result " + title + " but that doesn't seem like a verified result so I'm ignoring it", logger.DEBUG)
continue
item = title, download_url, size, seeders, leechers
if mode != 'RSS':
logger.log(u"Found result: %s with %s seeders and %s leechers" % (title, seeders, leechers), logger.DEBUG)
items.append(item)
# For each search mode sort all the items by seeders if available
items.sort(key=lambda tup: tup[3], reverse=True)
results += items
return results
示例15: _send_to_kodi
def _send_to_kodi(command, host=None, username=None, password=None, dest_app="KODI"): # pylint: disable=too-many-arguments
"""Handles communication to KODI servers via HTTP API
Args:
command: Dictionary of field/data pairs, encoded via urllib and passed to the KODI API via HTTP
host: KODI webserver host:port
username: KODI webserver username
password: KODI webserver password
Returns:
Returns response.result for successful commands or False if there was an error
"""
# fill in omitted parameters
if not username:
username = sickbeard.KODI_USERNAME
if not password:
password = sickbeard.KODI_PASSWORD
if not host:
logger.log(u'No %s host passed, aborting update' % dest_app, logger.WARNING)
return False
for key in command:
if isinstance(command[key], text_type):
command[key] = command[key].encode('utf-8')
enc_command = urlencode(command)
logger.log(u"%s encoded API command: %r" % (dest_app, enc_command), logger.DEBUG)
# url = 'http://%s/xbmcCmds/xbmcHttp/?%s' % (host, enc_command) # maybe need for old plex?
url = 'http://%s/kodiCmds/kodiHttp/?%s' % (host, enc_command)
try:
req = Request(url)
# if we have a password, use authentication
if password:
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
req.add_header("Authorization", authheader)
logger.log(u"Contacting %s (with auth header) via url: %s" % (dest_app, ss(url)), logger.DEBUG)
else:
logger.log(u"Contacting %s via url: %s" % (dest_app, ss(url)), logger.DEBUG)
try:
response = urlopen(req)
except (BadStatusLine, URLError) as e:
logger.log(u"Couldn't contact %s HTTP at %r : %r" % (dest_app, url, ex(e)), logger.DEBUG)
return False
result = response.read().decode(sickbeard.SYS_ENCODING)
response.close()
logger.log(u"%s HTTP response: %s" % (dest_app, result.replace('\n', '')), logger.DEBUG)
return result
except Exception as e:
logger.log(u"Couldn't contact %s HTTP at %r : %r" % (dest_app, url, ex(e)), logger.DEBUG)
return False