Python-网络编程
一、模拟网络编程
1、在服务器创建接口:导入flask模块(python面向web开发的框架)
2、客户端给服务器发送请求:导入requests模块(发送网络请求)
二、服务器创建接口
import flask from flask import request import pymysql def connect_mysql(sql): conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='mytable', charset='utf8') cur = conn.cursor() cur.execute(sql) data = cur.fetchall() if 'select' not in sql: conn.commit() cur.close() conn.commit() return data server = flask.Flask(__name__) #创建web接口 @server.route('/login', methods=['get','post']) #登录页,methods默认为get请求 def login(): cookie = request.cookies.get('sign') #获取cookies中指定key对应的value # print(request.cookies) #获取请求发过来的cookies username = request.values.get('username','') #获取请求参数data中指定key对应的value password = request.values.get('password','') # username = request.json.get('username') #获取请求参数json中指定key对应的value # password = request.json.get('password') sql = 'select * from userinfo where username = "%s" and password = "%s"'%(username, password) if username and password and cookie: if connect_mysql(sql) and cookie == '1': #暂将cookie写死,仅模拟传参 return '{"msg":"登录成功","code":"200"}' else: return '{"msg":"用户名密码错误或cookie错误","code":"301"}' else: return '{"msg":"缺少参数","code":300}' server.run(port=8000,debug=True) #启动server,port默认为5000
三、客户端发送请求
import requests url = 'http://127.0.0.1:8000/login' data = {'username': 'xsj', 'password': '123456'} cookie = {'sign': '1'} r = requests.get(url, data=data, json=data, cookies=cookie) #data必须是dict类型;请求中可添加json/cookies等参数 print(r.status_code) #打印返回码 print(r.text) #以字符串形式,打印请求结果 print(r.content) #以二进制形式,打印请求结果 print(r.json()) #返回结果是json类型时,可获取json类型 print(r.url) #打印请求url print(r.headers) #打印headers