How to use the flask.g function in Flask

To help you get started, we’ve selected a few Flask examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CCExtractor / sample-platform / mod_test / controllers.py View on Github external
def stop_test(test_id):
    """
    Admin or Test User can stop the running test.

    :param test_id: Test ID of the test which user want to stop
    :type test_id: int
    """
    test = Test.query.filter(Test.id == test_id).first()
    test_fork = TestFork.query.filter(TestFork.user_id == g.user.id, TestFork.test_id == test_id).first()
    if not g.user.is_admin and test_fork is None:
        g.log.warning('user with id: {g.user.id} tried to access restricted endpoint')
        abort(403)
    message = "Canceled by user"
    if g.user.is_admin:
        message = "Canceled by admin"
    test_progress = TestProgress(test.id, TestStatus.canceled, message)
    g.db.add(test_progress)
    g.db.commit()
    g.log.info(f'test with id: {test_id} stopped')
    return redirect(url_for('.by_id', test_id=test.id))
github pallets / flask / tests / test_appctx.py View on Github external
def test_app_ctx_globals_methods(app, app_ctx):
    # get
    assert flask.g.get('foo') is None
    assert flask.g.get('foo', 'bar') == 'bar'
    # __contains__
    assert 'foo' not in flask.g
    flask.g.foo = 'bar'
    assert 'foo' in flask.g
    # setdefault
    flask.g.setdefault('bar', 'the cake is a lie')
    flask.g.setdefault('bar', 'hello world')
    assert flask.g.bar == 'the cake is a lie'
    # pop
    assert flask.g.pop('bar') == 'the cake is a lie'
    with pytest.raises(KeyError):
        flask.g.pop('bar')
    assert flask.g.pop('bar', 'more cake') == 'more cake'
    # __iter__
    assert list(flask.g) == ['foo']
github alerta / alerta / alerta / utils / logging.py View on Github external
def format(self, record):

        fmt = record.name.split('.').pop(0)
        if flask.has_request_context():
            record.request_id = g.request_id if hasattr(g, 'request_id') else '-'
            record.endpoint = request.endpoint
            record.method = request.method
            record.url = request.url
            record.reqargs = request.args
            record.data = request.get_data(as_text=True)
            record.remote_addr = request.remote_addr
            record.user = g.login if hasattr(g, 'login') else None
            fmt = 'request'

        formatter = logging.Formatter(self.formatters.get(fmt, self.default_formatter))
        return formatter.format(record)
github TkTech / notifico / notifico / views / account / forms.py View on Github external
def validate_password(form, field):
        if not User.login(g.user.username, field.data):
            raise wtf.ValidationError('Password is incorrect.')
github bluecatlabs / gateway-workflows / Certified / Text Record / update_text_record_example / update_text_record_example_page.py View on Github external
# Put form processing code here
            g.user.logger.info('Success - Text Record Modified - Object ID: ' + util.safe_str(text_record.get_id()))
            flash('Success - Text Record Modified - Object ID: ' + util.safe_str(text_record.get_id()), 'succeed')
            return redirect(url_for('update_text_record_exampleupdate_text_record_update_text_record_page'))

        except Exception as e:
            flash(util.safe_str(e))
            # Log error and render workflow page
            g.user.logger.warning('%s' % util.safe_str(e), msg_type=g.user.logger.EXCEPTION)
            form.txt_filter.data = ''
            form.name.data = ''
            form.text.data = ''
            return render_template('update_text_record_example_page.html',
                                   form=form,
                                   text=util.get_text(module_path(), config.language),
                                   options=g.user.get_options())

    else:
        g.user.logger.info('Form data was not valid.')
        form.txt_filter.data = ''
        form.name.data = ''
        form.text.data = ''
        return render_template('update_text_record_example_page.html',
                               form=form,
                               text=util.get_text(module_path(), config.language),
                               options=g.user.get_options())
github AUCR / AUCR / aucr_app / plugins / auth / routes.py View on Github external
def search():
    """AUCR search plugin flask blueprint."""
    if not g.search_form.validate():
        return redirect(url_for('auth.search'))
    page = request.args.get('page', 1, type=int) or 1
    posts, total = Message.search(g.search_form.q.data, page, int(current_app.config['POSTS_PER_PAGE']))
    search_messages, total = Message.search(g.search_form.q.data, page, int(current_app.config['POSTS_PER_PAGE']))
    next_url = url_for('auth.search', q=g.search_form.q.data, page=page + 1) \
        if total['value'] > page * int(current_app.config['POSTS_PER_PAGE']) else None
    prev_url = url_for('auth.search', q=g.search_form.q.data, page=page - 1) if page > 1 else None
    return render_template('search.html', title=_('auth.search'), messages=search_messages, next_url=next_url,
                           prev_url=prev_url, posts=posts, page=page)
github fredriko / metacurate-lexicon / src / models / api / views.py View on Github external
def post(self):
        result = []
        arguments = parser.parse_args()
        text = arguments["text"]
        text = text.strip()
        if len(text) > 0:
            sentences = split_and_tokenize(text)
            for sentence in sentences:
                result.append(list(g.metacurate_trigrams[g.metacurate_bigrams[sentence]]))
            return {"sentences": result}, 200
        else:
            api.abort(400, "No text to tokenize is specified in the request.")
github sunlightlabs / calloncongress / calloncongress / i18n.py View on Github external
query = {
        'lang': kwargs.get('language', get_lang(default=settings.DEFAULT_LANGUAGE)),
        'hash': hashlib.md5(s).hexdigest(),
    }
    if query.get('lang') == 'en':
        return s

    trans = g.db.translations.find_one(query)
    if trans:
        return trans['translation']
    else:
        try:
            trans = translator.translate(s, target=query.get('lang'))
            query.update(translation=trans.translatedText)
            s = query.get('translation')
            g.db.translations.save(query)
        except GTranslatorError:
            pass
    return s