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的轻便web框架Bottle

基本映射 映射使用在根据不同URLs请求来产生相对应的返回内容.Bottle使用route() 修饰器来实现映射. from bottle import route, run@rou...

python简单鼠标自动点击某区域的实例

功能:间隔5毫秒,快速点击屏幕某区域,循环45000000次 from ctypes import * import time time.sleep(5) for i in rang...

解决Pytorch训练过程中loss不下降的问题

在使用Pytorch进行神经网络训练时,有时会遇到训练学习率不下降的问题。出现这种问题的可能原因有很多,包括学习率过小,数据没有进行Normalization等。不过除了这些常规的原因,...

python实现简易版计算器

python实现简易版计算器

学了一周的Python,这篇文章算是为这段时间自学做的小总结。 一、Python简介        Python是一门十分优美...

python如何给字典的键对应的值为字典项的字典赋值

问题 1:需要得到一个类似{“demo”:{“key”:”value”}}这样格式的字典dic。 dic = dict() dic_temp = dict() dic_temp =...