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内置map和six.moves.map的区别详解

python内置map返回的是列表,而six.moves.map返回的是iter。 >>> map(lambda a: a*2, [1, 2, 3]) [2, 4,...

python在不同层级目录import模块的方法

使用python进行程序编写时,经常会使用第三方模块包。这种包我们可以通过python setup install 进行安装后,通过import XXX或from XXX import...

Python中的getopt函数使用详解

函数原型: getopt.getopt(args, shortopts, longopts=[]) 参数解释:     args:args...

Python中的引用知识点总结

Python中的引用知识点总结

本篇介绍Python中的引用。 首先想一想如图示例。 在python中,值是靠引用来传递来的。 用id()来判断两个变量是否为同一个值的引用。如图。 图解引用。如图。 可变类型...

Python socket实现的文件下载器功能示例

本文实例讲述了Python socket实现的文件下载器功能。分享给大家供大家参考,具体如下: 文件下载器 先写客户端再写服务端 1.tcp下载器客户端 import socket...