这个 Flask 代码中的 g 对象是什么? [英] What is the g object in this Flask code?

查看:30
本文介绍了这个 Flask 代码中的 g 对象是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这段代码对每个响应进行计时,但我不确定 g 应该来自哪里.什么是g?

I found this code that times each response, but I'm not sure where g is supposed to come from. What is g?

@app.before_request
def before_request():
  g.start = time.time()

@app.teardown_request
def teardown_request(exception=None):
    diff = time.time() - g.start
    print diff

推荐答案

g 是 Fl​​ask 提供的一个对象.它是一个全局命名空间,用于在单个应用程序上下文中保存您想要的任何数据.例如,before_request 处理程序可以设置 g.user,它可以被路由和其他函数访问.

g is an object provided by Flask. It is a global namespace for holding any data you want during a single app context. For example, a before_request handler could set g.user, which will be accessible to the route and other functions.

from flask import g

@app.before_request
def load_user():
    user = User.query.get(request.session.get("user_id"))
    g.user = user

@app.route("/admin")
def admin():
    if g.user is None or not g.user.is_admin:
        return redirect(url_for("index"))

一个应用上下文持续一个请求/响应周期,g 不适合跨请求存储数据.使用数据库、redis、会话或其他外部数据源来持久化数据.

An app context lasts for one request / response cycle, g is not appropriate for storing data across requests. Use a database, redis, the session, or another external data source for persisting data.

请注意,开发服务器和任何 Web 服务器都会在日志中输出计时信息.如果您真的想分析您的代码,您可以使用 Werkzeug 应用程序分析器.

Note that the dev server and any web server will output timing information in the logs already. If you really want to profile your code, you can use the Werkzeug application profiler.

这篇关于这个 Flask 代码中的 g 对象是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆