Http是常用的通讯协议,使用的对应Python库名为requests和Flask;
from flask import Flask,request,make_response
app = Flask(__name__)
@app.route('/', methods=['GET', 'PUT', 'POST'])
def index():
if request.method == 'GET':
if request.args['status'] == 'ok':
data = {"result": "success","msg": "welcome to use get."}
return data
elif request.method == 'PUT':
if request.form['User'] == 'FK2000':
if request.form['Password'] == '12345':
print(request.form)
data = {"result": "success","cookies": "9f6e7t3j5l1k2s0x"}
return data
elif request.method == 'POST':
if request.form['action'] == 'upload_log':
if request.cookies['cookies'] == "9f6e7t3j5l1k2s0x":
print(request.headers['mp3'])
data = {"result": "success","msg": "upload log ok."}
return data
elif request.form['action'] == 'upload':
if request.cookies['cookies'] == "9f6e7t3j5l1k2s0x":
print(request.files)
request.files['file'].save('./1024.mp3')
file_bytes = request.files['file'].stream.read()
data = {"result": "success","msg": "upload ok."}
response = make_response(data)
header_add = {'upload':'ok'}
response.headers = header_add
return response
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000, debug=True)
上段为Flask服务器部分,下段为requests客户端部分;
import requests
def get_status(r):
status_dict = {}
status_dict['url'] = r.url
status_dict['encoding'] = r.encoding
status_dict['status_code'] = r.status_code
status_dict['request_headers'] = r.request.headers
status_dict['request_body'] = r.request.body
status_dict['respond_headers'] = r.headers
status_dict['respond_body'] = r.text
status_dict['respond_body_bytes'] = r.content
status_dict['respond_body_json'] = r.json()
print('-'*60)
print(status_dict)
print('-'*60)
return status_dict
url = 'http://127.0.0.1:5000'
r = requests.get(url, params = {'status':'ok'}, timeout = (5, 27))
if r.status_code == requests.codes.ok:
get_status(r)
else:
print(r.raise_for_status())
r = requests.put(url, data = {'User':'FK2000','Password':'12345'})
cookies = {'cookies':r.json()['cookies']}
form_data = {'action':'upload_log','type':'mp3'}
key_value = {'key':'mp3'}
headers_add = {'mp3':'ok'}
r = requests.post(url, data = form_data,
params = key_value,
headers = headers_add,
cookies = cookies)
form_data = {'action':'upload','type':'mp3'}
with open('./1024.mp3','rb') as f:
file_data = f.read()
r = requests.post(url, data = form_data,
params = key_value,
headers = headers_add,
cookies = cookies,
files = {'file':file_data})
print(r.headers['upload'])
r = requests.options(url)
print(r.headers['Allow'])
|