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

查看:125
本文介绍了这个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 是Flask提供的对象.它是一个全局名称空间,用于保存单个应用程序上下文中所需的任何数据.例如,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天全站免登陆