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计算开方、立方、圆周率,精确到小数点后任意位的方法

Python计算开方、立方、圆周率,精确到小数点后任意位的方法

Python计算的位数 在电脑上做了一个实验,看看python能计算到多少位,一下是结果。 x = math.sqrt((3)) print ("%.53f"%(x)) print...

对numpy的array和python中自带的list之间相互转化详解

a=([3.234,34,3.777,6.33]) a为python的list类型 将a转化为numpy的array: np.array(a) array([ 3.234,...

python将txt文档每行内容循环插入数据库的方法

如下所示: import pymysql import time import re def get_raw_label(rece): re1 = r'"([\s\S]*?...

python TKinter获取文本框内容的方法

如下所示: #coding:utf-8 import urllib,urllib2 import Tkinter #导入TKinter模块 ytm=Tkinter.Tk() #创...

python中Matplotlib实现绘制3D图的示例代码

Matplotlib 也可以绘制 3D 图像,与二维图像不同的是,绘制三维图像主要通过 mplot3d 模块实现。但是,使用 Matplotlib 绘制三维图像实际上是在二维画布上展示,...