Python tornado.escape.json_encode() Examples

The following are 30 code examples of tornado.escape.json_encode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.escape , or try the search function .
Example #1
Source File: controller.py    From teleport with Apache License 2.0 6 votes vote down vote up
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() 
Example #2
Source File: sourcefile.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
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 
Example #3
Source File: image.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
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,)) 
Example #4
Source File: account.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
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)) 
Example #5
Source File: account.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
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.unsubscribe_from_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': False}))
            else:
                return self.redirect('/user/%s' % (user_name)) 
Example #6
Source File: shake.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
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()) 
Example #7
Source File: shake.py    From mltshp with Mozilla Public License 2.0 6 votes vote down vote up
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({'error':'Shake not found.'})
            else:
                return self.redirect(shake.path())

        if not user.unsubscribe(shake):
            if is_json:
                return self.write({'error':'error'})
            else:
                return self.redirect(shake.path())
        else:
            if is_json:
                return self.write(json_encode({'subscription_status': False}))
            else:
                return self.redirect(shake.path()) 
Example #8
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: base.py    From webspider with MIT License 6 votes vote down vote up
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 
Example #10
Source File: handlers.py    From ooi2 with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #11
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
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) 
Example #12
Source File: create_receive_handler.py    From backend with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #13
Source File: web.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #14
Source File: simpleservice.py    From simpleservice with Apache License 2.0 6 votes vote down vote up
def get(self):
    """
    Handles `/env` resource.
    """
    try:
      logging.info("/env 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,
          "env" : str(os.environ),
        }
      ))
      self.finish()
    except Exception, e:
      logging.debug(e)
      self.set_status(404) 
Example #15
Source File: simpleservice.py    From simpleservice with Apache License 2.0 6 votes vote down vote up
def get(self):
    """
    Handles `/info` resource.
    """
    try:
      logging.info("/info 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,
          "from" : self.request.remote_ip
        }
      ))
      self.finish()
    except Exception, e:
      logging.debug(e)
      self.set_status(404) 
Example #16
Source File: test_handlers.py    From dokomoforms with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #17
Source File: test_handlers.py    From dokomoforms with GNU General Public License v3.0 6 votes vote down vote up
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
        ) 
Example #18
Source File: simpleservice.py    From simpleservice with Apache License 2.0 6 votes vote down vote up
def get(self):
    """
    Handles `/health` resource.
    """
    try:
      logging.info("/health 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(
        {
          "healthy" : True
        }
      ))

      if HEALTH_MAX > HEALTH_MIN and HEALTH_MIN >= 0: # make sure no shenanigans take place
        delay_response = random.randrange(float(HEALTH_MIN), float(HEALTH_MAX))
        time.sleep(delay_response/1000.0)
      self.finish()
    except Exception, e:
      logging.debug(e)
      self.set_status(404) 
Example #19
Source File: test_handlers.py    From dokomoforms with GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #20
Source File: simpleservice.py    From simpleservice with Apache License 2.0 6 votes vote down vote up
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) 
Example #21
Source File: test_debug_mode.py    From dokomoforms with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #22
Source File: web.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
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/2009/06/25/json-hijacking.aspx/ and
        https://github.com/facebook/tornado/issues/1009
        """
        if self._finished:
            raise RuntimeError("Cannot write() after finish()")
        if not isinstance(chunk, (bytes, unicode_type, dict)):
            message = "write() only accepts bytes, unicode, and dict objects"
            if isinstance(chunk, list):
                message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
            raise TypeError(message)
        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) 
Example #23
Source File: httpserver_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def finish(self):
            response_body = utf8(json_encode(self.chunk_lengths))
            self.connection.write_headers(
                ResponseStartLine('HTTP/1.1', 200, 'OK'),
                HTTPHeaders({'Content-Length': str(len(response_body))}))
            self.connection.write(response_body)
            self.connection.finish() 
Example #24
Source File: escape_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def test_json_encode(self):
        # json deals with strings, not bytes.  On python 2 byte strings will
        # convert automatically if they are utf8; on python 3 byte strings
        # are not allowed.
        self.assertEqual(json_decode(json_encode(u("\u00e9"))), u("\u00e9"))
        if bytes is str:
            self.assertEqual(json_decode(json_encode(utf8(u("\u00e9")))), u("\u00e9"))
            self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9") 
Example #25
Source File: template.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def generate(self, **kwargs):
        """Generate this template with the given arguments."""
        namespace = {
            "escape": escape.xhtml_escape,
            "xhtml_escape": escape.xhtml_escape,
            "url_escape": escape.url_escape,
            "json_encode": escape.json_encode,
            "squeeze": escape.squeeze,
            "linkify": escape.linkify,
            "datetime": datetime,
            "_tt_utf8": escape.utf8,  # for internal use
            "_tt_string_types": (unicode_type, bytes),
            # __name__ and __loader__ allow the traceback mechanism to find
            # the generated source code.
            "__name__": self.name.replace('.', '_'),
            "__loader__": ObjectDict(get_source=lambda name: self.code),
        }
        namespace.update(self.namespace)
        namespace.update(kwargs)
        exec_in(self.compiled, namespace)
        execute = namespace["_tt_execute"]
        # Clear the traceback module's cache of source data now that
        # we've generated a new template (mainly for this module's
        # unittests, where different tests reuse the same name).
        linecache.clearcache()
        return execute() 
Example #26
Source File: debug.py    From dokomoforms with GNU General Public License v3.0 5 votes vote down vote up
def post(self):
        """Add a facility."""
        global compressed_facilities
        if not revisit_online:
            raise tornado.web.HTTPError(502)
        new_facility = json_decode(self.request.body)
        c_facilities_json = json_decode(compressed_facilities)
        facility_data = (
            c_facilities_json['facilities']['children']['wn']['data'][0]
        )
        uncompressed = json_decode(lzs.decompressFromUTF16(facility_data))
        uncompressed.append({
            '_version': 0,
            'active': True,
            'coordinates': new_facility['coordinates'],
            'createdAt': '2014-04-23T20:32:20.043Z',
            'href': (
                'http://localhost:3000/api/v0/facilities/{}.json'.format(
                    new_facility['uuid']
                )
            ),
            'identifiers': [],
            'name': new_facility['name'],
            'properties': new_facility['properties'],
            'updatedAt': '2014-04-23T20:32:20.043Z',
            'uuid': new_facility['uuid'],
        })
        compressed = lzs.compressToUTF16(json_encode(uncompressed))
        c_facilities_json['facilities']['children']['wn']['data'] = [
            compressed
        ]
        compressed_facilities = json_encode(c_facilities_json).encode()
        self.set_status(201) 
Example #27
Source File: image.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def get(self, share_key):
        sharedfile = Sharedfile.get_by_share_key(share_key)
        value = {
            'title' : escape.xhtml_escape(sharedfile.get_title()),
            'title_raw' : sharedfile.get_title()
        }
        # prevents IE from caching ajax requests.
        self.set_header("Cache-Control","no-store, no-cache, must-revalidate");
        self.set_header("Pragma","no-cache");
        self.set_header("Expires", 0);
        return self.write(escape.json_encode(value)) 
Example #28
Source File: base.py    From webspider with MIT License 5 votes vote down vote up
def render_json(self, data):
        self.set_header('Content-Type', 'application/json')
        self.finish(json_encode(data)) 
Example #29
Source File: rest.py    From cookiecutter-tornado with GNU General Public License v3.0 5 votes vote down vote up
def finish(self, chunk=None):
        if chunk is not None:
            chunk = json_encode(chunk)
        super(RESTfulHandler, self).finish(chunk) 
Example #30
Source File: test_handlers.py    From dokomoforms with GNU General Public License v3.0 5 votes vote down vote up
def test_login_email_does_not_exist(self):
        with patch.object(handlers.Login, '_async_post') as p:
            dummy = lambda: None
            dummy.body = json_encode({'status': 'okay', 'email': 'test_email'})
            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, 422, msg=response.body)