本文整理汇总了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))
示例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)
示例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()
示例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)
示例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)
示例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')
示例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
)
示例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())
示例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)
示例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
示例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
示例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,))
示例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))
示例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())
示例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())