看了張宏倫的全棧學習視頻阐枣,在此做個筆記匪补。
一、創(chuàng)建項目環(huán)境
1.安裝flask
2.工程目錄
本人已安裝Anaconda,所以直接創(chuàng)建項目easy_blog_flask。目錄結(jié)構(gòu)如下:staic放css,圖片等靜態(tài)資源弓坞;templates放模板文件;run.py是程序入口;config.py配置參數(shù)车荔。
3.創(chuàng)建數(shù)據(jù)庫渡冻,建立表
由于本人用mac進行開發(fā),所以用mamp進行數(shù)據(jù)庫的操作忧便。安裝好mamp后族吻,啟動mamp,點擊start servers開啟服務(wù)珠增,在preferences進行端口以及項目路徑設(shè)置超歌。
端口:
路徑:
建立數(shù)據(jù)庫:點擊Open WebStart page,然后點擊MySQL下的phpMyAdmin蒂教。點擊左邊欄的New創(chuàng)建數(shù)據(jù)庫blogDB,然后創(chuàng)建表post,如下:
4.開始代碼
在config.py中進行一些項目的參數(shù)配置:
HOST="localhost"
PORT=8889
USER='root'
PASSWORD='root'
DATABASE='blogDB'
CHARSET='utf8'
在templates文件夾下創(chuàng)建界面巍举,套用模板layout.html,首頁index.html,文章列表list.html,文章詳情post.html。在run.py中連接數(shù)據(jù)庫:
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ù)庫
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ù)庫
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
結(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/ 就是項目根地址.
6.頁面之間的跳轉(zhuǎn)以及URL定義
比如首頁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')
如上所見炭分, route()裝飾器把一個函數(shù)綁定到對應的 URL 上桃焕。這樣index.html就可以跳轉(zhuǎn)到list.html界面了。要在界面之間進行參數(shù)傳遞捧毛,可以在URL綁定相應的變量观堂。比如在文字列表頁面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ù)看獲取相應的文章呀忧,然后返回給post.html頁面:
#文章詳情頁
@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)
因為從數(shù)據(jù)看獲取的數(shù)據(jù)時tuple师痕,不能進行更改,而時間要進行轉(zhuǎn)換就要把tuple進行轉(zhuǎn)換后才能更改荐虐,再傳給post.html頁面.
7. 模板渲染
post.html頁面獲取到相應的文章item過后七兜,在此頁面展示文章內(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ù)提交
在首頁進行文章的編輯,然后提交給數(shù)據(jù)庫福扬,跳轉(zhuǎn)到文字列表界面腕铸。那么在首頁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="內(nèi)容"></textarea>
<button type="submit">提交</button>
</form>
用handel函數(shù)進行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ù)庫铛碑,跳轉(zhuǎn)到list.html頁面狠裹,展示文章列表,那么run.py中l(wèi)ist函數(shù)就要從數(shù)據(jù)庫獲取所以數(shù)據(jù)汽烦,然后傳遞給list.html頁面涛菠。run.py的list函數(shù):
#文章列表頁
@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 %}