예제 #1
1
def unauthorized_redirect(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.setup_app(app)
    res = lm.unauthorized()
    assert res.headers["Location"] == "/login?next=%2F"
    assert LOGIN_MESSAGE in get_flashed_messages()
예제 #2
0
파일: default.py 프로젝트: WYM/Whisper
def index():
	data = db.posts.find()
	if get_flashed_messages():
		message = get_flashed_messages()[0]
	else:
		message = 'Making splendid shots of our life!'
	return render_template('index.html', data = data, message = message, get_avatar = get_avatar, time_span = time_span)
    def render(self):
        self.count += 1
        self.set_classes('page col s10 offset-s1')
        htm=u"""<div class="row"><div%s>\n""" % self.get_attributes()
        
        # if this is static session will not be available
        try:
            messages = get_flashed_messages()
            if messages:
                htm += u'<ul class="messages">'
                for message in get_flashed_messages():
                    htm += '<li>%s</li>' % message
                htm += '</ul>' 
        except:
            pass
        
        htm+=u"""<header class="pageHeader">\n\t%s</header>\n""" % self.title
        for s in self.sections:
            if s[0]:
                htm+=u"""<section id=\"%s\" class="pageSection col s12">\n\t%s</section>\n""" %(s[0],''.join(s[1]))
            else:
                htm+=u"""<section class="pageSection col s12">\n\t%s</section>\n""" % ''.join(s[1])

        htm+=u"""<footer class="pageFooter col s12">\n\t%s</footer>\n""" % self.foot
        htm+=u"""</div></div>\n"""
        return htm
예제 #4
0
def create_account():

    if flask.request.method == "GET":
        return flask.render_template(
            "create_account.html",
            languages=model.Language.all(),
            native_languages=model.Language.native_languages(),
            flashed_messages=flask.get_flashed_messages(),
            default_learned=model.Language.default_learned(),
        )

    form = flask.request.form
    if flask.request.method == "POST" and form.get("create_account", False):
        password = form.get("password", None)
        email = form.get("email", None)
        name = form.get("name", None)
        code = form.get("code", None)
        language = model.Language.find(form.get("language", None))
        native_language = model.Language.find(form.get("native_language", None))

        if not (code == "Kairo" or code == "unibe" or code == "klubschule"):
            flask.flash("Invitation code is not recognized. Please contact us.")
        elif password is None or email is None or name is None:
            flask.flash("Please enter your name, email address, and password")
        else:
            try:
                zeeguu.db.session.add(model.User(email, name, password, language, native_language))
                zeeguu.db.session.commit()
            except ValueError:
                flask.flash("The username could not be created. Please contact us.")
                return flask.render_template(
                    "create_account.html",
                    flashed_messages=flask.get_flashed_messages(),
                    languages=model.Language.all(),
                    native_languages=model.Language.native_languages(),
                    default_learned=model.Language.default_learned(),
                )
            except sqlalchemy.exc.IntegrityError:
                print "integrity error"
                flask.flash(email + " is already in use. Please select a different email.")
                return flask.render_template(
                    "create_account.html",
                    flashed_messages=flask.get_flashed_messages(),
                    languages=model.Language.all(),
                    native_languages=model.Language.native_languages(),
                    default_learned=model.Language.default_learned(),
                )

            print "looking for the user"
            user = model.User.authorize(email, password)
            flask.session["user"] = user.id
            return flask.redirect(flask.url_for("account.my_account"))

    return flask.render_template(
        "create_account.html",
        flashed_messages=flask.get_flashed_messages(),
        languages=model.Language.all(),
        native_languages=model.Language.native_languages(),
        default_learned=model.Language.default_learned(),
    )
예제 #5
0
def add_news():
    if request.method == 'POST':
        if 'cancel' in request.form:
            return redirect(url_front())
        creator = session['username']
        created = now()
        title = request.form['title']

        get_flashed_messages()
        if title == "":
            flash("Please enter a title")
            return html.back()

        text = request.form['text']
        data.execute("INSERT INTO News(creator, created, title, text) VALUES(?,?,?,?)", creator, created, title, text)
        return redirect(url_front())
    else:
        w = html.WebBuilder()
        w.form()
        w.formtable()
        w.textfield("title", "Overskrift")
        w.textarea("text", "Tekst")

        form = w.create()
        return render_template("form.html", form=form)
예제 #6
0
파일: views.py 프로젝트: wuvt/wuvt-site
def login():
    errors = []

    if app.config['AUTH_METHOD'] == 'oidc':
        from wuvt import oidc

        # pull all flashed messages off the session, otherwise they will be
        # displayed post login, which is not what we want
        get_flashed_messages()

        target = request.values.get('next', '')
        if not target or not is_safe_url(target):
            target = url_for('admin.index')

        return oidc.oidc.redirect_to_auth_server(target)

    if 'username' in request.form:
        user = User.query.filter(
            User.username == request.form['username']).first()
        if user and user.check_password(request.form['password']):
            login_user(user, get_user_roles(user))

            log_auth_success("local", user.username)
            return redirect_back('admin.index')
        else:
            log_auth_failure("local", request.form['username'])
            errors.append("Invalid username or password.")

    return render_template('auth/login.html',
                           next=request.values.get('next') or "",
                           errors=errors)
예제 #7
0
파일: logout.py 프로젝트: mreider/fritter
def logout():
    current_app.logger.info("logout")
    if "google_token" in session:
        session.pop("google_token")
    get_flashed_messages()
    logout_user()
    return redirect(url_for("index"))
예제 #8
0
    def render(self):
        self.count += 1
        htm = u"""<div%s>\n""" % self.get_attributes()

        # if this is static session will not be available
        try:
            messages = get_flashed_messages()
            if messages:
                htm += u'<ul class="messages">'
                for message in get_flashed_messages():
                    htm += "<li>%s</li>" % message
                htm += "</ul>"
        except:
            pass

        htm += u"""<header class="pageHeader">\n\t%s</header>\n""" % self.title
        for s in self.sections:
            if s[0]:
                htm += u"""<section id=\"%s\" class="pageSection">\n\t%s</section>\n""" % (s[0], "".join(s[1]))
            else:
                htm += u"""<section class="pageSection">\n\t%s</section>\n""" % "".join(s[1])

        htm += u"""<footer class="pageFooter">\n\t%s</footer>\n""" % self.foot
        htm += u"""</div>\n"""
        return htm
예제 #9
0
def scriptlist():
    sign_out = '/user/sign-out'
    user = current_user.name
    email_verified = True
    # TODO: display flashed messages in scriptlist. For now, just clear queue
    get_flashed_messages()
    return render_template('scriptlist.html', user=user, sign_out=sign_out,
                           email_verified=email_verified)
예제 #10
0
파일: hiddennote.py 프로젝트: w4/HiddenNote
def complete():
    """Show the user the link to their post."""
    if not get_flashed_messages(False, 'post_id') or not get_flashed_messages(False, 'post_key'):
        abort(404)

    id = get_flashed_messages(False, 'post_id')[0]
    key = get_flashed_messages(False, 'post_key')[0]
    return render_template("pages/complete.html", id=id, key=key)
예제 #11
0
파일: auth.py 프로젝트: atbrox/dpxdt
def login_auth():
    # TODO: Handle when the 'error' parameter is present
    params = dict(
        code=request.args.get('code'),
        client_id=config.GOOGLE_OAUTH2_CLIENT_ID,
        client_secret=config.GOOGLE_OAUTH2_CLIENT_SECRET,
        redirect_uri=config.GOOGLE_OAUTH2_REDIRECT_URI,
        grant_type='authorization_code'
    )
    payload = urllib.urlencode(params)
    logging.debug('Posting for token to url=%r, payload=%r',
                  GOOGLE_OAUTH2_TOKEN_URL, payload)
    fetch_request = urllib2.Request(GOOGLE_OAUTH2_TOKEN_URL, payload)
    conn = urllib2.urlopen(fetch_request, timeout=FETCH_TIMEOUT_SECONDS)
    data = conn.read()
    result_dict = json.loads(data)

    params = dict(
        access_token=result_dict['access_token']
    )
    payload = urllib.urlencode(params)
    target_url = '%s?%s' % (GOOGLE_OAUTH2_USERINFO_URL, payload)
    logging.debug('Fetching user info from url=%r', target_url)
    fetch_request = urllib2.Request(target_url)
    conn = urllib2.urlopen(fetch_request, timeout=FETCH_TIMEOUT_SECONDS)
    data = conn.read()
    result_dict = json.loads(data)
    logging.debug('Result user info dict: %r', result_dict)
    email_address = result_dict['email']

    if not result_dict['verified_email']:
        abort(flask.Response('Your email address must be verified', 403))

    user_id = '%s:%s' % (models.User.GOOGLE_OAUTH2, result_dict['id'])
    user = models.User.query.get(user_id)
    if not user:
        user = models.User(id=user_id)

    # Email address on the account may change, user ID will stay the same.
    # Do not allow the user to claim existing build invitations with their
    # old email address.
    if user.email_address != email_address:
        user.email_address = email_address

    user.last_seen = datetime.datetime.utcnow()

    db.session.add(user)
    db.session.commit()

    login_user(user)
    confirm_login()

    # Clear all flashed messages from the session on login.
    flask.get_flashed_messages()

    final_url = urllib.unquote(request.args.get('state'))
    logging.debug('User is logged in. Redirecting to url=%r', final_url)
    return redirect(final_url)
예제 #12
0
def index():
    #session.clear()
    if session.get('logged_in') == True:
        return redirect(url_for('your_questions'))
    else:
        #return render_template('index.html')
        session.clear()  # ToDo: Check the security sufficiency of this viz-a-viz cookies and replay attack
        get_flashed_messages()  # provides user feedback (and debugging msgs)
        return redirect(url_for('login'))
예제 #13
0
def get_flash(category=None, sep='\n'):
    """Get selective formatted flash messages

    :param category: category
    :param sep: separator for multiple messages
    """
    if not category:
        return sep.join(get_flashed_messages())
    return sep.join([m for k, m in get_flashed_messages(with_categories=True) if k == category])
예제 #14
0
def make_cache_key(*args, **kwargs):
    path = request.path
    lang = g.locale
    cache_key = (path + lang).encode('utf-8')
    
    if get_flashed_messages():
        msgs = "|".join([msg[0] for msg in get_flashed_messages(with_categories=True)])
        cache_key += "/"+msgs
    
    return cache_key
예제 #15
0
 def test():
     messages = flask.get_flashed_messages(with_categories=True)
     self.assert_equal(len(messages), 3)
     self.assert_equal(messages[0], ("message", u"Hello World"))
     self.assert_equal(messages[1], ("error", u"Hello World"))
     self.assert_equal(messages[2], ("warning", flask.Markup(u"<em>Testing</em>")))
     return ""
     messages = flask.get_flashed_messages()
     self.assert_equal(len(messages), 3)
     self.assert_equal(messages[0], u"Hello World")
     self.assert_equal(messages[1], u"Hello World")
     self.assert_equal(messages[2], flask.Markup(u"<em>Testing</em>"))
예제 #16
0
 def test():
     messages = flask.get_flashed_messages(with_categories=True)
     assert len(messages) == 3
     assert messages[0] == ('message', u'Hello World')
     assert messages[1] == ('error', u'Hello World')
     assert messages[2] == ('warning', flask.Markup(u'<em>Testing</em>'))
     return ''
     messages = flask.get_flashed_messages()
     assert len(messages) == 3
     assert messages[0] == u'Hello World'
     assert messages[1] == u'Hello World'
     assert messages[2] == flask.Markup(u'<em>Testing</em>')
예제 #17
0
 def test():
     messages = flask.get_flashed_messages(with_categories=True)
     self.assert_equal(len(messages), 3)
     self.assert_equal(messages[0], ('message', u'Hello World'))
     self.assert_equal(messages[1], ('error', u'Hello World'))
     self.assert_equal(messages[2], ('warning', flask.Markup(u'<em>Testing</em>')))
     return ''
     messages = flask.get_flashed_messages()
     self.assert_equal(len(messages), 3)
     self.assert_equal(messages[0], u'Hello World')
     self.assert_equal(messages[1], u'Hello World')
     self.assert_equal(messages[2], flask.Markup(u'<em>Testing</em>'))
예제 #18
0
파일: flask_tests.py 프로젝트: smalls/flask
 def test():
     messages = flask.get_flashed_messages(with_categories=True)
     assert len(messages) == 3
     assert messages[0] == ("message", u"Hello World")
     assert messages[1] == ("error", u"Hello World")
     assert messages[2] == ("warning", flask.Markup(u"<em>Testing</em>"))
     return ""
     messages = flask.get_flashed_messages()
     assert len(messages) == 3
     assert messages[0] == u"Hello World"
     assert messages[1] == u"Hello World"
     assert messages[2] == flask.Markup(u"<em>Testing</em>")
예제 #19
0
파일: memes.py 프로젝트: findgriffin/hactar
def api_meme(meme):
    """Handle meme requests through the api"""
    if request.method == 'GET':
        first = get_meme(meme)
        return jsonify(first.dictify())
    elif request.method == 'DELETE':
        delete_meme(meme)

        return jsonify({meme: u'deleted', 'flashes': get_flashed_messages()})
    else:
        updated = update_content(meme)
        resp = {meme: updated.dictify(), 'flashes': get_flashed_messages()}
        return jsonify(resp)
예제 #20
0
    def post(self):
    #----------------------------------------------------------------------
        '''
        update user settings
        '''
        try:
            # get the user from the database
            userid = flask.session['user_id']
            thisuser = racedb.User.query.filter_by(id=userid).first()
        
            pagename = 'User Settings'
            buttontext = 'Update'
            successtext = '{} updated'.format(thisuser.name)
            displayonly = False
        
            # create the form
            form = UserSettingsForm(email=thisuser.email, name=thisuser.name)
            form.hidden_userid.data = userid
        
            # 
            if form.validate_on_submit():
                flask.get_flashed_messages()    # clears flash queue
    
                # action and commit requested
                if flask.request.form['whichbutton'] == buttontext:
                    thisuser.email = form.email.data
                    thisuser.name = form.name.data
                    if form.password.data:
                        thisuser.set_password(form.password.data)

                    # commit database updates and close transaction
                    db.session.commit()
                    return flask.redirect(flask.request.args.get('next') or flask.url_for('index'))
                
                # cancel requested - note changes may have been made in url_for('updatepermissions') which need to be rolled back
                # TODO: get rid of this???  It should not work
                elif flask.request.form['whichbutton'] == 'Cancel':
                    db.session.rollback() # throw out any changes which have been made
                    return flask.redirect(flask.request.args.get('next') or flask.url_for('index'))
        
            # commit database updates and close transaction
            db.session.commit()
            return (flask.redirect(flask.request.args.get('next')) or flask.url_for('index'))
            
        except Exception,e:
            # roll back database updates and close transaction
            db.session.rollback()
            cause = 'Unexpected Error: {}\n{}'.format(e,traceback.format_exc())
            flask.flash(cause)
            app.logger.error(traceback.format_exc())
            raise
예제 #21
0
	def am_i_ok(self):					#do a self_examination, generate errors
								# for each field, if ok, f.value_clean <= f.dtyp(f.value_raw) 
		get_flashed_messages()				#clear any flash errors
		field_labels = self._field_labels()
		return (
			all(
				[self._field_ok(field, 
						lambda error: flash(error, 'error')) 	# true if not error
					for field in self.fields] +
				[self._validator_ok( f_invalid,
						lambda error: flash(error % field_labels, 'error'))
					for f_invalid in self.validators]
				)
			)
예제 #22
0
    def gen_key(**kwargs):
        path = request.path
        lang = g.locale
        reqstr = ""
        if request.args:
            for k,v in request.args.items():
                reqstr += "&{}={}".format(str(k), str(v))
        key = namespace + ":" + path + lang + reqstr
        cache_key = key.encode('utf-8')

        if get_flashed_messages():
            msgs = "|".join([msg[0] for msg in get_flashed_messages(with_categories=True)])
            cache_key += "/"+msgs

        return cache_key
예제 #23
0
 def get(self):
     if (current_app.config.get('TESTING', True) or
        current_user.is_authenticated()):
         return redirect(url_for('home'))
     context = {'messages': get_flashed_messages(),
                'username': session.pop('username', '')}
     return make_response(render_template('login.html', **context))
예제 #24
0
def index():
    username = session.get('username')
    if not username:
        return redirect(url_for('login'))
    payments = bank.get_payments_of(bank.open_database(), username)
    return render_template('index.html', payments=payments, username=username,
                           flash_messages=get_flashed_messages())
예제 #25
0
파일: test_basic.py 프로젝트: LianYun/flask
 def test_filters2():
     messages = flask.get_flashed_messages(
         category_filter=['message', 'warning'])
     assert len(messages) == 2
     assert messages[0] == u'Hello World'
     assert messages[1] == flask.Markup(u'<em>Testing</em>')
     return ''
예제 #26
0
파일: basic.py 프로젝트: 005/flask
 def test():
     messages = flask.get_flashed_messages()
     self.assert_equal(len(messages), 3)
     self.assert_equal(messages[0], u'Hello World')
     self.assert_equal(messages[1], u'Hello World')
     self.assert_equal(messages[2], flask.Markup(u'<em>Testing</em>'))
     return ''
예제 #27
0
def clear_flashed_messages():
    """
    Clear pending flashed messages. This is useful when redirecting the user to a
    remote site where they cannot see the messages. If they return much later,
    they could be confused by a message for an action they do not recall.
    """
    list(get_flashed_messages())
예제 #28
0
def login_message(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.login_message = u"Log in or the owl will eat you."
    lm.setup_app(app)
    lm.unauthorized()
    assert u"Log in or the owl will eat you." in get_flashed_messages()
예제 #29
0
def get_flashed_messages_except(with_categories=False, category_exclude_filter=[]):
    all_messages = get_flashed_messages(with_categories=True)
    filtered_messages = filter(lambda (c, m): c not in category_exclude_filter, all_messages)
    if with_categories:
        return filtered_messages
    else:
        return [message for category, message in filtered_messages]
예제 #30
0
파일: util.py 프로젝트: fiorda/pybossa
def last_flashed_message():
    """Return last flashed message by flask."""
    messages = get_flashed_messages(with_categories=True)
    if len(messages) > 0:
        return messages[-1]
    else:
        return None
예제 #31
0
def handle_csrf_error(e):
    current_app.logger.error(f"{e.description}")
    if gettext(u'CSRF error.') not in get_flashed_messages(
            category_filter=('fail', )):
        flash(gettext(u'CSRF error.'), 'fail')
    return redirect(request.url, code=400)
예제 #32
0
 def test_filter():
     messages = flask.get_flashed_messages(category_filter=['message'],
                                           with_categories=True)
     self.assert_equal(len(messages), 1)
     self.assert_equal(messages[0], ('message', u'Hello World'))
     return ''
예제 #33
0
파일: app.py 프로젝트: willianflasky/growup
def test2():
    # 将test1存入的参数在这里取到
    messages = get_flashed_messages()
    print(messages)
    return "test2"
예제 #34
0
 def render(self):
     htm = u'<ul class="messages">'
     for message in get_flashed_messages():
         htm += '<li>%s</li>' % message
     htm += '</ul>'
     return htm
예제 #35
0
def register():
    return render_template('/auth/register.html',
                           form=UserRegister(),
                           title="Register",
                           error=get_flashed_messages())
예제 #36
0
def index():
    messages = get_flashed_messages()
    print(messages)
    results = db[ALBUMS].find({})
    return render_template("index.html", data = results)
예제 #37
0
    def test_login_view(self):
        self.create_users()

        with self.flask_app.test_client() as c:
            resp = c.get('/accounts/login/')
            self.assertEqual(resp.status_code, 200)

            # check that we have no logged-in user
            self.assertContext('user', None)

            frm = self.get_context('form')
            self.assertTrue(isinstance(frm, LoginForm))
            self.assertEqual(frm.data, {'username': None, 'password': None})

            # make a post missing the username
            resp = c.post('/accounts/login/',
                          data={
                              'username': '',
                              'password': '******',
                          })
            self.assertEqual(resp.status_code, 200)

            # check form for errors
            frm = self.get_context('form')
            self.assertEqual(frm.errors,
                             {'username': [u'This field is required.']})

            # check that no messages were generated
            self.assertFalse('_flashes' in session)

            # check that the auth API does not indicate a logged-in user
            self.assertEqual(auth.get_logged_in_user(), None)

            # make a post with a bad username/password combo
            resp = c.post('/accounts/login/',
                          data={
                              'username': '******',
                              'password': '******',
                          })
            self.assertEqual(resp.status_code, 200)

            # both fields were present so no form errors, but flash the user
            # indicating bad username/password combo
            self.assertTrue('_flashes' in session)
            messages = get_flashed_messages()

            self.assertEqual(messages, [
                'Incorrect username or password',
            ])

            # check that the auth API does not indicate a logged-in user
            self.assertEqual(auth.get_logged_in_user(), None)

            # make a post with an inactive user
            resp = c.post('/accounts/login/',
                          data={
                              'username': '******',
                              'password': '******',
                          })
            self.assertEqual(resp.status_code, 200)

            # still no logged-in user
            self.assertContext('user', None)

            # check that the auth API does not indicate a logged-in user
            self.assertEqual(auth.get_logged_in_user(), None)

            # finally post as a known good user
            resp = c.post('/accounts/login/',
                          data={
                              'username': '******',
                              'password': '******',
                          })
            self.assertEqual(resp.status_code, 302)

            # check that we now have a logged-in user
            self.assertEqual(auth.get_logged_in_user(), self.normal)
예제 #38
0
def entries():
    show = request.args.get('show', 'unread')
    read = {'all': None, 'unread': False, 'read': True}[show]

    has_enclosures = request.args.get('has-enclosures')
    has_enclosures = {None: None, 'no': False, 'yes': True}[has_enclosures]

    important = request.args.get('important')
    important = {None: None, 'no': False, 'yes': True}[important]

    if not request.args.get('q'):
        sort = request.args.get('sort', 'recent')
        assert sort in ('recent', 'random')
    else:
        sort = request.args.get('sort', 'relevant')
        assert sort in ('relevant', 'recent', 'random')

    reader = get_reader()

    feed_url = request.args.get('feed')
    feed = None
    feed_tags = None
    if feed_url:
        feed = reader.get_feed(feed_url, None)
        if not feed:
            abort(404)
        feed_tags = list(reader.get_feed_tags(feed))

    args = request.args.copy()
    query = args.pop('q', None)
    if query is None:

        def get_entries(**kwargs):
            yield from reader.get_entries(sort=sort, **kwargs)

        get_entry_counts = reader.get_entry_counts

    elif not query:
        # if the query is '', it's not a search
        args.pop('sort', None)
        return redirect(url_for('.entries', **args))

    else:

        def get_entries(**kwargs):
            for sr in reader.search_entries(query, sort=sort, **kwargs):
                yield EntryProxy(sr, reader.get_entry(sr))

        def get_entry_counts(**kwargs):
            return reader.search_entry_counts(query, **kwargs)

    # TODO: render the actual search result, not the entry
    # TODO: catch and flash syntax errors
    # TODO: don't show search box if search is not enabled

    error = None

    # TODO: duplicated from feeds()
    tags_str = tags = args.pop('tags', None)
    if tags is None:
        pass
    elif not tags.strip():
        # if tags is '', it's not a tag filter
        return redirect(url_for('.entries', **args))
    else:

        try:
            tags = yaml.safe_load(tags)
        except yaml.YAMLError as e:
            error = f"invalid tag query: invalid YAML: {e}: {tags_str}"
            return stream_template(
                'entries.html', feed=feed, feed_tags=feed_tags, error=error
            )

    kwargs = dict(
        feed=feed_url,
        read=read,
        has_enclosures=has_enclosures,
        important=important,
        feed_tags=tags,
    )
    entries = get_entries(**kwargs, limit=request.args.get('limit', type=int))

    with_counts = request.args.get('counts')
    with_counts = {None: None, 'no': False, 'yes': True}[with_counts]
    counts = get_entry_counts(**kwargs) if with_counts else None

    try:
        first = next(entries)
        entries = itertools.chain([first], entries)
    except StopIteration:
        pass
    except InvalidSearchQueryError as e:
        error = f"invalid search query: {e}"
    except ValueError as e:
        # TODO: there should be a better way of matching this kind of error
        if 'tag' in str(e).lower():
            error = f"invalid tag query: {e}: {tags_str}"
        else:
            raise

    entries = list(entries)

    entries_data = None
    if feed_url:
        entries_data = [e.id for e in entries]

    # Ensure flashed messages get removed from the session,
    # otherwise they keep adding up and never disappear.
    # Assumes the template will call get_flashed_messages() at some point.
    # https://github.com/lemon24/reader/issues/81
    get_flashed_messages()

    return stream_template(
        'entries.html',
        entries=entries,
        feed=feed,
        feed_tags=feed_tags,
        entries_data=entries_data,
        error=error,
        counts=counts,
    )
예제 #39
0
def user():
    v = get_flashed_messages()
    print(v)
    return "from user : %s" % v
예제 #40
0
def posts():
    return render_template('/admin/posts.html',
                           posts=Post().fetch_all(),
                           message=get_flashed_messages())
예제 #41
0
def category_page():
    return render_template('/admin/categories.html',
                           cat=Category().fetch_all(),
                           form=CreateCategory(),
                           message=get_flashed_messages())
예제 #42
0
def dashboard():
    return render_template('/admin/dashboard.html',
                           message=get_flashed_messages())
예제 #43
0
def index():
    res = ''
    for msg in get_flashed_messages():
        res = res + msg + '<br>'
    res += 'hello'
    return res
예제 #44
0
def show2():
    return get_flashed_messages(category_filter='show2').__str__()
예제 #45
0
def render(**context):
    if request.is_xhr:
        context['messages'] = get_flashed_messages()
        return json.dumps(context)

    return render_template('index.html', **context)
예제 #46
0
def get_recommendation(id):
    title = get_flashed_messages()[0]
    neighbours = find_neighbours(id)
    return render_template('recommendation_page.html', title=title, id_list1=neighbours[:len(neighbours)//2],
                           id_list2=neighbours[len(neighbours)//2:], name_list=name_list, link_list=link_list)
예제 #47
0
def get_grouped_flashes():
    msgs = get_flashed_messages(with_categories=True)
    groups = defaultdict(list)
    for group, msg in msgs:
        groups[group].append(msg)
    return groups
예제 #48
0
def index():
    flash_messages = get_flashed_messages(with_categories=True)
    staticfile = url_for('static', filename="wall.css")
    return render_template("index.html", 
            messages = flash_messages, 
            styles = staticfile)
예제 #49
0
def addBoxFunction():

    # Force flash() to get the messages on the same page as the redirect.
    get_flashed_messages()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Get variable
        name = request.form.get("name")
        length = request.form.get("length")
        width = request.form.get("width")
        height = request.form.get("height")
        weight_ne = request.form.get("weight_ne")
        weight_ex = request.form.get("weight_ex")
        price_de = request.form.get("price_de")
        price_eu = request.form.get("price_eu")
        price_ex = request.form.get("price_ex")

        # Check length
        getInputLength(name, 100, "Name is too long (100)", "danger",
                       "/addBox")
        getInputLength(length, 6, "Length is too big (6)", "danger", "/addBox")
        getInputLength(width, 6, "Width is too big (6)", "danger", "/addBox")
        getInputLength(height, 6, "Height is too big (6)", "danger", "/addBox")
        getInputLength(weight_ne, 6, "Weight non-express is too big (6)",
                       "danger", "/addBox")
        getInputLength(weight_ex, 6, "Weight express is too big (6)", "danger",
                       "/addBox")
        getInputLength(price_de, 6, "Price for DE is too big (6)", "danger",
                       "/addBox")
        getInputLength(price_eu, 6, "Price for EU is too big (6)", "danger",
                       "/addBox")
        getInputLength(price_ex, 6, "Price for Express is too big (6)",
                       "danger", "/addBox")

        # Ensure the box name was submitted
        if not name:
            flash("must provide box name", "warning")
            return redirect("/addBox")

        # Ensure the box name fits server-side
        if not re.search("^[a-zA-Z 0-9]{1,100}$", name):
            flash("Invalid box name", "danger")
            return redirect("/addBox")

        # Ensure the box length was submitted
        if not length:
            flash("must provide box length", "warning")
            return redirect("/addBox")

        # Ensure the box length fits server-side
        if not re.search("^[0-9]+$", length):
            flash("Invalid box length", "danger")
            return redirect("/addBox")

        # Ensure the box width was submitted
        if not width:
            flash("must provide box width", "warning")
            return redirect("/addBox")

        # Ensure the box width fits server-side
        if not re.search("^[0-9]+$", width):
            flash("Invalid box width", "danger")
            return redirect("/addBox")

        # Ensure the box height was submitted
        if not height:
            flash("must provide box height", "warning")
            return redirect("/addBox")

        # Ensure the box height fits server-side
        if not re.search("^[0-9]+$", height):
            flash("Invalid box height", "danger")
            return redirect("/addBox")

        # Ensure the box weight_ne was submitted
        if not weight_ne:
            flash("must provide box weight non-express", "warning")
            return redirect("/addBox")

        # Ensure the box weight_ne fits server-side
        if not re.search("^[0-9]+$", weight_ne):
            flash("Invalid box weight non-express", "danger")
            return redirect("/addBox")

        # Ensure the box weight_ex was submitted
        if not weight_ex:
            flash("must provide box weight express", "warning")
            return redirect("/addBox")

        # Ensure the box weight_ex fits server-side
        if not re.search("^[0-9]+$", weight_ex):
            flash("Invalid box weight express", "danger")
            return redirect("/addBox")

        # Ensure the box price in DE was submitted
        if not price_de:
            flash("must provide box price in DE", "warning")
            return redirect("/addBox")

        # Ensure the box price in DE fits server-side
        if not re.search("^[0-9]+\.?[0-9]+$", format(float(price_de), ".2f")):
            flash("Invalid box price in DE", "danger")
            return redirect("/addBox")

        # Ensure the box price in EU was submitted
        if not price_eu:
            flash("must provide box price in EU", "warning")
            return redirect("/addBox")

        # Ensure the box price in EU fits server-side
        if not re.search("^[0-9]+\.?[0-9]+$", format(float(price_eu), ".2f")):
            flash("Invalid box price in EU", "danger")
            return redirect("/addBox")

        # Ensure the box express price was submitted
        if not price_ex:
            flash("must provide box express price", "warning")
            return redirect("/addBox")

        # Ensure the box express price fits server-side
        if not re.search("^[0-9]+\.?[0-9]+$", format(float(price_ex), ".2f")):
            flash("Invalid box express price", "danger")
            return redirect("/addBox")

        # Insert box name, length, width, height, price DE, price EU and price EX into the table
        db.session.add(
            Boxes(name=name,
                  length=length,
                  width=width,
                  height=height,
                  weight_ne=weight_ne,
                  weight_ex=weight_ex,
                  price_de=price_de,
                  price_eu=price_eu,
                  price_ex=price_ex))
        db.session.commit()

        # Flash result & redirect
        flash("Box added", "success")
        return redirect("/administration")

    else:

        return render_template("addBox.html",
                               name=getUserName(),
                               picture=getUserPicture(),
                               role=getUserRole())
예제 #50
0
def regloginpage():
    msg = ''
    for m in get_flashed_messages(with_categories=False,
                                  category_filter=['reglogin']):
        msg = msg + m
    return render_template('login.html', msg=msg)
예제 #51
0
 def test_with(self):
     with self.client:
         self.client.get('/user/member')
         ms = get_flashed_messages()
         assert len(ms) == 1
         assert ms[0].startswith('You must be signed in to access ')
예제 #52
0
 def messages():
     return jsonify(get_flashed_messages(True))
예제 #53
0
 def test_filters2():
     messages = flask.get_flashed_messages(category_filter=['message', 'warning'])
     self.assert_equal(len(messages), 2)
     self.assert_equal(messages[0], u'Hello World')
     self.assert_equal(messages[1], flask.Markup(u'<em>Testing</em>'))
     return ''
예제 #54
0
def login():
    return render_template('/auth/login.html',
                           form=UserRegister(),
                           title="Login",
                           error=get_flashed_messages())
예제 #55
0
# Returns a response object (a WSGI application) that, if called, redirects the client to the target location.
flask.redirect(location, code=302, Response=None)
# example:
@app.route('/')
def test():
    return flask.redirect('/index')     
    # note: if the return value is string, it will return to the client. if it's callable object, it will be called and return the result to client

flask.flash(message, category='message')
# Flashes a message to the next request. 
# In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages().
# category – the category for the message. 
    # The following values are recommended: 'message' for any kind of message, 'error' for errors, 'info' for information messages and 'warning' for warnings. However any kind of string can be used as category.

flask.get_flashed_messages(with_categories=False, category_filter=[])
# Pulls all flashed messages from the session and returns them. return a list.
# Further calls in the same request to the function will return the same messages.
# By default just the messages are returned.
# but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead.


flask.render_template(template_file, **context)
# Renders a template from the template folder with the given context.
# template_name – the name of the template to be rendered
# context – the variables that should be available in the context of the template.
# example:
# flask.render_template('test.html', llll = 'llll', wwww = 'wwwww')
# here is test.html
# <html><body><p>llll is {{llll}} and wwww is {{wwww}}</p></body></html>
예제 #56
0
def save_flashed_messages():
    """
    Save flashed messages so they can be relayed back to trusted clients.
    """
    for index, (category, message) in enumerate(get_flashed_messages(with_categories=True)):
        db.session.add(UserFlashMessage(user=g.user, seq=index, category=category, message=message))
예제 #57
0
def create_post():
    return render_template('/admin/create-post.html',
                           form=CreatePost(),
                           message=get_flashed_messages())
예제 #58
0
def index():
    res = ''
    for msg, category in get_flashed_messages(with_categories=True):
        res = res + category + msg + '<br>haha'
    res += 'hello'
    return res
예제 #59
0
def create_book():
    return render_template('/admin/create-book.html',
                           form=CreateBook(),
                           message=get_flashed_messages())
예제 #60
0
 def test_filter():
     messages = flask.get_flashed_messages(category_filter=['message'],
                                           with_categories=True)
     assert list(messages) == [('message', u'Hello World')]
     return ''