当前位置: 首页>>代码示例>>Python>>正文


Python escape.json_encode方法代码示例

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


在下文中一共展示了escape.json_encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def get(self, *args, **kwargs):

    method = self.get_argument("method")
    address = self.get_argument("address")
    callback = self.get_argument("callback")
    self.application.log('HTTP_GET', '/api/receive/' + self.request.query )


    if method != 'create':
      raise tornado.web.MissingArgumentError('method')

    input_address = self.application.bitcoind.getnewaddress('')

    from models import ForwardingAddress
    self.application.log('CREATE', 'FORWARDING_ADDRESS', ",".join([address, input_address, callback]) )
    ForwardingAddress.create(self.application.db_session, address, input_address, callback)

    result = {
      'input_address': input_address,
      'fee_percent' : 0,
      'destination' : address,
      'callback_url': callback
    }

    self.write(json_encode(result)) 
开发者ID:bitex-coin,项目名称:backend,代码行数:27,代码来源:create_receive_handler.py

示例2: write

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def write(self, chunk):
        """Writes the given chunk to the output buffer.

        To write the output to the network, use the flush() method below.

        If the given chunk is a dictionary, we write it as JSON and set
        the Content-Type of the response to be ``application/json``.
        (if you want to send JSON as a different ``Content-Type``, call
        set_header *after* calling write()).

        Note that lists are not converted to JSON because of a potential
        cross-site security vulnerability.  All JSON output should be
        wrapped in a dictionary.  More details at
        http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish().  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk) 
开发者ID:viewfinderco,项目名称:viewfinder,代码行数:26,代码来源:web.py

示例3: write_json

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def write_json(self, code, message='', data=None):
        if self._mode != self.MODE_JSON:
            log.w('request `{}`, should be json request.\n'.format(self.request.uri))
            self.write('should be json request.')
            self.finish()
            return

        if not isinstance(code, int):
            raise RuntimeError('`code` must be a integer.')
        if not isinstance(message, str):
            raise RuntimeError('`msg` must be a string.')

        if data is None:
            data = list()

        _ret = {'code': code, 'message': message, 'data': data}

        self.set_header("Content-Type", "application/json")
        self.write(json_encode(_ret))
        self.finish() 
开发者ID:tp4a,项目名称:teleport,代码行数:22,代码来源:controller.py

示例4: post

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def post(self):
        login_id = self.get_argument('login_id')
        password = self.get_argument('password')
        if login_id and password:
            auth = KanColleAuth(login_id, password)
            try:
                flash_url, world_ip, token, starttime, owner = yield auth.get_flash()
                result = {'status': 1,
                          'world_ip': world_ip,
                          'token': token,
                          'starttime': starttime,
                          'owner': owner}
            except OoiAuthError as e:
                result = {'status': 0, 'message': e.message}
            self.set_header('Content-Type', 'application/json')
            self.write(json_encode(result))

        else:
            self.send_error(400) 
开发者ID:acgx,项目名称:ooi2,代码行数:21,代码来源:handlers.py

示例5: write

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def write(self, chunk):
        """Writes the given chunk to the output buffer.

        To write the output to the network, use the flush() method below.

        If the given chunk is a dictionary, we write it as JSON and set
        the Content-Type of the response to be application/json.
        (if you want to send JSON as a different Content-Type, call
        set_header *after* calling write()).

        Note that lists are not converted to JSON because of a potential
        cross-site security vulnerability.  All JSON output should be
        wrapped in a dictionary.  More details at
        http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish().  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk) 
开发者ID:omererdem,项目名称:honeything,代码行数:26,代码来源:web.py

示例6: test_debug_post_revisit

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def test_debug_post_revisit(self):
        body = {
            'uuid': 'a',
            'name': 'b',
            'properties': {},
            'coordinates': [0, 0],
        }
        response = self.fetch(
            '/debug/facilities', method='POST', body=json_encode(body),
            _disable_xsrf=False
        )
        self.assertEqual(response.code, 201, msg=response.body)

        facility_response = self.fetch('/debug/facilities')
        lzs = lzstring.LZString()
        facility_json = json_decode(facility_response.body)
        compressed = facility_json['facilities']['children']['wn']['data'][0]
        facilities = lzs.decompressFromUTF16(compressed)
        self.assertEqual(json_decode(facilities)[-1]['name'], 'b') 
开发者ID:SEL-Columbia,项目名称:dokomoforms,代码行数:21,代码来源:test_handlers.py

示例7: test_login_success

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def test_login_success(self):
        dokomoforms.handlers.auth.options.https = False
        with patch.object(handlers.Login, '_async_post') as p:
            dummy = lambda: None
            dummy.body = json_encode(
                {'status': 'okay', 'email': 'test_creator@fixtures.com'}
            )
            p.return_value = tornado.gen.Task(
                lambda callback=None: callback(dummy)
            )
            response = self.fetch(
                '/user/login?assertion=woah', method='POST', body='',
                _logged_in_user=None
            )
        self.assertEqual(response.code, 200, msg=response.body)
        self.assertEqual(
            response.headers['Set-Cookie'].lower().count('secure'),
            1
        ) 
开发者ID:SEL-Columbia,项目名称:dokomoforms,代码行数:21,代码来源:test_handlers.py

示例8: test_login_success_secure_cookie

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def test_login_success_secure_cookie(self):
        dokomoforms.handlers.auth.options.https = True
        with patch.object(handlers.Login, '_async_post') as p:
            dummy = lambda: None
            dummy.body = json_encode(
                {'status': 'okay', 'email': 'test_creator@fixtures.com'}
            )
            p.return_value = tornado.gen.Task(
                lambda callback=None: callback(dummy)
            )
            response = self.fetch(
                '/user/login?assertion=woah', method='POST', body='',
                _logged_in_user=None
            )
        self.assertEqual(response.code, 200, msg=response.body)
        self.assertIn('secure', response.headers['Set-Cookie'].lower()) 
开发者ID:SEL-Columbia,项目名称:dokomoforms,代码行数:18,代码来源:test_handlers.py

示例9: get

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def get(self):
    """
    Handles `/endpoint0` resource.
    """
    try:
      logging.info("/endpoint0 serving from %s has been invoked from %s", self.request.host, self.request.remote_ip)
      self.set_header("Content-Type", "application/json")
      self.write(json_encode(
        {
          "version" : VERSION,
          "host" : self.request.host,
          "result" : "all is well"
        }
      ))
      self.finish()
    except Exception, e:
      logging.debug(e)
      self.set_status(404) 
开发者ID:mhausenblas,项目名称:simpleservice,代码行数:20,代码来源:simpleservice.py

示例10: request

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def request(self, method, url, headers=None, data=None, json=None, form=None, **kwargs):
        if not headers:
            headers = {}

        if json is not None:
            headers['Content-Type'] = 'application/json'
            data = json_encode(json)

        elif form is not None:
            headers['Content-Type'] = 'application/x-www-form-urlencoded'
            data = urlencode(form)

        response = self.fetch(url, method=method, headers=headers, body=data, allow_nonstandard_methods=True,
                              **kwargs)

        if response.code / 100 != 2:
            logger.error(response.body)

        return response 
开发者ID:JustForFunnnn,项目名称:webspider,代码行数:21,代码来源:base.py

示例11: create_from_json_oembed

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def create_from_json_oembed(link=None, oembed_doc=None, thumbnail_file_path=None):
        """
        Ideally this is a link right now. Specificallly a video link.

        JSON object, thumbnail_path, and the actual url comes in, a sha1 should be created from the url and the
            file_key takes that sha1 value. Then call get_from_file with the type=link
            value set along with the thumbnail path in place.

            The resulting sourcefile should then have the data field set with the oembed doc.

            A source file should be created and returned.
        """
        sha1_key = Sourcefile.get_sha1_file_key(file_path=None, file_data=link)
        sf = Sourcefile.get_from_file(thumbnail_file_path, sha1_key, type='link')
        if sf:
            sf.data = json_encode(oembed_doc)
            sf.save()
        return sf 
开发者ID:MLTSHP,项目名称:mltshp,代码行数:20,代码来源:sourcefile.py

示例12: post

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def post(self, share_key, comment_id):
        shared_file = models.Sharedfile.get_by_share_key(share_key)
        user = self.get_current_user_object()
        comment = Comment.get("id=%s", comment_id)

        if not shared_file or not comment:
            raise tornado.web.HTTPError(404)

        existing_comment_like = models.CommentLike.get("comment_id = %s and user_id = %s",
                comment.id, user.id)

        if existing_comment_like:
            existing_comment_like.deleted = 1
            existing_comment_like.save()

        json = self.get_argument("json", False)
        if json:
            self.set_header("Cache-Control","no-store, no-cache, must-revalidate");
            self.set_header("Pragma","no-cache");
            self.set_header("Expires", 0);
            count = models.CommentLike.where_count("comment_id = %s", comment.id)
            return self.write(json_encode({'response':'ok', 'count': count, 'like' : True }))
        else:
            return self.redirect("/p/%s?salty" % (share_key,)) 
开发者ID:MLTSHP,项目名称:mltshp,代码行数:26,代码来源:image.py

示例13: post

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def post(self, user_name):
        is_json = self.get_argument('json', None)
        user = self.get_current_user_object()

        shake_owner = User.get('name="%s"' % (user_name))
        if not shake_owner:
            raise tornado.web.HTTPError(404)

        if not user.subscribe_to_user(shake_owner):
            if is_json:
                return self.write(json_encode({'error':'error'}))
            else:
                return self.redirect('/user/%s' % (user_name))
        else:
            if is_json:
                return self.write(json_encode({'subscription_status': True}))
            else:
                return self.redirect('/user/%s' % (user_name)) 
开发者ID:MLTSHP,项目名称:mltshp,代码行数:20,代码来源:account.py

示例14: post

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def post(self, shake_id):
        is_json = self.get_argument('json', None)
        user = self.get_current_user_object()

        shake = Shake.get('id=%s and deleted=0', shake_id)
        if not shake:
            if is_json:
                return self.write(json_encode({'error':'Shake not found.'}))
            else:
                return self.redirect(shake.path())

        if not user.subscribe(shake):
            if is_json:
                return self.write(json_encode({'error':'error'}))
            else:
                return self.redirect(shake.path())
        else:
            if is_json:
                return self.write(json_encode({'subscription_status': True}))
            else:
                return self.redirect(shake.path()) 
开发者ID:MLTSHP,项目名称:mltshp,代码行数:23,代码来源:shake.py

示例15: get

# 需要导入模块: from tornado import escape [as 别名]
# 或者: from tornado.escape import json_encode [as 别名]
def get(self):
        if self.get_argument('oauth_token', None):
            user = yield self.get_authenticated_user()
            del user["description"]
            self.set_secure_cookie(self.COOKIE_NAME, json_encode(user))
            self.redirect(self.get_argument('next', '/'))
        else:
            yield self.authorize_redirect(callback_uri=self.request.full_url()) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:10,代码来源:twitterdemo.py


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