laitimes

A library of HTTP requests from Python

author:The Lost Little Bookboy's Note

Brief introduction

requests are third-party libraries used to make standard HTTP requests in Python. It abstracts the complexity behind the request into a nice, simple API so that you can focus on interacting with the service and consuming the data in your application.

Installation

Install using pip

pip install requests
           

HTTP request format

The use of requests is actually very simple, for different HTTP methods, there are different method requests correspondence, such as get, post, delete, etc

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

Sample code

Using the flask restful tutorial we shared earlier, write a background program first

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

app.run(host='0.0.0.0', port=5000, use_reloader=True, debug=True)
           

When you're done, start the flask service

A library of HTTP requests from Python

requests

Get request example

Let's start with a get request without arguments

import requests

r = requests.get('http://127.0.0.1:5000/users')
print(r.json())
print(r.status_code)
           

The result of the run is as follows

A library of HTTP requests from Python

requests

Let's look at a get request with parameters

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)
           

The result of the run is as follows

A library of HTTP requests from Python

requests

Example of a POST request

Let's look at POST requests, which carry JSON data

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)
           

The result of the run is as follows

A library of HTTP requests from Python

requests

Let's look at the example of submitting a file on a POST request

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)
           

The result of the run is as follows

A library of HTTP requests from Python

requests

Example of a delete request

Finally, take a look at the delete request example

import requests

r = requests.delete('http://127.0.0.1:5000/users')
print(r.json())
print(r.status_code)
           

The result of the run is as follows

A library of HTTP requests from Python