用Flask搭建一個(gè)簡(jiǎn)易的博客

看了張宏倫的全棧學(xué)習(xí)視頻,在此做個(gè)筆記。

一、創(chuàng)建項(xiàng)目環(huán)境

1.安裝flask
2.工程目錄

本人已安裝Anaconda,所以直接創(chuàng)建項(xiàng)目easy_blog_flask。目錄結(jié)構(gòu)如下:

staic放css,圖片等靜態(tài)資源;templates放模板文件;run.py是程序入口;config.py配置參數(shù)。

3.創(chuàng)建數(shù)據(jù)庫(kù),建立表

由于本人用mac進(jìn)行開(kāi)發(fā),所以用mamp進(jìn)行數(shù)據(jù)庫(kù)的操作。安裝好mamp后,啟動(dòng)mamp,點(diǎn)擊start servers開(kāi)啟服務(wù),在preferences進(jìn)行端口以及項(xiàng)目路徑設(shè)置。
端口:


路徑:

建立數(shù)據(jù)庫(kù):點(diǎn)擊Open WebStart page,然后點(diǎn)擊MySQL下的phpMyAdmin。點(diǎn)擊左邊欄的New創(chuàng)建數(shù)據(jù)庫(kù)blogDB,然后創(chuàng)建表post,如下:

4.開(kāi)始代碼

在config.py中進(jìn)行一些項(xiàng)目的參數(shù)配置:

HOST="localhost"
PORT=8889
USER='root'
PASSWORD='root'
DATABASE='blogDB'
CHARSET='utf8'

在templates文件夾下創(chuàng)建界面,套用模板layout.html,首頁(yè)index.html,文章列表list.html,文章詳情post.html。在run.py中連接數(shù)據(jù)庫(kù):

import sys
from flask import *
import warnings
warnings.filterwarnings("ignore")
import pymysql
from config import *
import time
import numpy as np

app = Flask(__name__)
app.config.from_object(__name__)
#鏈接數(shù)據(jù)庫(kù)
def connectdb():
    db=pymysql.connect(host=HOST,user=USER,passwd=PASSWORD,db=DATABASE,port=PORT,charset=CHARSET)
    db.autocommit(True)
    cursor=db.cursor()
    return (db,cursor)
#關(guān)閉數(shù)據(jù)庫(kù)
def closedb(db,cursor):
    db.close()
    cursor.close()
#首頁(yè)
@app.route('/')
def index():
    return render_template('index.html')

if __name__ =='__main__':
    app.run(debug=True)
5.測(cè)試

進(jìn)入項(xiàng)目根目錄,然后python run.py結(jié)果如下:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 330-801-124

http://127.0.0.1:5000/ 就是項(xiàng)目根地址.

6.頁(yè)面之間的跳轉(zhuǎn)以及URL定義

比如首頁(yè)index.html跳轉(zhuǎn)到列表界面list.html,那么在index.html中:<a href="{{url_for('list')}}">文章列表</a>。而run.py中l(wèi)ist函數(shù)為:

@app.route('/list')
def list():
    return render_template('list.html')

如上所見(jiàn), route()裝飾器把一個(gè)函數(shù)綁定到對(duì)應(yīng)的 URL 上。這樣index.html就可以跳轉(zhuǎn)到list.html界面了。要在界面之間進(jìn)行參數(shù)傳遞,可以在URL綁定相應(yīng)的變量。比如在文字列表頁(yè)面list.html跳轉(zhuǎn)到文字詳情界面post.html要傳遞文章id,那么在list.html界面要傳遞參數(shù)id:

<div>
    {% for item in arr %}
    <h5>第{{item[0]}}篇文章:</h5>
        <div class="artical">
            <h4>
                <a href="{{url_for('post',post_id=item[0])}}">
                    {{item[1]}}
                </a>
            </h4>
            <p> {{item[3]}}</p>
        </div>
    {% endfor %}
</div>

而在run.py中接收參數(shù)post_id,然后從數(shù)據(jù)看獲取相應(yīng)的文章,然后返回給post.html頁(yè)面:

#文章詳情頁(yè)
@app.route('/post/<post_id>')#<post_id>參數(shù)
def post(post_id):
    (db,cursor) = connectdb()
    cursor.execute('select * from post where id=%s',post_id)
    item1=cursor.fetchone()
    item=np.array(item1)
    item[-1]=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(item[-1])))
    closedb(db,cursor)
    return render_template('post.html',item=item)

以上為什么要item=np.array(item1)因?yàn)閺臄?shù)據(jù)看獲取的數(shù)據(jù)時(shí)tuple,不能進(jìn)行更改,而時(shí)間要進(jìn)行轉(zhuǎn)換就要把tuple進(jìn)行轉(zhuǎn)換后才能更改,再傳給post.html頁(yè)面.

7. 模板渲染

post.html頁(yè)面獲取到相應(yīng)的文章item過(guò)后,在此頁(yè)面展示文章內(nèi)容:

{% extends 'layout.html' %}
{% block body %}
<h1>文章詳情</h1>
<h2>{{item[1]}}</h2>
<h5>{{item[-1]}}</h5>
<p>{{item[2]}}</p>
{% endblock %}
8.表單數(shù)據(jù)提交

在首頁(yè)進(jìn)行文章的編輯,然后提交給數(shù)據(jù)庫(kù),跳轉(zhuǎn)到文字列表界面。那么在首頁(yè)index.html頁(yè)面:

<form action="{{url_for('handel')}}" method="post">
    <h4>添加文章</h4>
    <input type="text" name="title" placeholder="標(biāo)題">
    <textarea name="content" cols="30" rows="10" placeholder="內(nèi)容"></textarea>
    <button type="submit">提交</button>
</form>

用handel函數(shù)進(jìn)行post表單提交,在run.py中接收數(shù)據(jù):

#處理提交
@app.route('/handel',methods=['POST'])
def handel():
    data = request.form
    arr=[data['title'],data['content'],int(time.time())]
    print(arr)
    (db,cursor) = connectdb()
    cursor.execute("insert into post(title,content,timestamp) values(%s,%s,%s)",arr)
    db.commit()
    closedb(db,cursor)
    return redirect(url_for('list'))  #跳轉(zhuǎn)到list.html界面

獲取到文字結(jié)構(gòu)然后插入數(shù)據(jù)庫(kù),跳轉(zhuǎn)到list.html頁(yè)面,展示文章列表,那么run.py中l(wèi)ist函數(shù)就要從數(shù)據(jù)庫(kù)獲取所以數(shù)據(jù),然后傳遞給list.html頁(yè)面。run.py的list函數(shù):

#文章列表頁(yè)
@app.route('/list')
def list():
    (db,cursor) = connectdb()
    cursor.execute("select * from post")
    data=cursor.fetchall()
    closedb(db,cursor)
    arr=[]
    for i in range(0,len(data)):
        lists=np.array(data[i])
        lists[-1]=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(lists[-1])))
        arr.append(lists)
    return render_template('list.html',arr=arr)

在list.html頁(yè)面渲染:

{% for item in arr %}
    <h5>第{{item[0]}}篇文章:</h5>
        <div class="artical">
            <h4>
                <a href="{{url_for('post',post_id=item[0])}}">
                    {{item[1]}}
                </a>
            </h4>
            <p> {{item[3]}}</p>
        </div>
    {% endfor %}
這樣,一個(gè)簡(jiǎn)單的博客網(wǎng)站就搭建成功了。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容