5.flask返回網頁模板(前后端不分離,傳統寫法)
在項目目錄中新建template文件夾,在文件夾中新建hello.html
hello.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{person.username}}</h1>
<em>{{person['age']}}</em> #兩種方式都可以顯示
</body>
</html>
在app.py中編寫模擬操作數據庫返回網頁模板等操作。
app.py:
from flask import Flask, request, render_template
from flask_cors import CORS
app = Flask(__name__)
CORS(app) #解決跨域問題
@app.route('/')
def hello():
uname = request.args['username'] #get方式獲 得username
print(uname)
return 'hello'+uname
@app.route('/info')
def info():
#假設person_info是從數據庫中查找出來的數據
person_info = {}
person_info['username'] = 'zhangsan'
person_info['age'] = 28
# 返回一個網頁模板;參數一:模板名稱,參數二:對模板中數據進行賦值(這是一種前后端不分離的形式)
return render_template('hello.html',person=person_info)
if __name__ == '__main__':
app.run()
當訪問127.0.0.1:5000/info時,網頁顯示和服務器回應(html代碼):
這就是前后端不分離的開發方式。
6.一個綜合實例
6.1前后端不分離,用傳統方式完成
思路:當用戶第一次通過get方式(跳轉或輸入url)進入該頁面時,返回表單模板html,如果用戶填寫完畢,提交時(post),獲取用戶填寫的num,并使用random模塊生成隨機數,綁定在random.html上并返回。
random.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/random_int" method="post">
多少以內的隨機數:<input type="name" name="num" value="{{ num }}">
<input type="submit">
</form>
<div>生成的隨機數為{{ random_num }}</div>
</body>
</html>
app.py:
@app.route('/random_int',methods=['GET','POST'])
def random_int():
if request.method =='GET':
return render_template('random.html')
elif request.method == 'POST':
num = int(request.form['num']) #獲取表單提交的id值,要把字符串類型轉換為int類型
random_num = random.randint(0,num) #生成一個隨機數
return render_template('random.html', random_num = random_num, num = num)
當訪問127.0.0.1:5000/random_int時,輸入隨機數最大值10后,點擊提交,返回頁面為:
這種方式會重新刷新整個頁面,(這樣不好),頁面如果會讓你復雜的話,響應時間會很長。
6.2前后端分離,用ajax請求完成
思路:前半部分與傳統方式一致,但是在前端用戶提交表單后,在服務器生成隨機數,只返回該隨機數,有前端頁面自己綁定數據。不在刷新整個頁面,只改變頁面的一部分。
random_ajax.html:
<body>
多少以內的隨機數:<input type="name" id="num">
<button onclick="getRandom()">ok</button>
<div>生成的隨機數為:</div>
<div id="result"></div>
<script>
function getRandom() {
let input = document.getElementById('num') //獲取用戶輸入框
//ajax請求
let xhr = new XMLHttpRequest()
xhr.open('post', 'http://127.0.0.1:5000/random_ajax', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded') //post請求固定寫法
xhr.send('num=' + input.value) //post請求發送參數的形式
xhr.onload = function () { //回調函數
let div = document.getElementById('result') //獲取顯示結果的div
div.innerText = xhr.responseText //把服務器響應回來的值更新給相應div頁面
}
}
</script>
</body>
app.py:
@app.route('/random_ajax',methods=['GET','POST'])
def random_ajax():
if request.method =='GET': #如果請求方式是get,返回網頁模板
return render_template('random_ajax.html')
elif request.method == 'POST':
num = int(request.form['num']) #獲取表單提交的num值,要把字符串類型轉換為int類型
random_num = random.randint(0,num) #生成一個隨機數
return str(random_num) #返回生成的隨機數str數據類型
form Data:10
用戶輸入傳給服務器的數據
image.png
Response:服務器響應數據為8
不再是html模板