在這裏先說一下最開始所經歷的一些錯誤app=Flask(_name_),當初拼寫的時候怎麼都報錯後來發現此處是兩個'_'css
配置文件html
app.config.from_object(__name__) 在當前文件中查詢配置項flask
app.config.from_envvar('FLASKR_SETTINGS', silent=True) 在文件中查詢配置現,其中FLASKR_SETTINGS表明環境變量,silent=True表明Flask不關心該環境變量鍵值是否存在瀏覽器
@app.route('/')
def index():
return 'This is index'
此處route修飾器把一個函數綁定到一個URL上,@app.route('hello'),這個意思就是http://127.0.0.1/hellocookie
@app.route('/user<username>')app
def show_user(username):函數
return 'My name is %s'%username編碼
此處route中<username>表明一個參數,在地址欄中輸入http://127.0.0.1/user/Sky,網頁則會返回My name is Skyurl
from flask import url_forspa
@app.route('/login')
def index():return '這是一個新的url'
print url_for('login')
此處url_for()來針對一個特定的函數構建一個 URL,在時運行則會print出所構造好的地址地址欄中輸入http://127.0.0.1/login便可訪問
爲何你要構建 URLs 而不是在模版中硬編碼?這裏有三個好的理由:
1. 反向構建一般比硬編碼更具有描述性。更重要的是,它容許你一次性修改 URL, 而不是處處找 URL 修改。
2.構建 URL 可以顯式地處理特殊字符和Unicode轉義,所以你沒必要去處理這些。
3.若是你的應用不在 URL 根目錄下(好比,在 /myapplication 而不在 /),url_for()將會適當地替你處理好。
放置靜態文件時給靜態文件生成URL
url_for('static',filename='style.css')
這個文件是應該存儲在文件系統上的static/style.css
渲染文件
from flask import render_template
@app.route('/hello/')
@app.route('/hello<name>')
def hello(name=None):
return render_template('hello.html',name=name)
此處將會從templates處查找模版文件hello.html
請求對象
from flask import request
request.method==['GET','POST']
文件上傳
在HTML表單中設置屬性enctype="multipart/form-data",不然瀏覽器不會傳送文件
from flask import request
@app.route('/upload',methods=['GET','POST'])
def upload_file():
if request.method=='POST'
f=request.files['file']
f.save('/uploads'+secure_filename(f.filename)) 由於客戶端的名稱可能會被僞造,因此永遠不要相信,傳遞給secure_filename來打到效果
COOKIE操做
讀取cookie:
username=request.cookies.get('username')
存儲cookie:
from flask import make_response,render_template
loadc=make_response(render_template())
loadc.set_cookie('usernmae','the username')
重定向
錯誤重定向
若是出現出錯的話能夠定義一個裝飾器
@app.errorhandler(404) 表明沒有該文件
def page_not_found(error):
return render_tamplater('**.html'),404 此處404是在render_tamplate調用,告訴Flask該頁的錯誤代碼是404
未完待續...