1. 前后台數據交互
1.1 socket搭建后台
【注意點】:
1. 前台發送的數據是用\r\n進行換行
2. 路由:請求的路徑,獲得路由的途徑是通過后台對前台發送的數據進行拆分(split)得到,一般路徑在前台發送的數據的信息頭的1號位
3. 后台響應信息時,不僅需要發送響應的數據給前台,還要再次之前想瀏覽器發送響應頭信息

# 用socket建立一個服務器 import socket server = socket.socket() server.bind(('localhost', 8801)) server.listen(5) print('瀏覽器訪問:http://localhost:8801') while True: client, _, = server.accept() data = client.recv(1024) # print(data) # 用\r\n作為換行 # print(data.decode('utf-8')) request_data = data.decode('utf-8') # type: str # 拿到請求的路徑(路由) header = request_data.split('\r\n')[0] router = header.split(' ')[1] print('前台請求路徑:', router) # 響應時,不僅需要發送響應數據,還要高旭瀏覽器響應頭的信息 client.send(b'HTTP1.1 200 OK\r\nContent-Type: text/html;charset=utf8\r\n\r\n') # client.send('<h1>后台頁面</h1>'.encode('utf-8')) if router == '/index': with open('要返回給前台的頁面.html', 'rb') as rf: client.send(rf.read()) else: client.send(b'<h1 style="color:red;text-align:center">404</h1>') client.close()
1.2 flask搭建后台(ajax獲取前台數據)
原生socket搭建后台時候,需要我們自己對前台發送的數據進行切分,這樣比較麻煩。
於是,可以通過ajax獲取前台的數據發送個給后台。這樣不需要進行拆分就可以直接獲
得我們所需要的信息。
1.2.1 ajax獲取前台數據
http協議:前台發送請求給后台(請求方式、請求路徑、請求內容),后台返回響應給前台(頁面、數據)
ajax完成的是頁面中的局部數據請求,不會頁面改變
環境:
# pip3 install flask
# pip3 install -i https://pypi.douban.com/simple flask
# pip3 install -i https://pypi.douban.com/simple flask-cors
【注意點】:
1. 固定使用方式:$.ajax() ,前台發送請求給后台(可以攜帶數據),拿到后台響應的數據
2. 攜帶是數據以字典的形式發送:{
url: 請求的后台地址:接口,
type: 請求的方式 get post,
data: 要提交給后台的數據,
success: 后台成功的響應,
error: 后台錯誤的響應
...
}

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>請求</title> </head> <body> <h1>ajax請求</h1> <form action=""> <input type="text" name="username" id="username"> <input type="text" name="password" id="password"> <button id="btn" type="button">請求</button> </form> </body> <script src="../jq/jquery-3.4.1.js"></script> <script> $('#btn').click(function () { user = $('#username').val(); pwd = $('#password').val(); if (user && pwd) { $.ajax({ url: 'http://localhost:8888/get_data', type: 'post', data: { username: user, password: pwd }, success: function (response) { console.log(response) }, error: function (error) { console.log(error) } }) } }); </script> </html>
1.2.2 flask搭建后台
【注意點】:
1. 需要解決跨域問題,因為前台可能是pycharm打開的,后台是flask打開,他們不是來自 同源,非同源的數據會影響瀏覽器的功能,所以要解決跨域問題。
2. flask處理路由時候,一個響應對應一個路由
from flask import Flask, request # 解決跨域問題,因為前台是pycharm開啟的,后台是flask開啟 from flask_cors import CORS app = Flask(__name__) CORS(app, supports_credentials=True) # flask處理路由:一個響應對應一個路徑 @app.route('/') @app.route('/index') def home(): return '<h1>Home Page</h1>' # @app.route('/favicon.ico') # def icon(): # return @app.route('/get_data', methods=['GET]', 'POST']) def get_data(): print(request.method) if request.method == 'GET': username = request.args['username'] password = request.args['password'] print(username, password) if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username == 'wangyong' and password == "123": return 'login success' return 'login failed' if __name__ == '__main__': app.run(host='localhost', port='8888')