本文整理汇总了Python中database.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_user_info
def get_user_info(self, code):
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
r = client.request_access_token(code)
access_token = r.access_token
expires_in = r.expires_in
print r.access_token, r.expires_in
client.set_access_token(access_token, expires_in)
uid = client.get.account__get_uid().uid
print uid
user = User.verify_user_openID(accountType=User.USER_TYPE_SINA_WEIBO, accountID=uid)
if not user:
user_info = client.get.users__show(uid=uid)
user = User.new(
username="%s_%s" % (User.USER_TYPE_SINA_WEIBO, uid),
accountType=User.USER_TYPE_SINA_WEIBO,
accountID=uid,
)
user.screen_name = user_info.screen_name
user.gender = user_info.gender
user.headPortrait_url = user_info.profile_image_url # avatar_large?
print user_info
user.openIDinfo = user_info
else:
print "old user"
if user.last_login == None:
user.bonus_notification = 1
else:
last_login_date = datetime.fromtimestamp(user.last_login)
if last_login_date.date() < datetime.today().date():
user.bonus_notification = 1
user.last_login = int(time.time())
self.got_user_info(uid, user)
示例2: post
def post(self):
print "Got Venmo payment update"
print self.request.body
js = json.loads(self.request.body)
date = js['date_created']
updateType = js['type']
data = js['data']
if updateType == "payment.created":
driverID = data['target']['user']['id']
passengerID = data['actor']['id']
driver = User.gql('WHERE venmoID=' + driverID).get()
passenger = User.gql('WHERE venmoID=' + passengerID).get()
payment = Payment(type="Venmo", dateCreated=date, lastUpdate=date, status=data['status'],
driver=driver, passenger=passenger, apiID=data['id'],
amount=data['amount'], note=data['note'])
payment.put()
# send channel updates to each
channel.send_message(str(driver.key().id()), "{}");
channel.send_message(str(passenger.key().id()), "{}");
elif updateType == "payment.updated":
status = data['status']
payment = Payment.gql("WHERE apiID=" + data['id'])
payment.status = status
payment.lastUpdated = date # need to check that this is working properly
# add in logic for payment processing
# check the status and update user/ride info accordingly
self.processPayment(data, status, payment)
payment.put()
示例3: post
def post(self):
if self.get_argument("username", default=None) is None:
# TODO Check whether username is exist
username = "GUEST_" + hashlib.md5(str(time.time()) + str(random())).hexdigest()[0:8]
password = hashlib.md5(str(time.time()) + str(random())).hexdigest()
user = User.new(username=username, password=hashlib.md5(password).hexdigest())
user.screen_name = username.replace("GUEST_", u"游客")[0:6]
else:
username = self.get_argument("username")
password = hashlib.md5(self.get_argument("password")).hexdigest()
user = User.verify_user(username, password)
if user is None:
message = {"status": "failed", "content": "invalid username or password"}
else:
message = {"status": "success", "username": user.username, "password": password}
self.session["user_id"] = user.id
if user.last_login == None:
user.bonus_notification = 1
else:
last_login_date = datetime.fromtimestamp(user.last_login)
if last_login_date.date() < datetime.today().date():
user.bonus_notification = 1
user.last_login = int(time.time())
self.set_header("Access-Control-Allow-Origin", "*")
self.write(json.dumps(message))
示例4: authorized
def authorized():
global facebook_graph
# check to make sure the user authorized the request
if not 'code' in request.args:
flash('You did not authorize the request')
return redirect(url_for('index'))
code = request.args['code']
access_token_url = 'https://graph.facebook.com/oauth/access_token'
access_token_url_params = {'client_id': app.config['FB_CLIENT_ID'],
'redirect_uri': url_for('login.authorized', _external=True),
'client_secret': app.config['FB_CLIENT_SECRET'],
'code': code
}
access_token_text = requests.get(access_token_url, params=access_token_url_params).text
access_token = re.split('=|&', access_token_text)[1]
facebook_graph = facebook.GraphAPI(access_token)
me = facebook_graph.get_object("me")
fb_id = me['id']
session['fb_id'] = fb_id
session['name'] = me['name']
session['logged_in'] = True
user = User.query.filter_by(fb_id=fb_id).first()
if user is None:
user = User(fb_id, access_token)
db.session.add(user)
db.session.commit()
else:
user.access_token = access_token
db.session.merge(user)
db.session.commit()
return redirect(url_for('index'))
示例5: create_user
def create_user(Session,username,password,public_key,creator):
s=Session
user=get_user(s,username)
if user is None:
if creator:
cid=creator.id
else:
cid=None
u=User(name=username,password=genpw(password),creator=cid,public_key=public_key)
s.add(u)
s.commit()
return True
else:
u=user
if not creator: return False
if u.id==creator.id or creator.name=='admin':
if not password is None:
if password=='':
u.password=''
else:
u.password=genpw(password)
if not public_key is None:
u.public_key=public_key
s.merge(u)
s.commit()
return True
return False
示例6: create_user
def create_user(username, password, email):
salt = make_salt()
hashed = hash_password(password, salt)
u = User(username=username,
email=email,
salt=salt,
password=hashed)
u.put()
示例7: test_getUser
def test_getUser():
u = User(
user_id=111222333,
first_name='Denis',
username='denisbalyko',
last_name='Balyko'
)
u_test = InstanceTelegramTest.getUser()
assert type(u) == type(u_test), 'type getUser'
assert u_test.__repr__() == u.__repr__(), 'eq getUser'
示例8: test_getHalfUser
def test_getHalfUser():
u = User(
user_id=111222333,
first_name='Denis2',
username='',
last_name='BalykoTest'
)
u_test = InstanceTelegramTestNoCommand.getUser()
assert type(u) == type(u_test), 'type getUser'
assert u_test.__repr__() == u.__repr__(), 'eq getUser'
示例9: post
def post(self):
username = self.request.get('user')
password = self.request.get('password')
password_repeated = self.request.get('verify')
email = self.request.get('email')
# Validate input and generate needed error messages
if not validations.is_valid_username:
username_error = 'Invalid Username'
elif User.username_exists(username):
username_error = 'That username is already in use.'
else:
username_error = ''
password_error = ('' if validations.is_valid_password(password)
else 'Invalid Password.')
password_repeated_error = ('' if (password_error or
password == password_repeated)
else 'Passwords do not match.')
email_error = ('' if (not email or validations.is_valid_email(email))
else 'Invalid Email Address.')
errors = [username_error, password_error,
password_repeated_error, email_error]
# If success, send to welcome page
if all(not error for error in errors):
# Success!
# Hash password
hashed_pwd = auth.make_pw_hash(username, password)
# Add to database
new_user_entry = User(username=username,
password=hashed_pwd,
email=email,
parent=ndb.Key('Users', 'user_group'))
# if email:
# new_user_entry.email = email
new_user_entry.put()
# Add cookie
self.force_login(username)
redirect_when_finished = self.request.get('redirect_when_finished')
return self.redirect_with_queries(
'/welcome',
[('redirect_when_finished', redirect_when_finished)])
else:
# If any checks failed, send back to the signup page
# with error messages. Repopulate fields except for passwords.
self.response.out.write(self.template.render(
entered_username=username,
email=email,
username_error=username_error,
password_error=password_error,
password_repeated_error=password_repeated_error,
email_error=email_error
))
示例10: handleUserJoin
def handleUserJoin(obj):
if not obj['joined']: return
u = RUser(obj['u'], 0, r)
if u.isOnline() and not u.getCurrentServer()['sid'] == obj['sid']: #If the user is online, kick them from the first server
push(obj['sid'], {"a": "kick", "u": obj['u'], "msg": "User joined another server..."})
u.joinServer(obj['sid'])
u.addServerHistory(obj['sid'])
# Join Message
q = User.select().where(User.username == obj['u'])
if not q.count():
packs = [{"a": "sendto", "user": obj['u'], "msg": i} for i in need_reg_msgs]
push(obj['sid'], packs)
return
resp = [
{"a": "sendto", "user": obj['u'], "msg": "{C_RED}{C_ITALIC}Your user level has been synced."},
{"a": "user_level", "user": obj['u'], "level": q[0].level}]
push(obj['sid'], resp)
msg = [{"a": "sendto", "user": None, "msg": "{C_AQUA}%s {C_GOLD}{C_ITALIC}has joined %s" % (q[0].username, u.getCurrentServer()['name'])}]
for fr in q[0].getFriends():
tmp = RUser(fr.username, fr.id, r)
if tmp.perma['CFG_NOTI_FRIEND_JOIN'] is False: continue
if tmp.isOnline():
msg[0]['user'] = tmp.name
push(tmp.getCurrentServer()['sid'], msg)
示例11: attempt_login
def attempt_login(self, entered_username, password):
"""Attempt to login given a username and password.
If the credentials are invalid, return False and do nothing.
If the credentials are valid, add a user cookie and return True.
Args:
entered_username (str): Username for the attempted login
password (str): plaintext password user enters
Returns:
bool: True if login was successful, False if not
"""
user_in_db = User.get_by_username(entered_username)
if (user_in_db is not None and
auth.password_is_valid(entered_username,
password,
user_in_db.password)):
# If we have a match, the credentials are good
self.force_login(entered_username)
return True
else:
return False
示例12: prepare
def prepare(self):
domain_query = DomainLogs.select().where(DomainLogs.domain == self.request.host).first()
if not domain_query:
user = User.select().where(User.domain == self.request.host.split(".")[-3]).first()
if not user:
return
domain_query = DomainLogs()
domain_query.user_id = user.id
domain_query.domain = self.request.host
domain_query.save()
log = DNSLogs()
log.ip = self.request.headers.get('X-Forwarded-For')
log.user_id = user.id
log.domain_id = domain_query.id
log.save()
if not self.request.uri == "/favicon.ico":
log = UrlLogs()
packet = "%s %s %s\n" % (self.request.method, self.request.uri, self.request.version)
for header in self.request.headers:
packet += "%s: %s\n" % (header, self.request.headers.get(header))
packet += "\n%s" % self.request.body
log.url = self.request.uri
log.ip = self.request.headers.get("X-Forwarded-For")
log.domain_id = domain_query.id
log.user_id = domain_query.user_id
log.packet = packet
log.save()
示例13: api_v1_login
def api_v1_login():
if "username" not in request.json or "password" not in request.json:
abort(418)
user = User.get_user_by_name(request.json["username"])
if not user.login(request.json["password"]):
abort(418)
return success()
示例14: post
def post(self):
try:
user = User.get_by_id(self.getUser())
self.sendActivationEmail(user.email, user.activationCode)
self.render("verify.html", color="green", status="Email Sent")
except:
self.render("verify.html", color="end", status="Email failed to send")
示例15: post
def post(self):
player_id = self.get_argument("id", -1);
player = User.find(_id = player_id)
portrait = None
family = "-1"
position = "-1"
percentage = 0
if player.headPortrait_url is not None:
portrait = player.headPortrait_url
#if player.family is not None:
# family = player.family.name
# position= player.family_position.name
if player.total_games > 0:
percentage = (player.won_games * 1.0) / player.total_games
message = {
"status": "success",
"name": player.screen_name,
"head_portrait": portrait,
"family": family,
"position": position,
"level": player.level,
"asset": player.asset,
"percentage": "%.2f%%" % (percentage * 100),
"total_games": player.total_games,
"won_games": player.won_games,
"max_reward": player.max_reward,
"last_login": datetime.fromtimestamp(player.last_login).strftime("%Y-%m-%d %H:%M:%S"),
"signature": player.signature or "This guy is too lazy to leave a signature",
"friends": str(player.friends),
"gender": player.gender
}
self.write(json.dumps(message))
self.finish()