本文整理汇总了Python中db.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: join
def join():
if request.method == 'GET':
return render_template('join.html')
username = request.form.get('username')
password = request.form.get('password')
email = request.form.get('email')
if not username:
flash('Please input username')
return redirect(url_for('join'))
elif not password:
flash('Please input password')
return redirect(url_for('join'))
elif not email:
flash('Please input email')
return redirect(url_for('join'))
try:
# use the .get() method to quickly see if a user with that name exists
user = User.get(username=username)
flash('That username is already taken')
except User.DoesNotExist:
# if not, create the user and store the form data on the new model
user = User.create(username=username,
password=md5(password).hexdigest(),
email=email,join_date=datetime.datetime.now())
# mark the user as being 'authenticated' by setting the session vars
auth_user(user)
return redirect(url_for('homepage'))
示例2: create_user
def create_user(self, name, team):
newbie = User(name=name, team=team, loyalists=100, leader=True)
self.sess.add(newbie)
cap = Region.capital_for(team, self.sess)
newbie.region = cap
self.sess.commit()
return newbie
示例3: r_success
def r_success():
nickname = request.form["nickname"]
email = request.form["email"]
passwd = request.form["passwd"]
repasswd = request.form["repasswd"]
if passwd != repasswd:
return "비밀번호가 다릅니다."
if len(passwd) < 8:
return """
<script>
alert("비밀번호를 8자리 이상 적어주세요.");
history.back();
</script>
"""
if not len(email) or not len(nickname):
return """
<script>
alert("모두 채워 주세요.");
history.back();
</script>
"""
if is_already_registered(email, nickname) == 2:
return "메일"
if is_already_registered(email, nickname) == 3:
return "별명"
new = User()
new.nickname = nickname
new.email = email
new.pw = passwd
db.session.add(new)
db.session.commit()
return render_template("index.html")
示例4: get
def get(self, name):
user = User.find_one({"user_domain": name})
user.user_say = markdown2.markdown(user.user_say)
user.user_jointime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.user_jointime))
likenum = User.find({"user_id": user._id}).count()
user.gravatar = get_avatar(user.user_email, 100)
self.render("userhome.html", user=user, likenum=likenum)
示例5: index
def index(response):
form_id = response.get_field('form_id', 'front')
if form_id == 'front':
response.write(LOGIN_HTML)
elif form_id == 'login':
user = response.get_field('user')
try:
user = User.get(user=user)
set_user(response, user)
response.redirect('/profile')
except DoesNotExistError:
response.redirect('/')
elif form_id == 'signup':
user = response.get_field('user')
passwd1 = response.get_field('passwd1')
#passwd2 = response.get_field('passwd2')
first = response.get_field('first')
last = response.get_field('last')
dob = response.get_field('dob')
logger.info('adding user {} ({} {}) with passwd {}'.format(user, first, last, passwd1))
if user and first and last and passwd1:
try:
user = User.add(user=user, passwd=passwd1, first=first, last=last, dob=dob)
set_user(response, user)
response.redirect('/profile')
except IntegrityError:
response.write(LOGIN_HTML)
else:
response.write(LOGIN_HTML)
示例6: get
def get(self, node):
page = self.get_argument("page", 1)
share_res = Share.find({'sharetype': node}).sort(
'_id', DESCENDING).limit(10).skip((int(page) - 1) * 10)
pagesum = (share_res.count() + 9) / 10
shares = []
for share in share_res:
user = User.by_sid(share.user_id)
share.name = user.user_name
share.published = time.strftime(
'%Y-%m-%d %H:%M:%S', time.localtime(share.published))
share.domain = user.user_domain
share.markdown = filter_tags(
markdown2.markdown(share.markdown))[:100]
share.gravatar = get_avatar(user.user_email, 16)
shares.append(share)
members = User.find().sort('_id', DESCENDING).limit(20)
members_dict = []
for member in members:
member.gravatar = get_avatar(member.user_email, 25)
members_dict.append(member)
node_about = options.node_about[node]
self.render(
"node.html", shares=shares, members=members_dict,
pagesum=pagesum, page=page, node=node, node_about=node_about)
示例7: add_user
def add_user(self, user: User):
if user.hash is None:
raise ValueError("User doesn't have a hash.")
if user.hash == owner_hash:
for perm in all_perms.keys():
user.add_permission(perm)
self.session.add(user)
示例8: recruit_from_comment
def recruit_from_comment(self, comment):
session = self.session
if not comment.author: # Deleted comments don't have an author
return
name = comment.author.name.lower()
if name == self.config.username.lower():
return
# Is this author already one of us?
found = session.query(User).filter_by(
name=name).first()
if not found:
# Getting the author ID triggers a lookup on the userpage. In the
# case of banned users, this will 404. @failable would normally
# catch that just fine, but I want to check it here so that in the
# future, I can do things like e.g. add to an 'ignored' list and
# save myself the lookup
try:
author_id = comment.author.id
except NotFound:
logging.warn("Ignored banned user %s" % name)
return
team = 0
assignment = self.config['game']['assignment']
if assignment == 'uid':
base10_id = base36decode(author_id)
team = base10_id % 2
elif assignment == "random":
team = random.randint(0, 1)
is_leader = name in self.config["game"]["leaders"]
newbie = User(name=name,
team=team,
loyalists=100,
leader=is_leader)
session.add(newbie)
cap = Region.capital_for(newbie.team, session)
if not cap:
logging.fatal("Could not find capital for %d" %
newbie.team)
newbie.region = cap
session.commit()
logging.info("Created combatant %s", newbie)
reply = ("Welcome to Chroma! You are now a %s "
"in the %s army, commanding a force of loyalists "
"%d people strong. You are currently encamped at %s"
) % (newbie.rank,
num_to_team(newbie.team, self.config),
newbie.loyalists,
cap.markdown())
comment.reply(reply)
else:
#logging.info("Already registered %s", comment.author.name)
pass
示例9: test_user_change_info
def test_user_change_info(self):
self.create_test_data()
query = User().update(authentication_level=2, email='[email protected]',
phone_number='1231231234', name='new_name', title='new_title').where(User.pk == self._user.pk)
query.execute()
pk = self._user.pk
self._user_2 = User().get(pk=pk)
self.assertEqual(self._user_2.authentication_level, 2)
self.assertEqual(self._user_2.phone_number, '1231231234')
self.assertEqual(self._user_2.name, 'new_name')
self.assertEqual(self._user_2.title, 'new_title')
示例10: before_request
def before_request():
g.user = None
try:
if 'id' in session:
g.user = User.get(User.id == session['id'])
except User.DoesNotExist:
g.user = None
if "test" in request.headers:
g.user = User.get(User.id == request.headers.get("test"))
示例11: post
def post(self):
oldpass = self.get_argument('oldpass', '')
newpass = self.get_argument('newpass', '')
newpass = hashlib.md5(newpass).hexdigest()
user = User.by_sid(self.current_user['user_id'])
if user.user_pass == hashlib.md5(oldpass).hexdigest():
user = User.by_sid(self.current_user['user_id'])
user['user_pass'] = newpass
user.save()
self.redirect('/setting')
else:
self.redirect('/setting') # self.write('Wrong password')
示例12: create_test_data
def create_test_data(self):
self._company = Company().create(name='test_name', phone_number='1223456789', address='123 test road, testville test')
self._user = User().create(name='test_name', email='[email protected]', title='the_boss',
secret_question='what is the answer?',
phone_number='1234567891', authentication_level=3, company=self._company.pk)
self._user.set_password('test_password')
self._user.set_secret_answer('42')
self._admin = User().create(name='admin', email='[email protected]', title='the_boss',
secret_question='what is the answer?',
phone_number='1234567891', authentication_level=1, company=self._company.pk)
self._admin.set_password('test_password')
self._admin.set_secret_answer('42')
示例13: get
def get(self, name):
user = User.find_one({'user_domain': name})
user.user_jointime = time.strftime(
'%Y-%m-%d %H:%M:%S', time.localtime(user.user_jointime))
likes = User.find({'user_id': user._id})
likenum = likes.count()
for like in likes:
share = Share.by_id(like.share_id)
like.title = share.title
like.id = share.id
like.type = share.sharetype
user.gravatar = get_avatar(user.user_email, 100)
self.render("userlike.html", user=user, likenum=likenum, likes=likes)
示例14: create
def create():
new = User()
new.userId = request.form['id']
new.userPw = request.form['pw']
new.nickname = request.form['nickname']
if new.userId and new.userPw and new.nickname :
db.session.add(new)
try:
db.session.commit()
except IntegrityError:
return "이미 있습니다."
return "%s (%s %s)" % (new.nickname, new.userId, new.userPw)
else:
return "내용을 전부 채워야합니다"
示例15: on_post
def on_post(self, req, resp):
doc = req.context['doc']
users=Session.query(User).all()
unique=True
for user in users:
if doc['email'] == user.email:
unique=False
if unique:
user = User(name=doc['name'], email=doc['email'].lower(), signedin=False,registerTime=datetime.datetime.today())
print(datetime.datetime.today())
user.salt = bcrypt.gensalt()
user.pw_hash = bcrypt.hashpw(doc['password'].encode('utf-8'), user.salt)
s=smtplib.SMTP_SSL('smtp.gmail.com',465)
s.ehlo()
s.login('[email protected]','[email protected]')
code=randint(1000000,10000000)
user.code=code
msg=MIMEText('Hi '+user.name+', your verification URL is: '+'http://192.168.1.127:8000/confirmation/'+str(code))
msg['From']='[email protected]'
msg['To']=user.email
msg['Subject']='PhoenixNow Account Confirmation'
s.send_message(msg)
s.close()
Session.add(user)
Session.flush()
Session.commit()
req.context['user'] = user.id
req.context['result'] = {"result": "success", "action": "register"}
else:
user=get_user(req,resp)
td=datetime.timedelta(minutes=30)
if datetime.datetime.today()-td<user.registerTime or user.emailVerified==True:
description = "User was already made"
title = "User creation conflict"
raise falcon.HTTPConflict(title=title, description=description)
else:
Session.delete(user)
Session.flush()
user = User(name=doc['name'], email=doc['email'], signedin=False,registerTime=datetime.datetime.today())
print(datetime.datetime.today())
user.salt = bcrypt.gensalt()
user.pw_hash = bcrypt.hashpw(doc['password'].encode('utf-8'), user.salt)
s=smtplib.SMTP_SSL('smtp.gmail.com',465)
s.ehlo()
s.login('[email protected]','[email protected]')
code=randint(1000000,10000000)
user.code=code
msg=MIMEText('Hi '+user.name+', your verification URL is: '+'http://192.168.1.127:8000/confirmation/'+str(code))
msg['From']='[email protected]'
msg['To']=user.email
msg['Subject']='PhoenixNow Account Confirmation'
s.send_message(msg)
s.close()
Session.add(user)
Session.flush()
Session.commit()
req.context['user'] = user.id
req.context['result'] = {"result": "success", "action": "register"}