本文整理汇总了Python中utils.to_json函数的典型用法代码示例。如果您正苦于以下问题:Python to_json函数的具体用法?Python to_json怎么用?Python to_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(_):
pp.pprint(flags.FLAGS.__flags)
if not os.path.exists(FLAGS.checkpoint_dir):
os.makedirs(FLAGS.checkpoint_dir)
if not os.path.exists(FLAGS.sample_dir):
os.makedirs(FLAGS.sample_dir)
with tf.Session() as sess:
if FLAGS.dataset == 'mnist':
dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size, y_dim=10,
dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)
else:
dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size,
dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)
if FLAGS.is_train:
dcgan.train(FLAGS)
else:
dcgan.load(FLAGS.checkpoint_dir)
to_json("./web/js/gen_layers.js", dcgan.h0_w, dcgan.h1_w, dcgan.h2_w, dcgan.h3_w, dcgan.h4_w)
z_sample = np.random.uniform(-1, 1, size=(FLAGS.batch_size, dcgan.z_dim))
samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})
save_images(samples, [8, 8], './samples/test_%s.png' % strftime("%Y-%m-%d %H:%M:%S", gmtime()))
示例2: main
def main(_):
pp.pprint(flags.FLAGS.__flags)
if not os.path.exists(FLAGS.checkpoint_dir):
os.makedirs(FLAGS.checkpoint_dir)
if not os.path.exists(FLAGS.sample_dir):
os.makedirs(FLAGS.sample_dir)
with tf.Session() as sess:
if FLAGS.dataset == 'mnist':
dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size, y_dim=10,
dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)
else:
dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size,
dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)
if FLAGS.is_train:
dcgan.train(FLAGS)
else:
dcgan.load(FLAGS.checkpoint_dir)
to_json("./web/js/layers.js", [dcgan.h0_w, dcgan.h0_b, dcgan.g_bn0],
[dcgan.h1_w, dcgan.h1_b, dcgan.g_bn1],
[dcgan.h2_w, dcgan.h2_b, dcgan.g_bn2],
[dcgan.h3_w, dcgan.h3_b, dcgan.g_bn3],
[dcgan.h4_w, dcgan.h4_b, None])
# Below is codes for visualization
OPTION = 2
visualize(sess, dcgan, FLAGS, OPTION)
示例3: _send_api_command
def _send_api_command(self, request):
"""
Send an API command to Galah.
:param request: A properly formed JSON object to send Galah.
:returns: A ``requests.Response`` object.
"""
request = copy.copy(request)
# Extract any files
file_args = {}
for i in (k for k, v in request.items() if isinstance(v, file)):
file_args[str(i)] = request.pop(i)
try:
requester = self._requester()
if not file_args:
return requester.post(
urlparse.urljoin(config.CONFIG["host"], "/api/call"),
data = utils.to_json(request),
headers = {"Content-Type": "application/json"},
verify = _get_verify()
)
else:
return requester.post(
urlparse.urljoin(config.CONFIG["host"], "/api/call"),
data = {"request": utils.to_json(request)},
files = file_args,
verify = _get_verify()
)
except requests.exceptions.SSLError as e:
logger.critical(
"There was a problem with communicating via SSL: %s.",
str(e),
exc_info = True
)
sys.exit(1)
except requests.exceptions.ConnectionError:
logger.critical(
"Galah did not respond at %s.",
urlparse.urljoin(config.CONFIG["host"], "/api/call"),
exc_info = True
)
sys.exit(1)
示例4: get
def get(self, slug):
match = ndb.Key('Match', slug).get()
if not match:
self.response.status_int = 404
return
self.response.headers['Content-Type'] = 'application/json'
self.response.write(utils.to_json(match.to_dict()))
示例5: on_logged_in
def on_logged_in(self, userid, gadget, wavelet):
waveid = wavelet.wave_id
if not models.Login.exists(waveid, userid):
# Wait, this user has no login. Bail out.
gadget.set_status(Gadget.LOGIN)
return
blogger = utils.Blogger.open(wavelet.wave_id, userid)
if not blogger:
# There was some error. Bail out.
gadget.set_status(Gadget.LOGIN)
return
blogs = blogger.get_blogs()
if len(blogs) == 0:
# User has no blogs. Bail out for now.
gadget.set_status(Gadget.LOGIN)
return
blog = blogs[0]["id"]
connection = models.Connection.get(waveid)
if connection:
connection.owner = userid
connection.blog = blog
connection.post = None
else:
connection = models.Connection(waveid=waveid, owner=userid, blog=blog)
connection.put()
gadget.set_owner(userid)
gadget.set_status(Gadget.CONNECTED)
gadget.set("blogs", utils.to_json(blogs))
gadget.set_blog(blog)
示例6: get_auth_url
def get_auth_url(self):
waveid = self.request.get('waveid')
userid = self.request.get('userid')
if (not waveid) or (not userid):
return
return to_json({
'url': Blogger.get_auth_url(waveid, userid, _UPGRADE_URL)
})
示例7: check_user_auth
def check_user_auth(self):
waveid = self.request.get('waveid')
userid = self.request.get('userid')
if (not waveid) or (not userid):
return
return to_json({
'isSignedIn': models.Login.exists(waveid, userid)
})
示例8: one_election_drive_tally
def one_election_drive_tally(request, election):
"""
JavaScript-based driver for the entire tallying process, now done in JavaScript.
"""
if election.tally_type != "homomorphic":
return HttpResponseRedirect(reverse(one_election_view,args=[election.election_id]))
election_pk = election.public_key
election_pk_json = utils.to_json(election_pk.toJSONDict())
election_sk = election.private_key
if election_sk:
election_sk_json = utils.to_json(election_sk.toJSONDict())
else:
election_sk_json = None
return render_template(request, 'drive_tally', {'election': election, 'election_pk_json' : election_pk_json, 'election_sk_json' : election_sk_json})
示例9: convert_to_json
def convert_to_json(self, *args, **kwargs):
return_val = func(self, *args, **kwargs)
try:
return render_json(utils.to_json(return_val))
except Exception, e:
import logging
logging.error("problem with serialization: " + str(return_val) + " / " + str(e))
raise e
示例10: social_cart
def social_cart(request):
data = SocialCartResource().to_dict(obj=request.user, request=request)
return render(request, 'cart/social_cart.j.html', {
'cart_json': to_json(data),
'is_empty': not data['buys'] and \
not data['pending_shipping_requests'] and \
not data['pickup_requests'] and \
not data['shipping_requests']
})
示例11: one_election_keyshares_tally_manage
def one_election_keyshares_tally_manage(request, election):
election_pk_json = utils.to_json(election.public_key.toJSONDict())
keyshares = election.get_keyshares()
ready_p = True
for keyshare in keyshares:
ready_p = ready_p and (keyshare.decryption_factors != None)
return render_template(request,"keyshares_tally_manage", {'election': election, 'election_pk_json': election_pk_json, 'ready_p' : ready_p})
示例12: post
def post(self):
request = to_json(self.request.body)
# Verify the token on the Google servers
url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={}".format(request.get('token'))
result = urlfetch.fetch(url=url,
method=urlfetch.GET,
)
if result.status_code == 200:
content = to_json(result.content)
# Need to check the 'aud' property once we have a user to actually test this stuff with.
# For now we'll just assume everything worked and return a formatted new user
user = User.query(User.email==content.get('email')).get()
if user is None:
# Need to create a new user
user = User()
user.email = content.get('email')
user.put()
self.response.status_int = 200
self.response.headers['Access-Control-Allow-Origin'] = "http://www.myvoyagr.co"
self.response.write(user.format())
else:
# Get all the trips associated with the user and add it to the response
trips = {}
trip_qry = Trip.query(ancestor=user.key).fetch()
for trip in trip_qry:
trips[trip.name] = trip.key.id()
self.response.status_int = 200
self.response.headers['Access-Control-Allow-Origin'] = "http://www.myvoyagr.co"
self.response.write({'user': user.format(), 'trips' : trips})
return
else:
self.response.status_int = 400
self.response.headers['Access-Control-Allow-Origin'] = "http://www.myvoyagr.co"
self.response.write({'error': 'There was an error authenticating the user'})
return
示例13: post_status
def post_status(room_id):
# print request.get_json()
update_status = request.get_json()
# update statuses
status = statuses.get(room_id)
# update given fields
if update_status.get("status"):
status.status = update_status.get("status")
status.timestamp = utils.get_currrent_time_str()
if update_status.get("status") == "FIRE":
print "fire alert!"
emailer.send_email(
"[email protected], [email protected], [email protected], [email protected], [email protected]",
"FIRE Alert! [%s]" % room_id, "Status Details: \n" + utils.to_json(status))
# send_message("9492664065", "There is FIRE at room [%s]!" % (room_id))
if update_status.get("occupancy"):
status.occupancy = update_status.get("occupancy")
# if update_status.get("carbon_detected"):
if "carbon_detected" in update_status:
status.carbon_detected = update_status.get("carbon_detected")
return utils.to_json({"Update": True})
示例14: serialize
def serialize(self, obj, **kw):
"""
Function for serializing object => string.
This can be overwritten for custom
uses.
The default is to do nothing ('serializer'=None)
If the connection is intialized with 'serializer' set to
'json.gz', 'json', 'gz', or 'zip', we'll do the
transformations.
"""
serializer = kw.get('serializer', self._serializer)
if serializer == "json.gz":
return utils.to_gz(utils.to_json(obj))
elif serializer == "json":
return utils.to_json(obj)
elif serializer == "gz":
assert(isinstance(obj, basestring))
return utils.to_gz(obj)
elif serializer == "zip":
assert(isinstance(obj, basestring))
return utils.to_zip(obj)
elif serializer == "pickle":
return utils.to_pickle(obj)
elif serializer is not None:
raise NotImplementedError(
'Only json, gz, json.gz, zip, and pickle'
'are supported as serializers.')
return obj
示例15: post
def post(self, slug):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
return
values = json.loads(self.request.body)
event = models.Event(parent=ndb.Key('Match', slug))
event.body = values.get('body')
event.meta = values.get('meta')
event.user = user
event.put()
self.response.headers['Content-Type'] = 'application/json'
self.response.write(utils.to_json(event.to_dict()))