flask框架自定义过滤器示例【markdown文件读取和展示功能】

yipeiwu_com6年前Python基础

本文实例讲述了flask框架自定义过滤器。分享给大家供大家参考,具体如下:

除了一些内置的join length safe等过滤器外, flask还提供了自定义过滤器的功能.

一. 自定义一个mardown过滤器

自定义一个markdown过滤器, 使过滤器可以像safe解析html标签一样解析md语法.

  • 安装库
pip install Markdown==2.3.1
  • 自定义过滤器

使用@app.template_filter(‘md')过滤器, 此时便拥有了名为md的过滤器.

@app.template_filter('md')
def markdown_to_html(txt):
  from markdown import markdown
  return markdown(txt)

  • 使用示例

views

@app.route('/', methods=['POST', 'GET'])
def index():
  return render_template('index.html', body='# hello')

  • 模板中直接使用
{{ body|md|safe }}

二. 添加读取文件的功能

读取md文件, 并输出到html中

  • 定义读文件函数
def read_md(filename):
  with open(filename) as md_file:
    content = reduce(lambda x, y: x+y, md_file.readline())
  return content.decode('utf-8')

  • 上下文管理器

此时read_md函数可以全局使用

@app.context_processor
def inject_methods():
  return dict(read_md=read_md)

  • 可以在模板中调用函数
{{ read_md('test.md')|md|safe}}

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

相关文章

对Python 语音识别框架详解

如下所示: from win32com.client import constants import os import win32com.client import pythonc...

python定时检查某个进程是否已经关闭的方法

本文实例讲述了python定时检查某个进程是否已经关闭的方法。分享给大家供大家参考。具体如下: import threading import time import os impo...

python批量导入数据进Elasticsearch的实例

ES在之前的博客已有介绍,提供很多接口,本文介绍如何使用python批量导入。ES官网上有较多说明文档,仔细研究并结合搜索引擎应该不难使用。 先给代码 #coding=utf-8 f...

python自动zip压缩目录的方法

本文实例讲述了python自动zip压缩目录的方法。分享给大家供大家参考。具体实现方法如下: 这段代码来压缩数据库备份文件,没有使用python内置的zip模块,而是使用了zip.exe...

Python定时执行之Timer用法示例

本文实例讲述了Python定时执行之Timer用法。分享给大家供大家参考。具体分析如下: java中Timer的作用亦是如此。python中的线程提供了java线程功能的子集。 #!...