學flask也有一個多星期了,對這個web框架也有了一點的了解,梳理一些基礎的知識點,還是小白一只,代碼寫得比較low,若文章有錯誤的地方歡迎大佬隨時指正,代碼中被注釋掉的代碼是關於預防csrf,無視即可
主程序腳本:
1 from flask import Flask, render_template, request, redirect, url_for 2 3 # from flask_wtf import CSRFProtect 4 5 app = Flask(__name__) # 聲明一個Flask的類,__name__參數的作用是為了確定程序的根目錄,以便獲得靜態文件的模板文件 6 # app.config["SECRET_KEY"] = "12345678" 7 # 8 # CSRFProtect(app) 9 10 11 @app.route('/') # @app.router()是一個裝飾器,它的作用就是把試圖函數(可以簡單的理解成就是它下面的函數)與某一個url(后面括號中的部分)綁定,當訪問這個url時,就會運行這個視圖函數 12 def Helloworld(): 13 return redirect(url_for('home')) url_for對視圖函數進行反轉,第一個參數為視圖函數名,如果視圖函數有參數,可加在后面,返回url,redirect是重定向到括號里面的url,這里為url_for的返回值 14 15 16 @app.route("/regist/", methods=["get", "post"]) # methods指定請求這個url的方法,默認是get,這里指定使用get或post兩種方式 17 def regist(): 18 if request.method == "GET": 19 return render_template("csrf_regist.html") # render_template對頁面進行渲染,如果頁面中存在待接受的參數,可將參數放在后面 20 21 else: 22 print(request.form) # 如果請求方式為post,則在后台輸出用戶輸入的信息。request可以獲取到前端用戶輸入的信息,request.args獲取get請求,request.form獲取post請求 23 24 return redirect(url_for('login')) # 對login視圖函數進行反轉,並進行重定向 25 26 27 @app.route("/login/", methods=["get", "post"]) 28 def login(): 29 if request.method == "GET": 30 return render_template("csrf_login.html") 31 32 else: 33 print(request.form) 34 35 return redirect(url_for('home')) 36 37 38 @app.route('/home/') 39 def home(): 40 return render_template('csrf_home.html') 41 42 43 if __name__ == "__main__": 44 app.run()
首頁(csrf_home.html)代碼
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>csrf首頁</title> 6 </head> 7 <body> 8 <h1>歡迎來到首頁,請選擇登陸或注冊</h1> 9 <a href="{{ url_for('login') }}">登陸</a> # 當用戶點擊登陸時,跳轉到登陸頁面 10 <a href="{{ url_for('regist') }}">注冊</a> # 當用戶點擊注冊時,跳轉到注冊頁面 11 </body> 12 </html>
注冊(csrf_regist.html)代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>csrf的注冊頁面</title> </head> <body> <form action="", method="post"> <table> <tbody> {# <td>#} {# <input type="text" name="csrf_token", value="{{ csrf_token() }}">#} {# </td>#} <td> <tr>用戶名:</tr> <tr><input type="text" name="username" value=""></tr><br> </td> <td> <tr>密碼:</tr> <tr><input type="password" name="password" value=""></tr><br> <input type="submit" value="注冊"> </td> </tbody> </table> </form> </body> </html>
登陸(csrf_login.html)代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>csrf登陸頁面</title> </head> <body> <form action="", method="post"> <table> <tbody> {# <td>#} {# <input type="text" name="csrf_token", value="{{ csrf_token() }}">#} {# </td>#} <td> <tr>用戶名:</tr> <tr><input type="text" name="username" value=""></tr><br> </td> <td> <tr>密碼:</tr> <tr><input type="password" name="password" value=""></tr><br> <input type="submit" value="登陸"> </td> </tbody> </table> </form> </body> </html>