Python Web Flask源码解读!模板渲染过程!

Flask Web开发_Github源代码 立即下载

关于我

编程界的一名小小程序猿,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是我们团队的主要技术栈。

Github: github.com/hylinux1024

微信公众号:angrycode

Python资源共享群:484031800

前面对 Flask 启动流程 和路由原理都进行了源码走读。今天我们看看 模板渲染 的过程。

0x00 使用模板

首先看一个来自官方文档使用模板渲染的例子

from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
复制代码

在项目目录下需要有一个 templates 目录,并创建了一个 hello.html 文件

/templates
    /hello.html
复制代码

hello.html 的内容为

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}
复制代码

这个模板中 name 是参数,通过调用 render_template 方法就可以根据参数实现 html 模板文件的渲染。

0x01 Flask.render_template

def render_template(template_name, **context):
    """Renders a template from the template folder with the given
    context.
    :param template_name: the name of the template to be rendered
    :param context: the variables that should be available in the
                    context of the template.
    """
    current_app.update_template_context(context)
    return current_app.jinja_env.get_template(template_name).render(context)
复制代码

方法的注释很清楚,从 templates 文件夹中找到名称为 template_name 的文件进行渲染。其中 current_app 是通过以下语句初始化

_request_ctx_stack = LocalStack()
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
复制代码

LocalStack 就是一个 栈的实现类 。而 _request_ctx_stack 是在 Flask.request_context() 方法中将当前的上下文实例 push 到栈里面的

def request_context(self, environ):
    """Creates a request context from the given environment and binds
    it to the current context.  This must be used in combination with
    the `with` statement because the request is only bound to the
    current context for the duration of the `with` block.
    Example usage::
        with app.request_context(environ):
            do_something_with(request)
    :params environ: a WSGI environment
    """
    return _RequestContext(self, environ)
复制代码

_RequestContext 类实现了上下文管理器协议,它可以在 with 语句中使用

class _RequestContext(object):
    """The request context contains all request relevant information.  It is
    created at the beginning of the request and pushed to the
    `_request_ctx_stack` and removed at the end of it.  It will create the
    URL adapter and request object for the WSGI environment provided.
    """
    def __init__(self, app, environ):
        self.app = app
        self.url_adapter = app.url_map.bind_to_environ(environ)
        self.request = app.request_class(environ)
        self.session = app.open_session(self.request)
        self.g = _RequestGlobals()
        self.flashes = None
    def __enter__(self):
        _request_ctx_stack.push(self)
    def __exit__(self, exc_type, exc_value, tb):
        # do not pop the request stack if we are in debug mode and an
        # exception happened.  This will allow the debugger to still
        # access the request object in the interactive shell.
        if tb is None or not self.app.debug:
            _request_ctx_stack.pop()
复制代码

执行 __enter__() 时操作 push ,退出 with 语句时就执行 pop 操作。

回到 request_context() 方法,它是在 wsgi_app() 中被调用的

def wsgi_app(self, environ, start_response):
    """The actual WSGI application.  This is not implemented in
    `__call__` so that middlewares can be applied:
        app.wsgi_app = MyMiddleware(app.wsgi_app)
    :param environ: a WSGI environment
    :param start_response: a callable accepting a status code,
                           a list of headers and an optional
                           exception context to start the response
    """
    with self.request_context(environ):
        rv = self.preprocess_request()
        if rv is None:
            rv = self.dispatch_request()
        response = self.make_response(rv)
        response = self.process_response(response)
        return response(environ, start_response)
复制代码

从路由原理文章的分析知道, wsgi_app() 在服务端接收到客户端请求时就会执行。 所以当请求来临时,就会把当前 Flask 实例的请求上下文实例保存到栈实例 _request_ctx_stack 中;请求处理后,就从栈里面弹出当前请求的上下文实例。

LocalProxy 是一个代理类,它的构造函数传递了一个 lambda 表达式: lambda: _request_ctx_stack.top.app 。 这个操作就把当前的上下文实例通过 LocalProxy 进行了封装,即 current_app 是当前 Flask 实例的上下文的代理。 所以当 current_app.jinja_env 这个语句其实就是访问 Flask 的实例属性 jinja_env ,这个属性是在 Flask 的构造函数中进行初始化的。

class Flask(object):
    ...
    #: 源码太长了省略
    #: options that are passed directly to the Jinja2 environment
    jinja_options = dict(
        autoescape=True,
        extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']
    )
    def __init__(self, package_name):
        ...
        #: 源码太长省略部分源码
        #: the Jinja2 environment.  It is created from the
        #: :attr:`jinja_options` and the loader that is returned
        #: by the :meth:`create_jinja_loader` function.
        self.jinja_env = Environment(loader=self.create_jinja_loader(),
                                     **self.jinja_options)
        self.jinja_env.globals.update(
            url_for=url_for,
            get_flashed_messages=get_flashed_messages
        )
复制代码

jinja_env 是一个 Environment 实例。 这个是 jinja 模板引擎提供的类, Flask 框架的模板渲染就是通过 jinja 来实现的。 Environment 需要一个 loader ,是通过以下方法获取的

def create_jinja_loader(self):
    """Creates the Jinja loader.  By default just a package loader for
    the configured package is returned that looks up templates in the
    `templates` folder.  To add other loaders it's possible to
    override this method.
    """
    if pkg_resources is None:
        return FileSystemLoader(os.path.join(self.root_path, 'templates'))
    return PackageLoader(self.package_name)
复制代码

默认情况下是从 templates 目录下构造一个 FileSystemLoader 的实例,这个类的作用就是从文件系统中加载模板文件的。

0x02 Environment.get_template

@internalcode
def get_template(self, name, parent=None, globals=None):
    """Load a template from the loader.  If a loader is configured this
    method ask the loader for the template and returns a :class:`Template`.
    If the `parent` parameter is not `None`, :meth:`join_path` is called
    to get the real template name before loading.
    The `globals` parameter can be used to provide template wide globals.
    These variables are available in the context at render time.
    If the template does not exist a :exc:`TemplateNotFound` exception is
    raised.
    .. versionchanged:: 2.4
       If `name` is a :class:`Template` object it is returned from the
       function unchanged.
    """
    if isinstance(name, Template):
        return name
    if parent is not None:
        name = self.join_path(name, parent)
    return self._load_template(name, self.make_globals(globals))
复制代码

get_template() 方法内部调用了 _load_template() 方法

@internalcode
def _load_template(self, name, globals):
    if self.loader is None:
        raise TypeError('no loader for this environment specified')
    if self.cache is not None:
        template = self.cache.get(name)
        if template is not None and (not self.auto_reload or \
                                     template.is_up_to_date):
            return template
    template = self.loader.load(self, name, globals)
    if self.cache is not None:
        self.cache[name] = template
    return template
复制代码

_load_template() 方法首先会检查是否有缓存,如果缓存可用就使用缓存;缓存不可用就使用 loader 加载模板,这个 loader 就是前面提到的 FileSystemLoader 的实例(默认情况下)。

0x03 BaseLoader.load

@internalcode
def load(self, environment, name, globals=None):
    ...
    # 省略部分源码
    return environment.template_class.from_code(environment, code, globals, uptodate)
复制代码

BaseLoader 是 FileSystemLoader 的基类。这个 load 方法实现了模板的编译、加载等逻辑。最后是使用 environment.template_class.from_code() 方法。其中 template_class 是 Template 类,它代表编译后的模板对象。 from_code 是 Template 类的静态方法,可以用来创建一个 Template 实例。当 load 方法返回时,就得到了一个 Template 对象。 最后回到 render_template 方法

def render_template(template_name, **context):
    ...
    return current_app.jinja_env.get_template(template_name).render(context)
复制代码

执行了 Template 对象的 render() 方法。

0x04 Template.render

def render(self, *args, **kwargs):
    """This function accepts either a dict or some keyword arguments which
    will then be the context the template is evaluated in.  The return
    value will be the rendered template.
    :param context: the function accepts the same arguments as the
                    :class:`dict` constructor.
    :return: the rendered template as string
    """
    ns = self.default_context.copy()
    if len(args) == 1 and isinstance(args[0], utils.MultiDict):
        ns.update(args[0].to_dict(flat=True))
    else:
        ns.update(dict(*args))
    if kwargs:
        ns.update(kwargs)
    context = Context(ns, self.charset, self.errors)
    exec self.code in context.runtime, context
    return context.get_value(self.unicode_mode)
复制代码

这个方法接收一个 dict 类型参数,用于给模板传递参数。该方法的**核心是执行 exec **函数。 exec 是 Python 内置函数,它可以动态的执行 Python 代码。

0x05 总结一下

Flask 使用 Jinja 作为模板引擎。执行路径为

Flask.render_template => Environment.get_template => Template.render => exec
复制代码
基于python3.5+flask+mysql+oracle的一键生成系统完整demo 基于python3.5+flask的一键生成系统完整demo, 支持mysql,sqlserver,oracle。 一键生成model及增删改查页面+逻辑,拿来即用 立即下载

相关推荐

一个基于flask的web应用诞生 flask和mysql相连(4)

一个基于flask的web应用诞生第四篇,这篇文章主要介绍了如何让flask和mysql进行互联,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

复盘Flask-web网页开发——模板渲染

jinja2 是 Flask 作者开发的一个模板系统,起初是仿 Django 模板的一个模板引擎,为 Flask 提供模板支持,由于其灵活,快速和安全等优点被广泛使用。当我们开发 Web 应用程序时,通常需要将数据动态地渲染到 HTML 模板中,而 Python jinja2 模版技术正是为此而生的。模板在 Python 的web开发中广泛使用,它能够有效的将业务逻辑和页面逻辑分开,使代码可读性增强、并且更加容易理解和维护。部分的文件,模板文件在经过动态赋值后,返回给用户。模板简单来说就是一个其中包含。

m0_66151412的博客 398

实战指南:如何优雅解决SpringBoot3与Mybatis-Plus的版本兼容性问题

本文深入解析SpringBoot3与Mybatis-Plus的版本兼容性问题,提供实战解决方案。通过Maven依赖排除策略、Gradle配置方案及自动配置覆盖策略,有效解决包冲突和初始化顺序问题,确保项目平稳升级。适用于开发者快速解决SpringBoot3与Mybatis-Plus的集成难题。

weixin_28432777的博客 607

python flask源码_Python Web Flask源码解读(一)——启动流程

关于我一个有思想的程序猿,终身学习实践者,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是我们团队的主要技术栈。Github:https://github.com/hylinux1024微信公众号:终身开发者(angrycode)0x00 什么是WSGIWeb Server Gateway Interface它由Python标准定义的一套We...

weixin_39553705的博客 316

数字设计与计算机体系结构习题答案,数字设计和计算机体系结构习题答案DigitalDesignandComputerArchitecture.pdf...

数字设计和计算机体系结构习题答案DigitalDesignandComputerArchitecture.pdfDavid Money Harris and Sarah L. Harris, Digital Design and Computer Architecture, © 2007 by Elsevier Inc.Exercise SolutionsC H A P T E R ...

weixin_39851408的博客 1802

解决vscode无法运行npm命令的问题(cmd可行)

Powershell以及vscode中npm命令使用不了

无痕坚守本心的博客 2760

Python轻量级框架Flask开发web应用(附源码自取)

Python Flask 框架是一款轻量级的 Web 开发框架,由 Armin Ronacher 创建,遵循 MVC(Model-View-Controller)模式的设计理念,虽然它本身并未严格强制此模式,但提供了足够灵活的基础结构来构建 web 应用程序。Flask 基于 Werkzeug WSGI 工具包和 Jinja2 模板引擎,以其小巧精悍、易于扩展的特点深受开发者喜爱,特别适合小型至中型规模的 Web 项目,同时也能够通过扩展支持大型项目需求。

我的身体只需要很少的粮食就能养活;而我的灵魂却非常地贪婪,需要日月星辰、山川湖泊和大自然的滋养。 3485

基于Stigmergy的团队LLM wiki协作机制与FastAPI工程实践

大语言模型驱动的知识管理正在改变个人笔记与团队文档的维护方式,但当多人共同维护一个维基时,如何避免版本覆盖、上下文丢失和幻觉污染成为核心挑战。Stigmergy这一源自生物学的协作机制提供了新思路:通过共享环境中的痕迹(如评论、标记、修订历史)实现异步协作,无需实时沟通或中心协调者。本文将原理落地为可工程化的系统,设计Page、Revision、Trace三大实体,并结合向量索引与LLM审查流程,最终用FastAPI与SQLite搭建一个最小可运行原型。从白蚁筑巢到团队知识库,Stigmergy让每个参与者

weixin_34174322的博客 370

【Python程序开发系列】使用Flask实现前后端分离的简单实现(案例+源码)

使用Flask实现前后端分离的简单实现(案例+源码)

数据杂坛 1867

<蓝桥杯软件赛>零基础备赛20周--第16周--GCD和LCM

gcd,lcm

罗勇军的博客 7619

彻底清理Easy Connect残留:从服务到驱动的完整卸载指南

在企业网络接入场景中,远程客户端常因内核驱动、系统服务和网络过滤组件导致卸载残留,进程无法结束、文件被锁定、注册表项顽固存在。其原理在于驱动挂载网络协议栈,服务守护进程,卸载时资源占用导致清理不彻底。彻底清理的技术价值在于恢复系统纯净、避免网络异常和软件冲突。典型应用场景包括企业办公机、个人笔记本更换或重装客户端。本文针对深信服Easy Connect,提供从停止服务、删除驱动到清理注册表和虚拟网卡的分步操作链路,并给出验证方法和避坑经验。

weixin_31292729的博客 277

python flask源码解析_用尽洪荒之力学习Flask源码

[TOC]一直想做源码阅读这件事,总感觉难度太高时间太少,可望不可见。最近正好时间充裕,决定试试做一下,并记录一下学习心得。首先说明一下,本文研究的Flask版本是0.12。首先做个小示例,在pycharm新建flask项目"flask_source"后,默认创建项目入口"flask_source.py"文件。运行该文件,在浏览器上访问 http://127.0.0.1:5000/上可以看到“he...

weixin_39844549的博客 543

人像抠图 + OpenGL ES 还能这样玩?没想到吧(附带源码)

OpenGL ES 利用抠图算法实现人像留色。

字节流动 3万+

python web 模版_Python Web Flask源码解读!模板渲染过程!

关于我编程界的一名小小程序猿,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是我们团队的主要技术栈。微信公众号:angrycodePython资源共享群:484031800前面对 Flask 启动流程 和路由原理都进行了源码走读。今天我们看看 模板渲染 的过程。0x00 使用模板首先看一个来自官方文档使用模板渲染的例子from flask...

weixin_39637589的博客 245

【深度学习新浪潮】李飞飞团队VAGEN框架深度解析:让VLM智能体学会“三思而后行“

VAGEN框架的真正价值,不仅在于性能指标的突破,更在于重新定义了VLM智能体的发展方向——人工智能的进步不应只追求"做得对",更要实现"想得清"。李飞飞团队通过强制显式思考、动态表示适配和精细化奖励三大创新,让智能体第一次具备了可解释的世界建模能力。正如人类通过"观察-预测-行动"认识世界,VAGEN为AI注入的这种思考范式,或许正是通往通用人工智能的关键一步。对于开发者而言,开源的VAGEN框架不仅提供了强大的工具,更揭示了一个重要理念:让AI学会思考,比让它学会执行更重要。

专注:太空算力、AI infra、异构调度、大模型成本工程 286

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Python Web Flask源码解读(三)——模板渲染过程

关于我 一个有思想的程序猿,终身学习实践者,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是我们团队的主要技术栈。 Github:https://github.com/hylinux1024 微信公众号:终身开发者(angrycode) 前面对Flask启动流程和路由原理都进行了源码走读。今天我们看看模板渲染的过程。 0x00 ...

weixin_30364147的博客 277

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

python flask源码解析_flask 源码解析:简介

这是 flask 源码解析系列文章的其中一篇,本系列所有文章列表:flask 简介Flask 官网上对它的定位是一个“微” python web 开发框架。Flask is a micro web development framework for Python.python 语言 web 框架很多:Django、Tornado、webpy、bottle……,flask 的特点是简单可扩展。简单有...

weixin_26840895的博客 763

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

测试之路 python-flask框架:模板渲染

哈喽,大家好,我是小王,上期我们说道路由与蓝图的概念,本期我们就来说说模板渲染01 模板渲染Jinja2是flask中的一个必不可少的模板渲染引擎,主要作用就是渲染一个有富文本标签的页面,使用者能够更好的通过UI页面进行数据传递,视图函数在接收到数据请求时,将该请求做相关处理,然后再返通过渲染的方式,将处理结果返回给页面。render_template()方法,就是渲染的...

weixin_44649708的博客 995

python flask源码解析_Flask 源码解析

目标:阅读源码了解瓶服务器启动后,用户访问http://127.0.0.1:5000/后浏览“Hello World”这个过程Flask的工作原理及代码框架。flask_ source.py源码:from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world():return 'Hello World!'if _...

weixin_35698867的博客 511

python2.7的flask框架之模板(html)渲染( Jinja2 模板引擎&render_template() 方法)

用 Python 生成 HTML 十分无趣,而且相当繁琐,因为我们必须手动对 HTML 做转义来保证应用的安全。为此,Flask 配备了  Jinja2 模板引擎。我们可以使用 render_template() 方法来渲染模板。并且需要做的一切就是将模板名和我们想作为关键字的参数传入模板的变量。来看一个简单的模板渲染的实例: from flask import render_template...

luyaran的博客 3114

【Flask】模板渲染

后台 from flask import Flask,render_template,request,redirect,session,url_for,jsonify,make_response,Markup,flash,get_flashed_messages app = Flask(__name__) app.config.from_object("settings.Developme...

欢迎关注【微信公众号】测试开发Guide,从功能测试进阶测试开发 1080

Python Web Flask源码解读(一)

关于我 编程界的一名小小程序猿,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是我们团队的主要技术栈。 联系:hylinux1024@gmail.com 0x00 什么是WSGI Web Server Gateway Interface 它由Python标准定义的一套Web Server与Web Application的接口交互规范。 W...

weixin_30337157的博客 464

python flask 模板渲染

render_template 使用render_template可以传递载参数进行模板渲染 这里直接贴一下我的测试代码 from flask import Flask, render_template app = Flask(__name__) @app.route('/') def test(): context = { 'title_name':"test_render"...

weixin_30414155的博客 279

Python--flask 模板渲染Jinja2

Python–flask 模板渲染Jinja2 模板是一个包含响应文本的文件,其中包含用占位变量表示的动态部分,其具体值只在请 求的上下文中才能知道。使用真实值替换变量,再返回最终得到的响应字符串,这一过程 称为渲染。为了渲染模板,Flask 使用了一个名为 Jinja2 的强大模板引擎。 jinja2介绍 jinja2是Flask作者开发的一个模板系统,起初是仿django模板的一个模板引擎,为...

Andre_151 796
上一篇: 如何在 Python 中用中文做数学运算?
下一篇: Python基础 ,快速实现命令行参数解析!
普通网友
博客等级 码龄7年 438粉丝 263原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址