本文整理汇总了Python中models.User.key方法的典型用法代码示例。如果您正苦于以下问题:Python User.key方法的具体用法?Python User.key怎么用?Python User.key使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.key方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def add_user():
try:
data = json.loads(request.data)
email = data['email']
password = data['password']
salt = uuid.uuid4().hex
hashed_password = hashlib.sha512(password + salt).hexdigest()
user = User(
email=email,
password=hashed_password,
salt=salt
)
user.key = ndb.Key(User, email)
user.put()
except CapabilityDisabledError:
logging.error(u'App Engine Datastore is currently in read-only mode.')
abort(500)
except BadValueError:
abort(400)
except TypeError:
abort(400)
except Exception as e:
logging.error(e.args[0])
abort(500)
return Response(json.dumps({ "status": "ok" }), mimetype='application/json');
示例2: session_from_facebook
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def session_from_facebook():
"""
uses the facebook session cookie to create a site specific session.
it will also fetch profile information from facebook and add
the user to the datastore if it does not exist yet
"""
import facebook
# get facebook user id and token from facebook cookie
fb_user = facebook.get_user_from_cookie(request.cookies,
app.config['FACEBOOK_APPLICATION_ID'],
app.config['FACEBOOK_APPLICATION_SECRET'])
if fb_user:
# check whether the user is already in the datastoreg
user = User.all().filter('facebook_id =', str(fb_user['uid'])).get()
if user is None:
# if not we fetch his profile information via the facebook graph api
graph = facebook.GraphAPI(fb_user["access_token"])
profile = graph.get_object("me")
# now we can put the user in the datastore
user = User(key_name=generate_key(),
facebook_id=str(profile['id']),
facebook_token=request.values.get('access_token'),
email=profile['email'],
name=profile['name'])
user.save()
# last but not least we add the user's key to the session cookie
session['user_key'] = user.key().name()
return "ok"
示例3: worker_authors
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def worker_authors(request):
r = Repository.get(db.Key(request.POST["repo"]))
logging.info("processing repository: %s" % r.name)
base_url = "http://github.com/%s/%s" % (r.owner.name, r.name)
url = base_url + "/network_meta"
logging.info(" downloading network_meta from: %s" % url)
try:
s = urllib2.urlopen(url).read()
except urllib2.HTTPError:
logging.info("Probably bad repo, skipping.")
return HttpResponse("Probably bad repo, skipping.\n")
logging.info(" network_meta loaded")
try:
data = simplejson.loads(s)
except ValueError:
logging.info("Probably bad repo, skipping.")
return HttpResponse("Probably bad repo, skipping.\n")
logging.info(" network_meta parsed")
dates = data["dates"]
nethash = data["nethash"]
url = "%s/network_data_chunk?nethash=%s&start=0&end=%d" % (base_url,
nethash, len(dates)-1)
logging.info(" downloading commits from: %s" % url)
s = urllib2.urlopen(url).read()
logging.info(" parsing commits...")
data = simplejson.loads(s, encoding="latin-1")
logging.info(" processing authors...")
commits = data["commits"]
m = [(x["author"], x["id"]) for x in commits]
m = dict(m)
logging.info(m)
authors = m.keys()
authors = list(set(authors))
authors.sort()
logging.info(authors)
queue = get_github_queue()
for author in authors:
q = User.gql("WHERE name = :1", author)
u = q.get()
if u is None:
u = User(name=author, email="None")
u.save()
task = taskqueue.Task(url="/hooks/worker/user_email/",
params={'user': u.key(),
'r_user_id': r.owner.name,
'r_repository': r.name,
'r_sha': m[u.name]
})
queue.add(task)
q = Author.gql("WHERE user = :1 AND repo = :2", u, r)
a = q.get()
if a is None:
a = Author(repo=r, user=u)
a.save()
logging.info(" done.")
return HttpResponse("OK\n")
示例4: test_get_username
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def test_get_username(self):
username = "test_user"
password = "password"
password_hash_salt = make_pw_hash(username, password)
user = User(username=username, password_hash_salt=password_hash_salt)
assert UserRepository.username_not_taken(username)
user.put()
assert not UserRepository.username_not_taken(username)
user_id = UserRepository.user_id_from_username_password(username, password)
assert user_id == user.key().id()
示例5: create_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def create_user(self, request):
"""Creates a new player. Requires email and a unique username."""
if User.query(User.name == request.user_name).get():
raise endpoints.ConflictException(
'A Player with that name already exists!')
user = User(name=request.user_name, email=request.email)
user.key = ndb.Key(User, user.name)
user.put()
return StringMessage(message='User {} created!'.format(
request.user_name))
示例6: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def register(self, username, name, password, email, usertype):
user = User.all().filter('username =', username).get()
if user == None:
pw = make_pw_hash(username, password)
user = User(username=username, name=name, password=pw, email=email, usertype=usertype)
user.put()
user_id = user.key().id()
self.set_cookie('user_id', user_id)
self.redirect('/')
else:
error = 'The user allready exists'
random = make_salt()
self.render('register', username=username, name=name, email=email, error=error)
示例7: userSignup
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def userSignup(self, userData):
# check if email exist
user = User.gql("WHERE email = :1", userData["email"])
if user.count() == 1:
return user.get().key().id()
else:
# encode password
password = userData["password"] + PASSWORD_SALT
h = hashlib.md5()
h.update(password)
user = User(
name=userData["name"], email=userData["email"], password=h.hexdigest(), gender=userData["gender"]
)
user.put()
key = "UserSchoolUpvote.%i" % user.key().id()
memcache.add(key, "")
key = "UserSchoolDownvote.%i" % user.key().id()
memcache.add(key, "")
return user.key().id()
示例8: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def post(self):
user_name = self.request.get('username')
user_password = self.request.get('password')
user_verify = self.request.get('verify')
user_email = self.request.get('email')
name = utils.valid_username(user_name)
password = utils.valid_password(user_password)
verify = utils.valid_verify(user_verify, user_password)
email = utils.valid_email(user_email)
nameerror = passworderror = verifyerror = emailerror = ""
if not name:
nameerror = "That's not a valid username"
if not password:
passworderror = "That's not a valid password"
if password and not verify:
verifyerror = "Your passwords didn't match"
if user_email and not email:
emailerror = "That's not a valid email"
if (not (name and password and verify)) or (user_email and not email):
self.render_signup(user_name, nameerror, passworderror,
verifyerror, user_email, emailerror)
else:
# lookup user
u = User.gql("WHERE username = '%s'"%user_name).get()
# If user already exists
if u:
nameerror = "That user already exists"
self.render_signup(user_name, nameerror, passworderror,
verifyerror, user_email, emailerror)
else:
# make salted password hash
h = utils.make_pw_hash(user_name, user_password)
u = User(username=user_name, password=h)
u.put()
user_id = u.key().id()
uid_cookie = str(self.put_user_id_cookie(user_id, h))
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/"%uid_cookie)
self.redirect("/")
示例9: check
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def check(form1):
if (data["username_error"] == "" and
data["password_validity_error"] == "" and
data["verify_error"] == ""): #and
# data["email_error"] == ""):
user = User(username = username,
password = password,
email = email)
user.put()
user_id = user.key().id()
secure_val = make_secure_val(str(user_id))
hashed_thing = secure_val.split(',')[0]
salt = secure_val.split(',')[1]
user.salt = salt
user.put()
self.response.set_cookie("user_id",str(user_id) + '|' + hashed_thing)
self.redirect('/welcome', code=302)
return form1
示例10: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def post(self):
#get all the parameters
username = self.request.get("username")
password = self.request.get("password")
verifypw = self.request.get("verify")
email = self.request.get("email")
#process all the possible error
error_username = self.check_username(username)
error_password = self.check_password(password)
error_verifypw = self.check_verifypw(password, verifypw)
error_email = self.check_email(email)
#print out the error
if error_username:
self.render_front(error_username=error_username)
elif error_password:
self.render_front(username = username, error_password = error_password)
elif error_verifypw:
self.render_front(username = username, password= password, error_verifypw = error_verifypw)
elif error_email:
self.render_front(username=username, password = password, verifypw = verifypw,
error_email = error_email)
else:
#hash the password
password = util.make_pw_hash(password)
#everything is right on its way
if email:
user = User(username = username, password = password, email= email)
else:
user= User(username = username, password = password)
#here should be some technique to prevent collision
user.put()
user_id = str(user.key().id())
cookie = util.make_secure_val(user_id)
self.response.headers.add_header('Set-Cookie','user_id=%s'%cookie)
#redirect to the HomePage
self.redirect("/")
示例11: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def post(self):
user_name = self.request.get('username')
user_password = self.request.get('password')
user_verify = self.request.get('verify')
user_email = self.request.get('email')
error_username = ''
error_password = ''
error_verify = ''
error_email = ''
# verufy all parameters
if not(valid_username(user_name)):
error_username = 'invalid username'
user_name = ''
if not(valid_password(user_password)):
error_password = 'invalid password'
user_password = ''
user_verify = ''
elif not(user_password == user_verify):
error_verify = 'passwords not identical'
user_password = ''
user_verify = ''
if user_email and not(valid_email(user_email)):
error_email = 'invalid email'
user_email = ''
if is_existing_username(user_name):
error_username = 'user already exist'
user_name = ''
if not(error_username or error_email or error_verify or
error_password):
# if no error, create new user account
u = User(username=user_name, password=make_pw_hash(
user_name, user_password), email=user_email)
u.put()
self.set_cookie('userId', make_secure_val(str(u.key().id())))
self.redirect("/")
else:
self.write_form(user_name, user_password,
user_verify, user_email, error_username,
error_password, error_verify, error_email)
示例12: get
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def get(self):
secret = int(self.request.get('secret'))
user = User(secret=secret)
user.put()
self.response.out.write(user.key().id())
示例13: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def post(self):
### Session verification code ###
session = get_current_session()
try:
if not session['key'] or session['key'] == '':
self.redirect('/?exception=NoSession')
else:
mainuser = User.get(session['key'])
template_values = {
'pagename': 'friendsinvite',
}
try:
emails = self.request.get('emails').lower().replace(' ','').split(',')
if len(emails) > 30:
self.redirect('/friends?exception=TooManyArguments')
else:
users = User.all().filter("email IN", emails)
alreadyuser = []
for user in users:
alreadyuser.append(str(user.key()))
emails.remove(user.email)
friendships = Friendship.all().filter("user =", session['key']).filter("friend =", str(user.key()))
for friendship in friendships:
alreadyuser.remove(str(friendship.friend))
for email in emails:
confirmcode = RandomString(64)
subject = mainuser.nick + ' invites you to Animo!'
body = """Hey!
You've been invited to subscribe and play Animo by your friend """ + mainuser.nick + """(""" + mainuser.fname + """ """ + mainuser.lname + """). Please follow the following link to register and play:
http://""" + APPID + """/register/invitation?referer=""" + session['key'] + """&email=""" + email + """&code=""" + confirmcode + """
Tom"""
message = sendmail(email, subject, body)
message.send()
newuser = User()
newuser.email = email
newuser.active = False
newuser.status = confirmcode
newuser.put()
friendship = Friendship()
friendship.user = session['key']
friendship.friend = str(newuser.key())
friendship.status = 0
friendship.put()
for key in alreadyuser:
user = User.get(key)
securitycode = SecurityCode()
url = 'https://' + APPID + '/notifications/add'
form_fields = {"key": key, "message": user.nick + " wants to be friends with you. Click to accept.", "url": "/friends/invite/confirm?key=" + key + "&friend=" + str(user.key()), "code": securitycode.get()}
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url=url,payload=form_data,method=urlfetch.POST,headers={'Content-Type': 'application/x-www-form-urlencoded'})
friendship = Friendship()
friendship.user = session['key']
friendship.friend = key
friendship.status = 0
friendship.put()
self.redirect('/friends')
except ValueError:
self.redirect('/?exception=WrongParameter')
except KeyError:
self.redirect('/?exception=NoSession')
示例14: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import key [as 别名]
def post(self):
if request.json:
params = request.json
elif request.form:
params = request.form
else:
return {'status':'error',
'description':'Request Failed!'}, 400
# Check Requirements <Email, Password>
if not 'email' in params:
return {'status':'error',
'description':'Email Address input error!'}, 400
elif not 'password' in params:
return {'status':'error',
'description':'Password Missing'}, 400
# Check email address is unique
if User.email_exists(params['email']):
return {'status':'error',
'description':'Already registered Email address'}, 400
# Make username based on email address when it was not submitted.
if not 'username' in params or params['username'] == "" or params['username'] == None:
username = params['email'].split('@')[0]
username = User.make_valid_username(username)
# username = User.make_unique_username(username)
else:
username = params['username']
if User.username_exists(username):
return {'status':'error',
'description':'Username already exists.'}, 400
# Check User Birthday
if not 'birthday' in params or params['birthday']=="":
birthday = None
else:
birthday = params['birthday']
u = User(email=params['email'],
username=username,
fb_id=None,
birthday=birthday)
# Password Hashing
u.hash_password(params['password'])
u.key = md5('ACTIVATION'+str(int(random.random()*10000))).hexdigest()
# Database Insert/Commit
try:
db.session.add(u)
db.session.commit()
except:
return {'status':'error',
'description':'Something went wrong.'}, 500
send_awaiting_confirm_mail(u)
g.user = u
token = g.user.generate_auth_token()
return {'status':'success',
'data':{'user':{'id': g.user.id,
'username': g.user.username,
'email': g.user.email,
'birthday': g.user.birthday,
'confirmed_at':g.user.confirmed_at.strftime("%Y-%m-%d %H:%M:%S") if g.user.confirmed_at else None},
'token': token.decode('ascii')}}, 201