本文整理汇总了Python中utils.json_encode函数的典型用法代码示例。如果您正苦于以下问题:Python json_encode函数的具体用法?Python json_encode怎么用?Python json_encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了json_encode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _next
def _next():
from models.users import User
token = request.args.get("token")
nsfw = request.args.get("nsfw")
nsfw = nsfw == 'true'
if not token:
return Response(status=403)
user = User.q.filter_by(token=token).first()
if not user:
return Response(status=403)
if not len(user.likes) >= 3:
# IF USER LIKED ARTICLES ARE NOT MORE THAN 5
# RETURN RANDOM
article = user.random_article(nsfw=nsfw)
if not article:
return Response(status=404)
user.visit(article)
return Response(json_encode({'article': article.serialize()}),
mimetype="application/json")
suggested_article = user.suggested_articles(nsfw=nsfw)
if not suggested_article:
article = user.random_article(nsfw=nsfw)
if not article:
return Response(status=404)
user.visit(article)
return Response(json_encode({'article': article.serialize()}),
mimetype="application/json")
visited_article = user.visit(suggested_article)
return Response(json_encode({"article": visited_article.serialize()}),
mimetype="application/json")
开发者ID:vargi,项目名称:reko,代码行数:35,代码来源:app.py
示例2: example_websocket_action
def example_websocket_action(self, message):
"""
This `WebSocket <https://developer.mozilla.org/en/WebSockets/WebSockets_reference/WebSocket>`_
action gets exposed to the client automatically by way of the 'WebSocket'
hook at the bottom of this file. The way it works is like this:
.. rubric:: How The WebSocket Hook Works
Whenever a message is received via the `WebSocket <https://developer.mozilla.org/en/WebSockets/WebSockets_reference/WebSocket>`_
Gate One will automatically
decode it into a Python :class:`dict` (only JSON-encoded messages are accepted).
Any and all keys in that :class:`dict` will be assumed to be 'actions' (just
like :js:attr:`GateOne.Net.actions` but on the server) such as this one. If
the incoming key matches a registered action that action will be called
like so::
key(value)
# ...or just:
key() # If the value is None ('null' in JavaScript)
...where *key* is the action and *value* is what will be passed to said
action as an argument. Since Gate One will automatically decode the message
as JSON the *value* will typically be passed to actions as a single :class:`dict`.
You can provide different kinds of arguments of course but be aware that
their ordering is unpredictable so always be sure to either pass *one*
argument to your function (assuming it is a :class:`dict`) or 100% keyword
arguments.
The *self* argument here is automatically assigned by
:class:`TerminalApplication` using the `utils.bind` method.
The typical naming convention for `WebSocket <https://developer.mozilla.org/en/WebSockets/WebSockets_reference/WebSocket>`_
actions is: `<plugin name>_<action>`. Whether or not your action names
match your function names is up to you. All that matters is that you line
up an *action* (string) with a *function* in `hooks['WebSocket']` (see below).
This `WebSocket <https://developer.mozilla.org/en/WebSockets/WebSockets_reference/WebSocket>`_
*action* duplicates the functionality of Gate One's built-in
:func:`gateone.TerminalWebSocket.pong` function. You can see how it is
called by the client (browser) inside of example.js (which is in this
plugin's 'static' dir).
"""
message = {'terminal:example_pong': timestamp}
self.write_message(json_encode(message))
# WebSockets are asynchronous so you can send as many messages as you want
message2 = {'go:notice': 'You just executed the "example_action" action.'}
self.write_message(json_encode(message2))
# Alternatively, you can combine multiple messages/actions into one message:
combined = {
'go:notice': 'Hurray!',
'terminal:bell': {'term': self.current_term}
}
self.write_message(json_encode(combined))
开发者ID:CyberShadow,项目名称:GateOne,代码行数:53,代码来源:example.py
示例3: get_connect_string
def get_connect_string(self, term):
"""
Attached to the (server-side) `terminal:ssh_get_connect_string` WebSocket
action; writes the connection string associated with *term* to the WebSocket
like so::
{'terminal:sshjs_reconnect': {*term*: <connection string>}}
In ssh.js we attach a WebSocket action to 'terminal:sshjs_reconnect'
that assigns the connection string sent by this function to
`GateOne.Terminal.terminals[*term*]['sshConnectString']`.
"""
self.term_log.debug("get_connect_string() term: %s" % term)
session = self.ws.session
session_dir = self.ws.settings['session_dir']
for f in os.listdir(os.path.join(session_dir, session)):
if f.startswith('ssh:'):
terminal, a_colon, connect_string = f[4:].partition(':')
terminal = int(terminal)
if terminal == term:
# TODO: Make it so we don't have to use json_encode below...
message = {
'terminal:sshjs_reconnect': json_encode(
{term: connect_string})
}
self.write_message(message)
return # All done
开发者ID:medhamsh,项目名称:GateOne,代码行数:27,代码来源:ssh.py
示例4: send_message
def send_message(fd, event):
"""
Sends the log enumeration result to the client. Necessary because
IOLoop doesn't pass anything other than *fd* and *event* when it handles
file descriptor events.
"""
message = q.get()
#logging.debug('message: %s' % message)
if message == 'complete':
io_loop.remove_handler(fd)
total_bytes = 0
logs_dir = os.path.join(users_dir, "logs")
log_files = os.listdir(logs_dir)
for log in log_files:
log_path = os.path.join(logs_dir, log)
total_bytes += os.stat(log_path).st_size
out_dict = {
'total_logs': len(log_files),
'total_bytes': total_bytes
}
# This signals to the client that we're done
message = {'terminal:logging_logs_complete': out_dict}
self.write_message(message)
return
message = json_encode(message)
if message not in results:
# Keep track of how many/how much
if results:
results.pop() # No need to keep old stuff hanging around
results.append(message)
self.write_message(message)
开发者ID:argolab,项目名称:GateOne,代码行数:31,代码来源:logging_plugin.py
示例5: get_connect_string
def get_connect_string(self, term):
"""
Writes the connection string associated with *term* to the `WebSocket <https://developer.mozilla.org/en/WebSockets/WebSockets_reference/WebSocket>`_
like so::
{'sshjs_reconnect': {*term*: <connection string>}}
In ssh.js we attach an action (aka handler) to :js:attr:`GateOne.Net.actions`
for 'sshjs_reconnect' messages that attaches the connection string to
`GateOne.Terminal.terminals[*term*]['sshConnectString']`
"""
logging.debug("get_connect_string() term: %s" % term)
session = self.ws.session
session_dir = self.ws.settings['session_dir']
for f in os.listdir(os.path.join(session_dir, session)):
if f.startswith('ssh:'):
terminal, a_colon, connect_string = f[4:].partition(':')
terminal = int(terminal)
if terminal == term:
# TODO: Make it so we don't have to use json_encode below...
message = {
'terminal:sshjs_reconnect': json_encode(
{term: connect_string})
}
self.write_message(message)
return # All done
开发者ID:adityaU,项目名称:GateOne,代码行数:26,代码来源:ssh.py
示例6: save_bookmarks
def save_bookmarks(bookmarks, tws):
"""
Handles saving *bookmarks* for clients.
"""
out_dict = {
'updates': [],
'count': 0,
'errors': []
}
try:
user = tws.get_current_user()['upn']
bookmarks_db = BookmarksDB(tws.settings['user_dir'], user)
updates = bookmarks_db.sync_bookmarks(bookmarks)
out_dict.update({
'updates': updates,
'count': len(bookmarks),
})
out_dict['updateSequenceNum'] = bookmarks_db.get_highest_USN()
except Exception as e:
import traceback
logging.error("Got exception synchronizing bookmarks: %s" % e)
traceback.print_exc(file=sys.stdout)
out_dict['errors'].append(str(e))
if out_dict['errors']:
out_dict['result'] = "Upload completed but errors were encountered."
else:
out_dict['result'] = "Upload successful"
message = {'bookmarks_save_result': out_dict}
tws.write_message(json_encode(message))
开发者ID:10xEngineer,项目名称:GateOne,代码行数:29,代码来源:bookmarks.py
示例7: send_message
def send_message(fd, event):
"""
Sends the log enumeration result to the client. Necessary because
IOLoop doesn't pass anything other than *fd* and *event* when it handles
file descriptor events.
"""
io_loop.remove_handler(fd)
message = q.get()
tws.write_message(json_encode(message))
开发者ID:acasajus,项目名称:GateOne,代码行数:9,代码来源:logging_plugin.py
示例8: opt_esc_handler
def opt_esc_handler(text, tws):
"""
Handles text passed from the special optional escape sequance handler. We
use it to tell ssh.js what the SSH connection string is so it can use that
information to duplicate sessions (if the user so desires). For reference,
the specific string which will call this function from a terminal app is:
\x1b]_;ssh|<whatever>\x07
"""
message = {'sshjs_connect': text}
tws.write_message(json_encode(message))
开发者ID:acasajus,项目名称:GateOne,代码行数:10,代码来源:ssh.py
示例9: get
def get(self):
"""Batch delete."""
start = timer.time()
count = int( models.Event.all().count() );
# check if there is something to delete
if count > 0:
db.delete([item for item in models.Event.all()])
if models.Event.all().count() == 0:
self.write( utils.json_encode({
'message':'All events succesfully deleted.',
'load_time': timer.time() - start
}) )
else:
self.write( utils.json_encode({
'message':'Delete failed. Try again.',
'load_time': timer.time() - start
}) )
开发者ID:ronbeltran,项目名称:restfultornado,代码行数:20,代码来源:main.py
示例10: rename_tags
def rename_tags(self, renamed_tags):
"""
Handles renaming tags.
"""
user = self.get_current_user()["upn"]
bookmarks_db = BookmarksDB(self.ws.settings["user_dir"], user)
out_dict = {"result": "", "count": 0, "errors": [], "updates": []}
for pair in renamed_tags:
old_name, new_name = pair.split(",")
bookmarks_db.rename_tag(old_name, new_name)
out_dict["count"] += 1
message = {"bookmarks_renamed_tags": out_dict}
self.write_message(json_encode(message))
开发者ID:kooroo,项目名称:GateOne,代码行数:13,代码来源:bookmarks.py
示例11: get_connect_string
def get_connect_string(term, tws):
"""
Writes the connection string associated with *term* to the websocket like
so:
{'sshjs_reconnect': json_encode({*term*: <connection string>})}
In ssh.js we attach an action (aka handler) to GateOne.Net.actions for
'sshjs_reconnect' messages that attaches the connection string to
GateOne.terminals[*term*]['sshConnectString']
"""
session = tws.session
session_dir = tws.settings['session_dir']
for f in os.listdir(session_dir + '/' + session):
if f.startswith('ssh:'):
terminal, a_colon, connect_string = f[4:].partition(':')
terminal = int(terminal)
if terminal == term:
message = {
'sshjs_reconnect': json_encode({term: connect_string})
}
tws.write_message(json_encode(message))
return # All done
开发者ID:acasajus,项目名称:GateOne,代码行数:22,代码来源:ssh.py
示例12: get
def get(self):
arguments = self.request.arguments()
if 'mac' in arguments:
#GET /clients/:mac
mac_string = self.request.get("mac")
client = get_client_with_mac(utils.mac_string_to_int(mac_string))
if client is None:
client = []
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(utils.json_encode(utils.query_to_array(client), True))
return
#GET /clients/(:t1)(:limit)
pass
开发者ID:gallagth,项目名称:snaptrack-webservices,代码行数:14,代码来源:clients.py
示例13: like
def like():
from models.users import User
token = request.args.get("token")
url_id = request.json.get("url")
if not token:
return Response(status=403)
user = User.q.filter_by(token=token).first()
if not user:
return Response(status=403)
from models.users import Article
article = Article.q.fetch_by_id(url_id)
user.like(article)
return Response(json_encode({"message": "liked"}))
开发者ID:vargi,项目名称:reko,代码行数:15,代码来源:app.py
示例14: updateserver
def updateserver(request):
server = QateServerInfo()
server.ip = request.POST.get('ip').encode("utf-8")
server.name = request.POST.get('name').encode("utf-8")
server.env = request.POST.get('env').encode("utf-8")
server.pd = request.POST.get('pd').encode("utf-8")
server.role = request.POST.get('role').encode("utf-8")
server.desc = request.POST.get('desc').encode("utf-8")
update_server_info(server)
response = json_encode({
"result": "ok"
})
return HttpResponse(response, content_type="application/json")
开发者ID:wwwzyb2002,项目名称:mysite,代码行数:15,代码来源:views.py
示例15: post
def post(self):
"""
Generate randmomized events for a user.
:Arguments:
user_id : int
User id
num_of_events : int
Number of events to generate, max of 100,000 per request
time : str
Time represents ``minutes``, ``days``, ``hours``, ``weeks`` in datetime.timedelta() eg. datetime.timedelta(days=7)
delta : int
Delta is any int value for datetime.timedelta() eg. datetime.timedelta(days=7)
"""
start = timer.time()
time = self.get_argument("time", None)
delta = self.get_argument("delta", 0)
num_of_events = self.get_argument("num_of_events", 0)
user_id = self.get_argument("user_id", 0)
time = str(time) if time in ['minutes','hours','days','weeks'] else None
if not time:
raise tornado.web.HTTPError(404)
user = models.User.all().filter("id =",int(user_id)).get()
if not user:
raise tornado.web.HTTPError(404)
if int(num_of_events) > MAX_NUMBER_OF_EVENTS:
num_of_events = MAX_NUMBER_OF_EVENTS
now = datetime.now()
for i in xrange(1,int(num_of_events)+1):
r = random.randrange(1,int(delta))
e = models.Event(user=user,
name='Event'+str(r),
created=now - utils.timedelta_wrapper(time, int(r)) )
e.put()
d = {}
d["load_time"] = timer.time() - start
d["count"] = models.Event.all().count()
return self.write(utils.json_encode(d))
开发者ID:ronbeltran,项目名称:restfultornado,代码行数:48,代码来源:main.py
示例16: getpageserverinfos
def getpageserverinfos(request):
env = request.POST.get('env').encode("utf-8")
pd = request.POST.get('pd').encode("utf-8")
key = request.POST.get('key').encode("utf-8")
pageNum = int(request.POST.get('page')) - 1
pageSize = int(request.POST.get('rows'))
total, page_server_infos, cpu_total, mem_total, disk_total = get_page_server_infos_from_db(env, pd, key, pageNum, pageSize)
response = json_encode({
"total": total,
"rows": page_server_infos,
"cpu_total": cpu_total,
"mem_total": mem_total,
"disk_total": disk_total
})
return HttpResponse(response, content_type="application/json")
开发者ID:wwwzyb2002,项目名称:mysite,代码行数:17,代码来源:views.py
示例17: post
def post(self):
"""
Example Handler for an HTTP PUT request. Doesn't actually do anything.
"""
# If data is POSTed to this handler via an XMLHTTPRequest send() it
# will show up like this:
posted_as_a_whole = self.request.body # xhr.send()
# If data was POSTed as arguments (i.e. traditional form) it will show
# up as individual arguments like this:
posted_as_argument = self.get_argument("arg") # Form elem 'name="arg"'
# This is how you can parse JSON:
parsed = tornado.escape.json_decode(posted_as_an_argument)
# For writing JSON it is recommended to use the json_encode() function
# from Gate One's utils.py (since it takes care of Python 3 support):
from utils import json_encode
json_output = {'result': 'Success!'}
self.write(json_encode(json_output))
开发者ID:aryamazaheri,项目名称:GateOne,代码行数:17,代码来源:example.py
示例18: get_bookmarks
def get_bookmarks(self, updateSequenceNum):
"""
Returns a JSON-encoded list of bookmarks updated since the last
*updateSequenceNum*.
If *updateSequenceNum* resolves to False, all bookmarks will be sent to
the client.
"""
user = self.get_current_user()["upn"]
bookmarks_db = BookmarksDB(self.settings["user_dir"], user)
if updateSequenceNum:
updateSequenceNum = int(updateSequenceNum)
else: # This will force a full download
updateSequenceNum = 0
updated_bookmarks = bookmarks_db.get_bookmarks(updateSequenceNum)
message = {"bookmarks_updated": updated_bookmarks}
self.write_message(json_encode(message))
开发者ID:kooroo,项目名称:GateOne,代码行数:17,代码来源:bookmarks.py
示例19: likes
def likes():
from models.users import User
token = request.args.get("token")
offset = request.args.get("offset", 0)
if not token:
return Response(status=403)
user = User.q.filter_by(token=token).first()
if not user:
return Response(status=403)
from models.articles import ArticleLike
article_likes = ArticleLike.q.filter({"user": user.id}).\
sort([("_id", -1)]).skip(offset).all()
bundle = [{"url": i.url, "title": i.title} for i in article_likes]
return Response(json_encode({"articles": bundle}))
开发者ID:vargi,项目名称:reko,代码行数:17,代码来源:app.py
示例20: get_bookmarks
def get_bookmarks(updateSequenceNum, tws):
"""
Returns a JSON-encoded list of bookmarks updated since the last
*updateSequenceNum*.
If "updateSequenceNum" resolves to False, all bookmarks will be sent to
the client.
"""
user = tws.get_current_user()['upn']
bookmarks_db = BookmarksDB(tws.settings['user_dir'], user)
if updateSequenceNum:
updateSequenceNum = int(updateSequenceNum)
else: # This will force a full download
updateSequenceNum = 0
updated_bookmarks = bookmarks_db.get_bookmarks(updateSequenceNum)
message = {'bookmarks_updated': updated_bookmarks}
tws.write_message(json_encode(message))
开发者ID:10xEngineer,项目名称:GateOne,代码行数:17,代码来源:bookmarks.py
注:本文中的utils.json_encode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论