requests 的使用其实非常简单,针对不同的 http 方法http请求,分别有不同的方法请求对应,如 get 、 post 、 delete 等

import requests
# get请求
r = requests.get(url='url')
r = requests.post(url='url')
r = requests.put(url='url')
r = requests.delete(url='url')
r = requests.head(url='url')
r = requests.options(url='url')
复制代码

示例代码

利用前面我们分享的 flask restful 教程,先写个后台程序

from flask import Flask, jsonify, request
from flask_restful import Api, Resource, reqparse
USERS = [
    {"name": "zhangsan"},
    {"name": "lisi"},
    {"name": "wangwu"},
    {"name": "zhaoliu"}
]
class Users(Resource):
    def get(self):
        return jsonify(USERS)
    def post(self):
        args = reqparse.RequestParser() 
            .add_argument('name', type=str, location='json', required=True, help="名字不能为空") 
            .parse_args()
        if args['name'] not in USERS:
            USERS.append({"name": args['name']})
        return jsonify(USERS)
    def delete(self):
        USERS = []
        return jsonify(USERS)
class UserId(Resource):
    
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('name', type=str)
        self.parser.add_argument('age', type=int)
    def get(self, userid):
        datas = self.parser.parse_args()
        
        return jsonify(
            {"name": USERS[int(userid)].get('name'), "age": datas.get('age')}
        )
    
    def post(self, userid):
        file = request.files['file']
        file.save('flask_file.txt')
        
        return jsonify({
            'msg' : 'success'
        })
app = Flask(__name__)
api = Api(app, default_mediatype="application/json")
api.add_resource(Users, '/users')
api.add_resource(UserId, '/user/')
app.run(host='0.0.0.0', port=5000, use_reloader=True, debug=True)
复制代码

完成后http请求,启动 flask 服务

get请求示例

先看个不带参的 get 请求

import requests
r = requests.get('http://127.0.0.1:5000/users')
print(r.json())
print(r.status_code)
复制代码

运行结果如下

js监听http请求_http请求_c 监听http请求

再看个带参数的 get 请求

import requests
param = {"name":"lisi", "age":"18"}
r = requests.get('http://127.0.0.1:5000/user/1', params=param)
print(r.json())
print(r.status_code)
复制代码

运行结果如下

http请求_c 监听http请求_js监听http请求

post请求示例

再来看看 post 请求,携带 json 数据

import requests
import json
param = {"name" : "xgx"}
headers = {"Content-type": "application/json"}
r = requests.post('http://127.0.0.1:5000/users', data=json.dumps(param), headers=headers)
print(r.json())
print(r.status_code)
复制代码

运行结果如下

http请求_js监听http请求_c 监听http请求

再来看看 post 请求时提交文件的示例

import requests
files = {'file': open('test.txt', 'rb')}
r = requests.post('http://127.0.0.1:5000/user/1', files=files)
print(r.json())
print(r.status_code)
复制代码

运行结果如下

http请求_c 监听http请求_js监听http请求

delete请求示例

最后看看 delete 请求示例

import requests
r = requests.delete('http://127.0.0.1:5000/users')
print(r.json())
print(r.status_code)
复制代码

运行结果如下

http请求_c 监听http请求_js监听http请求

限时特惠:本站每日持续更新海量设计资源,一年会员只需29.9元,全站资源免费下载
站长微信:ziyuanshu688