本文整理匯總了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')