def send_email(to, subject, html):
if isinstance(to, unicode):
to = to.encode('utf-8')
if isinstance(subject, unicode):
subject = subject.encode('utf-8')
if isinstance(html, unicode):
html = html.encode('utf-8')
data = {
'from': CONFIG.EMAIL_SENDER,
'to': to,
'subject': subject,
'html': html
}
data = urlencode(data)
request = HTTPRequest(
url=_MAILGUN_API_URL,
method='POST',
auth_username='api',
auth_password=CONFIG.MAILGUN_API_KEY,
body=data
)
client = AsyncHTTPClient()
try:
yield client.fetch(request)
except HTTPError as e:
try:
response = e.response.body
except AttributeError:
response = None
logging.exception('failed to send email:\nto: %s\nsubject: %s\nhtml: %s\nresponse: %s', to, subject, html, response)
python类urlencode()的实例源码
def push_state(self, request, title, url=''):
if request.is_mobile():
# FIXME hack????webview?????document.title???
script = '''
(function(){
var $body = $('body');
var $iframe = $('<iframe src="/@@/img/favicon.ico" style="display:none;"></iframe>').on('load', function() {
setTimeout(function() {
$iframe.off('load').remove()
}, 0)
}).appendTo($body);
})();
'''
self._append_script(script, False)
title = self._escape_value(title)
# ??ajax???pushState
if not request.headers.has_key('kss'):
self._append_script('document.title=%s' % title, False)
return
form = self.request.form
# ?????
if form.has_key('back'):
return
else:
form['back'] = True
kss = request.getURL()
if form:
kss += '?%s' % urllib.urlencode(form)
data = json.dumps({'form':form, 'url':kss})
if not url:
url = urllib.unquote(kss)
script = "History.trigger=false;History.pushState(%s, %s, '%s')" % (data, title, url)
self._append_script(script, False)
def api_query(self, command, req={}):
if (command == "returnTicker" or command == "return24Volume"):
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command))
return json.loads(ret.read())
elif (command == "returnOrderBook"):
ret = urllib2.urlopen(urllib2.Request(
'https://poloniex.com/public?command=' + command + '¤cyPair=' + str(req['currencyPair'])))
return json.loads(ret.read())
elif (command == "returnMarketTradeHistory"):
ret = urllib2.urlopen(urllib2.Request(
'https://poloniex.com/public?command=' + "returnTradeHistory" + '¤cyPair=' + str(
req['currencyPair'])))
return json.loads(ret.read())
else:
req['command'] = command
req['nonce'] = int(time.time() * 1000)
post_data = urllib.urlencode(req)
sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
headers = {
'Sign': sign,
'Key': self.APIKey
}
ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
jsonRet = json.loads(ret.read())
return self.post_process(jsonRet)
def emit(self, record):
"""
Emit a record.
Send the record to the Web server as a percent-encoded dictionary
"""
try:
import httplib, urllib
host = self.host
h = httplib.HTTP(host)
url = self.url
data = urllib.urlencode(self.mapLogRecord(record))
if self.method == "GET":
if (url.find('?') >= 0):
sep = '&'
else:
sep = '?'
url = url + "%c%s" % (sep, data)
h.putrequest(self.method, url)
# support multiple hosts on one IP address...
# need to strip optional :port from host, if present
i = host.find(":")
if i >= 0:
host = host[:i]
h.putheader("Host", host)
if self.method == "POST":
h.putheader("Content-type",
"application/x-www-form-urlencoded")
h.putheader("Content-length", str(len(data)))
h.endheaders(data if self.method == "POST" else None)
h.getreply() #can't do anything with the result
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def printWatchlistHits(serverurl, watchlistid, watchlisttype, rows):
global cb
pp = pprint.PrettyPrinter(indent=2)
print rows
getparams = {"cb.urlver": 1,
"watchlist_%d" % watchlistid : "*",
"rows": rows }
if watchlisttype == 'modules':
getparams["cb.q.server_added_timestamp"] = "-1440m"
r = cb.cbapi_get("%s/api/v1/binary?%s" % (serverurl, urllib.urlencode(getparams)))
parsedjson = json.loads(r.text)
pp.pprint(parsedjson)
elif watchlisttype == 'events':
getparams["cb.q.start"] = "-1440m"
r = cb.cbapi_get("%s/api/v1/process?%s" % (serverurl, urllib.urlencode(getparams)))
parsedjson = json.loads(r.text)
pp.pprint(parsedjson)
else:
return
print
print "Total Number of results returned: %d" % len(parsedjson['results'])
print
def _getToken():
result = urllib.urlencode({'grant_type': 'client_credentials', 'client_id': 'kodiexodus-7erse', 'client_secret': 'XelwkDEccpHX2uO8NpqIjVf6zeg'})
result = client.request('https://anilist.co/api/auth/access_token', post=result, headers={'Content-Type': 'application/x-www-form-urlencoded'}, error=True)
result = utils.json_loads_as_str(result)
return result['token_type'], result['access_token']
def get_plugin_url(queries):
try:
query = urllib.urlencode(queries)
except UnicodeEncodeError:
for k in queries:
if isinstance(queries[k], unicode):
queries[k] = queries[k].encode('utf-8')
query = urllib.urlencode(queries)
addon_id = sys.argv[0]
if not addon_id: addon_id = addonId()
return addon_id + '?' + query
def movie(self, imdb, title, localtitle, aliases, year):
try:
aliases.append({'country': 'us', 'title': title})
url = {'imdb': imdb, 'title': title, 'year': year, 'aliases': aliases}
url = urllib.urlencode(url)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
aliases.append({'country': 'us', 'title': tvshowtitle})
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year, 'aliases': aliases}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None: return
url = urlparse.parse_qs(url)
url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])
url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
url = urllib.urlencode(url)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None: return
url = urlparse.parse_qs(url)
url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])
url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
url = urllib.urlencode(url)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
'''
Takes TV show information, encodes it as name value pairs, and returns
a string of url params
Keyword arguments:
imdb -- string - imdb tv show id
tvdb -- string - tvdb tv show id
tvshowtitle -- string - name of the tv show
localtvshowtitle -- string - regional title of the tv show
year -- string - year the tv show was released
Returns:
url -- string - url encoded params
'''
try:
data = {
'imdb': imdb,
'tvdb': tvdb,
'tvshowtitle': tvshowtitle,
'year': year
}
url = urllib.urlencode(data)
return url
except Exception:
return
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def movie(self, imdb, title, localtitle, aliases, year):
try:
aliases.append({'country': 'us', 'title': title})
url = {'imdb': imdb, 'title': title, 'year': year, 'aliases': aliases}
url = urllib.urlencode(url)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
aliases.append({'country': 'us', 'title': tvshowtitle})
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year, 'aliases': aliases}
url = urllib.urlencode(url)
return url
except:
return
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None: return
url = urlparse.parse_qs(url)
url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])
url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
url = urllib.urlencode(url)
return url
except:
return