本文整理汇总了Python中tornado.escape.to_basestring函数的典型用法代码示例。如果您正苦于以下问题:Python to_basestring函数的具体用法?Python to_basestring怎么用?Python to_basestring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_basestring函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _oauth_access_token_url
def _oauth_access_token_url(self, request_token: Dict[str, Any]) -> str:
consumer_token = self._oauth_consumer_token()
url = self._OAUTH_ACCESS_TOKEN_URL # type: ignore
args = dict(
oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
oauth_token=escape.to_basestring(request_token["key"]),
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
oauth_version="1.0",
)
if "verifier" in request_token:
args["oauth_verifier"] = request_token["verifier"]
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
signature = _oauth10a_signature(
consumer_token, "GET", url, args, request_token
)
else:
signature = _oauth_signature(
consumer_token, "GET", url, args, request_token
)
args["oauth_signature"] = signature
return url + "?" + urllib.parse.urlencode(args)
示例2: _oauth_request_token_url
def _oauth_request_token_url(self, callback_uri=None, extra_params=None):
consumer_token = self._oauth_consumer_token()
url = self._OAUTH_REQUEST_TOKEN_URL
args = dict(
oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
)
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
if callback_uri == "oob":
args["oauth_callback"] = "oob"
elif callback_uri:
args["oauth_callback"] = urlparse.urljoin(
self.request.full_url(), callback_uri)
if extra_params:
args.update(extra_params)
signature = _oauth10a_signature(consumer_token, "GET", url, args)
else:
signature = _oauth_signature(consumer_token, "GET", url, args)
args["oauth_signature"] = signature
x = url + "?" + urllib.urlencode(args)
print "XXX", x
return x
示例3: _oauth_request_token_url
def _oauth_request_token_url(
self, callback_uri: str = None, extra_params: Dict[str, Any] = None
) -> str:
handler = cast(RequestHandler, self)
consumer_token = self._oauth_consumer_token()
url = self._OAUTH_REQUEST_TOKEN_URL # type: ignore
args = dict(
oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
oauth_version="1.0",
)
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
if callback_uri == "oob":
args["oauth_callback"] = "oob"
elif callback_uri:
args["oauth_callback"] = urllib.parse.urljoin(
handler.request.full_url(), callback_uri
)
if extra_params:
args.update(extra_params)
signature = _oauth10a_signature(consumer_token, "GET", url, args)
else:
signature = _oauth_signature(consumer_token, "GET", url, args)
args["oauth_signature"] = signature
return url + "?" + urllib.parse.urlencode(args)
示例4: _oauth_request_parameters
def _oauth_request_parameters(self, url, access_token, parameters={},
method="GET"):
"""Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request.
"""
consumer_token = self._oauth_consumer_token()
base_args = dict(
oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
oauth_token=escape.to_basestring(access_token["key"]),
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=str(int(time.time())),
oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
oauth_version="1.0",
)
args = {}
args.update(base_args)
args.update(parameters)
if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
signature = _oauth10a_signature(consumer_token, method, url, args,
access_token)
else:
signature = _oauth_signature(consumer_token, method, url, args,
access_token)
base_args["oauth_signature"] = escape.to_basestring(signature)
return base_args
示例5: test_cookie_tampering_future_timestamp
def test_cookie_tampering_future_timestamp(self):
handler = CookieTestRequestHandler()
# this string base64-encodes to '12345678'
handler.set_secure_cookie('foo', binascii.a2b_hex(b'd76df8e7aefc'))
cookie = handler._cookies['foo']
match = re.match(br'12345678\|([0-9]+)\|([0-9a-f]+)', cookie)
self.assertTrue(match)
timestamp = match.group(1)
sig = match.group(2)
self.assertEqual(
_create_signature(handler.application.settings["cookie_secret"],
'foo', '12345678', timestamp),
sig)
# shifting digits from payload to timestamp doesn't alter signature
# (this is not desirable behavior, just confirming that that's how it
# works)
self.assertEqual(
_create_signature(handler.application.settings["cookie_secret"],
'foo', '1234', b'5678' + timestamp),
sig)
# tamper with the cookie
handler._cookies['foo'] = utf8('1234|5678%s|%s' % (
to_basestring(timestamp), to_basestring(sig)))
# it gets rejected
with ExpectLog(gen_log, "Cookie timestamp in future"):
self.assertTrue(handler.get_secure_cookie('foo') is None)
示例6: handle_stream
def handle_stream(self, stream, address):
self.selected_db = 0
self._stream = stream
CRLF = b'\r\n'
n_args = yield gen.Task(stream.read_until, CRLF)
n_args = to_basestring(n_args)
while n_args and n_args[0] == '*':
yield gen.Task(stream.read_until, CRLF)
command = yield gen.Task(stream.read_until, CRLF)
command = to_basestring(command)
# Read command arguments
arg_num = int(n_args.strip()[1:]) - 1
if arg_num > 0:
for __ in range(0, arg_num):
# read the $N line
yield gen.Task(stream.read_until, CRLF)
# read the argument line
arg = yield gen.Task(stream.read_until, CRLF)
arg = to_basestring(arg)
if command == 'SELECT\r\n':
self.selected_db = int(arg.strip())
stream.write(b'+OK\r\n')
# Read the next command
n_args = yield gen.Task(stream.read_until, CRLF)
n_args = to_basestring(n_args)
示例7: process_data
def process_data(self, data, cmd_line):
data = to_basestring(data)
data = data[:-2] # strip \r\n
if data == '$-1':
response = None
elif data == '*0' or data == '*-1':
response = []
else:
head, tail = data[0], data[1:]
if head == '*':
return partial(self.consume_multibulk, int(tail), cmd_line)
elif head == '$':
return partial(self._consume_bulk, tail)
elif head == '+':
response = tail
elif head == ':':
response = int(tail)
elif head == '-':
if tail.startswith('ERR'):
tail = tail[4:]
response = ResponseError(tail, cmd_line)
else:
raise ResponseError('Unknown response type %s' % head,
cmd_line)
return response
示例8: format_command
def format_command(self, *tokens, **kwargs):
cmds = []
for t in tokens:
e_t = self.encode(t)
e_t_s = to_basestring(e_t)
cmds.append('$%s\r\n%s\r\n' % (len(e_t), e_t_s))
return '*%s\r\n%s' % (len(tokens), ''.join(cmds))
示例9: b64_decode
def b64_decode(val):
val = utf8(val)
result = base64.b64decode(val)
return to_basestring(result)
示例10: _parse_json
def _parse_json(request):
s = to_basestring(request.body)
if underscore_case:
json_dict = json.loads(s, object_hook=_process_camel_case)
else:
json_dict = json.loads(s)
return ObjectDict(json_dict)
示例11: get_current_user
def get_current_user(self):
'''
Fetch current users information.
'''
user = escape.to_basestring(self.get_secure_cookie("mobius_user"))
if user is None:
return None
return JSONObject(user)
示例12: do_api_request
def do_api_request(path, method, post_data={}, body=''):
try:
url = urljoin('https://%s.hackpad.com/api/1.0/' % settings.get('hackpad_domain'), path)
args = dict(
oauth_consumer_key=escape.to_basestring(settings.get('hackpad_oauth_client_id')),
oauth_signature_method='HMAC-SHA1',
oauth_timestamp=str(int(time.time())),
oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
oauth_version='1.0a',
)
signature = _oauth10a_signature(
{
'key':settings.get('hackpad_oauth_client_id'),
'secret':settings.get('hackpad_oauth_secret')
},
method,
url,
args
)
args['oauth_signature'] = signature
api_link = url + '?' + urllib.urlencode(args)
logging.info(api_link)
hackpad = {}
if method.lower() == 'post':
r = requests.post(
api_link,
data=body,
headers={'Content-Type': 'text/plain'},
verify=False
)
hackpad = r.json
else:
r = requests.get(
api_link,
headers={'Content-Type': 'text/plain'},
verify=False
)
hackpad = r.json
except:
logging.info(sys.exc_info()[0])
hackpad = {}
return hackpad
示例13: post
def post(self):
'''
Create new user.
'''
email = escape.to_basestring(self.get_argument('email'))
password = escape.to_basestring(self.get_argument('password'))
log.info("Creating new user: {} - {}".format(email, password))
hashed_password = yield hash_password(password, salt=None, loop=self._loop)
try:
new_user = yield create_user(email, hashed_password, loop=self._loop)
if new_user is None:
raise RequestError("Failed to create user. User possibly already exists.")
if "password" in new_user:
del new_user.password
self.set_secure_cookie("mobius_user", new_user.json_string)
self.redirect(self.get_argument("next_page", "/"))
except RequestError as req_err:
self.render("login.html", error=str(req_err))
示例14: on_message
def on_message(self, message):
parsed = escape.json_decode(message)
chat = {
'parent': 'inbox',
'body': parsed['body'] if len(parsed['body']) <= 128 else 'D`oh.',
'user': parsed['user'],
'time': datetime.datetime.now().strftime('%H:%M:%S %Y-%m-%d')
}
self.update_channel_history(chat)
chat['html'] = escape.to_basestring(
self.render_string('include/message.html', message=chat)
)
self.waiters.broadcast(self.chnl, chat)
示例15: on_message
def on_message(self, message):
parsed = escape.json_decode(message)
logger.warning('GOT MESSAGE %s' % parsed)
if 'dummy' in parsed:
return
chat = {
'parent': 'inbox',
'body': parsed['body'] if len(parsed['body']) <= 128 else 'D`oh.',
'user': parsed['user'],
'time': datetime.datetime.now().strftime('%H:%M:%S %Y-%m-%d')
}
self.update_channel_history(chat)
chat['html'] = escape.to_basestring(
self.render_string('include/message.html', message=chat)
)
self.send_updates(chat)