1.Post類的定義
一個博客文章應該包含最基本的欄位:標題、作者、發表時間、摘要、內容、參考(參考可以寫進內容里),從最簡單的開始,將欄位先寫成英文title, author, timestamp, summary, content,當然一個資料庫表中肯定需要一個主鍵id的,在Flask中作為資料庫模型類,必須繼承db.Model,
1 from . import db 2 from datetime import datetime 3 4 class Post(db.Model): 5 __tablename__ = 'posts' 6 id = db.Column(db.Integer, primary_key=True) 7 title = db.Column(db.String(64), index=True) 8 summary = db.Column(db.Text, index=True) 9 content = db.Column(db.Text) 10 timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) 11 author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
Post類定義好后,我們就可以使用Flask-WTF表單模塊來進行渲染到前端,這里我們需要定義一個PostForm類,用于前端的資料收集,當資料提交后由視圖函式edit-post類將用戶提交的資料寫入資料庫中,
PostForm類:
1 # -*- coding:utf-8 -*- 2 from flask_wtf import FlaskForm 3 from wtforms import StringField, SubmitField, TextAreaField 4 from wtforms.validators import DataRequired, Length 5 6 # 文章類表單 7 class PostForm(FlaskForm): 8 title = StringField('文章標題', validators=[DataRequired(), Length(0, 64)]) 9 summary = TextAreaField('摘要', validators=[DataRequired()]) 10 content = TextAreaField('留下你的痕跡', validators=[DataRequired()]) 11 submit = SubmitField('提交')
接下來就是在視圖函式中將表單傳入前端模板進行渲染,在這之前需要定義視圖函式用于外部用戶訪問的路由,
edit-post視圖函式:
1 # -*- coding:utf-8 -*- 2 # 匯入必要的模塊 3 from flask import render_template,redirect, url_for, flash 4 from . import main 5 from ..auth.forms import PostForm 6 from .. import db 7 from ..models import Post 8 from flask_login import current_user, login_required 9 from ..models import Permission 10 11 # 寫博客的視圖函式 12 @main.route('/edit-post', methods=['GET', 'POST']) 13 @login_required 14 def edit_post(): 15 if not current_user.is_authenticated: 16 return redirect(url_for('main.index')) 17 form = PostForm() 18 if current_user.can(Permission.WRITE) and form.validate_on_submit(): 19 post = Post(title=form.title.data, summary=form.summary.data, content=form.content.data, author=current_user._get_current_object()) 20 db.session.add(post) 21 db.session.commit() 22 return redirect(url_for('main.post', id=post.id)) 23 return render_template('edit-post.html', form=form)
視圖函式撰寫完成后,接下來就是處理edit-post.html模板了,因為Jinja2支持模板繼承,所以edit-post.html通過繼承base.html模板來完善布局,這里使用了開源專案editormd,使用markdown語法來撰寫文章,并且可以及時預覽撰寫的文章效果,
edit-post.html模板:
1 {% extends 'base.html' %} 2 3 {% block title %}云網傳輸小窩-寫文章{% endblock %} 4 5 {% block styles %} 6 {{ super() }} 7 <link rel="stylesheet" href="{{ url_for('static',filename='editormd/css/editormd.css') }}"/> 8 {% endblock styles %} 9 10 {% block page_content %} 11 <div class="row"> 12 <h1 class="text-center">編輯文章,書寫心靈</h1> 13 14 <form method="POST"> 15 {{ form.hidden_tag() }} 16 <div style="float: right; margin-bottom: 5px;">{{ form.submit() }}</div> 17 <div class="form-group"> 18 <h4>{{ form.title.label }}</h4> 19 {{ form.title(, style="font-size:24px; height:48px") }} 20 </div> 21 <div class="form-group"> 22 <h4>{{ form.summary.label }}</h4> 23 {{ form.summary(style="height:100px; width:100%; resize:none; font-size:20px;", ) }} 24 </div> 25 <div class="form-group"> 26 <h4>{{ form.content.label }}</h4> 27 <div id="editormd" class="form-control"> 28 {{ form.content(style="display:none;") }} 29 </div> 30 </div> 31 </form> 32 </div> 33 {% endblock %} 34 35 {% block scripts %} 36 {{ super() }} 37 <script src="{{ url_for('static',filename='editormd/editormd.min.js') }}"></script> 38 <script type="text/javascript"> 39 //初始化編輯器 40 var testEditor; 41 $(function () { 42 testEditor = editormd("editormd", { 43 width: "100%", 44 height: 740, 45 path: '/static/editormd/lib/', 46 theme: "", 47 previewTheme: "", 48 editorTheme: "pastel-on-dark", 49 markdown: "", 50 codeFold: true, 51 saveHTMLToTextarea: true, // 保存 HTML 到 Textarea 52 searchReplace: true, 53 htmlDecode: "style,script,iframe|on*", // 開啟 HTML 標簽決議,為了安全性,默認不開啟 54 emoji: true, 55 taskList: true, 56 tocm: true, // Using [TOCM] 57 tex: true, // 開啟科學公式TeX語言支持,默認關閉 58 flowChart: true, // 開啟流程圖支持,默認關閉 59 sequenceDiagram: true, // 開啟時序/序列圖支持,默認關閉, 60 imageUpload: true, 61 imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"], 62 imageUploadURL: "/Center/RichTextUpload", 63 onl oad: function () { 64 //干點什么 65 } 66 }); 67 }); 68 //獲取編輯器內容 69 var blogcontent = encodeURIComponent(testEditor.getMarkdown()); 70 </script> 71 {{ pagedown.include_pagedown() }} 72 {% endblock scripts %}
最總的頁面效果如下所示,嗯...不錯哦!
最后我們測驗一下,寫一個小文章來看看效果,文章提交后,其實我這里只是把md的內容直接保存在資料庫了,并沒有進行處理,當用戶查看文章詳情時,會從資料庫中讀取md資料,前端editormd開源專案會根據md的內容進行渲染,其效果跟寫文章的效果是一樣的,
2.總結
- 繼續加油!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/141661.html
標籤:Python
下一篇:Flask中資料庫的多對多關系
