本文整理汇总了Python中models.User.put方法的典型用法代码示例。如果您正苦于以下问题:Python User.put方法的具体用法?Python User.put怎么用?Python User.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.put方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def post(self):
format = self.request.get('format', 'json').lower()
id = self.request.get('level_id', None)
if id is None:
res = {"response": {"error": "no level id with submission"}}
else:
level = Level.get_by_id(long(id))
user_name = self.request.get('user')
user = User.all().filter('name =', user_name).get()
if user is None:
user = User(name = user_name)
user.put()
score = self.request.get('score', 0)
words_found = self.request.get('words_found').split(",")
submission = Submission()
submission.user = user
submission.level = level
submission.score = score
submission.words_found = words_found
submission.time = datetime.datetime.now()
submission.put()
res = {"response": {"status" : "OK"}}
if format == "json":
self.response.out.write(simplejson.dumps(res))
elif format == "xml":
self.response.out.write(dict2xml(res).to_string())
示例2: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def post(self, **kwargs):
role = self.request.get('role', default_value=None)
tenantKey = self.request.get('tenant_key', default_value=None)
unitKey = self.request.get('unit_key', default_value=None)
locationKey = self.request.get('location_key', default_value = None)
username = self.request.get('username', default_value=None)
password = self.request.get('password', default_value=None)
if not all([role,locationKey,username,password]):
self.abort(400)
if role == 'tenant' and not tenantKey:
self.abort(400)
key = None
if role == 'tenant':
key = ndb.Key(Location, int(locationKey),
Unit, int(unitKey),
Tenant, int(tenantKey))
elif role == 'manager':
key = ndb.Key(Location, int(locationKey))
else:
self.response.status = 400
self.response.status_message = 'Role must be either tenant or manager.'
user = User()
try:
user.role = role
user.related_key = key
user.username = username
user.password = password
user.put()
except Exception as msg:
self.abort(500, details=msg)
return
self.response.write(json.dumps(user.to_dict()))
示例3: get_or_create_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def get_or_create_user():
user = users.get_current_user()
u = User.get_user(user)
if not u and users.is_current_user_admin():
u = User(user=user, role='admin')
u.put()
return u
示例4: get
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def get(self):
org = self.request.get('organization')
event = self.request.get('event')
datetime = self.request.get('datetime')
name = self.request.get('name')
email = self.request.get('email')
user_key_name = name+':'+email
userkey = db.Key.from_path('User', user_key_name)
event_key_name = '.'.join([org, event, datetime])
logging.warning(event_key_name)
eventkey = db.Key.from_path('Event', event_key_name)
try:
user = User(key=userkey,
name=name,
email=email,
event=eventkey)
user.put()
except db.Error:
resultdata = {'status': 'error'}
logging.error(traceback.format_exc())
else:
resultdata = {'status': 'success'}
resultjson = json.dumps(resultdata)
self.response.out.write(resultjson)
示例5: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def post(self):
name = self.request.get("name")
pwd = self.request.get("pwd")
verifypwd = self.request.get("verifypwd")
email = self.request.get("email")
if pwd != verifypwd or name == "":
error = True
self.render_Html(name, email, error)
Uname = self.get_query("User")
for i in Uname:
if name in i.userName:
error = True
self.render_Html(name, email, error)
break
else:
pwdHash = make_hash(pwd)
user = User(userName=name, email=email, passHash=pwdHash)
self.response.headers.add_header('Set-Cookie',
'{}={}; Path=/'
.format('username',
make_hash(name)))
user.put()
self.make_cookie(name, make_hash(name))
self.redirect("/welcome?username={}".format(name))
示例6: get
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def get(self):
user = users.get_current_user()
if(user):
userQuery = User.query(User.userid == user.user_id())
userEntity = None
for thisUser in userQuery:
userEntity = thisUser
formCheck(self, user)
missedLectureCheck(user)
if userEntity.email is None:
userEntity.email = user.email()
userEntity.put()
if userEntity is None:
userEntity = User(
userid=user.user_id(),
score=0,
streak=0,
count=0,
history=[],
email = user.email())
module1Query = Module.query(Module.code == 'GENG0013')
for module in module1Query:
for lecture in module.lectures:
userEntity.lectures.append(lecture)
module2Query = Module.query(Module.code == 'GENG0002')
for module in module2Query:
for lecture in module.lectures:
userEntity.lectures.append(lecture)
challengeQuery = Challenge.query().order(Challenge.challengeid)
for challenge in challengeQuery:
userEntity.challenges.append(challenge)
userEntity.put()
self.redirect('/info')
completedChalls = []
for challenge in userEntity.challenges:
if challenge.complete:
completedChalls.append(challenge)
template_values = {
'username' : userEntity.username,
'logout' : users.create_logout_url(self.request.uri),
'score' : userEntity.score,
'count' : userEntity.count,
'streak' : userEntity.streak,
'completedChalls' : completedChalls
}
template = JINJA_ENVIRONMENT.get_template('/assets/home.html')
self.response.write(template.render(template_values))
else:
self.redirect(users.create_login_url(self.request.uri))
示例7: create_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [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)
示例8: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def post(self):
email = self.request.get("email")
name = self.request.get("name")
password = self.request.get("password")
password2 = self.request.get("password2")
if '' in (email, name, password, password2):
self.redirect('/login?error=All+fields+are+required.')
else:
if password == password2:
if User.get_by_id(email) == None:
user = User(id=email,
email=email,
name=name,
password=encrypt(password),
verified=False,
vcode=encrypt(os.urandom(256))
)
user.put()
send_verification(name,email,user.vcode)
session = Session(self.request)
session.set(email)
self.redirect('/')
else:
self.redirect('/login?error=This+email+is+already+registered.')
else:
self.redirect('/login?error=Passwords+must+be+identical.')
示例9: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def current_user(self):
try:
"""Returns the active user, or None if the user has not logged in."""
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, self.get_config('facebook', 'app_id'), self.get_config('facebook', 'app_secret'))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = User.get_by_key_name(cookie["uid"])
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = User(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
email=profile["email"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
try:
name = user.name.split()
fname = name[0]
lname = name[len(name)-1]
deferred.defer(export_email_mailchimp,{'email':user.email,"fname":fname,"lname":lname})
except:
pass
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
except:
self._current_user = None
示例10: GET
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def GET(self):
web.header('Content-Type', 'application/json')
inputs = web.input()
# look for existing user by email
existingUser = User.GetByEmail(inputs.user_email)
if (existingUser):
return "User Exists"
else: # not existing, create new database record
newUser = User(
user_name = inputs.user_name,
user_email = inputs.user_email,
user_phone = inputs.user_phone,
address_street = inputs.address_street,
address_street2 = inputs.address_street2,
address_city = inputs.address_city,
address_state = inputs.address_state,
address_zipcode = inputs.address_zipcode
)
newUser.put()
return "Success"
示例11: create_user_account_if_possible
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def create_user_account_if_possible ():
# If the user account doesn't already exist.
user = UserManager.get_current_user_by_email_address()
# Check that the user's key matches the user_id from AppEngine and
# update it if necessary. This is because accounts created in the
# /users/ section won't have the AppEngine user id.
current_user_id = UserManager.get_current_user_id()
if user and user.key.id() != str(current_user_id):
# Remove the current user, because the key is immutable
user.key.delete()
# Either the user exists (and we just deleted the old entry
# in the datastore) or they don't but they're an admin. (For any other
# kind of user we would bail out.)
if user or UserManager.is_admin():
user = users.get_current_user()
new_user = User(
id=user.user_id(),
email=user.email(),
is_primary=(User.query().count() == 0)
)
new_user.put()
return new_user
示例12: POST
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def POST(self):
web.header('Content-Type', 'application/json')
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
userItem = simplejson.loads(web.data())
existingUser = User.GetByEmail(userItem['user_email'])
if (existingUser):
return '{"status": "Error - User Exists"}'
else: # not existing, create new database record
newUser = User(
user_name = userItem['user_name'],
user_email = userItem['user_email'],
user_phone = userItem['user_phone'],
address_street = userItem['address_street'],
address_street2 = userItem['address_street2'],
address_city = userItem['address_city'],
address_state = userItem['address_state'],
address_zipcode = userItem['address_zipcode']
)
newUser.put()
return '{"status": "Success"}'
示例13: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def post(self):
form = RegisterForm(self.request.POST)
if form.validate():
# Submit the query in the datastore
email = db.GqlQuery("SELECT * FROM User WHERE email='%s'"
% form.email.data)
username = db.GqlQuery("SELECT * FROM User WHERE username='%s'"
% form.username.data)
username, email = username.get(), email.get()
# if there is no record in the datastore with the provided data
# create a new user.
if email is None and username is None:
hashedPass = bcrypt.hashpw(form.passwd.data, bcrypt.gensalt(2))
newuser = User(name=form.name.data,
surname=form.surname.data,
email=form.email.data,
username=form.username.data,
password=hashedPass)
newuser.put()
# Create the session for the new user
self.session['username'] = form.username.data
self.redirect("/")
# todo: refactor the if to catch both mailError
# and usernameError at the same time.
elif email is not None:
self.render("register.html", form=form,
mailError="This Mail Is Already Registered",
username=self.session.get("username"))
elif username is not None:
self.render("register.html", form=form,
usernameError="This Username Is Taken :-(",
username=self.session.get("username"))
else:
self.render("register.html", form=form,
username=self.session.get("username"))
示例14: current_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def current_user(self):
if self.session.get("user"):
return self.session.get("user")
else:
cookie = facebook.get_user_from_cookie(self.request.cookies,
FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET)
if cookie:
user = User.get_by_key_name(cookie["uid"])
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = User(
key_name = str(profile["id"]),
id = str(profile["id"]),
name = profile["name"],
profile_url = profile["link"],
access_token = cookie["access_token"]
)
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self.session["user"] = dict(
name = user.name,
profile_url = user.profile_url,
id = user.id,
access_token = user.access_token
)
return self.session.get("user")
return None
示例15: authorize
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import put [as 别名]
def authorize():
error = request.args.get('error')
code = request.args.get('code')
state = request.args.get('state')
#TODO: Handle state here
if error:
flash(error, 'error')
#TODO: Handle error here
return redirect(url_for('home'))
if not code:
#TODO: No code received, something went wrong
return redirect(url_for('home'))
else:
reddit = get_reddit()
access_info = reddit.get_access_information(code)
praw_user = reddit.get_me()
user = User.get_by_id(praw_user.name)
if not user:
user = User(
id=praw_user.name,
username=praw_user.name,
created_reddit=datetime.fromtimestamp(praw_user.created)
)
user.access_token = access_info['access_token']
user.refresh_token = access_info['refresh_token']
user.put()
session['user'] = user.username
return redirect(url_for('home'))