本文整理汇总了Python中www.models.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_expired_confirmation_token
def test_expired_confirmation_token(self):
u = User(password_hash='cat')
db.session.add(u)
db.session.commit()
token = u.generate_confirmation_token(1)
time.sleep(2)
self.assertFalse(u.confirm(token))
示例2: api_register_user
def api_register_user(*, email, name, passwd):
#判断name是否为空:
if not name or not name.strip():
raise APIValueError('name')
#判断email是否为空及是否满足email格式:
if not email or not _RE_EMAIL.match(email):
raise APIValueError('email')
#判断password首付为空及是否满足password格式:
if not passwd or not _RE_SHA1.match(passwd):
raise APIValueError('passwd')
#数据中查询对应的email信息:
users = yield from User.findAll('email=?', [email])
#判断查询结果是否存在,若存在则返回异常提示邮件已存在:
if len(users) > 0:
raise APIError('register:failed', 'email', 'Email is already in use.')
#生成唯一ID:
uid = next_id()
#重构唯一ID和password成新的字符串:
sha1_passwd = '%s:%s' % (uid, passwd)
#构建用户对象信息:
#hashlib.sha1().hexdigest():取得SHA1哈希摘要算法的摘要值。
user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='http://www(first).gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
#将用户信息存储到数据库:
yield from user.save()
# make session cookie:
#构造session cookie信息:
r = web.Response()
#aiohttp.web.StreamResponse().set_cookie():设置cookie的方法。
r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) #max_age:定义cookie的有效期(秒);
user.passwd = '******'
r.content_type = 'application/json'
#以json格式序列化响应信息; ensure_ascii默认为True,非ASCII字符也进行转义。如果为False,这些字符将保持原样。
r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
return r
示例3: api_register_user
def api_register_user(*, email, name, passwd): # https://www.python.org/dev/peps/pep-3102/
if not name or not name.strip():
raise APIValueError('name')
if not email or not _RE_EMAIL.match(email):
raise APIValueError('email')
if not passwd or not _RE_SHA1.match(passwd):
raise APIValueError('passwd')
users = yield from User.findAll('email=?', [email])
if len(users) > 0:
raise APIError('register:failed', 'email', 'email already in use')
uid = next_id()
sha1_passwd = '%s:%s' % (uid, passwd) # get SHA1 for uid+passwd
user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(),
image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
yield from user.save()
# make session cookie:
r = web.Response()
r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
user.passwd = '******'
r.content_type = 'application/json'
r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
return r
示例4: test_invalid_confirmation_token
def test_invalid_confirmation_token(self):
u1 = User(password_hash='cat')
u2 = User(password_hash='dog')
db.session.add(u1)
db.session.add(u2)
db.session.commit()
token = u.generate_confirmation_token()
self.assertFalse(u2.confirm(token))
示例5: test_save
def test_save():
loop = asyncio.get_event_loop()
loop.run_until_complete(www.orm.create_pool(loop, user='root', password='root', db='awesome'))
u = User(name='Test', email='[email protected]', passwd='1234567890', image='about:blank')
loop.run_until_complete(u.save())
loop.stop()
示例6: edit_profile
def edit_profile():
here = url_for('edit_profile')
next_url = request.args.get('next_url', here) # This is circular
user = flask.g.user
Audit(flask.g, '', '/user/profile', '', result='').write()
form=dict()
form['password']=''
form['password2']=''
if request.method == 'POST':
valid = True
if request.form['name']:
user.name = request.form['name']
else:
valid = False
flash(u'Error: you have to provide a contact name', 'error')
if request.form['email']:
user.email = request.form['email']
else:
valid = False
flash(u'Error: you have to provide a contact email', 'error')
if request.form['company']:
user.set_data('company', request.form['company'])
else:
flash(u'Please provide a company name', 'warning')
if request.form['phone']:
user.set_data('phone', request.form['phone'])
else:
flash(u'Please provide a phone number', 'warning')
if request.form['mobile']:
user.set_data('mobile', request.form['mobile'])
# Optional
if valid:
User.commit()
if next_url == here: # only flash if we're coming back here...
Audit(flask.g, '', '/user/profile', '', result='Update Success').write()
flash(u'Profile successfully updated', 'success')
return redirect(next_url)
form['name']=user.name
form['email']=user.email
form['company']=user.get_data('company', '')
form['phone'] =user.get_data('phone', '')
form['mobile'] =user.get_data('mobile', '')
return render_template('user.profile.haml', form=form)
示例7: post
def post(self):
t = db.select("select * from users where email=?", request.form['email'])
if t:
raise APIValueError(data=request.form['email'], message="email has already been registered")
user = User(
email=request.form['email'],
password=request.form['password'],
name=request.form['username'],
image=request.form['image'] if request.form.has_key('image') else "about:blank",
admin=1,
)
user.insert()
示例8: api_get_users
def api_get_users(*, page='1'):
#获取页面索引,默认为1:
page_index = get_page_index(page)
#查询数据库中User表中用户总数:
num = yield from User.findNumber('count(id)')
p = Page(num, page_index)
if num == 0:
return dict(page=p, users=())
#查询数据库中User表中对应分页的用户结果;(limit为mysql的分页查询条件)
users = yield from User.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
for u in users:
u.passwd = '******'
return dict(page=p, users=users)
示例9: cookie2user
def cookie2user(cookie_str):
'''
Parse cookie and load user if cookie is valid.
'''
#若cookie信息为空在返回None:
if not cookie_str:
return None
try:
#将cookie信息按照‘-’进行切片处理:
L = cookie_str.split('-')
#若切片数组长度不为3,则返回None:
if len(L) != 3:
return None
#分别取到uid,cookie有效期,用户信息摘要值:
uid, expires, sha1 = L
#若cookie有效期小于当前时间,则返回None:
if int(expires) < time.time():
return None
#根据uid在数据库中查询对应的用户信息:
user = yield from User.find(uid)
#查询结果为空,则返回None:
if user is None:
return None
#重组用户信息并计算SHA1摘要值,同cookie中的用户信息摘要值比对:
s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)
if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
#打印(无效SHA1摘要值)日志:
logging.info('invalid sha1')
return None
user.passwd = '******'
return user
except Exception as e:
logging.exception(e)
return None
示例10: login
def login():
next_url = request.args.get('next_url', '/')
# if we are already logged in, go back to were we came from
if flask.g.user.id is not None:
Audit(flask.g, '', '/user/login', '', result='Already logged in').write()
return redirect(next_url)
if request.method == 'POST':
email = request.form['email']
user = User.get_if_password_valid(flask.g.site.tag, email, request.form['password'])
print "Trying to Login : %s - %s" % (flask.g.site.tag, email, )
if user:
print "Trying to Login - SUCCESS"
flask.g.user = user # Fix up g, so that Audit works
Audit(flask.g, '', '/user/login', email, result='Success').write()
session['userid']=user.id
return redirect(next_url)
else:
print "Trying to Login - FAILURE"
Audit(flask.g, '', '/user/login', email, result='Failure').write()
flash("Email and password don't match", 'error')
Audit(flask.g, '', '/user/login', '', result='').write()
# Previous request.form rolls over to next iteration automatically
return render_template('user.login.haml', next_url=next_url)
示例11: authenticate
def authenticate(*, email, passwd):
#判断email(用户名)及password是否为空;为空则抛出异常:
if not email:
raise APIValueError('email', 'Invalid email.')
if not passwd:
raise APIValueError('passwd', 'Invalid password.')
#数据中查询对应的email信息:
users = yield from User.findAll('email=?', [email])
#判断查询结果是否存在,若不存在则抛出异常:
if len(users) == 0:
raise APIValueError('email', 'Email not exist.')
#获取查询结果集的第一条数据:
user = users[0]
# check passwd:
#调用摘要算法SHA1组装登陆信息;计算摘要值同数据库中的信息进行比配:
sha1 = hashlib.sha1()
sha1.update(user.id.encode('utf-8'))
sha1.update(b':')
sha1.update(passwd.encode('utf-8'))
if user.passwd != sha1.hexdigest():
#登陆信息不匹配则跑出异常:
raise APIValueError('passwd', 'Invalid password.')
# authenticate ok, set cookie:
#构造session cookie信息:
r = web.Response()
#aiohttp.web.StreamResponse().set_cookie():设置cookie的方法。
r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
user.passwd = '******'
r.content_type = 'application/json'
#以json格式序列化响应信息; ensure_ascii默认为True,非ASCII字符也进行转义。如果为False,这些字符将保持原样。
r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
return r
示例12: before_request
def before_request():
#print "REQUEST_HOST='%s'" % (request.host,)
host_name = request.host.lower()
# if ':' in host_name: host_name = host_name[:host_name.find(':')]
if host_name in Site.domain_to_tag:
# This is for DNS resolved versions
site_tag = Site.domain_to_tag[host_name]
else:
# This is for subdomains of the main site : Just strip off the subdomain
site_tag = host_name[:host_name.find('.')].lower()
#print "REQUEST_HOST_TAG='%s'" % (site_tag,)
flask.g.site = Site.query().filter_by(tag=site_tag).first()
if flask.g.site is None:
print "FAILED TO FIND SITE_TAG : DEFAULTING"
# Default if all else fails
flask.g.site = Site.query().filter_by(tag=Site.tag_main).first()
if 'userid' in session:
flask.g.user = User.get(session['userid'])
else:
flask.g.user = User(flask.g.site.tag, '[email protected]', 'Not logged in') # Creates a user with id=None
#session.pop('hash')
if 'hash' not in session:
session['hash'] = ''.join([ '%02x' % ord(ch) for ch in urandom(4) ])
print "Created session hash '%s'" % (session['hash'],)
flask.g.hash = session['hash']
flask.g.ip = request.remote_addr
示例13: register
def register():
form = request.form
name = form.get('name')
user = User.get(name=name)
password = form.get('password')
if request.method == 'GET':
return render('register.html')
elif user is not None:
error = 'UserName Is Registered'
return render('register.html', error=error)
password = md5_hash(password, salt=name)
user = User(name=name, password=password)
user.insert()
return log_the_user_in()
示例14: do_signup
def do_signup(sender, interval):
logger("Entering do_signup (%s)" % (sender))
try:
try:
user = User(phonenumber=sender,interval=int(interval))
except (ValueError, IndexError):
user = User(phonenumber=sender)
user.save()
except:
logger("user already exists! %s" % sender)
#TODO send a message back? fail silently?
#raise Exception, "User '%s' already exists" % sender
raise
return
signup_email = "Thank you for signing up! How to play: we will send you a message listing a definition and a choice of four words. You must choose the correct word corresponding to that definition. Respond with only the number of the word that you believe is correct. Text 'stats' to see how you're doing and 'quit' to leave WordiSMS."
SMS(user.phonenumber, signup_email).send()
logger("Exiting do_signup")
return
示例15: log_the_user_in
def log_the_user_in():
form = request.form
user = User.get(name=form['name'])
sign = md5_hash(user.id + user.password)
app.signed_cookie[user.name] = sign
form['sign'] = sign
del form['password']
request.set_cookie(form)
return redirect('/hello')