Python flask 模块,g() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用flask.g()

项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:hotface    作者:linhanqiuinc24    | 项目源码 | 文件源码
def login():
    """Logs the user in."""
    if current_user is not None and current_user.is_authenticated:
        return redirect_or_next(url_for("forum.index"))

    current_limit = getattr(g, 'view_rate_limit', None)
    login_recaptcha = False
    if current_limit is not None:
        window_stats = limiter.limiter.get_window_stats(*current_limit)
        stats_diff = flaskbb_config["AUTH_REQUESTS"] - window_stats[1]
        login_recaptcha = stats_diff >= flaskbb_config["LOGIN_RECAPTCHA"]

    form = LoginForm(request.form)
    if form.validate_on_submit():
        try:
            user = User.authenticate(form.login.data, form.password.data)
            login_user(user, remember=form.remember_me.data)
            return redirect_or_next(url_for("forum.index"))
        except AuthenticationError:
            flash(_("Wrong username or password."), "danger")

    return render_template("auth/login.html", form=form,
                           login_recaptcha=login_recaptcha)
项目:hotface    作者:linhanqiuinc24    | 项目源码 | 文件源码
def login():
    """Logs the user in."""
    if current_user is not None and current_user.is_authenticated:
        return redirect_or_next(url_for("forum.index"))

    current_limit = getattr(g, 'view_rate_limit', None)
    login_recaptcha = False
    if current_limit is not None:
        window_stats = limiter.limiter.get_window_stats(*current_limit)
        stats_diff = flaskbb_config["AUTH_REQUESTS"] - window_stats[1]
        login_recaptcha = stats_diff >= flaskbb_config["LOGIN_RECAPTCHA"]

    form = LoginForm(request.form)
    if form.validate_on_submit():
        try:
            user = User.authenticate(form.login.data, form.password.data)
            login_user(user, remember=form.remember_me.data)
            return redirect_or_next(url_for("forum.index"))
        except AuthenticationError:
            flash(_("Wrong username or password."), "danger")

    return render_template("auth/login.html", form=form,
                           login_recaptcha=login_recaptcha)
项目:pubchem-ranker    作者:jacobwindsor    | 项目源码 | 文件源码
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def test_url_processors(self):
        app = flask.Flask(__name__)

        @app.url_defaults
        def add_language_code(endpoint, values):
            if flask.g.lang_code is not None and \
               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
                values.setdefault('lang_code', flask.g.lang_code)

        @app.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code', None)

        @app.route('/<lang_code>/')
        def index():
            return flask.url_for('about')

        @app.route('/<lang_code>/about')
        def about():
            return flask.url_for('something_else')

        @app.route('/foo')
        def something_else():
            return flask.url_for('about', lang_code='en')

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/foo')
        self.assert_equal(c.get('/foo').data, b'/en/about')
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)
项目:flask-vue-example    作者:levi-lq    | 项目源码 | 文件源码
def require(self, func):
        @wraps(func)
        def _decorator(*args, **kwargs):
            if hasattr(g, "identity") and g.identity.can(self):
                return func(*args, **kwargs)
            else:
                return {"status": "failure", "result": {"error": u"????????"}}, 403
        return _decorator
项目:plexivity    作者:mutschler    | 项目源码 | 文件源码
def get_locale():
    # if a user is logged in, use the locale from the user settings
    user = getattr(g, 'user', None)
    if user is not None and hasattr(user, "locale"):
        return user.locale

    translations = [str(translation) for translation in babel.list_translations()]
    return request.accept_languages.best_match(translations)
项目:plexivity    作者:mutschler    | 项目源码 | 文件源码
def get_timezone():
    user = getattr(g, 'user', None)
    if user is not None:
        return user.timezone
项目:microcosm-flask    作者:globality-corp    | 项目源码 | 文件源码
def register_session_factory(graph, key, session_factory):
    """
    Register a session creation function so that a new session (of user-defined type)
    will be saved to `flask.g` on every request (and closed on teardown).

    In other words: this os a mechanism to register a SQLAlchemy session instance
    or similar without coupling the web and database tiers directly.

    The session function should have the signature:

        def session_factory(graph):
            return Session()

    If the session instance is closeable, it will be closed on teardown.

    """
    @graph.flask.before_request
    def begin_session():
        setattr(g, key, session_factory(graph))

    @graph.flask.teardown_request
    def end_session(*args, **kwargs):
        # NB: session will be none if there's an error raised in `before_request`
        session = getattr(g, key, None)
        if session is not None and hasattr(session, "close"):
            session.close()
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def test_url_processors(self):
        app = flask.Flask(__name__)

        @app.url_defaults
        def add_language_code(endpoint, values):
            if flask.g.lang_code is not None and \
               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
                values.setdefault('lang_code', flask.g.lang_code)

        @app.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code', None)

        @app.route('/<lang_code>/')
        def index():
            return flask.url_for('about')

        @app.route('/<lang_code>/about')
        def about():
            return flask.url_for('something_else')

        @app.route('/foo')
        def something_else():
            return flask.url_for('about', lang_code='en')

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/foo')
        self.assert_equal(c.get('/foo').data, b'/en/about')
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)
项目:osm-wikidata    作者:EdwardBetts    | 项目源码 | 文件源码
def get_username():
    if hasattr(g, 'user'):
        if g.user.is_authenticated:
            user = g.user.username
        else:
            user = 'not authenticated'
    else:
        user = 'no user'

    return user
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
def test_url_processors(self):
        app = flask.Flask(__name__)

        @app.url_defaults
        def add_language_code(endpoint, values):
            if flask.g.lang_code is not None and \
               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
                values.setdefault('lang_code', flask.g.lang_code)

        @app.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code', None)

        @app.route('/<lang_code>/')
        def index():
            return flask.url_for('about')

        @app.route('/<lang_code>/about')
        def about():
            return flask.url_for('something_else')

        @app.route('/foo')
        def something_else():
            return flask.url_for('about', lang_code='en')

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/foo')
        self.assert_equal(c.get('/foo').data, b'/en/about')
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)
项目:isni-reconcile    作者:cmh2166    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:isni-reconcile    作者:cmh2166    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:isni-reconcile    作者:cmh2166    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:isni-reconcile    作者:cmh2166    | 项目源码 | 文件源码
def test_url_processors(self):
        app = flask.Flask(__name__)

        @app.url_defaults
        def add_language_code(endpoint, values):
            if flask.g.lang_code is not None and \
               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
                values.setdefault('lang_code', flask.g.lang_code)

        @app.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code', None)

        @app.route('/<lang_code>/')
        def index():
            return flask.url_for('about')

        @app.route('/<lang_code>/about')
        def about():
            return flask.url_for('something_else')

        @app.route('/foo')
        def something_else():
            return flask.url_for('about', lang_code='en')

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/foo')
        self.assert_equal(c.get('/foo').data, b'/en/about')
项目:isni-reconcile    作者:cmh2166    | 项目源码 | 文件源码
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def test_url_processors(self):
        app = flask.Flask(__name__)

        @app.url_defaults
        def add_language_code(endpoint, values):
            if flask.g.lang_code is not None and \
               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
                values.setdefault('lang_code', flask.g.lang_code)

        @app.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code', None)

        @app.route('/<lang_code>/')
        def index():
            return flask.url_for('about')

        @app.route('/<lang_code>/about')
        def about():
            return flask.url_for('something_else')

        @app.route('/foo')
        def something_else():
            return flask.url_for('about', lang_code='en')

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/foo')
        self.assert_equal(c.get('/foo').data, b'/en/about')
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_url_processors(self):
        app = flask.Flask(__name__)

        @app.url_defaults
        def add_language_code(endpoint, values):
            if flask.g.lang_code is not None and \
               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
                values.setdefault('lang_code', flask.g.lang_code)

        @app.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code', None)

        @app.route('/<lang_code>/')
        def index():
            return flask.url_for('about')

        @app.route('/<lang_code>/about')
        def about():
            return flask.url_for('something_else')

        @app.route('/foo')
        def something_else():
            return flask.url_for('about', lang_code='en')

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/foo')
        self.assert_equal(c.get('/foo').data, b'/en/about')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)
项目:fallball-connector    作者:ingrammicro    | 项目源码 | 文件源码
def filter(self, record):
        record.reseller_name = str(getattr(g, 'reseller_name', None))
        return True
项目:fallball-connector    作者:ingrammicro    | 项目源码 | 文件源码
def log_response(response):
    if response.content_type == 'application/json':
        try:
            data = json.loads(response.data)
        except:
            data = response.data.decode()
    else:
        data = response.data.decode()

    return {"type": "response",
            "app": "fallball_connector",
            "status_code": response.status_code,
            "status": response.status,
            "headers": parse_headers(response.headers),
            "time": datetime.datetime.now().isoformat(' '),
            "data": data,
            "company": getattr(g, 'company_name', None)}
项目:craftbeerpi3    作者:Manuel83    | 项目源码 | 文件源码
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected')
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
def test_before_request_and_routing_errors(self):
        app = flask.Flask(__name__)
        @app.before_request
        def attach_something():
            flask.g.something = 'value'
        @app.errorhandler(404)
        def return_something(error):
            return flask.g.something, 404
        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, b'value')
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
def test_request_locals(self):
        self.assert_equal(repr(flask.g), '<LocalProxy unbound>')
        self.assertFalse(flask.g)
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
def test_url_processors(self):
        app = flask.Flask(__name__)

        @app.url_defaults
        def add_language_code(endpoint, values):
            if flask.g.lang_code is not None and \
               app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
                values.setdefault('lang_code', flask.g.lang_code)

        @app.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code', None)

        @app.route('/<lang_code>/')
        def index():
            return flask.url_for('about')

        @app.route('/<lang_code>/about')
        def about():
            return flask.url_for('something_else')

        @app.route('/foo')
        def something_else():
            return flask.url_for('about', lang_code='en')

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/foo')
        self.assert_equal(c.get('/foo').data, b'/en/about')