標籤:ola linear idt operator 變數 other 名稱 names his
MarkdownPad Document
python Flask教程
例子1:
import flaskfrom flask import *app=Flask(__name__) #建立新的開始@app.route(‘/‘) #路由設定def imdex(): #如果訪問了/則調用下面的局部變數 return ‘Post qingqiu !‘ #輸出if __name__ == ‘__main__‘: app.run() #運行開始
訪問:127.0.0.1:5000/
結果:
請求方式
例子2:
import flaskfrom flask import *app=Flask(__name__)#flask.request為請求方式@app.route(‘/‘,methods=[‘GET‘,"POST"]) #mthods定義了請求的方式def imdex(): if request.method==‘POST‘: #判斷請求 return ‘Post qingqiu !‘ else: return ‘Get qinqiu !‘if __name__ == ‘__main__‘: app.run()
GET請求返回的結果如下:
POST請求如下:
模板渲染
在同一目錄下建立一個templates的檔案夾,然后里面放入你要調用
的html。使用render_template(‘要調用的html‘)
例子3:
import flaskfrom flask import *app=Flask(__name__)@app.route(‘/‘,methods=[‘GET‘,"POST"])def imdex(): if request.method==‘POST‘: return ‘Post qingqiu !‘ else: return render_template(‘index.html‘) #調用htmlif __name__ == ‘__main__‘: app.run()
index.html代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>小灰灰的網路部落格</title></head><body><h1>Hello Word</h1></body></html>
結果:
動態摸版渲染
個人來認為吧,這個應該比較少用到,畢竟是這樣子的:/路徑/參數
例子:
import flaskfrom flask import *app=Flask(__name__)@app.route(‘/index‘)@app.route(‘/index/<name>‘) #html裡面的參數為name這裡也為name動態摸版調用def index(name): #html裡面的參數為name這裡也為name return render_template(‘index.html‘,name=name) #調用if __name__ == ‘__main__‘: app.run()
html代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>小灰灰的網路部落格</title></head><body><h1>Hello {{name}}!</h1></body></html>
結果:
接受請求參數
例子:
request.form.請求方式(‘表單裡的資料名稱‘) #用於接受表單傳來的資料
import flaskfrom flask import *app=Flask(__name__)@app.route(‘/index/<name>‘)def index(name): return render_template(‘index.html‘,name=name)@app.route(‘/login‘,methods=[‘GET‘,‘POST‘]) #可使用的請求有GET和POSTdef login(): error=None if request.method=="GET": #如果請求為GET開啟login.html return render_template(‘login.html‘) else: username=request.form.get(‘username‘) #擷取表單裡的username資料 password=request.form.get(‘password‘) #擷取表單裡的password資料 if username==‘admin‘ and password==‘admin‘: #判斷表單裡的username和password資料是否等於admin return ‘login ok‘ #如果是則返回登入成功if __name__ == ‘__main__‘: app.run()
html代碼:
這裡的{{ url_for(‘login‘) }} #代表著發送資料
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Login</title></head><body><form action="{{url_for(‘login‘)}}" method="POST"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value="login"></form></body></html>
結果如下
輸入admin admin
返回如下
python Flask篇(一)