暑假的時候用flask框架寫了一個個人博客,完全參照《Flask Web開發》這本書一步步完成的,不得不說光頭大叔這本書寫的非常好,用一個完整簡單的項目詳細的將flask框架基本功能和知識傳輸給讀者。個人博客的代碼已經托管在GitHub上面,放一下鏈接<a>https://github.com/RickyLin7/RL7-Blog</a>,很簡單的一個flask項目只是完成了比較基本的功能,自己加了兩三個無關緊要的功能罷了。基本功能篇也就到這了,但是實際開發中,要完成的功能肯定更多,所以近期打算用flask框架完成一個較為復雜的論壇系統,再把flask框架過一遍,順便寫筆記,希望以后求職能夠有所用處,整個過程都是邊做邊寫,實時記錄。</br>《Flask Web開發》這本書中的項目前端和后臺是結合起來做的,但是工作中前端和后臺應該是分開的,所以我這次先做好了前端的模板,然后再一步步的把功能添加進去。</br>OK,先創建一個標準的flask項目目錄樹
接著把html文件中的靜態文件路徑用url_for( )函數的形式全都改掉,例如
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.css') }}" type="text/css" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/animate.css') }}" type="text/css" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/font-awesome.min.css') }}" type="text/css" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/simple-line-icons.css') }}" type="text/css" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/font.css') }}" type="text/css" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/app.css') }}" type="text/css" />
記得有img路徑的話也要全改掉。因為在flask程序中有一個static路由,它會將靜態文件的引用變成一個特殊的路由,即/static/<filename>(默認設置下,Flask在程序根目錄中名為static的子目錄中尋找靜態文件)。
然后把前端模板中的靜態文件全都拖進static文件夾中,將html文件拖進templates文件夾中。簡單的準備工作完成后,就該把flask程序在自己的電腦上運行起來了,在app.py文件中寫入代碼
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__=='__main__':
app.run(debug=True)
然后打開終端進入虛擬環境運行python app.py
OK,打開瀏覽器訪問
localhost:5000
即可看見index.html了
在app.py中可以看到引用的一個函數render_template()
此函數為jinja2提供。這樣,Flask在程序文件夾中的子文件夾中尋找模板。第一個參數是文件名,隨后的參數都是鍵值對(name=name),表示模板中變量對應的真實值。下面順便閱讀下它的源碼
def render_template(template_name, **context):
"""Renders a template from the template folder with the given
context.
:param template_name: the name of the template to be rendered
:param context: the variables that should be available in the
context of the template.
"""
current_app.update_template_context(context)
return current_app.jinja_env.get_template(template_name).render(context)
好了,GG,起始篇就寫到這了,因為是起始篇所以多寫點,以后可能只寫難點,不過也看時間,時間多就盡量多寫點。