我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.flash()。
def changepass(): if request.method == 'POST': # process password change if request.form['pass1'] == request.form['pass2']: change_password(session['username'], request.form['pass1']) log_action(session['uid'], 8) session.pop('logged_in', None) session.pop('uid', None) session.pop('priv', None) session.pop('username', None) flash('Your password has been changed. Please login using your new password.') return redirect(url_for('home')) else: flash('The passwords you entered do not match. Please try again.') return render_template('changepass.html') return render_template('changepass.html') # # EDIT USER PAGE #
def adduser(): if request.method == 'POST': if request.form['pass1'] == request.form['pass2']: if user_exists(request.form['username']) == False: # create the user admin = 0 if request.form['status'] == 'admin': admin = 1 create_user(request.form['username'], request.form['pass1'], admin) log_action(session['uid'], 10) flash(request.form['username'] + ' has been created.') return render_template('adduser.html', acp=session['priv'], username=session['username']) else: flash('The username you entered is already in use.') return render_template('adduser.html', acp=session['priv'], username=session['username']) else: flash('The passwords you entered do not match. Please try again.') return render_template('adduser.html', acp=session['priv'], username=session['username']) return render_template('adduser.html', acp=session['priv'], username=session['username'])
def test_flash_signal(self): app = flask.Flask(__name__) app.config['SECRET_KEY'] = 'secret' @app.route('/') def index(): flask.flash('This is a flash message', category='notice') return flask.redirect('/other') recorded = [] def record(sender, message, category): recorded.append((message, category)) flask.message_flashed.connect(record, app) try: client = app.test_client() with client.session_transaction(): client.get('/') self.assert_equal(len(recorded), 1) message, category = recorded[0] self.assert_equal(message, 'This is a flash message') self.assert_equal(category, 'notice') finally: flask.message_flashed.disconnect(record, app)
def new(): form = ProjectForm(request.form) if request.method == 'POST' and form.validate(): user_repo_path = join('repos', form.name.data) if os.path.isdir(user_repo_path): flash(_('This project name already exists'), 'error') else: project = Project(form.name.data, current_user) db.session.add(project) db.session.commit() #project.create_project(form.name.data, current_user) flash(_('Project created successfuly!'), 'info') return redirect(url_for('branches.view', project=form.name.data, branch='master', filename='index')) return render_template('new.html', form=form)
def hipchat_configure_update(): signed_token = flask.request.args.get('signed_request') installed_room = verify_jwt(signed_token) try: installed_room.jamf_auth = ( flask.request.values.get('jamf_url'), flask.request.values.get('jamf_username'), flask.request.values.get('jamf_password') ) db.session.commit() except: flask.flash('The service account could not be validated. Please verify the URL, username and password.', 'error') else: flask.flash('The service account has been validated and saved!', 'success') send_notification( installed_room.hipchat_token, installed_room.hipchat_room_id, '''<p><b>A Jamf Pro service account has been configured!</b></p> <p>You may now search your Jamf Pro server's inventory from this room.''', color='purple', notify=True ) return flask.redirect(flask.url_for('hipchat_configure'))
def account_ban(login): """Ban (make inactive) account (POST handler)""" db = flask.current_app.container.get('db') user = db.session.query(User).filter_by(login=login).first() if user is None: flask.abort(404) ban = flask.request.form.get('active') == '0' unban = flask.request.form.get('active') == '1' if user.user_account.active and ban: user.user_account.active = False db.session.commit() flask.flash('User account {} has been disabled.'.format(login), 'success') elif not user.user_account.active and unban: user.user_account.active = True db.session.commit() flask.flash('User account {} has been enabled.'.format(login), 'success') else: flask.flash('Nope, no action has been performed', 'info') return flask.redirect( flask.url_for('admin.account_detail', login=login) )
def role_edit(name): """Edit role (POST handler)""" db = flask.current_app.container.get('db') role = db.session.query(Role).filter_by(name=name).first() if role is None: flask.abort(404) name = flask.request.form.get('name', '') desc = flask.request.form.get('description', None) if name == '': flask.flash('Couldn\'t make that role...', 'warning') return flask.redirect(flask.url_for('admin.index', tab='roles')) try: role.name = name role.description = desc db.session.commit() except sqlalchemy.exc.IntegrityError as e: flask.flash('Couldn\'t make that role... {}'.format(str(e)), 'warning') db.session.rollback() return flask.redirect(flask.url_for('admin.index', tab='roles')) flask.flash('Role {} has been edited'.format(name), 'success') return flask.redirect(flask.url_for('admin.role_detail', name=role.name))
def role_create(): """Create new role (POST handler)""" db = flask.current_app.container.get('db') name = flask.request.form.get('name', '') desc = flask.request.form.get('description', None) if name == '': flask.flash('Couldn\'t make that role...', 'warning') return flask.redirect(flask.url_for('admin.index', tab='roles')) try: role = Role(name, desc) db.session.add(role) db.session.commit() except sqlalchemy.exc.IntegrityError as e: flask.flash('Couldn\'t make that role... {}'.format(str(e)), 'warning') db.session.rollback() return flask.redirect(flask.url_for('admin.index', tab='roles')) return flask.redirect(flask.url_for('admin.role_detail', name=role.name))
def role_assignment_add(name): """Assign role to user (POST handler)""" db = flask.current_app.container.get('db') login = flask.request.form.get('login', '') user = db.session.query(User).filter_by(login=login).first() role = db.session.query(Role).filter_by(name=name).first() if user is None or role is None: flask.abort(404) account = user.user_account if account in role.user_accounts: flask.flash('User {} already has role {}'.format(login, name), 'error') else: role.user_accounts.append(account) db.session.commit() flask.flash('Role {} assigned to user {}'.format(name, login), 'success') return flask.redirect(flask.url_for('admin.role_detail', name=name))
def role_assignment_remove(name): """Remove assignment of role to user (POST handler)""" db = flask.current_app.container.get('db') login = flask.request.form.get('login', '') user = db.session.query(User).filter_by(login=login).first() role = db.session.query(Role).filter_by(name=name).first() if user is None or role is None: flask.abort(404) account = user.user_account if account not in role.user_accounts: flask.flash('User {} doesn\'t have role {}'.format(login, name), 'error') else: role.user_accounts.remove(account) db.session.commit() flask.flash('Role {} removed from user {}'.format(name, login), 'success') return flask.redirect(flask.url_for('admin.role_detail', name=name))
def org_detail(login): """Organization detail (GET handler) .. todo:: implement 410 (org deleted/archived/renamed) """ db = flask.current_app.container.get('db') ext_master = flask.current_app.container.get('ext_master') org = db.session.query(Organization).filter_by(login=login).first() if org is None: user = db.session.query(User).filter_by(login=login).first() if user is None: flask.abort(404) flask.flash('Oy! You wanted to access organization, but it\'s auser.' 'We redirected you but be careful next time!', 'notice') return flask.redirect(flask.url_for('core.user_detail', login=login)) tabs = {} ext_master.call('view_core_org_detail_tabs', org=org, tabs_dict=tabs) tabs = sorted(tabs.values()) active_tab = flask.request.args.get('tab', tabs[0].id) return flask.render_template( 'core/org.html', org=org, tabs=tabs, active_tab=active_tab )
def login(): error = None if request.method == 'POST': AllUser=session.query(User).all() for u in AllUser: if( request.form['username']==u.name and request.form['password']==u.password): login_session['logged_in'] = True flash('You were logged in.') login_session['U_Id']=u.id return redirect(url_for('home')) error = 'Invalid Credentials. Please try again.' return render_template('normallogin.html', error=error) else: state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32)) login_session['state'] = state return render_template('normallogin.html', error=error,STATE=state)
def newUser(): if 'logged_in' in login_session: flash('You need to logout first.') return redirect(url_for('logout')) else: if request.method == 'POST': AllUser=session.query(User).all() for x in AllUser: if x.name==request.form['UserName'] or x.email==request.form['Email']: error = 'Username or UserEmail Id already Exist. Please Enter another Name or Email ID' return render_template('newuser.html',error=error) newUser=User(email=request.form['Email'],name=request.form['UserName'],password=request.form['Password']) session.add(newUser) session.commit() login_session['U_Id'] =newUser.id login_session['logged_in'] = True flash('Hello %s'%request.form['UserName']) return redirect(url_for('home')) else: return render_template('newuser.html')
def newIssue(): if 'logged_in' not in login_session: flash('You need to login first.') return redirect(url_for('login')) else: #login_session['U_Id']=1 if request.method == 'POST': newIssue = Issue(author=login_session['U_Id'],title=request.form['I_Title'], content=request.form['I_Content'], lat=request.form['I_Lat'], lng=request.form['I_Lng'], image="url for image",type = request.form['I_Type'], anonFlag=request.form['I_AnonFlag']) session.add(newIssue) session.commit() #flash('New Restaurant %s Successfully Created' % newRestaurant.name) print request.form['I_Lat'] print request.form['I_Lng'] print request.form['I_Title'] print request.form['I_Content'] print request.form['I_Type'] print request.form['I_AnonFlag'] return redirect(url_for('home')) else: return render_template('newIssue.html')
def showDetailedIssue(I_Id): if 'logged_in' not in login_session: flash('You need to login first.') return redirect(url_for('login')) else: showDetailedIssue = session.query(Issue).filter_by(id = I_Id).one() showDetailedComment = session.query(Comment).filter_by(id = I_Id).order_by(asc(Comment.sqNo)).all() showDetailedUser= session.query(User).filter_by(id= showDetailedIssue.author).one() Author=showDetailedUser.name #temporarily harcoding the likes and dislikes part like=showDetailedIssue.like dislike=showDetailedIssue.dislike #showDetailedVote = session.query(Issue).filter_by(id = I_Id).all() #showDetailedVote = session,query(func.count()) SELECT count(*) # FROM (SELECT V_flag FROM Votes where V_IssueId = %s AND V_flag = true) # AS likes GROUP BY V_flag;""",(I_Id,)) if showDetailedIssue.anonFlag == 1: Author="Anonymous" return render_template('showdetailedissue.html', Issue=showDetailedIssue, Comment=showDetailedComment, like=like, dislike=dislike, Author=Author)
def editComment(C_Id,C_SqNo): if 'logged_in' not in login_session: flash('You need to login first.') return redirect(url_for('login')) else: #login_session['U_Id']=1 issuetocomment= session.query(Issue).filter_by(id = C_Id).one() usertocomment=session.query(User).filter_by(id= login_session['U_Id']).one() editComment=session.query(Comment).filter_by(id=C_Id).filter_by(author=login_session['U_Id']).filter_by(sqNo=C_SqNo).one() if request.method == 'POST': if request.form['C_Content']: editComment.content = request.form['C_Content'] session.add(editComment) session.commit() return redirect(url_for('showDetailedIssue',I_Id=C_Id )) else: #part to check if the user is the author of the comment return render_template('editcomment.html',Comment=editComment,Issue=issuetocomment)
def deleteComment(C_Id,C_SqNo): if 'logged_in' not in login_session: flash('You need to login first.') return redirect(url_for('login')) else: #login_session['U_Id']=1 issuetocomment= session.query(Issue).filter_by(id = C_Id).one() usertocomment=session.query(User).filter_by(id= login_session['U_Id']).one() commenttodelete=session.query(Comment).filter_by(id=C_Id).filter_by(author=login_session['U_Id']).filter_by(sqNo=C_SqNo).one() if request.method == 'POST': session.delete(commenttodelete) # flash('%s Successfully Deleted' % restaurantToDelete.name) session.commit() return redirect(url_for('showDetailedIssue',I_Id=commenttodelete.id )) else: #part to check if the user is the author of the comment return render_template('deletecomment.html', Comment=commenttodelete) #------------------------------------------------------------------------------------------------------------------
def showNearbyIssueList(): if 'logged_in' not in login_session: flash('You need to login first.') return redirect(url_for('login')) else: if request.method == 'POST': #Setting distance as 1KM radius 0.00654=1Km latmax=float(request.form['I_Lat'])+0.00654 latmin=float(request.form['I_Lat'])-0.00654 lngmax=float(request.form['I_Lng'])+0.00654 lngmin=float(request.form['I_Lng'])-0.00654 nearbyIssue=session.query(Issue).filter(Issue.lat<latmax,Issue.lat>latmin, Issue.lng<lngmax,Issue.lng>lngmin).all() return render_template('shownearbyissuelist.html', Issue=nearbyIssue) else: return render_template('getlocation.html') #----------------------------------------------------------------------------------------------------------------- # LOGIN
def auth_redirect(): err = ds_authentication.auth_redirect() # err is False or an error message # We will use the Flash technique to show the message on the home page. # Or a simpler alternative would be to show the error message on an intermediate # page, with a "Continue" link to the home page if err: flash(err) # flash("Debug info: " + str(request.headers)) # Authentication / re-authentication was successful # Figure out what to do next if "auth_redirect" in session: auth_redirect = session["auth_redirect"] if auth_redirect: session["auth_redirect"] = False return redirect(auth_redirect) return redirect(ds_recipe_lib.get_base_url(1))
def vk_authorized(): response = vk.authorized_response() if response is None: flask.flash(u'You denied the request to sign in.') return flask.redirect(util.get_next_url()) access_token = response['access_token'] flask.session['oauth_token'] = (access_token, '') me = vk.get( '/method/users.get', data={ 'access_token': access_token, 'format': 'json', }, ) user_db = retrieve_user_from_vk(me.data['response'][0]) return auth.signin_user_db(user_db)
def feedback(): if not config.CONFIG_DB.feedback_email: return flask.abort(418) form = FeedbackForm(obj=auth.current_user_db()) if not config.CONFIG_DB.has_anonymous_recaptcha or auth.is_logged_in(): del form.recaptcha if form.validate_on_submit(): body = '%s\n\n%s' % (form.message.data, form.email.data) kwargs = {'reply_to': form.email.data} if form.email.data else {} task.send_mail_notification('%s...' % body[:48].strip(), body, **kwargs) flask.flash('Thank you for your feedback!', category='success') return flask.redirect(flask.url_for('welcome')) return flask.render_template( 'feedback.html', title='Feedback', html_class='feedback', form=form, )
def black_list(del_id=None): produce.Async_log(g.user, request.url) db = db_op.haproxy_blacklist VAL = [] try: val = db.query.with_entities(db.id,db.addtime,db.ip,db.rule,db.expire).filter(db.stats=='0').order_by(desc(db.id)).limit(1000).all() if val: tables = ['????','??IP','IP???','????','??????',' ??'] if del_id: db.query.filter(db.id == str(del_id)).update({db.stats: '2'}) db_op.DB.session.commit() val = db.query.with_entities(db.id, db.addtime,db.ip,db.rule,db.expire).filter(db.stats == '0').order_by(desc(db.addtime)).limit(1000).all() for va in val: va = list(va) va.insert(3,ip_area.Search(str(va[2]))) VAL.append(va) return render_template('black_list.html',Main_Infos=g.main_infos,tables = tables,values = VAL) else: flash('??????!') return render_template('Message_static.html', Main_Infos=g.main_infos) except Exception as e: flash(e) return render_template('Message_static.html',Main_Infos=g.main_infos)
def backup_mysql_results(): produce.Async_log(g.user, request.url) try: if Redis.exists('finish_backup'): Infos = Redis.lrange('finish_backup',0,-1) if Infos: Infos = [eval(info) for info in set(Infos)] tt = time.strftime('%Y-%m-%d', time.localtime()) tables = ('??','?????','MYSQL???','?????',' ??') return render_template('backup_mysql_results.html',Main_Infos=g.main_infos,Infos=Infos,tt=tt,tables=tables) else: raise flash('????:?????????!') else: raise flash('????:?????????!') except Exception as e: if 'old' not in str(e): flash(str(e)) return render_template('Message_static.html',Main_Infos=g.main_infos)
def yahoo_authorized(): response = yahoo.authorized_response() if response is None: flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url()) flask.session['oauth_token'] = ( response['oauth_token'], response['oauth_token_secret'], ) fields = 'guid, emails, familyName, givenName, nickname' me = yahoo.get( '/v1/yql', data={ 'format': 'json', 'q': 'select %s from social.profile where guid = me;' % fields, 'realm': 'yahooapis.com', }, ) user_db = retrieve_user_from_yahoo(me.data['query']['results']['profile']) return auth.signin_user_db(user_db)
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)
def exportdox_csv(export_id): # Create a time object to append to file time = strftime("%Y-%m-%d-%H:%M:%S", gmtime()) _csv = open('{}.csv'.format(time), 'wb') # Create CSV writer to newly created file. outcsv = csv.writer(_csv) # Get all records, and write to CSV. records = db.session.query(Doxkit).all() [outcsv.writerow([getattr(curr, column.name) for column in Doxkit.__mapper__.columns]) for curr in records] _csv.close() # Notify user flash("Exported Dox! Stored in your D0xk1t path.", "success") return redirect(url_for('dox')) # GeoIP Module
def login_required(f): @wraps(f) def wrap(*args, **kwargs): if 'logged_in' in session: return f(*args, **kwargs) else: flash('You must be logged in to view this page.') return redirect(url_for('login')) return wrap ## # Admin Required Decorator
def admin_required(f): @wraps(f) def wrap(*args, **kwargs): if is_admin(session['uid']): return f(*args, **kwargs) else: flash('You must be an administrator to view that page.') return redirect(url_for('home')) return wrap ## # SQLite Database Connector # Returns the db connection.
def login(): error = None if request.method == 'POST': uid = check_login(request.form['username'], request.form['password']) if uid == False: error = 'Invalid credentials. Please try again.' login = request.form['username'] if user_exists(login): log_action(get_uid(login), 2) else: session['logged_in'] = True session['uid'] = uid session['username'] = request.form['username'] session['priv'] = is_admin(uid) log_action(session['uid'], 1) flash('You were just logged in.') return redirect(url_for('home')) #if request.form['username'] != 'ADMIN' or request.form['password'] != 'ADMIN': # error = 'Invalid Credentials. Please try again.' #else: # session['logged_in'] = True # flash('You were just logged in.') # return redirect(url_for('home')) return render_template('login.html', error=error) # # LOGOUT PAGE #
def logout(): log_action(session['uid'], 3) session.pop('logged_in', None) session.pop('uid', None) session.pop('priv', None) session.pop('username', None) flash('You were just logged out.') return redirect(url_for('home')) # # CHANGE PASSWORD PAGE #