本文整理汇总了Python中urllib.urlencode方法的典型用法代码示例。如果您正苦于以下问题:Python urllib.urlencode方法的具体用法?Python urllib.urlencode怎么用?Python urllib.urlencode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib
的用法示例。
在下文中一共展示了urllib.urlencode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post_request
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def post_request(vals, url):
"""
Build a post request.
Args:
vals: Dictionary of (field, values) for the POST
request.
url: URL to send the data to.
Returns:
Dictionary of JSON response or error info.
"""
# Build the request and send to server
data = urllib.urlencode(vals)
try:
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
except urllib2.HTTPError, err:
return {"error": err.reason, "error_code": err.code}
示例2: get_qrcode_url
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def get_qrcode_url(self, ticket, data=None):
"""
通过 ticket 换取二维码地址
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4
:param ticket: 二维码 ticket
:param data: 额外数据
:return: 二维码地址
"""
url = f"https://we.qq.com/d/{ticket}"
if data:
if isinstance(data, (dict, tuple, list)):
data = urllib.urlencode(data)
data = to_text(base64.b64encode(to_binary(data)))
url = f"{url}#{data}"
return url
示例3: __init__
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def __init__(
self,
params,
site_api='https://maps.googleapis.com/maps/api/streetview',
site_metadata='https://maps.googleapis.com/maps/api/streetview/metadata'):
# (params) Set default params
defaults = {
'size': '640x640'
}
for i in range(len(params)):
for k in defaults:
if k not in params[i]:
params[i][k] = defaults[k]
self.params = params
# (image) Create image api links from parameters
self.links = [site_api + '?' + urlencode(p) for p in params]
# (metadata) Create metadata api links and data from parameters
self.metadata_links = [site_metadata + '?' + urlencode(p) for p in params]
self.metadata = [requests.get(url, stream=True).json() for url in self.metadata_links]
示例4: reverseip
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def reverseip(url):
"""return domains from given the same server"""
# get only domain name
url = urlparse(url).netloc if urlparse(url).netloc != '' else urlparse(url).path.split("/")[0]
source = "http://domains.yougetsignal.com/domains.php"
useragent = useragents.get()
contenttype = "application/x-www-form-urlencoded; charset=UTF-8"
# POST method
opener = urllib2.build_opener(
urllib2.HTTPHandler(), urllib2.HTTPSHandler())
data = urllib.urlencode([('remoteAddress', url), ('key', '')])
request = urllib2.Request(source, data)
request.add_header("Content-type", contenttype)
request.add_header("User-Agent", useragent)
try:
result = urllib2.urlopen(request).read()
except urllib2.HTTPError, e:
print >> sys.stderr, "[{}] HTTP error".format(e.code)
示例5: search
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def search(self, query, stop=100):
'''
:type query : str
:param query: Query for search
:type stop : int
:param stop : Last result to retrieve.
:rtype: list
'''
links = []
start = 1
for page in range(int(round(int(stop), -1)) / 10):
URL = (self.bingsearch % (urllib.urlencode({'q': query}))) + '&first=' + str(start)
html = self.get_page(URL)
result = self.parse_links(html)
[links.append(_) for _ in result if _ not in links]
start = start + 10
return links
示例6: send_sms_builtin
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def send_sms_builtin(self, recipient, sender=None):
"""
Sends SMS through built-in gateway
"""
if not settings.SMS_HTTP_URL:
raise ValueError(_('System is not configured for built-in SMS support.'))
if sender is None:
location = self.created_by.location
sender = location.title
data = urllib.urlencode({
'username' : settings.SMS_HTTP_USERNAME,
'password' : settings.SMS_HTTP_PASSWORD,
'numberto' : recipient.replace(' ', ''),
'numberfrom': sender.encode(SMS_ENCODING),
'message' : self.body.encode(SMS_ENCODING),
})
from ssl import _create_unverified_context
f = urllib.urlopen(settings.SMS_HTTP_URL, data, context=_create_unverified_context())
return f.read()
示例7: send
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def send(self):
pwhash = md5(self.conf['sms_http_password']).hexdigest()
params = {
'username' : self.conf['sms_http_user'],
'password' : pwhash,
'message' : self.body,
'from' : self.sender,
'to' : self.recipient,
}
if self.msg:
dlruri = settings.SERVO_URL + '/api/messages/?id={0}'.format(self.msg.code)
params['notify_url'] = dlruri
params = urllib.urlencode(params)
r = urllib.urlopen(self.URL, params, context=_create_unverified_context()).read()
if 'ERROR:' in r:
raise ValueError(self.ERRORS.get(r, _('Unknown error (%s)') % r))
示例8: urlEncodeParams
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def urlEncodeParams(data):
"""
Return data URL-encoded.
This function specifically handles None and boolean values
to convert them to JSON-friendly strings (e.g. None -> 'null').
"""
copy = dict()
for key, value in six.iteritems(data):
if value is None:
copy[key] = 'null'
elif isinstance(value, bool):
copy[key] = json.dumps(value)
else:
copy[key] = value
return urllib.urlencode(copy, doseq=True)
示例9: _setParams
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def _setParams(self):
parsedURL = urlparse.urlparse(self.url)
# setting the path
if self.useAbsolutePath == True:
self._path = self.url
else:
self._path = parsedURL.path
self.qs = parsedURL.query
if self._path == '':
self._path = '/'
# fix the body if it is in dict format
if isinstance(self.body,dict):
self.body = urllib.urlencode(self.body)
# set other necessary parameters
self.targetName = parsedURL.netloc
self.targetPort = parsedURL.port
self.targetProtocol = (parsedURL.scheme).lower()
if self.targetProtocol == 'https':
self.isSSL = True
if self.targetPort == None: self.targetPort = 443
elif self.targetPort == None:
self.targetPort = 80
示例10: _setParams
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def _setParams(self):
parsedURL = urlparse.urlparse(self.url)
# setting the path
if self.useAbsolutePath == True:
self._path = self.url
else:
self._path = parsedURL.path
self.qs = parsedURL.query
if self._path == '':
self._path = '/'
# fix the body if it is in dict format
if isinstance(self.body,dict):
self.body = urllib.urlencode(self.body)
# set other necessary parameters
self.targetName = parsedURL.hostname
self.targetPort = parsedURL.port
self.targetProtocol = (parsedURL.scheme).lower()
if self.targetProtocol == 'https':
self.isSSL = True
if self.targetPort == None: self.targetPort = 443
elif self.targetPort == None:
self.targetPort = 80
示例11: upd
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def upd(category, sort, str):
post = urllib.urlencode({'checkbox_ftp':'on', 'checkbox_tor':'on','word':str})
request = urllib2.Request('http://krasfs.ru/search.php?key=newkey')#url, post)
request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)')
request.add_header('Host', 'www.krasfs.ru')
request.add_header('Accept', '*/*')
request.add_header('Accept-Language', 'ru-RU')
request.add_header('Referer', 'http://www.krasfs.ru')
try:
f = urllib2.urlopen(request)
html = f.read()
html = html.replace(chr(10),"")
n=html.find("<newkey>")
k=html.find("</newkey>")
key = html[n+8:k]
except IOError, e:
if hasattr(e, 'reason'):
print 'We failed to reach a server. Reason: '+ e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request. Error code: '+ e.code
key = "59165b78-bf91-11e1-86bf-c6ab051766ba"
示例12: run_simulation
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def run_simulation(self):
global TARGET, ADDR, VULN_VAR, TIMEOUT, REQ_TOTAL,\
METHOD, OTHER_VARIABLES
tmp = OTHER_VARIABLES
tmp[VULN_VAR] = self.genome
try:
if METHOD == 0:
prep = urllib.urlencode(tmp)
r = urllib.urlopen('http://%s/%s' % (TARGET, ADDR), data=prep, timeout=TIMEOUT)
else:
prep = urllib.urlencode(tmp)
req = urllib.Request('http://%s/%s' % (TARGET, ADDR), data=prep)
r = urllib.urlopen(req)
REQ_TOTAL += 1
self.m_text['text'] = r.get_data()
self.m_text['url'] = r.get_full_url()
self.m_text['status_code'] = r.getcode()
except:
pass
return self.m_text
示例13: call_method
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def call_method(method, data):
data.update({'access_token': TOKEN})
data = urllib.urlencode(data)
try:
result = urlfetch.fetch(
BASE_URL.format(method=method, qs=data),
method=urlfetch.GET,
deadline=10)
except DeadlineExceededError as e:
logging.exception(e)
return None
if result.status_code == 200:
return json.loads(result.content).get('data')
else:
logging.error(result.content)
return None
示例14: from_torrent_url
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def from_torrent_url(url):
import base64
import bencode
import hashlib
import urllib
from kmediatorrent.utils import url_get
torrent_data = url_get(url)
metadata = bencode.bdecode(torrent_data)
hashcontents = bencode.bencode(metadata['info'])
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest)
params = {
'dn': metadata['info']['name'],
'tr': metadata['announce'],
}
plugin.log.info(params)
paramstr = urllib.urlencode(params)
return 'magnet:?%s&%s' % ('xt=urn:btih:%s' % b32hash, paramstr)
示例15: _execute_request
# 需要导入模块: import urllib [as 别名]
# 或者: from urllib import urlencode [as 别名]
def _execute_request(self, path, post_params=None):
url = "https://flow.polar.com%s" % path
self._logger.debug("Requesting '%s'" % url)
if post_params != None:
postData = urllib.urlencode(post_params)
else:
postData = None
try:
response = self._url_opener.open(url, postData)
data = response.read()
except Exception, e:
self._logger.error("Error fetching %s: %s" % (url, e))
raise Exception(e)