本文整理汇总了Python中models.User.query方法的典型用法代码示例。如果您正苦于以下问题:Python User.query方法的具体用法?Python User.query怎么用?Python User.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_new_game
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def create_new_game(self, request):
"""Create a new tictactoe game between 2 players
Args:
NEW_GAME_REQUEST: Details of new game in GameForm format
Returns:
New game in GameForm format along with Confirmation message
Raises:
NotFoundException: if either user specified in input GameForm
is not found in user model
"""
userX = User.query(User.name == request.userX)
userO = User.query(User.name == request.userO)
if not userX:
raise endpoints.NotFoundException(
'User {} does not exist'.format(request.userX))
if not userO:
raise endpoints.NotFoundException(
'User {} does not exist'.format(request.userO))
game = Game.new_game(userX.key, userO.key)
game.put()
return game.to_form('Game created. {} to play first'.format(
request.userX))
示例2: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def post(self):
post = RequestPost.query(RequestPost.reference == cgi.escape(self.request.get('post_reference'))).get()
requester = User.query(User.username == cgi.escape(self.request.get('requester'))).get()
applicant = User.query(User.username == cgi.escape(self.request.get('applicant'))).get()
price_offer = cgi.escape(self.request.get('price_offer'))
#create a notify message
notifymsg = NotifiedMessage()
notifymsg.read = False
notifymsg.person_reference = requester.username
notifymsg.object_reference = post.reference
notifymsg.content = " offered $" + price_offer + " for "
notifymsg.price = price_offer
notifymsg.initiator = applicant.username
#push to requester's noti box
#logging.info(notifymsg)
if applicant.key not in post.job_applicants:
post.job_applicants.append(applicant.key)
post.price_offers_new.append(price_offer)
post.list_of_applicants.append(applicant.username)
post.num_applicants = post.num_applicants + 1
post.put()
notifymsg.put()
示例3: get_user_ranking
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def get_user_ranking(self, request):
"""Inefficient way to find ranking, for the user request
find the user and then compare win ratio with other users
if win ratio is equal, compare the number of losses"""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with the name {} does not exist!'.format(request.user_name))
users = User.query(User.name != request.user_name)
losses = user.losses
wins = user.wins
win_ratio = user.win_ratio
ranking = 0
total_users = 1
for other_user in users:
total_users = total_users + 1
if other_user.win_ratio < win_ratio:
ranking = ranking - 1
elif other_user.win_ratio == win_ratio:
if other_user.losses >= losses:
ranking = ranking - 1
ranking = total_users + ranking
#Create a ranking message
msg = "User {} Ranking {} Win Ratio {}".format(user.name, ranking, win_ratio)
return StringMessage(message = msg)
示例4: get
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def get(self):
"""Send an email to all users giving the user rankings"""
app_id = app_identity.get_application_id()
users = User.query(User.email != None).fetch()
rankings = User.query().order(-User.win_loss_ratio, -User.draws)
rankings = rankings.fetch()
# Create rankings table
rankings_format = "{:<15}{:<15}\n"
header = rankings_format.format("Name", "Win/loss ratio")
lines = [rankings_format.format(user.name, user.win_loss_ratio)
for user in rankings]
table = header + ''.join(lines)
# Email users
for user in users:
subject = 'Kalah rankings'
body = "Hello {}, here is an update on Kalah rankings:\n\n"
body = body.format(user.name)
body += table
mail.send_mail('[email protected]{}.appspotmail.com'.format(app_id),
user.email,
subject,
body)
示例5: new_game
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def new_game(self, request):
"""Creates a Game.
Args:
request: The NEW_GAME_REQUEST objects, which includes two players'
names
Returns:
GameForm with created game
Raises:
endpoints.NotFoundException: If the user does not exist.
endpoints.BadRequestException: If the game is created with one
user.
"""
user_x = User.query(User.name == request.user_name_x).get()
user_o = User.query(User.name == request.user_name_o).get()
if (not user_o) or (not user_x):
raise endpoints.NotFoundException(
'A User with that name does not exist!')
try:
game = Game.new_game(user_x.key, user_o.key)
history = History(game=game.key)
history.put()
except ValueError:
raise endpoints.BadRequestException('Players should be '
'different!')
return game.to_form('Good luck playing TicTacToe!')
示例6: new_game
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def new_game(self, request):
"""Creates new game"""
number_of_players = request.number_of_players
user = User.query(User.name == request.user_name).get()
opponent_key = None
if not user:
raise endpoints.NotFoundException(
'A User with that user name does not exist!')
if number_of_players != 2:
raise endpoints.BadRequestException(
'Number of players must be 2!')
else:
opponent = User.query(User.name == request.opponent_name).get()
if not opponent:
raise endpoints.NotFoundException(
'A User with that opponent name does not exists!')
opponent_key = opponent.key
rows = request.rows
columns = request.columns
try:
game = Game.new_game(
number_of_players,
user.key,
opponent_key,
rows,
columns)
except ValueError:
raise endpoints.BadRequestException('Dimensions must '
'be greater than 0!')
return game.to_form('New game is set, place your ships!')
示例7: send_sms
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def send_sms(request):
AUTH_TOKEN = '#########'
ACCOUNT_SID = '##########'
twilio_number = '+###########'
sender = User.query(User.username == request.sender_name).get()
acceptor = User.query(User.username == request.recipient_name).get()
print "Sender: ", sender.username
print "Acceptor:", acceptor.username
key = request.key.urlsafe()
sender_key = sender.key.urlsafe()
acceptor_key = acceptor.key.urlsafe()
sender_short_url = shorten_url("http://food-enthusiast.appspot.com/verify/" + key + "/" + sender_key)
acceptor_short_url = shorten_url("http://food-enthusiast.appspot.com/verify/" + key +"/" + acceptor_key)
print sender_short_url
print acceptor_short_url
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
#Send to creator
print("Sending message to ", sender.telephone)
print("Sending message to ", acceptor.telephone)
sender_body = "Please contact " + acceptor.first_name + "(" + acceptor.telephone + ") if needed. " + "Check in: " + sender_short_url
acceptor_body = "Please contact " + sender.first_name + "(" + sender.telephone + ") if needed. " + "Check in: " + acceptor_short_url
#Send to poster
client.messages.create(
to = (sender.telephone),
from_ = twilio_number,
body = sender_body
)
#Send to acceptor
client.messages.create(
to = (acceptor.telephone),
from_ = twilio_number,
body = acceptor_body
)
示例8: send_fire_notification
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def send_fire_notification(request):
AUTH_TOKEN = '#########'
ACCOUNT_SID = '##########'
twilio_number = '+###########'
sender = User.query(User.username == request.sender_name).get()
acceptor = User.query(User.username == request.recipient_name).get()
print "Sender: ", sender.username
print "Acceptor:", acceptor.username
key = request.key.urlsafe()
sender_key = sender.key.urlsafe()
acceptor_key = acceptor.key.urlsafe()
sender_short_url = shorten_url("http://food-enthusiast.appspot.com/fire/" + key + "/" + acceptor_key)
print sender_short_url
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
#Send to creator
print("Sending option to fire message to ", sender.telephone)
sender_body = acceptor.first_name + "(" + acceptor.telephone + ") hasn't checked in. Fire " + acceptor.first_name + "? " + sender_short_url
#Send to poster
client.messages.create(
to = sender.telephone,
from_ = twilio_number,
body = sender_body
)
示例9: create_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def create_user(self, request):
"""Create user w/ unique username and email."""
# check for empty user_name
if not request.user_name:
raise endpoints.BadRequestException('ERR_EMPTY_USERNAME')
# check for empty email
if not request.email:
raise endpoints.BadRequestException('ERR_EMPTY_EMAIL')
# check for unique username
if User.query(User.user_name == request.user_name).get():
raise endpoints.ConflictException('ERR_USERNAME_EXISTS: {}'.format(request.user_name))
# check if user is already registered
if User.query(User.email == request.email).get():
raise endpoints.ConflictException('ERR_EMAIL_EXISTS: {}'.format(request.email))
# create rating obj for new user
user_default_rating = Rating()
# create user
user = User(key=ndb.Key(User, request.user_name),
user_name=request.user_name,
email=request.email,
display_name=request.display_name,
mu=user_default_rating.mu,
sigma=user_default_rating.sigma)
user.put()
return UserResponse(user_name=user.user_name, email=user.email, display_name=user.display_name)
示例10: new_game
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def new_game(self, request):
"""Creates new game"""
user1 = User.query(User.name == request.player1_name).get()
if not user1:
raise endpoints.NotFoundException(
'User 1 does not exist!')
user2 = User.query(User.name == request.player2_name).get()
if not user2:
user2key = user2
else:
user2key = user2.key
player1_primary_grid = GameLogic.place_ship_on_grid(
request,
'1')
player2_primary_grid = GameLogic.place_ship_on_grid(
request,
'2')
player1_tracking_grid = GameLogic.create_default_grid()
player2_tracking_grid = GameLogic.create_default_grid()
game = Game.new_game(user1.key, user2key,
player1_primary_grid,
player2_primary_grid,
player1_tracking_grid,
player2_tracking_grid)
return game.to_form('Good luck playing Battleship!')
示例11: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def post(self):
text = cgi.escape(self.request.get('text'))
sender = cgi.escape(self.request.get('sender'))
recipient = cgi.escape(self.request.get('recipient'))
subject = cgi.escape(self.request.get('subject'))
parent_message = cgi.escape(self.request.get('parent'))
q = User.query(User.username == recipient)
user = q.get()
if(user):
if len(parent_message) > 0:
message_key = ndb.Key(urlsafe=parent_message)
message = Message(parent = message_key)
else:
message = Message()
message.subject = subject
message.text = text
message.sender = sender
message.recipient = recipient
message.time = datetime.datetime.now() - datetime.timedelta(hours=7) #For PST
message.put()
#Increment message count for navbar
q = User.query(User.username == recipient)
user = q.get()
user.message_count += 1
user.put()
self.redirect('/messages')
else:
self.redirect('/compose')
示例12: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def post(self):
user = users.get_current_user()
if(user):
username = str(self.request.get('username'))
taken = False
usernameQuery = User.query()
for allUsers in usernameQuery:
if allUsers.username == username:
taken = True
if taken:
self.get("Username taken. Please try another.")
else:
userQuery = User.query(User.userid == user.user_id())
for userEntity in userQuery:
if len(username) == 0:
self.response.write("Please enter a username.")
elif len(username) > 15:
self.response.write("Your username is too long.")
else:
userEntity.username = username
userEntity.put()
userEntity.put()
self.redirect('/')
else:
self.redirect(users.create_login_url(self.request.uri))
示例13: insertUser
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def insertUser(request):
errors = []
u = User()
u.user = re.escape(request.POST.get('user'))
u.email = request.POST.get('email')
password = re.escape(request.POST.get('password'))
salt = uuid.uuid4().hex
hashed_password = hashlib.sha512(password + salt).hexdigest()
u.password = hashed_password
u.salt = salt
u.locked = False
u.activated = False
u.attempts = 0
num_users = u.query(User.user==u.user).count()
num_emails = u.query(User.email==u.email).count()
if num_users == 0 and num_emails == 0:
code = hashlib.sha512(u.user + salt).hexdigest()
u.code = re.escape(code)
u.put()
params = { 'user' : u.user, 'code': code}
sendEmail(u.email, "Account verification url: http://dsswkvn.appspot.com/validateaccount?" + urllib.urlencode(params))
return True
else:
message = "No se ha podido insertar el usuario"
if (num_users != 0):
errors.append("User already exists")
if (num_emails != 0):
errors.append("Email already exists")
template_values = {
'errors': errors
}
return template_values
示例14: new_game
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def new_game(self, request):
"""Start a new game"""
#Check if players have registered
player1 = User.query(User.name == request.player1).get()
if not player1:
raise endpoints.ConflictException('Player 1 must register')
player2 = User.query(User.name == request.player2).get()
if not player2:
raise endpoints.ConflictException('Player 2 must register')
if player1 == player2:
raise endpoints.ConflictException('Cannot play against oneself')
#Create new game and put in datastore
game = Game(player1=player1.key,
player2=player2.key,
playerTurn=player1.key,
game_over=False
)
game.put()
#Create initial game board and set as ancestor of game
boardId = Board.allocate_ids(size=1, parent=game.key)[0]
boardKey = ndb.Key(Board, boardId, parent=game.key)
board = Board(key=boardKey)
board.put()
game.state = boardKey
game.put()
return StringMessage(message="Game between {0} and {1} created! {2}".format(player1.name, player2.name, game.key))
示例15: new_game
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import query [as 别名]
def new_game(self, request):
"""Creates new game"""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with that name %s does not exist!' % request.user_name)
### user b is another user online
opponent = User.query(User.name == request.opponent_name).get()
if not opponent:
raise endpoints.NotFoundException(
'A User with that name %s does not exist!' % request.opponent_name)
try:
### user is the one for the first move in the new game
game = Game.new_game(user=user.key, user_tic=request.user_tic,
opponent=opponent.key, opponent_tic=request.opponent_tic,
user_of_next_move=user.key)
except ValueError:
raise endpoints.BadRequestException('Value Error')
# Use a task queue to cache winning chance
taskqueue.add(url='/tasks/cache_winning_chance/')
taskqueue.add(url='/tasks/cache_winning_chance/', target="worker",
params={'user_name':request.user_name}, name="cache-winning-chance")
GLOBAL_CURRENT_USER_NAME = request.user_name
return game.to_form('Good luck playing Tic-Tac-Toe!')