本文整理汇总了Python中models.User.is_active方法的典型用法代码示例。如果您正苦于以下问题:Python User.is_active方法的具体用法?Python User.is_active怎么用?Python User.is_active使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.is_active方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def register(request):
context = {}
context["news"] = get_news_by_request(request)
user = User()
if request.method == 'POST':
form = UserCreateForm(request.POST, instance = user)
if form.is_valid():
pw = user.password
user.set_password(user.password)
user.theme_id=4
user.input_type_id=1
if not open_registration:
user.is_active = False
form.save()
ro = ReminderOffsets.objects.get(value=0)
user.reminder_offset.add(ro)
ro = ReminderOffsets.objects.get(value=2)
user.reminder_offset.add(ro)
if open_registration:
group = Group.objects.filter(name="BuLiTipp")[0]
user.groups.add(group)
user = authenticate(username=user.username, password=pw)
djlogin(request, user)
messages.success(request, "Benutzer erfolgreich angelegt! Tritt als nächstes einer Tippgemeinschaft bei!")
return HttpResponseRedirect(reverse("user", args=["tgchange"]))
else:
mail.send("BuLiTipp: User registriert", "[email protected]", "Bitte administriere den neuen User " + user.username+ " !")
messages.success(request, "Benutzer erfolgreich angelegt! Du kannst dich einloggen sobald der Administrator dich freigeschaltet hat.")
return HttpResponseRedirect(reverse("home"))
else:
form = UserCreateForm(instance=user)
context["form"] = form
return render(request, 'registration/register.html', context)
示例2: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def register():
form = RegistrationForm(csrf_enabled=False)
if request.method == 'POST' and form.validate():
user = User()
user.id = form.id.data
user.first_name = form.first_name.data
user.last_name = form.last_name.data
user.password = form.password.data
user.email = form.email.data
user.contact_no = form.contact_no.data
user.branch = form.branch.data
user.profile_type = request.form['profile_type']
profile_pic = request.files['profile_pic']
if profile_pic:
profile_pic_extension = ctrl.get_extension_of_file(profile_pic.filename)
user.profile_pic_extension = profile_pic_extension
file_op.save_profile_pic(profile_pic, user.id)
if user.profile_type != 'P':
ctrl.mkdir_p(os.path.join(app.config['SOLUTION_FILES_DEST'], user.id))
user.is_active = 'Y'
db_session = get_db_session()
insert_to_db(db_session, user)
return render_template('forms/registration_success.html')
return render_template('forms/register.html', form=form)
示例3: add_user_to_db
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def add_user_to_db(self, immutable_id, user_id, is_active):
user = User()
user.immutable_id = immutable_id
user.azure_user_id = user_id
user.is_active = is_active
user.created = datetime.datetime.now()
user.synced = datetime.datetime.now()
with session_scope() as session:
session.add(user)
示例4: login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def login():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
form = LoginForm()
if request.method == 'POST' and form.validate():
session['remember_me'] = form.remember_me.data
user = User(ident=form.username.data, password=form.password.data)
if user.is_active():
login_user(user, remember = session['remember_me'])
try:
os.stat(user.dl_dir)
except:
os.mkdir(user.dl_dir)
return redirect(url_for("index"))
return render_template("login.html", form=form)
示例5: create_or_login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def create_or_login(resp):
steam_id = long(resp.identity_url.replace("http://steamcommunity.com/openid/id/", ""))
account_id = int(steam_id & 0xFFFFFFFF)
_user = User.query.filter(User.id == int(account_id & 0xFFFFFFFF)).first()
if not _user:
_user = User(int(account_id & 0xFFFFFFFF), steam.user.profile(steam_id).persona or account_id)
db.session.add(_user)
db.session.commit()
login_attempt = login_user(_user)
if login_attempt is True:
flash(u"You are logged in as {}".format(_user.name), "success")
elif not _user.is_active():
flash(u"Cannot log you in as {}, your account has been disabled. If you believe this is in error, please contact {}.".format(_user.name, current_app.config["CONTACT_EMAIL"]), "danger")
else:
flash(u"Error logging you in as {}, please try again later.".format(_user.name), "danger")
return redirect(oid.get_next_url())
示例6: create_or_login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def create_or_login(resp):
"""
Handle a user after they have signed in with Steam.
If the user does not exist in our database, we will create an entry for them and attempt to log them in.
If the user already exists in our database, we will just attempt to log them in.
Will flash a message to the user according to their log in attempt:
- Successful: "Hi you're logged in"
- Failed, account inactive: "You're account has been disabled".
- Failed, account active: "Error on our end, try again later pls".
:param resp: Response from Steam's OpenID endpoint
:return: Redirect to the user's next-url.
"""
# Get the user's SteamID from the OpenID response.
steam_id = long(resp.identity_url.replace("http://steamcommunity.com/openid/id/", ""))
# Turn that SteamID into an account ID, and get the user with that id.
account_id = User.steam_id_to_account_id(steam_id)
_user = User.query.filter(User.id == account_id).first()
# If a user doesn't exist in our database with that ID, let's register them.
if not _user:
_user = User(account_id, steam.user.profile(steam_id).persona or account_id)
db.session.add(_user)
db.session.commit()
# Attempt to log the user in
login_attempt = login_user(_user, remember=True)
# Flash messages according to how that went
if login_attempt is True:
flash(u"You are logged in as {}".format(_user.name), "success")
elif not _user.is_active():
flash(u"Cannot log you in as {}, your account has been disabled. If you believe this is in error, please contact {}.".format(_user.name, current_app.config["CONTACT_EMAIL"]), "error")
else:
flash(u"Error logging you in as {}, please try again later.".format(_user.name), "error")
# Rediect the user to their next-url.
return redirect(oid.get_next_url())
示例7: register_view
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def register_view(self):
form = RegistrationForm(request.form)
if helpers.validate_form_on_submit(form):
user = User()
# hash password, before populating User object
form.password.data = hash(form.password.data)
form.populate_obj(user)
# activate the admin user
if user.email == app.config['ADMIN_USER']:
user.is_active = True
db.session.add(user)
db.session.commit()
flash('Please wait for your new account to be activated.', 'info')
return redirect(url_for('.login_view'))
link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>'
return self.render('admin/home.html', form=form, link=link, register=True)
示例8: edit
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def edit(nickname = None):
# wait a min. How about if no nick create new dude?
if not nickname:
user = User()
# nickname = g.nickname
else:
user = User.query.filter_by(nickname = nickname).first()
if user == None:
flash('User ' + nickname + ' not found.')
return redirect(url_for('index'))
form = EditForm(user.nickname)
if form.validate_on_submit():
user.nickname = form.nickname.data
user.about_me = form.about_me.data
user.rfid_access = form.rfid_access.data
user.rfid_tag = form.rfid_tag.data
user.first_name = form.first_name.data
user.last_name = form.last_name.data
user.is_active = form.is_active.data
db.session.add(user)
db.session.commit()
flash('Your changes have been saved.')
return redirect(url_for('edit', nickname = user.nickname))
else:
if nickname:
form.nickname.data = user.nickname
form.about_me.data = user.about_me
form.rfid_access.data = user.rfid_access
form.rfid_tag.data = user.rfid_tag
form.is_active.data = user.is_active
form.first_name.data = user.first_name
form.last_name.data = user.last_name
# only if a user we already have.
return render_template('edit.html',
form = form)
示例9: add_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def add_user(**credential):
"""
Create new User objects using passed credentials and return a User object.
"""
logging.debug('add_user: %s' % str(credential))
user = None
query = db.Query(User)
query_users = query.filter('username =', credential['username'])
if query_users.count()>1:
logging.error("There are several users with username = '%s' and email = '%s'" % (credential['username'], credential['email']))
user = query_users.get()
elif (credential.has_key('username')):
user = User(username = credential['username'])
if (credential.has_key('is_superuser') and
credential['is_superuser'].lower() in ('yes', 'true')): user.is_superuser = True
else:
user.is_superuser = False
user.is_active = True
user.put()
return user
示例10: create_or_login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def create_or_login(resp):
steam_id = long(resp.identity_url.replace("http://steamcommunity.com/openid/id/", ""))
account_id = int(steam_id & 0xFFFFFFFF)
_user = User.query.get(account_id)
new_user = False
if not _user:
_user = User(account_id)
new_user = True
db.session.add(_user)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
_user = User.query.get(account_id)
if not _user.signed_in:
_user.signed_in = True
db.session.add(_user)
db.session.commit()
if not _user.is_active():
flash(u"Cannot log you in, {}. You are banned.".format(_user.name), "danger")
return redirect(oid.get_next_url())
login_attempt = login_user(_user, remember=True)
if login_attempt is True and new_user and _user.profile_url:
flash(u"Welcome to mods.tf, {}!".format(_user.name), "success")
elif login_attempt is True and new_user and not _user.profile_url:
flash(u"Welcome to mods.tf! Unfortunately were unable to fetch your Steam user data."
u"We will try again soon. For now you will be represented by your numerical ID, {}.".format(_user.name), "success")
elif login_attempt is True and not new_user:
flash(u"Welcome back, {}.".format(_user.name), "success")
else:
flash(u"Error logging you in as {}, please try again later.".format(_user.name), "danger")
return redirect(oid.get_next_url())
示例11: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def post(self, request):
""" get data from request """
try:
data = JSONParser().parse(request)
data = data.get(PARAMETER_DATA)
except JSONDecodeError:
raise ParseError(detail="No data found on the request")
''' extract data from post body. first check if all variables are True '''
if not all( ( data.has_key(PARAMETER_EMAIL),
data.has_key(PARAMETER_FULL_NAME),
data.has_key(PARAMETER_ID)
) ):
raise ParseError("Some parameters are missing from request")
''' get all data from request '''
social_id = WebRequestParameter.get_data(PARAMETER_ID, data)
email = WebRequestParameter.get_data(PARAMETER_EMAIL, data)
name = WebRequestParameter.get_data(PARAMETER_FULL_NAME, data)
uuid = WebRequestParameter.get_data(PARAMETER_UUID, data)
avatar = WebRequestParameter.get_data(PARAMETER_AVATAR, data)
social_token = WebRequestParameter.get_data(PARAMETER_TOKEN, data)
''' check if user exists '''
user = User.objects(email=email, is_active=True).first()
if user is None:
''' create new user using email address'''
user = User(email=email, username=email)
if len(name) > 0:
first_name, last_name = name.split(" ")
user.first_name = first_name
user.last_name = last_name
user.name = name
user.last_login_time = datetime.datetime.now()
user.is_active = True
try:
user.save()
user.uid = str(user.id)
except:
traceback.print_exc()
raise APIException("Unable to save user data in DB. Try again later!")
""" add device push token """
device_type = WebRequestParameter.get_data(PARAMETER_DEVICE, data)
if device_type:
push_token = WebRequestParameter.get_data(PARAMETER_PUSH_TOKEN, data)
if push_token:
''' create and add device type '''
device_obj = Device(type=device_type, push_token=push_token)
user.devices.append(device_obj)
""" get or create social connector """
registration_type = WebRequestParameter.get_data(PARAMETER_REGISTRATION, data)
if registration_type:
connector = dict(id=social_id)
token = WebRequestParameter.get_data(PARAMETER_TOKEN, data)
if token:
connector[PARAMETER_TOKEN] = token
''' create social connector '''
social_link = {registration_type : connector}
UserManager().get_or_create_social_connector(uid=str(user.id), social_link=social_link)
''' generate new token '''
auth_token = AuthToken().generate_auth_token()
user.auth_token = auth_token
''' save user object '''
try:
user.save()
except:
raise APIException("Unable to save user data!")
''' save token in cache '''
cache_data = dict(uid=user.id, name=name, user=user)
cache.set(auth_token, cache_data, ten_minutes_in_seconds)
''' mark user as available '''
try:
online = OnlineChecker(user.uid)
online.is_available()
except Exception:
traceback.print_exc()
pass
''' return user token '''
user_token = dict(uid=str(user.id), token=auth_token, valability=ten_minutes_in_seconds)
""" return response """
return Response(user_token)
示例12: google_authorized
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def google_authorized(resp):
error = 'Something went wrong - Could not fetch data from Google'
if resp is None:
return authenticate_web_user(error='%s, error_description=%s' %(request.args['error_reason'], request.args['error_description']))
if isinstance(resp, OAuthException):
return authenticate_web_user(error=resp.message)
session['google_token'] = (resp['access_token'], '')
access_token = session['google_token'][0]
expires = resp.get('expires_in', None)
(me, me_plus, data, data_plus) = (None, None, {}, {})
if access_token and expires:
expires = datetime.utcnow() + timedelta(seconds=long(expires))
try:
me = google.get('userinfo')
except:
pass
try:
me_plus = google.get(GOOGLE_PLUS_API_URL+'people/me')
except:
pass
try:
error = me_plus.data['error']['message']
except:
pass
try:
error = me.data['error']['message']
except:
pass
else:
return authenticate_web_user(error=error)
if hasattr(me, 'data'):
data = me.data
if hasattr(me_plus, 'data'):
data_plus = me_plus.data
if not data and not data_plus:
return authenticate_web_user(error=error)
data.update(data_plus)
for k, v in dict(data).items():
v = str(v).strip()
if not v:
data.pop(k)
google_id = data['id']
oauth_object = GoogleOAuth.objects(google_id=google_id)
if oauth_object:
oauth_object = oauth_object[0]
user = User.objects(id=oauth_object.user.id)[0]
else:
user = User()
third_party_data = {v:k for k, v in THIRD_PARTY_DATA.items()}
fields_to_fetch = [third_party_data[k] for k, v in FIELDS_TO_FETCH.items()]
fields_to_update = list(set(fields_to_fetch) - set(user.fields_updated))
for field in fields_to_update:
db_field = THIRD_PARTY_DATA[field]
if db_field == 'location':
location = None
try:
location = data['location']
except:
pass
try:
for x in data['placesLived']:
location = x['value']
if x['primary']:
break
except:
pass
try:
location = data['hometown']['name']
except:
pass
if location:
user.location = location
elif db_field == 'gender':
genders = {v:k for k, v in GENDERS.items()}
try:
gender = genders[data[FIELDS_TO_FETCH[db_field]]]
user.gender = gender
except:
pass
else:
try:
exec "user.%s = '%s'" %(db_field, data[FIELDS_TO_FETCH[db_field]]) in locals()
except:
pass
user.is_active = True
user.save()
if not oauth_object:
oauth_object = GoogleOAuth()
oauth_object.google_id = google_id
oauth_object.user = user
oauth_object.access_token = access_token
oauth_object.expires = expires
oauth_object.created_at = datetime.utcnow()
oauth_object.save()
registered = False
if user.password:
registered = True
return authenticate_web_user(user=user, registered=registered)
示例13: facebook_authorized
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def facebook_authorized(resp):
error = 'Something went wrong - Could not fetch data from Facebook'
if resp is None:
return authenticate_web_user(error='%s, error_description=%s' %(request.args['error_reason'], request.args['error_description']))
if isinstance(resp, OAuthException):
return authenticate_web_user(error=resp.message)
session['oauth_token'] = (resp['access_token'], '')
access_token = session['oauth_token'][0]
expires = resp.get('expires', None)
(me, data) = (None, {})
if access_token and expires:
expires = datetime.utcnow() + timedelta(seconds=long(expires))
try:
me = facebook.get('/me')
except:
pass
try:
error = me.data['error']['message']
except:
pass
else:
return authenticate_web_user(error=error)
if hasattr(me, 'data'):
data = me.data
if not data:
return authenticate_web_user(error=error)
for k, v in dict(data).items():
v = str(v).strip()
if not v:
data.pop(k)
fb_id = data['id']
oauth_object = FaceBookOAuth.objects(fb_id=fb_id)
if oauth_object:
oauth_object = oauth_object[0]
user = User.objects(id=oauth_object.user.id)[0]
else:
user = User()
third_party_data = {v:k for k, v in THIRD_PARTY_DATA.items()}
fields_to_fetch = [third_party_data[k] for k, v in FIELDS_TO_FETCH.items()]
fields_to_update = list(set(fields_to_fetch) - set(user.fields_updated))
for field in fields_to_update:
db_field = THIRD_PARTY_DATA[field]
if db_field == 'last_name':
for x in FIELDS_TO_FETCH[db_field]:
try:
last_name += '%s ' %data[x]
user.last_name = last_name.strip()
except:
pass
elif db_field == 'location':
for x in FIELDS_TO_FETCH[db_field]:
try:
location = data[x]['name']
user.location = location
except:
pass
elif db_field == 'gender':
genders = {v:k for k, v in GENDERS.items()}
try:
gender = genders[data[FIELDS_TO_FETCH[db_field]]]
user.gender = gender
except:
pass
elif db_field == 'dob':
try:
dob = data[FIELDS_TO_FETCH[db_field]]
dob = dob.split('/')
dob = '%s-%s-%s' %(dob[2], dob[0], dob[1])
user.dob = dob
except:
pass
elif db_field == 'picture':
try:
picture = requests.get('%s/%s/picture?type=large' %(FACEBOOK_API_URL, fb_id)).url
user.picture = picture
except:
pass
else:
try:
exec "user.%s = '%s'" %(db_field, data[FIELDS_TO_FETCH[db_field]]) in locals()
except:
pass
user.is_active = True
user.save()
if not oauth_object:
oauth_object = FaceBookOAuth()
oauth_object.fb_id = fb_id
oauth_object.user = user
oauth_object.access_token = access_token
oauth_object.expires = expires
oauth_object.created_at = datetime.utcnow()
oauth_object.save()
registered = False
if user.password:
registered = True
return authenticate_web_user(user=user, registered=registered)
示例14: tg_einladung_new_form
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def tg_einladung_new_form(request, tg_id):
def return_empty_form():
context = {}
form = TG_Einladung_createForm(tg=tg, user=request.user.user)
context["news"] = get_news_by_request(request)
context["form"] = form
return render(request, 'tippgemeinschaft/einladung_create.html', context)
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse("home"))
try:
tg = Tippgemeinschaft.objects.get(pk = tg_id)
except:
return HttpResponseRedirect(reverse("home"))
if request.method == 'POST':
fuer = request.POST["fuer-autocomplete"]
# 2 cases: valid user, or email address
# case 1, user
if "user_select" in request.POST.keys():
user_select_id = request.POST["user_select"]
# case 2, email:
elif string.count(fuer, '@') == 1:
new_user = User()
new_user.username = fuer
new_user.first_name = string.split(fuer, '@')[0]
new_user.email = fuer
new_user.is_active = False
new_user.save()
user_select_id = new_user.id
else:
messages.warning(request, "User nicht gefunden, oder ungültige eMail-Adresse!")
return return_empty_form()
tg_e = TG_Einladung()
form = TG_Einladung_createForm(request.POST, instance = tg_e, tg=tg, user=request.user.user)
if form.is_valid():
tg_e.key = uuid.uuid4()
tg_e.tg = tg
tg_e.von = request.user.user
tg_e.fuer_id = user_select_id
try:
form.save()
except IntegrityError:
messages.warning(request, "Bereits eine Einladung an diesen User verschickt!")
return return_empty_form()
#mail schicken
von = tg_e.von.first_name if tg_e.von.first_name else tg_e.von.username
fuer = tg_e.fuer.first_name if tg_e.fuer.first_name else tg_e.fuer.username
args = (unicode(fuer), unicode(von), unicode(tg.bezeichner), unicode(tg.beschreibung), "http://"+request.get_host()+reverse("acc_tg_einladung", args=[tg_e.key]), "http://"+request.get_host()+reverse("del_tg_einladung", args=[tg_e.key]), )
try:
mail.send(TGE_SUBJECT % unicode(tg.bezeichner),
tg_e.fuer.email,
TGE_MSG % args,
TGE_MSG_HTML % args)
except SMTPRecipientsRefused:
tg_e.delete()
if new_user:
new_user.delete()
messages.warning(request, "Ungültige eMail-Adresse!")
return return_empty_form()
messages.success(request, "Erfolgreich eingeladen!")
return HttpResponseRedirect(reverse("show_tippgemeinschaft", args=[tg.id]))
else:
return return_empty_form()
示例15: twitter_authorized
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import is_active [as 别名]
def twitter_authorized(resp):
error = 'Something went wrong - Could not fetch data from Twitter'
if resp is None:
return authenticate_web_user(error='%s, error_description=%s' %(request.args['error_reason'], request.args['error_description']))
if isinstance(resp, OAuthException):
return authenticate_web_user(error=resp.message)
(access_token, me, data) = (None, None, None)
session['twitter_oauth'] = resp
try:
access_token = resp['oauth_token']
expires = datetime.utcnow() + timedelta(days=90)
except:
pass
if access_token:
twt_id = resp['user_id']
screen_name = resp['screen_name']
try:
me = twitter.get('users/show.json?screen_name=%s' %screen_name)
except:
pass
try:
error = me.data['error']['message']
except:
pass
else:
return authenticate_web_user(error=error)
if hasattr(me, 'data'):
data = me.data
if not data:
return authenticate_web_user(error=error)
for k, v in dict(data).items():
v = str(v).strip()
if not v:
data.pop(k)
oauth_object = TwitterOAuth.objects(twt_id=twt_id)
if oauth_object:
oauth_object = oauth_object[0]
user = User.objects(id=oauth_object.user.id)[0]
else:
user = User()
third_party_data = {v:k for k, v in THIRD_PARTY_DATA.items()}
fields_to_fetch = [third_party_data[k] for k, v in FIELDS_TO_FETCH.items()]
fields_to_update = list(set(fields_to_fetch) - set(user.fields_updated))
for field in fields_to_update:
db_field = THIRD_PARTY_DATA[field]
if db_field == 'first_name':
split_name = data[FIELDS_TO_FETCH[db_field]].split()
if len(split_name) > 1:
user.first_name = split_name[0]
else:
user.first_name = ' '.join(split_name)
elif db_field == 'last_name':
split_name = data[FIELDS_TO_FETCH[db_field]].split()
if len(split_name) > 1:
user.last_name = ' '.join(split_name[1:])
else:
try:
exec "user.%s = '%s'" %(db_field, data[FIELDS_TO_FETCH[db_field]]) in locals()
except:
pass
user.is_active = True
user.save()
if not oauth_object:
oauth_object = TwitterOAuth()
oauth_object.twt_id = twt_id
oauth_object.user = user
oauth_object.access_token = access_token
oauth_object.expires = expires
oauth_object.created_at = datetime.utcnow()
oauth_object.save()
registered = False
if user.password:
registered = True
return authenticate_web_user(user=user, registered=registered)