Encapsulates the Request class

review

Last time, we improved the login and registration related page, as well as the back-end interface, which is to complete the coding work of a function from 0 to 1. Maybe the front part will be rough, because the first may be the author’s lack of attainments, and the second is also related to our direct transformation from the existing framework, many things are not written from 0 to 1, but from 1 to 1.1, but the latter is different:

The following pages are written by ourselves, for our own use, from 0 to 1

Install requests library

The terminal enters pip3 Install Requests and executes.

Design the back-end Request interface

Remember, this is an interface testing platform (UI automation may be integrated later, but I haven’t figured that out yet). An interface automation platform, the core of course is the API request operation, so we urgently, speed up the progress, strike while the iron is hot, to some dry goods. Use Requests to assist us with interface automation requests.

Let’s create a new file: Middleware/httpClient.py

import datetime

import requests


class Request(object) :

    def __init__(self, url, session=False, **kwargs) :
        self.url = url
        self.session = session
        self.kwargs = kwargs
        if self.session:
            self.client = requests.session()
            return
        self.client = requests

    def get(self) :
        return self.request("GET")

    @staticmethod
    def get_elapsed(timer: datetime.timedelta) :
        if timer.seconds > 0:
            return f"{timer.seconds}.{timer.microseconds // 1000}s"
        return f"{timer.microseconds // 100}ms"

    def request(self, method: str) :
        status_code = 0
        elapsed = "-1ms"
        try:
            if method.upper() == "GET":
                response = self.client.get(self.url, **self.kwargs)
            elif method.upper() == 'POST':
                response = self.client.post(self.url, **self.kwargs)
            else:
                response = self.client.request(method, self.url, **self.kwargs)
            status_code = response.status_code
            ifstatus_code ! =200:
                return Request.response(False, status_code)
            elapsed = Request.get_elapsed(response.elapsed)
            data = response.json()
            return Request.response(True.200, data, response.headers, response.request.headers, elapsed=elapsed)
        except Exception as e:
            return Request.response(False, status_code, msg=str(e), elapsed=elapsed)

    def post(self) :
        return self.request("POST")

    @staticmethod
    def response(status, status_code=200, response=None, response_header=None,
                 request_header=None, elapsed=None, msg="success") :
        request_header = {k: v for k, v in request_header.items()}
        response_header = {k: v for k, v in response_header.items()}
        return {
            "status": status, "response": response, "status_code": status_code,
            "response_header": response_header, "request_header": request_header,
            "msg": msg, "elapsed": elapsed,
        }

Copy the code

If I were a product manager, Postman would be my prototype:

First of all, this is a Request Request class, which has a core method: Request. At present, we only support JSON Request, and then complete form, file and other types of Request.

What this class does is simply wrap a layer around the requests related methods.

The constructor provides a few options, including request information, URL, whether or not the request was requested as a session, and so on. Kwargs covers requests’ native parameters, which you can pass in whenever you want.

Get_elapsed is a processing of the request time based on postman, measured in seconds if the request response time is greater than 1s, and in milliseconds otherwise.

Response is to construct a return structure object to collate the data of this request.

Request encapsulates the core operations of the Requests library, is essentially native processing, and determines HTTP status codes.

Writing the Request Interface

The new controllers/request/HTTP. Py

from flask import Blueprint
from flask import jsonify
from flask import request

from app.middleware.HttpClient import Request

req = Blueprint("request", __name__, url_prefix="/request")


@req.route("/http", methods=['POST'])
def http_request() :
    data = request.get_json()
    method = data.get("method")
    if not method:
        return jsonify(dict(code=101, msg="Request mode cannot be empty."))
    url = data.get("url")
    if not url:
        return jsonify(dict(code=101, msg="Requested address cannot be empty"))
    body = data.get("body")
    headers = data.get("headers")
    r = Request(url, data=body, headers=headers)
    response = r.request(method)
    return jsonify(dict(code=0, data=response, msg="Operation successful"))

Copy the code

This is similar to the login/registration interface, which basically creates a blueprint prefixed with/Request, which then introduces the request class, makes the HTTP request, and returns a response.

Adjust the run. Py

We have created a new blueprint and need to register it with run.py:

from app.controllers.request.http import req
pity.register_blueprint(req)
Copy the code

That’s it for this section, next let’s write our first component: Postman. Is the front-end content, let’s do a page close to Postman, do not need more lofty, do things to seize the user’s use habits. After all, we are not 🍎, its idea is to let users to adapt to it.

Back end code address: github.com/wuranxu/pit…

Front-end code address: github.com/wuranxu/pit…