用Flask搭建一個簡易的部落格

meryin發表於2017-12-14

全棧學習視訊,在此做個筆記。

1.安裝flask

2.工程目錄

本人已安裝Anaconda,所以直接建立專案easy_blog_flask。目錄結構如下:

用Flask搭建一個簡易的部落格
staic放css,圖片等靜態資源;templates放模板檔案;run.py是程式入口;config.py配置引數。

3.建立資料庫,建立表

由於本人用mac進行開發,所以用mamp進行資料庫的操作。安裝好mamp後,啟動mamp,點選start servers開啟服務,在preferences進行埠以及專案路徑設定。 埠:

用Flask搭建一個簡易的部落格
路徑:
用Flask搭建一個簡易的部落格
建立資料庫:點選Open WebStart page,然後點選MySQL下的phpMyAdmin。點選左邊欄的New建立資料庫blogDB,然後建立表post,如下:
用Flask搭建一個簡易的部落格

4.開始程式碼

在config.py中進行一些專案的引數配置:

HOST="localhost"
PORT=8889
USER='root'
PASSWORD='root'
DATABASE='blogDB'
CHARSET='utf8'
複製程式碼

在templates資料夾下建立介面,套用模板layout.html,首頁index.html,文章列表list.html,文章詳情post.html。在run.py中連線資料庫:

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__)
#連結資料庫
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)
#關閉資料庫
def closedb(db,cursor):
    db.close()
    cursor.close()
#首頁
@app.route('/')
def index():
	return render_template('index.html')

if __name__ =='__main__':
	app.run(debug=True)
複製程式碼

5.測試

進入專案根目錄,然後python run.py結果如下:

 * 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/ 就是專案根地址.

6.頁面之間的跳轉以及URL定義

比如首頁index.html跳轉到列表介面list.html,那麼在index.html中:<a href="{{url_for('list')}}">文章列表</a>。而run.py中list函式為:

@app.route('/list')
def list():
	return render_template('list.html')
複製程式碼

如上所見, route()裝飾器把一個函式繫結到對應的 URL 上。這樣index.html就可以跳轉到list.html介面了。要在介面之間進行引數傳遞,可以在URL繫結相應的變數。比如在文字列表頁面list.html跳轉到文字詳情介面post.html要傳遞文章id,那麼在list.html介面要傳遞引數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中接收引數post_id,然後從資料看獲取相應的文章,然後返回給post.html頁面:

#文章詳情頁
@app.route('/post/<post_id>')#<post_id>引數
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)因為從資料看獲取的資料時tuple,不能進行更改,而時間要進行轉換就要把tuple進行轉換後才能更改,再傳給post.html頁面.

7. 模板渲染

post.html頁面獲取到相應的文章item過後,在此頁面展示文章內容:

{% extends 'layout.html' %}
{% block body %}
<h1>文章詳情</h1>
<h2>{{item[1]}}</h2>
<h5>{{item[-1]}}</h5>
<p>{{item[2]}}</p>
{% endblock %}
複製程式碼

8.表單資料提交

在首頁進行文章的編輯,然後提交給資料庫,跳轉到文字列表介面。那麼在首頁index.html頁面:

<form action="{{url_for('handel')}}" method="post">
	<h4>新增文章</h4>
	<input type="text" name="title" placeholder="標題">
	<textarea name="content" cols="30" rows="10" placeholder="內容"></textarea>
	<button type="submit">提交</button>
</form>
複製程式碼

用handel函式進行post表單提交,在run.py中接收資料:

#處理提交
@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'))  #跳轉到list.html介面
複製程式碼

獲取到文字結構然後插入資料庫,跳轉到list.html頁面,展示文章列表,那麼run.py中list函式就要從資料庫獲取所以資料,然後傳遞給list.html頁面。run.py的list函式:

#文章列表頁
@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頁面渲染:

{% 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 %}
複製程式碼

這樣,一個簡單的部落格網站就搭建成功了。

相關文章