本文整理汇总了Python中models.User.role方法的典型用法代码示例。如果您正苦于以下问题:Python User.role方法的具体用法?Python User.role怎么用?Python User.role使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.role方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_db
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def init_db(self):
engine = self.session.get_bind(mapper=None, clause=None)
inspector = Inspector.from_engine(engine)
if 'ab_user' not in inspector.get_table_names():
print "Security DB not found Creating..."
Base.metadata.create_all(engine)
print "Security DB Created"
self.migrate_db()
if self.session.query(Role).filter_by(name = self.auth_role_admin).first() is None:
role = Role()
role.name = self.auth_role_admin
self.session.add(role)
self.session.commit()
print "Inserted Role for public access", self.auth_role_admin
if not self.session.query(Role).filter_by(name = self.auth_role_public).first():
role = Role()
role.name = self.auth_role_public
self.session.add(role)
self.session.commit()
print "Inserted Role for public access", self.auth_role_public
if not self.session.query(User).all():
user = User()
user.first_name = 'Admin'
user.last_name = 'User'
user.username = 'admin'
user.password = 'general'
user.active = True
user.role = self.session.query(Role).filter_by(name = self.auth_role_admin).first()
self.session.add(user)
self.session.commit()
print "Inserted initial Admin user"
print "Login using Admin/general"
示例2: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def post(self, **kwargs):
role = self.request.get('role', default_value=None)
tenantKey = self.request.get('tenant_key', default_value=None)
unitKey = self.request.get('unit_key', default_value=None)
locationKey = self.request.get('location_key', default_value = None)
username = self.request.get('username', default_value=None)
password = self.request.get('password', default_value=None)
if not all([role,locationKey,username,password]):
self.abort(400)
if role == 'tenant' and not tenantKey:
self.abort(400)
key = None
if role == 'tenant':
key = ndb.Key(Location, int(locationKey),
Unit, int(unitKey),
Tenant, int(tenantKey))
elif role == 'manager':
key = ndb.Key(Location, int(locationKey))
else:
self.response.status = 400
self.response.status_message = 'Role must be either tenant or manager.'
user = User()
try:
user.role = role
user.related_key = key
user.username = username
user.password = password
user.put()
except Exception as msg:
self.abort(500, details=msg)
return
self.response.write(json.dumps(user.to_dict()))
示例3: sign_up
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def sign_up():
form = SignUpForm()
user = User()
if form.validate_on_submit():
user_name = request.form.get('user_name')
user_email = request.form.get('user_email')
register_check = User.query.filter(db.or_(
User.nickname == user_name, User.email == user_email)).first()
if register_check:
flash("error: The user's name or email already exists!")
return redirect('/sign-up')
if len(user_name) and len(user_email):
user.nickname = user_name
user.email = user_email
user.role = ROLE_USER
try:
db.session.add(user)
db.session.commit()
except:
flash("The Database error!")
return redirect('/sign-up')
flash("Sign up successful!")
return redirect('/index')
return render_template(
"sign_up.html",
form=form)
示例4: profile
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def profile():
if current_user.is_authenticated():
user = current_user
else:
user = None
form = ProfileForm(obj=user)
if not form.password or form.password == '':
del form.password
if form.validate_on_submit():
if user:
flash('Successfully updated your profile.')
else:
user = User()
user.role = 1
flash('Congratulations, you just created an account!')
form.populate_obj(user)
db.session.add(user)
db.session.commit()
if not current_user.is_authenticated():
login_user(user)
return redirect('/')
return render_template('demographic.html', form=form)
示例5: signin
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def signin():
form = SigninForm()
if form.validate_on_submit():
if len(User.query.filter_by(nickname=form.nickname.data).all()) > 0:
flash(gettext("Selected username already exists!"), category='alert-danger')
return redirect(url_for('signin'))
new_email = form.email.data
check_mail = User.query.filter_by(email=new_email).all()
#user mail already exists
if len(check_mail) > 0:
flash(gettext('Selected email is already in use!'), category='alert-danger')
return redirect(url_for('signin'))
user = User()
user.nickname = form.nickname.data
user.password = generate_password_hash(form.password.data)
user.email = new_email
user.language = form.language.data
# default role is user, not admin
user.role = USER_ROLES['ROLE_USER']
db.session.add(user)
db.session.commit()
flash(gettext('Thank you for joining us!'))
return redirect(url_for('index'))
return render_template('login/signin.html',
title=gettext('Sign In'),
form=form)
示例6: after_login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def after_login(resp):
if resp.email is None or resp.email == "":
redirect(url_for('login'))
user = User.query.filter_by(email = resp.email).first()
if user is None:
username = resp.nickname
if username is None or username == "":
username = resp.email.split('@')[0]
user = User(
username=username,
email=resp.email,
name=resp.fullname,
role=ROLE_USER
)
if user.email == os.environ.get('ADMIN_EMAIL', ''):
user.role = ROLE_ADMIN
app.db_session.add(user)
app.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'))
示例7: addUser
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def addUser():
form = AddUserForm()
customer_choices = [(a.id, a.name) for a in Customer.query.filter_by(customer_type=CUSTOMER_TYPES['TYPE_CUSTOMER']).all()]
customer_choices = [(0, '')] + customer_choices
maker_choices = [(a.id, a.name) for a in Maker.query.all()]
maker_choices = [(0, '')] + maker_choices
form.customer.choices = customer_choices
form.maker.choices = maker_choices
if form.validate_on_submit():
if len(User.query.filter_by(nickname=form.nickname.data).all()) > 0:
flash(gettext("Selected username already exists!"))
return redirect(url_for('users'))
new_email = form.email.data
check_mail = User.query.filter_by(email=new_email).all()
#user mail already exists
if len(check_mail) > 0:
flash(gettext('Selected email is already in use!'))
return redirect(url_for('users'))
user = User()
user.nickname = form.nickname.data
user.password = generate_password_hash(form.password.data)
user.email = form.email.data
user.role = form.role.data
if int(form.role.data) == USER_ROLES['ROLE_CUSTOMER']:
if form.customer.data and form.customer.data != '' and form.customer.data != 0:
user.customer_id = form.customer.data
else:
user.customer_id = None
elif int(form.role.data) == USER_ROLES['ROLE_MAKER']:
if form.maker.data and form.maker.data != '' and form.maker.data != 0:
user.maker_id = form.maker.data
else:
user.maker_id = None
else:
user.customer_id = None
user.maker_id = None
user.language = form.language.data
db.session.add(user)
db.session.commit()
flash(gettext("New user successfully added."))
return redirect(url_for("users"))
return render_template('settings/addUser.html',
title=gettext("Add New User"),
USER_ROLES=USER_ROLES,
form=form)
示例8: sign_up
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def sign_up():
form = SignUpForm()
if form.validate_on_submit():
nickname = request.form.get("nickname")
email = request.form.get("email")
pw = request.form.get("password")
re_pw = request.form.get("re_password")
name_email_check = User.query.filter(db.or_(User.nickname == nickname, User.email == email)).first()
if name_email_check:
flash("错误: 用户名或者邮件地址已经存在!")
return redirect(url_for("sign_up"))
pw_check = (pw != re_pw)
if pw_check:
flash("两次输入的密码不相同!")
return redirect(url_for("sign_up"))
import helperlib
if len(nickname) and len(email):
user = User()
user.nickname = nickname
user.email = email
user.password = helperlib.make_pw_hash(nickname, pw)
user.role = ROLE_USER
try:
db.session.add(user)
db.session.commit()
except:
flash("数据库错误!")
return redirect(url_for("sign_up"))
msg = Message("欢迎您来到行博", sender="[email protected]", recipients=[email])
msg.body = """欢迎您来到行博。
我是行博CEO 行云。
您注册的账户名称是:{0}
祝您开心健康每一天!""".format(nickname)
import helperlib
helperlib.send_mail_async(mail, msg)
flash("注册成功!注册邮件稍后发送至您的邮箱。")
logout_user()
return redirect(url_for("login"))
return render_template(
"sign_up.html",
form = form)
示例9: signup
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def signup():
form = SignupForm()
if form.validate_on_submit():
# flash('Login requested for OpenID="' + form.openid.data + '", remember_me=' + str(form.remember_me.data))
user = User()
user.created_time = datetime.now()
user.email = form.email.data
user.nickname = form.username.data
user.username = form.username.data
user.password = auth.getPassword(user.username,form.password.data)
user.role = ROLE_DEFAULT
user.is_imported = False
user.status = STATUS_NORMAL
db.session.add(user)
db.session.commit()
auth.login(user,True)
flash(u'注册成功')
return redirect('/')
return render_template('usersignup.html',form=form)
示例10: add_account
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def add_account():
"""新增账号"""
for index, breadcrumb in enumerate(session["breadcrumbs"]):
if "添加账号" == breadcrumb["text"]:
session["breadcrumbs"] = session["breadcrumbs"][: index + 1]
break
else:
session["breadcrumbs"].append({"text": "添加账号", "url": url_for("auth.add_account")})
new_user = None
if request.method == "POST":
if request.form["password"] != request.form["password2"]:
flash(u"两次输入的密码不相同", "danger")
return redirect(url_for("auth.add_account"))
user = User.query.filter_by(email=request.form["email"]).first()
if user is not None:
flash(u"此邮箱地址已注册过", "danger")
return redirect(url_for("auth.add_account"))
new_user = User()
new_user.username = request.form["username"]
new_user.email = request.form["email"]
new_user.password = request.form["password"]
new_user.display_name = request.form["display_name"]
new_user.role = Role.query.filter_by(id=request.form["role"]).first()
db.session.add(new_user)
db.session.commit()
flash(u"新增成功", "info")
return render_template(
"admin/account/account_edit.html",
user=new_user,
roles=Role.query.filter(db.and_(Role.name != "translator", Role.name != "customer_manager")).all(),
current_page="auth.account_page",
)
示例11: create_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def create_user():
search_form = SearchForm()
company_list = current_user.list_all_company()
# Remove Aurio Head company from the list
for company in company_list:
if company.name == "Aurio Head":
company_list.remove(company)
create_form = CreateUserForm()
if request.method == "POST":
user_obj = User()
user_obj.user_name = create_form.user_name.data
user_obj.name = create_form.name.data
user_obj.password = create_form.password.data
user_obj.hash_password() # Hashing password
user_obj.role = int(create_form.role.data)
user_obj.activate = True
if current_user.role == 3:
user_obj.company_id = int(create_form.selected_company.data)
elif current_user.role == 2:
user_obj.company_id = current_user.company_id
user_list = user_obj.list_all_exsit_user()
for user in user_list:
if user.user_name == user_obj.user_name:
flash("User_name is duplicate")
return render_template("create_user.html", search_form=search_form, create_form=create_form, list=company_list)
db.session.add(user_obj)
db.session.commit()
flash("User create success")
return render_template("create_user.html", search_form=search_form, create_form=create_form, list=company_list)
elif request.method == "GET":
if current_user.role == 1:
flash("You have no permission")
return redirect(url_for("main"))
else:
return render_template("create_user.html", search_form=search_form, create_form=create_form, list=company_list)
示例12: after_login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def after_login(resp):
print "After Login"
ses = get_session()
if resp.email is None or resp.email == "":
flash("Invalid login. Please try again.", "alert-error")
return redirect(url_for('login'))
user = ses.query(User).filter_by(email=resp.email).first()
if user is None:
nickname = resp.nickname
if nickname is None or nickname == "":
nickname = resp.email.split('@')[0]
user = User()
user.nickname = nickname
user.email = resp.email
user.role = ROLE_USER
ses.add(user)
ses.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'))
示例13: init_db
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def init_db(self):
try:
engine = self.session.get_bind(mapper=None, clause=None)
inspector = Inspector.from_engine(engine)
if 'ab_user' not in inspector.get_table_names():
log.info("Security DB not found Creating")
Base.metadata.create_all(engine)
log.info("Security DB Created")
self.migrate_db()
if self.session.query(Role).filter_by(name=self.auth_role_admin).first() is None:
role = Role()
role.name = self.auth_role_admin
self.session.add(role)
self.session.commit()
log.info("Inserted Role for public access %s" % (self.auth_role_admin))
if not self.session.query(Role).filter_by(name=self.auth_role_public).first():
role = Role()
role.name = self.auth_role_public
self.session.add(role)
self.session.commit()
log.info("Inserted Role for public access %s" % (self.auth_role_public))
if not self.session.query(User).all():
user = User()
user.first_name = 'Admin'
user.last_name = 'User'
user.username = 'admin'
user.password = generate_password_hash('general')
user.email = '[email protected]'
user.active = True
user.role = self.session.query(Role).filter_by(name=self.auth_role_admin).first()
self.session.add(user)
self.session.commit()
log.info("Inserted initial Admin user")
log.info("Login using Admin/general")
except Exception as e:
log.error("DB Creation and initialization failed, if just upgraded to 0.7.X you must migrate the DB. {0}".format(str(e)))
示例14: admin_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def admin_user():
create_form = CreateUserForm()
create_form.roles.query = Role.query.all()
delete_form = DeleteUserForm()
delete_form.users.query = User.query.all()
update_form = UpdateUserForm()
update_form.users.query = User.query.all()
update_form.roles.query = Role.query.all()
if request.method == 'POST':
if create_form.data['create'] and create_form.validate():
form = create_form
user = User.query.filter_by(user_id=form.create_id.data).first()
role = form.roles.data
if user == None:
user = User(
user_id=form.create_id.data,
user_name=form.create_name.data)
user.password = '123456'
user.role = role
db.session.add(user)
db.session.commit()
status = u'success'
message = u'成功添加登录用户'
session['message']=messages(status, message)
return redirect(url_for('admin'))
elif delete_form.data['delete'] and delete_form.validate():
form = delete_form
user = form.users.data
db.session.delete(user)
db.session.commit()
status = u'warning'
message = u'成功删除登录用户'
session['message']=messages(status, message)
return redirect(url_for('admin'))
elif update_form.data['update'] and update_form.validate():
form = update_form
user = form.users.data
role = form.roles.data
name = form.update_name.data
password = form.update_passwd.data
user.role = role
if password != '':
user.password = password
elif name != '':
user.user_name = name
db.session.add(user)
db.session.commit()
status = u'info'
message = u'成功修改登录用户信息'
session['message']=messages(status, message)
return redirect(url_for('admin'))
return render_template('admin-user.html', create_form=create_form, delete_form=delete_form, update_form=update_form)
示例15: edit
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import role [as 别名]
def edit(id=0):
#printException(str(request.form))
setExits()
id = cleanRecordID(id)
orgs = Organization.query.order_by(Organization.name)
u = getUserOrgs(id)
selectedOrgs = []
for s in u:
selectedOrgs.append(s.ID)
if id < 0:
flash("That is not a valid ID")
return redirect(g.listURL)
rec = None
if not request.form:
""" if no form object, send the form page """
# get the user record if you can
currentPassword = ""
if id > 0:
rec = User.query.get(id)
currentPassword = rec.password
else:
#have the request form
#ensure a value for the check box
inactive = request.form.get('inactive')
if not inactive:
inactive = "0"
if validForm():
if id > 0:
rec = User.query.get(id)
else:
## create a new record stub
rec = User(request.form['name'],request.form['email'])
db.session.add(rec)
#db.session.commit() # this loads the new ID into rec
rec.userName = db.null()
rec.password = db.null()
#Are we editing the current user's record?
editingCurrentUser = ''
if(g.user == rec.userName):
editingCurrentUser = request.form['userName'].strip()
else:
if(g.user == rec.email):
editingCurrentUser = request.form['email'].strip()
#update the record
rec.name = request.form['name'].strip()
rec.email = request.form['email'].strip()
rec.role = request.form['role'].strip()
rec.inactive = str(inactive)
user_name = ''
if request.form['userName']:
user_name = request.form['userName'].strip()
if user_name != '':
rec.userName = user_name
else:
rec.userName = db.null()
# Null values in db are returned as None
if str(rec.password) != 'NULL' and request.form['password'].strip() == '':
# Don't change the password
pass
else:
user_password = ''
if request.form['password'].strip() != '':
user_password = getPasswordHash(request.form['password'].strip())
if user_password != '':
rec.password = user_password
else:
rec.password = db.null()
try:
db.session.commit()
# create user_organization records
# in the case of a new user, rec.ID is now available
orgIDs = request.form.getlist("orgs")
if not orgIDs:
orgIDs = [request.form.get('org')]
makeUserOrgRecords(rec.ID,orgIDs)
db.session.commit()
# if the username or email address are the same as g.user
# update g.user if it changes
if(editingCurrentUser != ''):
setUserStatus(editingCurrentUser)
views.login.setUserSession(editingCurrentUser)
#.........这里部分代码省略.........