赞
踩
- from markdown import markdown
- import bleach
- class Post(db.Model):
- __tablename__='posts'
- id=db.Column(db.Integer,primary_key=True)
- body=db.Column(db.Text)
- timestamp=db.Column(db.DateTime,index=True,default=datetime.utcnow)
- html_body=db.Column(db.Text)
-
- @staticmethod
- def on_body_change(target,value,oldvalue,initiator):
- allowed_tags=['a','ul','strong','p','h1','h2','h3']
- html_body=markdown(value,output_format='html')
- html_body=bleach.clean(html_body,tags=allowed_tags,strip=True)
- html_body=bleach.linkify(htnl_body)
- target.html_body=html_body
-
- db.event.listen(Post.body,'set',Post.on_body_change)

我们在Post的模型中增加了一个html_body的字段用来存放,被转换成html格式的文本。并定义了一个静态成员函数on_body_change,在函数中
最后一行代码是调用SQLAlchemy中的监听器db.event.listen,它的第一个参数Post.body指定了监听的对象,第二个参数指定的是监听事件的类型,这里的'set'指明凡是修改Post对象的body字段都会触发该监听器。而其第三个参数就是我们自定义的Post的静态成员函数on_body_change,当监听事件发生,on_body_change作为回调函数被调用。
Github位置:
https://github.com/HymanLiuTS/flaskTs
克隆本项目:
Git clone Git@github.com:HymanLiuTS/flaskTs.Git
获取本文源代码:
Git checkout FL38
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。