SoFunction
Updated on 2024-11-19

Python to get the interface request time-consuming method details

You want to know if we're requesting aurlHow long do the handshake and request resources take when you use the Today we're usingpythonWrite a small case study to see.

import socket
import time

def funcRunTimes(func):
    def wrapper(*args):
        startTime = ()
        result = func(*args)
        endTime = ()
        execTime = endTime - startTime
        return (result,execTime)
    return wrapper

@funcRunTimes
def shakeHands(hosts,port):
    s = (socket.AF_INET, socket.SOCK_STREAM)
    try:
        ((hosts, port))
        return s
    except Exception as e:
        print(e)
        return None

@funcRunTimes
def websiteResponseTime(fd,methods,url):
    sendMsgs = "%s %s HTTP/1.1\r\nHost: 127.0.0.1:8080\r\n\r\n" %(methods,url)
    (())
    recv_data = ""
    while True:
        recv_data = str((15))
        break

    httpCode = recv_data.split(" ")[1]
    return httpCode

def main():
    hosts = ""
    port = 80

    methods = "GET"
    url = "/"

    print("Execute command as: %s %s:%d %s\n" % (methods, hosts, port, url))

    shakeInfo = shakeHands(hosts,port)
    if shakeInfo == None:
      print("errors")
      return
    responseInfo = websiteResponseTime(shakeInfo[0],methods,url)
    print("Interface status code is:" , responseInfo[0],"Handshake time: %.6fs" %(shakeInfo[1]) , "Time spent requesting interface: %.6fs" %(responseInfo[1]) ,"Total time spent: %.6fs" % (shakeInfo[1] + responseInfo[1]))

if __name__ == '__main__':
    main()

The project uses thepythondecorator, if there is also a change to thepythonFor those of you who don't know much about decorators, you can refer to the following article.python | Exploring python decorators

Project Showcase

Open the project and modify thehostsportmethodsas well asurlvariable, you can run thepythonThe time at which the program will be able to obtain the details of the page, which includeTCP/IPThe three handshake times, the request interface time, and finally the total time.

How to get handshake time

When getting the handshake time, you can't use thehttpLibraries, e.g..requests, because it will by default performtcp/ipthree handshakes before making a resource request, so we're going to use thesocketto do this demand.

existpythonMiddle.socketProvides a cross-platform network communication interface that can be used to create various types of network connections.

For example, the code is as follows.

import socket
s = (socket.AF_INET, socket.SOCK_STREAM)
(('127.0.0.1', 8080))

In the above code, we start by importing thesocketlibrary, which in turn uses the()Create asockethandles, and the middle parameters represent the meaning of each:

  • socket.AF_INET: DesignationIPv4Agreement.
  • socket.SOCK_STREAM: Specify the use ofTCPStreaming socket type.

(indicates contrast)The connection to the server is initiated with a tuple parameter of type Tuple and values of Remote Hostname and Remote Port.

As the above code, when the remote server can not be connected or other exceptions, the code will throw an exception, if there is no exception, it proves that the port through.

We only need to pull the current timestamp both before and after this to calculate the time spent on the handshake, for example:

import socket
import time
try:
    startTime = ()
    s = (socket.AF_INET, socket.SOCK_STREAM)
    (('127.0.0.1', 8080))
    endTime = ()
    print("runtimes: " , endTime-startTime)
except Exception as e:
    print("Catching anomalies" , e)

If there are no throw errors, we can get handshake time.

How to get the request time

After a successful handshake, we can send that server thehttpThe message is up. Pay attention.simplestThe format of the message is.

Request Method Request Route Version Number
Request header (hostname)
blank line

Example.

GET / HTTP/1.1
Host: 127.0.0.1:8080

If we don't add theHostrequest header, an error is thrown.HTTP/1.1 400 Bad Request: missing required Host header

existpythonIn this case, we directly use the()function to send a request, e.g.

s = (socket.AF_INET, socket.SOCK_STREAM)
(('127.0.0.1', 8080))
(b"GET / HTTP/1.1\r\nHost: 127.0.0.1:8080\r\n\r\n")

In the above code, the\r\nis a line break, also known asCRLFNote the last 2\r\nis to have a blank line to mark thehttpEnd of request header.

Generally, after we request an interface, we read the status code returned from the server so that development can verify that it was successful.

Here you can use the()function to read the information returned from the server, for example, to read the 15 bytes returned from the server(15)

We can refer to the method of calculating the handshake time to calculate the time of the resource request, the code is as follows:

import socket
import time
s = (socket.AF_INET, socket.SOCK_STREAM)
(('127.0.0.1', 8080))

startTime = ()
(b"GET / HTTP/1.1\r\nHost: 127.0.0.1:8080\r\n\r\n")
recv_data = str((15))
endTime = ()
print("runtimes: ", endTime - startTime,"Interface return status code: " , recv_data.split(" ")[1])

If both the remote host and the remote port are OK, we would probably get something like.

Make good use of decorators

We calculate the handshake time, and calculate the resource request time, are the same code, because the calculation of the function is different, so we need to be forced to write 2 times, at this time, you can use the decorator, to extract this additional non-core functions, and will calculate the handshake and calculate the resource request are encapsulated as a function, and then call the decorator through the function, you can get the two kinds of request time.

Let's start by abstracting the decorator:

def funcRunTimes(func):
    def wrapper(*args):
        startTime = ()
        result = func(*args)
        endTime = ()
        execTime = endTime - startTime
        return (result,execTime)
    return wrapper

We are infuncRunTimesReturns directly to thewrapperfunction, while thewrapperfunction, define the start time and the end time, and execute the function in the middle of the twofuncFinally, thefuncand the time the function was executed are encapsulated into a tuple for return.

At this point, we can encapsulate the function, for example, if we want to get the time of the handshake, we can write this.

@funcRunTimes
def shakeHands(hosts,port):
    s = (socket.AF_INET, socket.SOCK_STREAM)
    try:
        ((hosts, port))
        return s
    except Exception as e:
        print(e)
        return None

If this remote host can be connected, we directly return thesockethandle, if the connection is not available, directly print an error and return theNone

The call to the function is that we just receive the return value:

shakeInfo = shakeHands(hosts,port)

Attention.shakeInfois a tuple with 2 tuples, the first of which is thesockethandle, and the second is the time it takes to execute the function.

Let's wrap the resource request function a bit more and we'll be done with the project.

summarize

We usepython socketConnect to the server, and sendhttpmessage, and then calculate the time of the execution of the 2 functions, you can get the handshake and resource request time, and then finally extract the function to get the time, encapsulated as a decorator for the function to call, you can get the execution time of the function.

To this point this article on Python to obtain the interface request time-consuming method detailed article is introduced to this, more related Python interface request time-consuming content, please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!