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')