本文整理汇总了Python中webapp2_extras.json.encode函数的典型用法代码示例。如果您正苦于以下问题:Python encode函数的具体用法?Python encode怎么用?Python encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了encode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: create
def create( self ):
photo = self.request.get( "photo", None )
# photo がなかったらエラー
if photo is None:
message = "parameter missing"
logging.warn( message )
out = { "meta": functions.createMetaData( status="fail", code=400, message=message, method_name="createPhoto" ) };
self.response.out.write( json.encode(out) )
return
logging.info( "サイズは%d KB"%( len(photo)/1000 ) )
# 保存
entity = models.Photo()
if self.isBase64( photo ) == True:
logging.info( "Flashから渡ってきたので base64decode します" )
photo_bin = base64.b64decode( photo )
entity.setBlob( photo_bin )
else:
logging.info( "HTMLフォームから渡って来ました" )
entity.setBlob( photo )
entity.user_key = self.user.key if self.user else None
entity.put();
# 出力
out = {
"meta": functions.createMetaData( status="ok", code=200, method_name="createPhoto" ),
"response": {
"photos":[
entity.toDict(),
],
},
};
self.response.out.write( json.encode(out) )
开发者ID:noughts,项目名称:openfish,代码行数:35,代码来源:photos.py
示例2: create
def create( self ):
content = self.request.get( 'content' );
# content がなかったらエラー
if content == "":
message = "parameter missing"
logging.warn( message )
out = { "meta": functions.createMetaData( status="fail", code=400, message=message, method_name="showPosts" ) };
self.response.out.write( json.encode(out) )
return
# 保存
post = models.Post()
post.content = content
if self.user:
post.user_key = self.user.key
post.created_at = int(time())
post.put();
# 出力
out = {
"meta": functions.createMetaData( status="ok", code=200, method_name="createPost" ),
"response": {
"posts":[
post.toDict(),
],
},
};
self.response.out.write( json.encode(out) )
开发者ID:noughts,项目名称:openfish,代码行数:29,代码来源:posts.py
示例3: leave
def leave(user_key, group_key):
#Find the user to add the key to
user = User.find_by_key(user_key)
if (user == None):
raise Exception("Invalid key")
#Find the user to add the key to
group = Group.find_by_key(group_key)
if (group == None):
raise Exception("Invalid group key")
#Remove the user from the pending users
group_usernames = JSON.unquote(group.usernames)
group_usernames.remove(user.username)
group.usernames = JSON.encode(group_usernames)
group.increment_version()
group.put()
#Remove the list from the users lists
user_groups = JSON.unquote(user.groups)
user_groups.remove(group_key)
user.groups = JSON.encode(user_groups)
user.increment_version()
user.put()
return "Group left"
开发者ID:RyanMitch16,项目名称:code-u-final,代码行数:27,代码来源:models.py
示例4: 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
示例5: accept
def accept(user_key, group_key):
#Find the user to add the key to
user = User.find_by_key(user_key)
if (user == None):
raise Exception("Invalid key")
#Find the user to add the key to
group = Group.find_by_key(group_key)
if (group == None):
raise Exception("Invalid group key")
#Remove the user from the pending users
group_pending_usernames = JSON.unquote(group.pending_usernames)
group_pending_usernames.remove(user.username)
group.pending_usernames = JSON.encode(group_pending_usernames)
#Put the user in the confirmed users
group_usernames = JSON.unquote(group.usernames)
group_usernames.append(user.username)
group.usernames = JSON.encode(group_usernames)
group.increment_version()
group.put()
user.increment_version()
return "Group request accepted"
开发者ID:RyanMitch16,项目名称:code-u-final,代码行数:27,代码来源:models.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: show
def show(self, class_name):
id = self.request.get("id", None)
if id is None:
out = {
"meta": functions.createMetaData(
status="fail", code=400, method_name="showObjects", message="parameter missing"
)
}
self.response.out.write(json.encode(out))
return
# 文字列からモデルクラス取得
classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name)
klass = webapp2.import_string(classPath_str)
obj = klass.get_by_id(int(id))
if obj and obj.is_deleted == False:
out = {
"meta": functions.createMetaData(status="ok", code=200, method_name="showObjects"),
"response": {"objects": [obj.toDict(full=True)]},
}
else:
out = {
"meta": functions.createMetaData(
status="fail", code=400, method_name="showObjects", message="object not found"
)
}
self.response.out.write(json.encode(out))
开发者ID:noughts,项目名称:openfish,代码行数:29,代码来源:objects.py
示例8: login
def login( self ):
login = self.request.get( 'login', None );
password = self.request.get( 'password', None );
logging.info( "login=%s password=%s" % (login,password) );
# パラメータチェック
if (login is None) or (password is None):
out = { "meta": functions.createMetaData( status="fail", code=400, cc_code=1000, message="login and password required") };
logging.error( "login and password required" );
self.response.out.write( json.encode(out) )
return
# ログインしようとしているユーザーがメアドを verify 済みかチェック
auth_id = "own:"+ login
m = self.user_model
q = m.query( m.auth_ids==auth_id, m.verified==True )
result = q.get();
if result is None:
out = { "meta": functions.createMetaData( status="fail", code=400, cc_code=1000, message="ユーザーが存在しないか、メールアドレス認証が完了していません") };
logging.error( "ユーザーが存在しないか、メールアドレス認証が完了していません" );
self.response.out.write( json.encode(out) )
return
user = None
userInfo = self.auth.get_user_by_password( "own:"+ login, password, True, True, True )
# 2013/01/06 以前のバージョンは頭に「own:」がついてなかったので、それにも対応。
if userInfo is None:
logging.info( "2013/01/06 以前のバージョン方式でログインします" );
userInfo = self.auth.get_user_by_password( login, password, True, True, True )
if userInfo is None:
# ログイン失敗
logging.error( "Invalid email/username or password." );
out = {
"meta": functions.createMetaData(
status="fail", code=401, cc_code=1000, message="Invalid email/username or password."
),
};
self.response.out.write( json.encode(out) )
return
# ログイン成功
user = User.get_by_id( userInfo["user_id"] )
sessionId = self.serialize_user_token( auth_info=userInfo )
out = {
"meta": {
"status": "ok",
"code": 200,
"method_name": "loginUser",
"session_id": sessionId,
},
"response":{
"users": [
user.toDict( full=True ),
],
},
};
self.response.out.write( json.encode(out) )
开发者ID:noughts,项目名称:openfish,代码行数:59,代码来源:users.py
示例9: 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
示例10: create
def create( self ):
target_model = self.request.get( 'target_model', None );
target_id = self.request.get( 'target_id', None );
# パラメータが足りなかったらエラー
if target_model is None or target_id is None:
message = "parameter missing"
logging.warn( message );
out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createReport", message=message )};
self.response.out.write( json.encode(out) )
return
# 文字列からターゲットのモデルクラス取得
classPath_str = "models."+ target_model.capitalize()
klass = webapp2.import_string( classPath_str )
target_obj = klass.get_by_id( int(target_id) );
# ターゲットオブジェクトがなければエラー
if target_obj is None:
message = "target object not found"
logging.warn( message );
out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createReport", message=message )};
self.response.out.write( json.encode(out) )
return
# 保存
entity = models.Report()
entity.target_key = target_obj.key
entity.user_key = self.user.key if self.user else None
entity.put();
# 出力
out = {
"meta": functions.createMetaData( status="ok", code=200, method_name="createReport" ),
"response": {
"reports":[
entity.toDict(),
],
},
};
self.response.out.write( json.encode(out) )
# 管理者にメール
sender_address = "[email protected]"
recipient = "[email protected]"
subject = "通報を確認してください。"
targetKey_str = str( target_obj.key.id() )
modelName = target_model.capitalize().encode()
gql = "SELECT * FROM "+ modelName +" where __key__ = Key( '"+ modelName +"', "+ targetKey_str +" )"
body = """
通報がありました。
ターゲットのkeyは %(targetKey_str)s です
検索用 GQL は以下のとおりです。
%(gql)s
""" % locals()
mail.send_mail( sender_address, recipient, subject, body )
开发者ID:noughts,项目名称:openfish,代码行数:59,代码来源:reports.py
示例11: create
def create( self ):
target_model = self.request.get( 'target_model', None );
target_id = self.request.get( 'target_id', None );
# パラメータが足りなかったらエラー
if target_model is None or target_id is None:
message = "parameter missing"
logging.warn( message );
out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )};
self.response.out.write( json.encode(out) )
return
# ゲストならエラー
if self.user is None:
message = "login required"
logging.warn( message );
out = {"meta": functions.createMetaData( status="fail", code=401, method_name="createLike", message=message )};
self.response.out.write( json.encode(out) )
return
# 文字列からターゲットのモデルクラス取得
classPath_str = "models."+ target_model.capitalize()
klass = webapp2.import_string( classPath_str )
target_obj = klass.get_by_id( int(target_id) );
# ターゲットオブジェクトがなければエラー
if target_obj is None:
message = "target object not found"
logging.warn( message );
out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )};
self.response.out.write( json.encode(out) )
return
# 重複チェック
query = models.Like.query( models.Like.target_key==target_obj.key, models.Like.user_key==self.user.key, models.Like.is_deleted==False )
if query.get():
message = "already liked"
logging.warn( message );
out = {"meta": functions.createMetaData( status="fail", code=400, method_name="createLike", message=message )};
self.response.out.write( json.encode(out) )
return
# 保存
entity = models.Like()
entity.target_key = target_obj.key
entity.user_key = self.user.key
entity.put();
# 出力
out = {
"meta": functions.createMetaData( status="ok", code=200, method_name="createLike" ),
"response": {
"likes":[
entity.toDict(),
],
},
};
self.response.out.write( json.encode(out) )
开发者ID:noughts,项目名称:openfish,代码行数:58,代码来源:likes.py
示例12: create
def create( self ):
target_model = self.request.get( 'target_model', None );
target_id = self.request.get( 'target_id', None );
content = self.request.get( 'content', None );
rating = self.request.get( 'rating', None );
# パラメータが足りなかったらエラー
if content is None or target_model is None or target_id is None:
message = "parameter missing"
logging.error( message )
out = {
"meta": functions.createMetaData( status="fail", code=400, method_name="createComment", message=message ),
};
self.response.out.write( json.encode(out) )
return
# 文字列からモデルクラス取得
classPath_str = "models."+ target_model.capitalize()
klass = webapp2.import_string( classPath_str )
target_obj = klass.get_by_id( int(target_id) );
# ターゲットオブジェクトがなければエラー
if target_obj is None:
message = target_model +"#"+ target_id +" is not found"
logging.error( message )
out = {
"meta": functions.createMetaData( status="fail", code=400, method_name="createComment", message=message ),
};
self.response.out.write( json.encode(out) )
return
# 保存
comment = models.Comment()
comment.content = content
comment.rating = rating
comment.target_key = target_obj.key
if self.user:
comment.user_key = self.user.key
comment.put();
# 出力
out = {
"meta": functions.createMetaData( status="ok", code=200, method_name="createComment" ),
"response": {
"comments":[
comment.toDict(),
],
},
};
self.response.out.write( json.encode(out) )
开发者ID:noughts,项目名称:openfish,代码行数:52,代码来源:comments.py
示例13: post
def post(self):
self.response.content_type = 'application/json'
punto = self.request.get('punto')
codigo = self.request.get('codigo')
if punto == '1' and codigo == '48yB8dH4V58xbRx':
coordenadas = {'latitud':'4.680569', 'longitud': '-74.047702', 'clave':'true', 'punto':'2'}
self.response.write(json.encode(coordenadas))
elif punto == '2' and codigo == 'Ug1195M928451LU':
coordenadas = {'latitud':'4.676829', 'longitud': '-74.048194', 'clave':'true', 'punto':'3'}
self.response.write(json.encode(coordenadas))
else:
coordenadas = {'latitud':'0', 'longitud': '0', 'clave':'false'}
self.response.write(json.encode(coordenadas))
开发者ID:raerpo,项目名称:desafio,代码行数:13,代码来源:comunicacion.py
示例14: _train
def _train( self ):
params = {
"content": "卵かけご飯",
"categories": json.encode(["1","2"]),
}
request = webapp2.Request.blank( '/v1/bayes/train', POST=params )
response = request.get_response( openfish.main.app )
params = {
"content": "これは筆です",
"categories": json.encode(["3","4"]),
}
request = webapp2.Request.blank( '/v1/bayes/train', POST=params )
response = request.get_response( openfish.main.app )
开发者ID:noughts,项目名称:openfish,代码行数:14,代码来源:test.py
示例15: _upsert_member_or_volunteer_info
def _upsert_member_or_volunteer_info(list_member, sheet_dict, fields, typename):
"""Helper for `upsert_member_info()` and `upsert_volunteer_info()`.
"""
if list_member:
# Update existing
_update_mailchimp_record_from_dict(list_member, sheet_dict, fields, typename)
url = 'members/%s' % list_member['id']
logging.info('MailChimp: updating %s from %s', list_member, sheet_dict)
_make_request(url, 'PATCH', body=json.encode(list_member))
else:
# Create new
list_member = _create_mailchimp_record_from_dict(sheet_dict, fields, typename)
url = 'members'
logging.info('MailChimp: creating %s from %s', list_member, sheet_dict)
_make_request(url, 'POST', body=json.encode(list_member))
开发者ID:adam-p,项目名称:danforth-east,代码行数:15,代码来源:mailchimp.py
示例16: post
def post(self):
user = users.get_current_user()
useremail = ""
if user:
useremail = user.email()
else:
useremail = "public"
if authserv.isAuthorised(useremail):
doc_id = self.request.get('doc_id')
new_title = self.request.get('title')
new_eventdate = self.request.get('eventdate')
new_tags = self.request.get('tags')
new_description = self.request.get('descritption')
index = search.Index(_INDEX_NAME)
doc = index.get(doc_id)
dtSplt = new_eventdate.split('-')
docyear = int(dtSplt[0])
docmonth = int(dtSplt[1])
docday = int(dtSplt[2])
""" make a seach document"""
nodeMetadata = search.Document(
doc_id=doc_id,
fields=[
search.AtomField(name='uploader', value=doc.fields['uploader']),
search.AtomField(name='nodeID', value=doc.fields['nodeID']),
search.TextField(name='title', value=new_title),
# search.AtomField(name='filelink', value=filelink),
search.TextField(name='description', value=new_description),
search.TextField(name='eventdate', value=new_eventdate),
search.TextField(name='tags', value=new_tags),
search.GeoField(name='place', value=doc.fields['geopoint']),
search.DateField(name='eventdatestamp', value=date(docyear, docmonth, docday)),
search.DateField(name='stamp', value=datetime.now().date())])
""" put that search document in to the index """
rsp = ""
try:
search.Index(name=_INDEX_NAME).put(nodeMetadata)
rsp = json.encode({'rsp': 'OK', 'msg': 'saved the document'} )
except search.Error, e:
rsp = json.encode({'rsp': 'REJECT', 'msg': 'Did NOT SAVE'} )
开发者ID:dwagner4,项目名称:videobucket,代码行数:48,代码来源:editIndex.py
示例17: toJSON
def toJSON(self):
jsondata = {
"Blocks" : self.blocks,
"X" : self.X,
"Y" : self.Y
}
return json.encode(jsondata)
开发者ID:scottishidiot,项目名称:WGD,代码行数:7,代码来源:main.py
示例18: get
def get(self):
timestamp = int(round(time.time()*1000))
channel_id_param = self.request.get('channel_id')
auth_key_param = self.request.get('auth_key')
duration_param = self.request.get('duration')
if (channel_id_param == _CHANNEL_ID_FOR_TV8
and auth_key_param == _AUTH_KEY_FOR_TV8
and duration_param):
memcache.set(_HLS_MASTER_BASE_URI, timestamp, time=_TTL_1_HOUR)
logging.info('received ad trigger with channel_id %s, auth_key %s, timestamp %i, duration %s' %
(channel_id_param, auth_key_param, timestamp, duration_param))
self.response.content_type = 'application/json'
# for debugging purposes
# obj = {
# 'duration_param': duration_param,
# 'auth_key_param': auth_key_param,
# 'channel_id_param': channel_id_param,
# 'timestamp': timestamp
# }
obj = {
'success': True
}
self.response.write(json.encode(obj))
else:
logging.info('INVALID ad trigger with channel_id %s, auth_key %s, timestamp %i, duration %s' %
(channel_id_param, auth_key_param, timestamp, duration_param))
self.response.set_status(500)
self.response.write('A server error occurred!')
开发者ID:dobri-dobrev,项目名称:hoydaa-cast,代码行数:28,代码来源:trigger_api.py
示例19: create
def create(self, class_name):
logging.info(self.request.arguments())
if self.checkModel(class_name) == False:
return
if models.BlackList.checkBanned():
return
# 文字列からモデルクラス、エンティティ取得
classPath_str = "models." + functions.convertFromSnakeCaseToCamelCase(class_name)
klass = webapp2.import_string(classPath_str)
# マスタデータかどうかチェック & マスターデータだったら管理者以外は作成できないように。
if klass.isMasterData == True and users.is_current_user_admin() == False:
logging.warn("管理者以外がマスタデータを作成しようとしました")
return False
# 保存開始
entity = klass()
self.setPropertyFromRequestData(entity, self.request)
entity.put()
# 出力
out = {
"meta": functions.createMetaData(status="ok", code=200, method_name="createCustomObject"),
"response": {"objects": [entity.toDict()]},
}
self.response.out.write(json.encode(out))
开发者ID:noughts,项目名称:openfish,代码行数:28,代码来源:objects.py
示例20: 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
注:本文中的webapp2_extras.json.encode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论