本文整理汇总了Python中models.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test
def test(loop):
logging.error('1111111')
yield from orm.create_pool(loop=loop,user='pyblog_data',password='pyblog_data',db='pyblog')
logging.error('2222222')
u=User(name='Test',email='[email protected]',passwd='1234567890',image='blank')
logging.error('333333')
yield from u.save()
示例2: get_user_ranking
def get_user_ranking(self, request):
"""Inefficient way to find ranking, for the user request
find the user and then compare win ratio with other users
if win ratio is equal, compare the number of losses"""
user = User.query(User.name == request.user_name).get()
if not user:
raise endpoints.NotFoundException(
'A User with the name {} does not exist!'.format(request.user_name))
users = User.query(User.name != request.user_name)
losses = user.losses
wins = user.wins
win_ratio = user.win_ratio
ranking = 0
total_users = 1
for other_user in users:
total_users = total_users + 1
if other_user.win_ratio < win_ratio:
ranking = ranking - 1
elif other_user.win_ratio == win_ratio:
if other_user.losses >= losses:
ranking = ranking - 1
ranking = total_users + ranking
#Create a ranking message
msg = "User {} Ranking {} Win Ratio {}".format(user.name, ranking, win_ratio)
return StringMessage(message = msg)
示例3: after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash('Invalid login. Please try again.')
redirect(url_for('login'))
user = User.query.filter_by(email = resp.email).first()
if user is None:
nickname = resp.nickname
if nickname is None or nickname == "":
nickname = resp.email.split('@')[0]
nickname = User.make_unique_nickname(nickname)
user = User(nickname = nickname, email = resp.email, role = ROLE_USER)
models.session.add(user)
models.session.commit()
models.session.add(user.follow(user))
models.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('demo'))
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('demo'))
示例4: add_user
def add_user():
mobile = request.form.get('mobile')
username = request.form.get('username')
password = request.form.get('password')
u = User({'mobile': mobile, 'username': username,
'password': password})
u.upsert()
i = 0
lnames = []
while True:
login_name = request.form.get('accounts[{}][login_name]'.format(i))
login_password = request.form.get(
'accounts[{}][login_password]'.format(i))
if login_name and login_password:
a = Account({'user_id': u._id,
'login_name': login_name,
'login_password': login_password})
a.upsert()
lnames.append(login_name)
i += 1
else:
break
Account.delete_many({'user_id': u._id,
'login_name': {'$nin': lnames}})
return jsonify(status=200)
示例5: api_get_users
def api_get_users():
total = User.count_all()
page = Page(total, _get_page_index())
users = User.find_by("order by created_at desc limit ?,?", page.offset, page.limit)
for u in users:
u.password = "******"
return dict(users=users, page=page)
示例6: session_from_facebook
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"
示例7: __call__
def __call__(self, form, field):
try:
User.get(User.email == field.data)
except Exception:
pass
else:
raise ValidationError('User with this email already exists')
示例8: chat
def chat():
# Require login
if 'username' not in session:
return redirect('/login/')
# Get chat buddy
name_them = request.args.get('user', None)
user_them = None
if name_them:
try:
user_them = User.get(User.username == name_them)
except:
pass
# Bad user - add error
if not user_them:
if name_them:
errors = ["Could not find user %s." % name_them]
else:
errors = ["Please specify a user to chat with."]
return render_template('chat.html', data={'errors': errors});
# Chat avatars
user_you = User.get(User.username == session['username'])
return render_template('chat.html', data={'yourPic': user_you.imageUrl, 'theirPic': user_you.imageUrl, 'otherUsername': name_them, 'myLanguage': user_you.language })
示例9: get
def get(self, boker_id):
boker = Boker.get_by_id(int(boker_id))
if boker:
deferred.defer(update_num_view, str(boker.key()))
# Check post type, Video or Photo
if boker.video_id and boker.video_source:
self.template = 'video.html'
if self.current_user is not None:
user = User.get_by_key_name(self.current_user['id'])
can_like = not Like.already_like(user, boker)
else:
can_like = False
else:
active_contest = Contest.active_contest()
if active_contest:
is_nominee = Contest.is_nominee(boker)
if self.current_user is not None:
user = User.get_by_key_name(self.current_user['id'])
can_vote = not Vote.already_vote(user)
can_like = not Like.already_like(user, boker)
else:
can_vote = False
can_like = False
querystring = self.request.GET
return self.render_response(self.template, locals())
else:
self.abort(404)
示例10: add_interests
def add_interests(user_id, interests):
logger.warning('add_interests user_id:%s interests:%s' % (user_id, str(interests)))
user = User.get_by_id(user_id)
for interest in interests:
if not interest:
continue
if interest not in user.get('interests', []):
User.push_user_field(user_id, 'interests', interest)
network = user.get('network')
interest = interest.strip('#').lower()
interest_data = Interest.get_by_name_network(interest, network)
int_col = get_interest_collection()
if not interest_data:
#Add a new one
interest_data = {
'name' : interest,
'num_followers' : 1,
'followers' : [user_id],
'network' : network,
'created' : datetime.datetime.now(),
'creator' : user_id
}
user_id = int_col.insert(interest_data)
else:
#Update existing
# push={}
# updates = {}
followers = interest_data.get('followers')
if user_id not in followers:
updates = {"$push" : {'followers' : user_id}, "$set" : { "num_followers" : len(followers) + 1 }}
int_col.update({"name" : interest}, updates)
示例11: create_new_user_activation
def create_new_user_activation(user_id):
"""
Called when a new user is added to system, sets up activation and emails link to user
Not part of tasks.new_user as that's notification based and will probably be refactored into a separate file soon
"""
logger.warning('Starting user activation process for %s' % str(user_id))
user = User.objects.get(_id = user_id)
random_phrase = activation_phrases[randint(0, len(activation_phrases)-1)]
#Generate random user activation hash
activation_hash = User.create_activation_hash(user._id, randint(0,1000))
User.set_user_field(user_id, 'activation_hash', activation_hash)
if user.email in settings.SKIP_VALIDATION_ADDRESSES:
user.activated = True
User.set_user_field(user_id, 'activated', True)
return "Email validation skipped for %s" % user._id
url = 'http://keen.to/activate-%s-%s' % (random_phrase, activation_hash)
name = user.first_name
if not name:
name = user.name
logger.warning('Sending email to %s' % str(user_id))
send_activation(name, user.email, url)
logger.warning('Email sent to %s' % str(user_id))
return "Email sent to %s" % user._id
示例12: after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash('Invalid login. Please try again.')
return redirect(url_for('login'))
user = User.query.filter_by(email=resp.email).first()
if user is None:
nickname = resp.nickname
if nickname is None or nickname == "":
nickname = resp.email.split('@')[0]
nickname = User.make_unique_nickname(nickname)
user = User(nickname=nickname, email=resp.email, role=ROLE_USER)
db.session.add(user)
db.session.commit()
# make the user follow him/herself
db.session.add(user.follow(user))
db.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember=remember_me)
return redirect(url_for('user', nickname=user.nickname))
示例13: sign_up
def sign_up():
_name = request.form['inputName']
_user_name = request.form['inputUserName']
_password = request.form['inputPassword']
username_list = g.sql_session.query(User.username).all()
if (_user_name,) not in username_list:
user = User()
user.name = _name
user.username = _user_name
user.password = generate_password_hash(_password)
user.type = 1
g.sql_session.add(user)
try:
g.sql_session.commit()
except Exception as e:
flash(str(e))
g.sql_session.rollback()
return redirect(url_for('.show_sign_up'))
session['user'] = _user_name
session['name'] = _name
session['type'] = user.type
return redirect(url_for('.user_home'))
else:
flash("The duplicated username")
return redirect(url_for('.show_sign_up'))
示例14: new_user
def new_user():
u = User()
u.from_json(request.json)
print request.json
db.session.add(u)
db.session.commit()
return jsonify({})
示例15: after_login
def after_login(resp):
if resp.identity_url is None or resp.identity_url == "":
flash(_('Invalid login. Please try again'))
return redirect(url_for('login'))
user = User.query.filter_by(identity_url = resp.identity_url).first()
if user is None:
nickname = resp.nickname
email = resp.email
if nickname is None or nickname == "":
if email is None or email == "":
nickname = resp.identity_url.strip("/").split("/")[-1]
else:
nickname = resp.email.split('@')[0]
nickname = User.make_unique_nickname(nickname)
user = User(identity_url = resp.identity_url, nickname = nickname, email = resp.email, role = ROLE_USER)
db.session.add(user)
db.session.commit()
# make the user follow him/herself
db.session.add(user.follow(user))
db.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('index'))