本文整理汇总了Python中webapp2_extras.json.decode函数的典型用法代码示例。如果您正苦于以下问题:Python decode函数的具体用法?Python decode怎么用?Python decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了decode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_post
def test_post(self):
# create widget in DB and get its id
widget = copy.copy(self.json_widget)
ident = model.Widget.put(widget).key().id()
self.assertEqual(1, len(model.Widget.all().fetch(2)))
# update widget with the same id through API
widget = copy.copy(self.json_widget)
widget['email_field'] = '[email protected]'
response = self.testapp.post('/rest/Widget/' + str(ident),
params = json.encode(widget),
expect_errors=True,
content_type = "application/json; charset=utf-8")
self.assertEqual(response.status_int, 200)
self.assertEqual(json.decode(response.body)['code'], 200)
# get widget with the same id through API and verify that email field is correct
response = self.testapp.get('/rest/Widget/' + str(ident),
params = self.str_widget,
expect_errors=True)
self.assertEqual(response.status_int, 200)
self.assertEqual(json.decode(response.body)['code'], 200)
self.assertEqual(json.decode(response.body)['message']['email_field'], "[email protected]")
开发者ID:datinc,项目名称:algae,代码行数:26,代码来源:test_api.py
示例2: get
def get(self):
id = self.request.get('id')
try:
opener = urllib2.build_opener()
opener.addheaders = [('App-Token', settings.TRANSPARENCIA_TOKEN), ('Content-Type', 'application/json'), ('Accept', 'application/json')]
result = opener.open(settings.uri('candidatos')+"/"+id)
profile = json.decode(result.read())
result = opener.open(settings.uri('candidatos')+"/"+id+ "/bens")
bens = json.decode(result.read())
profile["bens"] = bens
result = opener.open(settings.uri('candidatos')+"/"+id+ "/doadores")
doadores = json.decode(result.read())
profile["doadores"] = doadores
result = opener.open(settings.uri('candidatos')+"/"+id+ "/candidaturas")
candidaturas = json.decode(result.read())
profile["candidaturas"] = candidaturas
result = opener.open(settings.uri('candidatos')+"/"+id+ "/estatisticas")
estatisticas = json.decode(result.read())
profile["estatisticas"] = estatisticas
except urllib2.URLError, e:
profile = []
开发者ID:hackaton-transparencia-brasil,项目名称:seleicao,代码行数:25,代码来源:profile.py
示例3: post
def post(self):
game_id = self.request.path
game_id = game_id.replace('/game/', '')
game_id = game_id.replace('/action', '')
username = str(self.request.get('player'))
player = ndb.gql("SELECT * FROM Player WHERE name = '" + username + "'").fetch()
player = player[0]
game_status = ndb.gql("SELECT * FROM GameStatus WHERE name = '" + username + "' AND game_id = " + game_id).fetch()
game_status = game_status[0]
action = str(self.request.get('action'))
if action == "bet":
value = int(self.request.get('value'))
if value > player.tokens:
self.response.out.write("Bet more than the number of tokens you have")
else:
player.tokens -= value
game_status.tokens -= value
actions_array = json.decode(game_status.your_actions)
actions_array.append("play")
game_status.your_actions = json.encode(actions_array)
player.put()
game_status.put()
self.response.out.write("ok")
elif action == "play":
dealer = ndb.gql("SELECT * FROM Dealer WHERE game_id = " + game_id).fetch()
dealer = dealer[0]
deck = json.decode(dealer.deck)
card1 = choice(deck)
deck.remove(card1)
card2 = choice(deck)
deck.remove(card2)
player_cards = [card1, card2]
game_status.your_cards_visible = json.encode(player_cards)
game_status.put()
check_games = ndb.gql("SELECT * FROM GameStatus WHERE game_id = " + game_id).fetch()
check_num = 1
for game_s in check_games:
if len(json.decode(game_s.your_cards_visible)) != 2:
check_num = 0
if check_num == 1:
d_card1 = choice(deck)
deck.remove(d_card1)
d_card2 = choice(deck)
deck.remove(d_card2)
d_visible = json.decode(dealer.dealer_card_v)
d_visible.append(d_card1)
dealer.dealer_card_v = json.encode(d_visible)
dealer.dealer_card_n = d_card2
dealer.deck = json.encode(deck)
dealer.put()
self.response.out.write("ok")
# elif action == "draw":
#
# elif action == "fold":
#
# elif action == "doubledown":
else:
self.response.out.write("error")
开发者ID:mulhaus1,项目名称:BlackJack,代码行数:59,代码来源:main.py
示例4: test_get
def test_get(self):
# create widget in DB and get its id
widget = copy.copy(self.json_widget)
ident = model.Widget.put(widget).key().id()
self.assertEqual(1, len(model.Widget.all().fetch(2)))
# get widget with the same id through API and verify that email field is correct
response = self.testapp.get('/rest/Widget/' + str(ident),
params = self.str_widget,
expect_errors=True)
self.assertEqual(response.status_int, 200)
self.assertEqual(json.decode(response.body)['code'], 200)
self.assertEqual(json.decode(response.body)['message']['email_field'], "[email protected]")
开发者ID:datinc,项目名称:algae,代码行数:15,代码来源:test_api.py
示例5: post
def post(self):
nota_json = json.decode(self.request.get('nota'))
nota = Nota()
if 'id' in nota_json:
nota = Nota.get_by_id(long(nota_json['id']))
nota.total = float(nota_json['total'])
nota.nombre = nota_json['nombre']
if 'fecha_impresion' in nota_json:
nota.fecha_impresion = datetime.datetime.fromtimestamp(float(nota_json['fecha_impresion'])/1000)
nota.put()
for orden_json in nota_json['ordenes']:
orden = Orden()
if 'id' in orden_json:
orden = Orden.get_by_id(long(orden_json['id']))
orden.cantidad = int(orden_json['cantidad'])
orden.producto = Producto.get_by_id(long(orden_json['producto']['id']))
orden.nota = nota
orden.put()
if 'modificadores_producto' in orden_json:
for modificador_producto_json in orden_json['modificadores_producto']:
if 'id' in modificador_producto_json:
orden_modificador_producto = OrdenModificadorProducto.get_by_id(long(modificador_producto_json['id']))
else:
orden_modificador_producto = OrdenModificadorProducto()
orden_modificador_producto.orden = orden
orden_modificador_producto.modificador_producto = ModificadorProducto.get_by_id(long(modificador_producto_json['modificador_producto']['id']))
orden_modificador_producto.put()
self.render_json(nota.to_dict())
开发者ID:ricardoricho,项目名称:pieldecafe-gae,代码行数:29,代码来源:handlers.py
示例6: post
def post(self, email):
# Http 쏘기 위한 공옹 루틴
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
self.response.content_type = "application/json"
user = db.UserEntity.get_by_id(email)
if user == None:
res_data = {"result": False, "reason": "email not exist"}
self.response.write(json.encode(res_data))
return
# 패스워드 틀림
req_data = json.decode(cgi.escape(self.request.body))
if user.password != req_data["password"]:
res_data = {"result": False, "reason": "password not match"}
self.response.write(json.encode(res_data))
return
# 결과 리턴
token = secret.get_jwt(user.auth_type, user.email, user.name)
res_data = {
"result": True,
"token": token,
"isWorking": user.is_working,
"totalWorkingSeconds": (datetime.now() - user.work_start_date_time).total_seconds(),
}
if user.intro_text != None:
res_data["introText"] = user.intro_text
if user.avatar_photo_blob_key != None:
userPhoto = db.BlobEntity.get_by_id(str(user.avatar_photo_blob_key))
if userPhoto != None:
res_data["avatarPhotoUrl"] = userPhoto.blob_url
self.response.write(json.encode(res_data))
开发者ID:ppz0th,项目名称:IMCLIMBER,代码行数:34,代码来源:user.py
示例7: post
def post(self):
json_form = json.decode(self.request.body)
new_todo = Todo(id=json_form["id"], title=json_form["title"], completed=json_form["completed"])
new_todo.put()
self.response.headers["Content-Type"] = "application/json"
result = {"result": "success"}
self.response.write(json.encode(result))
开发者ID:neoborn,项目名称:IS429GAETest,代码行数:7,代码来源:app.py
示例8: _put_candidate
def _put_candidate(candidato):
try:
opener = urllib2.build_opener()
opener.addheaders = [('App-Token', settings.TRANSPARENCIA_TOKEN),
('Content-Type', 'application/json'), ('Accept', 'application/json')]
uri = settings.uri('candidato_stats').format(
candidato_id=candidato['id'])
result = opener.open(uri)
candidato_stats = json.decode(result.read())
if candidato_stats:
candidato_stats = candidato_stats[0]
else:
candidato_stats = {}
Candidato(candidato_id=int(candidato['id']),
instrucao=candidato['instrucao'],
reeleicao=candidato['reeleicao'],
cargo=candidato['cargo'],
estado=candidato['estado'],
nome=candidato['nome'],
foto=candidato['foto'],
faltas_plenario=float(candidato_stats.get('faltas_plen', 0)),
faltas_comissoes=float(candidato_stats.get('faltas_com', 0))).put()
except urllib2.URLError, e:
print '>>>>>>>>>>>>>>>>>>>> %s' % str(e)
pass
开发者ID:rafaelnunes,项目名称:seleicao,代码行数:28,代码来源:api.py
示例9: test_json_start_post
def test_json_start_post(self):
request = webapp2.Request.blank("/")
request.method = "POST"
request.headers["Content-Type"] = "application/json"
request.body = json.encode({
'update': 1,
'message': {
u'date': 1450696897,
u'text': u'/start',
u'from': {
u'username': u'm_messiah',
u'first_name': u'Maxim',
u'last_name': u'Muzafarov',
u'id': 3798371
},
u'message_id': 1,
u'chat': {
u'type': u'group',
u'id': -11812986,
u'title': u'КС'
}
}
})
response = request.get_response(app)
self.assertEqual(response.status_int, 200)
self.assertIn("application/json", response.headers['Content-Type'])
self.assertDictEqual(
json.decode(response.body),
{
'method': 'sendMessage',
'text': u"Привет! Я буду исправлять твои ошибки в режиме inline (в любое время можно ввести `@spell_bot сообщение`, и я предложу исправления)",
'chat_id': -11812986,
}
)
开发者ID:m-messiah,项目名称:spell_bot,代码行数:34,代码来源:tests.py
示例10: test_config_replacement
def test_config_replacement(self):
d = 25000
memcache.set('already_clicked', d * 1000)
memcache.set('clicks_total', d * 1000 + 333333)
memcache.set('already_donated', d)
memcache.set('eur_goal', 50000)
memcache.set('eur_increment', EUR_INCREMENT)
self._create_config(
'{"firstvisit":"center","secondvisit":"top","default_locale":"en","strings":{'
+ '"en":{"heading":"Thanks!","subheading":"Every click is worth %increment%","about":"More about the <strong>dotHIV</strong> initiative","activated":"Already %donated% contributed:","money":"%unlocked%","clickcount":"%clicks% clicks"},'
+ '"de":{"heading":"Danke!","subheading":"Jeder Klick hilft mit %increment%","about":"Mehr über die <strong>dotHIV</strong> Initiative","activated":"Bereits %donated% gespendet:","money":"%unlocked%","clickcount":"%clicks% Klicks"}}}'
)
uri = '/c?domain=' + self.domain + '&from=inside'
request = Request.blank(uri, headers=[('Accept-Language', 'de,en-US;q=0.5,en;q=0.6')])
request.method = 'POST'
response = request.get_response(application)
config = json.decode(response.body)
self.assertEqual("Bereits 25.000 € gespendet:", str(config['activated']))
if EUR_INCREMENT < 0.01: # 0.001
self.assertEqual("25.333,33 €", str(config['money']))
self.assertEqual("Jeder Klick hilft mit 0,1 ct", str(config['subheading']))
self.assertEqual(round(25333.33 / 50000, 3), round(config['percent'], 3))
else: # 0.01
self.assertEqual("28.333,33 €", str(config['money']))
self.assertEqual("Jeder Klick hilft mit 1 ct", str(config['subheading']))
self.assertEqual(round(28333.33 / 50000, 3), round(config['percent'], 3))
self.assertEqual("25.333.333 Klicks", str(config['clickcount']))
开发者ID:dothiv,项目名称:clickcounter-backend,代码行数:27,代码来源:tests.py
示例11: validate
def validate(self):
request = webapp2.get_request()
data = json.decode(request.body)
if not isinstance(data, dict):
webapp2.abort(403, detail='not a dict')
for f in self.fields:
if not f.id in self.validations:
continue
try:
value = data[f.id].strip()
except KeyError:
value = ''
self.field_values[f.id] = value
for val in self.validations[f.id]:
val.input = f.id
if not val.validate(self):
webapp2.abort(403,
detail='validation error, id: %s name: %s value: %s'
% (f.id, f.name, value))
return self.field_values
开发者ID:ernestoalejo,项目名称:gaelib-python,代码行数:26,代码来源:ngforms.py
示例12: post
def post(self):
# remote_addr shows up as "::1" when calling from localhost
# or is it when using the simulated version of the
# GAE environment? not sure.
# print("remote ip is %s" % self.request.remote_addr)
raw = self.request.body
try:
obj = json.decode(raw)
except ValueError:
self.response.out.write("invalid json")
return
ami_launch = AMILaunch(parent=get_parent())
ami_launch.is_bioc_account = obj['accountId'] == "555219204010"
if not ami_launch.is_bioc_account:
ami_launch.account_hash = hashlib.md5(obj['accountId'].encode()).hexdigest()
ami_launch.ami_id = obj['imageId']
ami_launch.instance_type = obj['instanceType']
ami_launch.region = obj['region']
ami_launch.availability_zone = obj['availabilityZone']
is_aws_ip("foo")
ami_launch.bioc_version = get_bioc_version(obj['imageId'])
ami_info = get_ami_info(obj['imageId'])
if ami_info is not None:
ami_launch.ami_name = ami_info['name']
ami_launch.ami_description = ami_info['description']
ami_launch.put()
self.response.out.write("thanx\n")
开发者ID:Bioconductor,项目名称:ami_phone_home,代码行数:34,代码来源:phone_home.py
示例13: test
def test(self):
request = webapp2.Request.blank('/locations')
request.body = '{"latitude": 40.689068, "longitude": 74.044625, "message": u"Hollå!", "age": 1 }'
request.method = 'POST'
response = request.get_response(app)
assert response.status_int == 200
assert json.decode(response.body) == {}
开发者ID:peralmq,项目名称:olloapi,代码行数:7,代码来源:test_routes.py
示例14: create
def create(user_key, name=""):
#Find the user to add the key to
user = User.find_by_key(user_key)
if (user == None):
raise Exception("Invalid key")
if (name == ""):
name = "Untilted"
# Set the list to empty
usernames = [user.username]
pending_usernames = []
# Add the new item list to the database
group = Group(name=name, usernames=JSON.encode(usernames),
pending_usernames=JSON.encode(pending_usernames), version=0,photo="",photo_version=0)
group_key = (group.put()).urlsafe()
user_groups = JSON.decode(user.groups)
user_groups.append(group_key)
user.groups = JSON.encode(user_groups)
user.increment_version()
user.put()
return group_key
开发者ID:RyanMitch16,项目名称:code-u-final,代码行数:26,代码来源:models.py
示例15: _get_result
def _get_result(self, URL, MAX_RETRIES=5):
result = None
retries = 0
while not result and retries <= MAX_RETRIES:
result = _try_to_get_result(URL, self.token)
retries += 1
return json.decode(result)
开发者ID:peralmq,项目名称:olloapi,代码行数:7,代码来源:facebook.py
示例16: post
def post(self):
self.set_response_data()
user = self.get_user()
try:
location = convert.location(**json.decode(self.request.body))
except Exception, e:
print str(e)
self.abort(400)
开发者ID:peralmq,项目名称:olloapi,代码行数:8,代码来源:routes.py
示例17: test_put_unauth
def test_put_unauth(self):
response = self.testapp.put('/rest/Widgets',
params = self.str_widget,
expect_errors=True,
content_type = "application/json; charset=utf-8")
self.assertEqual(response.status_int, 401)
self.assertEqual(json.decode(response.body)['code'], 401)
开发者ID:datinc,项目名称:algae,代码行数:8,代码来源:test_api.py
示例18: parse_json
def parse_json(content, info_key):
result = json.decode(content)
if result['ok'] != 1:
raise Exception('JSON Not "OK" (%s)' % (content))
if info_key:
return result[info_key]
else:
return result
开发者ID:Etrnls,项目名称:etrnlabs,代码行数:8,代码来源:refresh.py
示例19: post
def post(self):
p = self.request.body
logging.info('Set list: ' + p)
data = json.decode(p)
uid = data['uid']
name = data['name']
songs = data['songs']
self.set_list(uid, name, songs)
开发者ID:sasq64,项目名称:chipstat,代码行数:8,代码来源:chipstat.py
示例20: test_incorrect_text
def test_incorrect_text(self):
request = webapp2.Request.blank("/")
request.method = "POST"
request.headers["Content-Type"] = "application/json"
request.body = json.encode({
'update': 1,
'inline_query': {
u'query': u'стртанный, ткест',
u'from': {
u'username': u'm_messiah',
u'first_name': u'Maxim',
u'last_name': u'Muzafarov',
u'id': 3798371
},
u'id': "1",
u'offset': 0,
}
})
response = request.get_response(app)
self.assertEqual(response.status_int, 200)
self.assertIn("application/json", response.headers['Content-Type'])
self.assertItemsEqual(
json.decode(json.decode(response.body)['results']),
[{
u"message_text": u"\u0441\u0442\u0440\u0442\u0430\u043d\u043d\u044b\u0439, \u0442\u043a\u0435\u0441\u0442",
u"type": u"article",
u"id": u"0",
u"title": u"spell",
u"description": u"\u0441\u0442\u0440\u0442\u0430\u043d\u043d\u044b\u0439, \u0442\u043a\u0435\u0441\u0442"
},
{
u'message_text': u'cnhnfyysq? nrtcn',
u'title': u'qwerty',
u'type': u'article',
u'description': u'cnhnfyysq? nrtcn',
u'id': u'1'
},
{
u'message_text': u'cnhnfyysq^ nrtcn',
u'title': u'mac',
u'type': u'article',
u'description': u'cnhnfyysq^ nrtcn',
u'id': u'2'
}]
)
开发者ID:m-messiah,项目名称:spell_bot,代码行数:45,代码来源:tests.py
注:本文中的webapp2_extras.json.decode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论