• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python escape.to_basestring函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tornado.escape.to_basestring函数的典型用法代码示例。如果您正苦于以下问题:Python to_basestring函数的具体用法?Python to_basestring怎么用?Python to_basestring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了to_basestring函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:bdarnell,项目名称:tornado,代码行数:25,代码来源:auth.py


示例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
开发者ID:nod,项目名称:greeneggs,代码行数:27,代码来源:old__netflix.py


示例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)
开发者ID:bdarnell,项目名称:tornado,代码行数:28,代码来源:auth.py


示例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
开发者ID:auscompgeek,项目名称:perfectgift,代码行数:27,代码来源:auth.py


示例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)
开发者ID:akkakks,项目名称:tornado,代码行数:26,代码来源:web_test.py


示例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)
开发者ID:quatrix,项目名称:tornado-redis,代码行数:25,代码来源:test_reconnect.py


示例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
开发者ID:cheungpat,项目名称:tornado-redis,代码行数:27,代码来源:client.py


示例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))
开发者ID:cheungpat,项目名称:tornado-redis,代码行数:7,代码来源:client.py


示例9: b64_decode

 def b64_decode(val):
     
     val = utf8(val)
     
     result = base64.b64decode(val)
     
     return to_basestring(result)
开发者ID:bluehawksky,项目名称:TornadoWeb,代码行数:7,代码来源:util.py


示例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)
开发者ID:barryloper,项目名称:dorthy,代码行数:7,代码来源:web.py


示例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)
开发者ID:ayeganov,项目名称:Mobius,代码行数:8,代码来源:server.py


示例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
开发者ID:JDoe,项目名称:theconversation,代码行数:44,代码来源:hackpad.py


示例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))
开发者ID:ayeganov,项目名称:Mobius,代码行数:20,代码来源:server.py


示例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)
开发者ID:niklak,项目名称:toredis_chat,代码行数:13,代码来源:handlers_.py


示例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)
开发者ID:shtalinberg,项目名称:toredis_chat,代码行数:16,代码来源:handlers.py


示例16: post

 async def post(self):
     """ Send system message in room, for attention users """
     room = self.get_argument('r', False)
     user = self.get_argument('u', False)
     message = self.get_argument('msg', 'no message')
     if not room or not user or user != 'system':
         raise tornado.web.HTTPError(404, 'Incorrect params of query')
     logging.info('Got system message {0}, room "{1}"'.format(message, room))
     chat = {
         "id": str(uuid.uuid4()),
         "body": message,
         "user": user,
         "time": str(int(time.time()))
     }
     chat['html'] = to_basestring(
         self.render_string('system_message.html', message=chat)
     )
     ChatSocketHandler.update_cache(chat, room)
     ChatSocketHandler.send_updates(chat, room)
开发者ID:avezhenya,项目名称:twaddle-chat,代码行数:19,代码来源:app.py


示例17: _on_request_token

 def _on_request_token(self, authorize_url, callback_uri, response):
     if response.error:
         raise Exception("Could not get request token")
     consumer_token = self._oauth_consumer_token()
     request_token = _oauth_parse_response(response.body)
     data = (base64.b64encode(request_token["key"]) + b("|") +
             base64.b64encode(request_token["secret"]))
     self.set_cookie("_oauth_request_token", data)
     args = dict(
             oauth_token=request_token["key"],
             oauth_consumer_key=escape.to_basestring(consumer_token['key']),
             )
     if callback_uri == "oob":
         self.finish(authorize_url + "?" + urllib.urlencode(args))
         return
     elif callback_uri:
         args["oauth_callback"] = urlparse.urljoin(
             self.request.full_url(), callback_uri)
     self.redirect(authorize_url + "?" + urllib.urlencode(args))
开发者ID:nod,项目名称:greeneggs,代码行数:19,代码来源:old__netflix.py


示例18: on_message

 def on_message(self, message):
     """ Performed when a message arrives from a client
     :param message:
     """
     room = self.get_argument('r', False)
     if not room:
         raise tornado.web.HTTPError(404, 'Incorrect params of query')
     logging.info('Got message {0} for room "{1}"'.format(message, room))
     parsed = json_decode(message)
     parsed['body'] = replace_smiles(spam_links(parsed['body']))
     chat = {
         "id": str(uuid.uuid4()),
         "body": parsed['body'],
         "user": parsed['user'],
         "time": str(int(time.time()))
     }
     chat['html'] = to_basestring(
         self.render_string('message.html', message=chat)
     )
     # put it in cache and give to listeners
     ChatSocketHandler.update_cache(chat, room)
     ChatSocketHandler.send_updates(chat, room)
开发者ID:avezhenya,项目名称:twaddle-chat,代码行数:22,代码来源:app.py


示例19: tex_escape

def tex_escape(text):
    return REGEX.sub(lambda match: CONV[match.group()], to_basestring(text))
开发者ID:junfenglx,项目名称:rdfy,代码行数:2,代码来源:rdfy.py


示例20: html_escape

 def html_escape(self, value):
     return self.ESCAPE_RE.sub(lambda m: self.ESCAPE_DICT[m.group(0)],
             escape.to_basestring(value))
开发者ID:demonye,项目名称:svndiff-gui,代码行数:3,代码来源:svndiff.py



注:本文中的tornado.escape.to_basestring函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python escape.to_unicode函数代码示例发布时间:2022-05-27
下一篇:
Python escape.recursive_unicode函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap