For automation and performance testing, there is a need to have a Web server that controls the return message data, so Python initially implements a simple Web server that can handle HTTP requests (Get,post,put) and complete the response.
Let's start with a brief explanation of how the Web server is implemented in Python in two steps:
1. Create a socket, bind to the specified IP and port, and keep listening
2. Create a handle class to respond when a request message is received
The main classes used are two:
The base class of the Httpserver:http server, which provides a common way for HTTP servers, you can declare the class directly when you create the server, or you can inherit from this class as needed.
Cgihttprequesthandler: The handle class that handles the request, inherits from the Basehttprequesthandler class, which is explained in the Python document that the class can handle get and post requests, and tries to find out and handle put requests.
For a detailed description of these two classes, refer to the Python Standard class library description: https://docs.python.org/2/library/
The source code is as follows:
Import socket
From OS import curdir,sep
From Basehttpserver import Httpserver
From Cgihttpserver import Cgihttprequesthandler
Import JSON
Class HttpHandler (Cgihttprequesthandler):
def do_get (self):
Try
f = Open (CurDir + Sep + self.path)
Print Self.path
print ' This is a GET method! '
Self.send_response (200)
Self.send_header (' Content-type ',
' text/html ')
Self.end_headers ()
Self.wfile.write (F.read ())
F.close ()
Except IOError:
Self.send_error (404, ' File not found:%s '% Self.path)
def do_post (self):
Try
Print Self.path
print ' This is a POST method! '
Self.data = Self.request.recv (1024x768). Strip ()
Self.data = Json.loads (self.data)
Print Self.data
SendData = {}
if Self.path = = '/getfile ':
f = Open (CurDir + Sep + '/test_body.txt ')
Filecontent = F.read ()
senddata[' content ' = filecontent
F.close ()
Self.send_response (200)
Self.send_header (' Content-type ',
' text/html ')
Self.end_headers ()
Self.wfile.write (SendData)
Except
Self.send_error (404, ' Invalid request:%s! '% self.path)
def do_put (self):
Try
Print Self.path
print ' This is a PUT method! '
Self.data = Self.request.recv (1024x768). Strip ()
Print Self.data
SendData = {}
if Self.path = = '/getfile ':
f = Open (CurDir + Sep + '/test_body.txt ')
Filecontent = F.read ()
senddata[' content ' = filecontent
F.close ()
Self.send_response (200)
Self.send_header (' Content-type ',
' text/html ')
Self.end_headers ()
Self.wfile.write (SendData)
Except
Self.send_error (404, ' Invalid request:%s! '% self.path)
def main ():
Try
Localip = Socket.gethostbyname (Socket.gethostname ())
Server_address = (localip,8080)
Http_server = Httpserver (Server_address,httphandler)
SA = Http_server.socket.getsockname ()
Print "Serving HTTP on", Sa[0], "Port", sa[1], "..."
print ' Press ^c once or twice to quit. '
Http_server.serve_forever ()
Except Keyboardinterrupt:
print ' ^c received,shutting down server. '
Http_server.socket.close ()
if __name__ = = ' __main__ ':
Main ()
A new Httpserver class is created in the main () function, bound to port 8080 on this machine, and remains monitored. When a request is received, different do_* functions are entered according to the requested method type. The processing logic of the function is simple, if the URL being sent is legitimate, the return code is set to 200, then the contents of a file are read and written to the return message. Such a simple Web server is done, you can test it with restclient.
HTTPS increases the SSL channel relative to HTTP, and the client and server must have a mutually trusted certificate to communicate. Oneself to this aspect of content before completely do not understand, took a lot of effort to initially put HTTPS request to pass.
Compared to the HTTP server, the HTTPS change is mainly when the server is established:
Class Securehttpserver (Httpserver):
def __init__ (self, server_address, Handlerclass):
Baseserver.__init__ (self, server_address, Handlerclass)
Self.socket = SSL. Sslsocket (Socket.socket (self.address_family,self.socket_type), keyfile= './server.key ', certfile= './server.crt ', Server_side=true)
Self.server_bind ()
Self.server_activate ()
Here, a new Securehttpserver class is declared, inheriting from the Httpserver class, where the constructor is redefined, primarily by creating a new sslsocket type of socket, and specifying the KeyFile and CertFile of the socket. KeyFile and CertFile These two files are manually generated after installing OpenSSL, perform the following OpenSSL command to generate the Pem file locally:
Req-new-x509-keyout server.pem-out Server.pem-day 365-nodes
Copy the certificate part of the Server.pem file to save as SERVER.CRT. Execute the following command to generate or delete the certificate locally:
Keytool-import-alias certificatekey-file Server.crt-keystore Server.jks
Keytool-delete-alias Certificatekey-keystore Server.jks
Upload the SERVER.JK to the system that sent the request as the certificate library.
A new handler class is declared to process the received request and adds a multithreaded mechanism:
Class Securehttphandler (Cgihttprequesthandler):
# def setup (self):
# self.connection = Self.request
# # self.rbufsize = 8192
# # self.wbufsize = 8192
# self.rfile = Socket._fileobject (Self.request, "RB", Self.rbufsize)
# self.wfile = Socket._fileobject (self.request, "WB", Self.wbufsize)
def commonprocess (self):
#处理请求的通用函数
Try
#设置不阻塞
Self.request.setblocking (0)
#设置超时时间为5秒
Self.request.settimeout (5)
#自己的处理代码
f = Open (CurDir + Sep + self.path)
Print Self.path
print ' This is a GET method! '
Self.send_response (200)
Self.send_header (' Content-type ',
' text/html ')
Self.end_headers ()
Self.wfile.write (F.read ())
F.close ()
Except
Logging.error (' Invalid request:%s! '% self.path)
Self.send_error (404, ' Invalid request:%s! '% self.path)
def do_get (self):
Logging.info (' Received url is%s '% Self.path)
Logging.info (' This is a GET method! ')
#self. Commonprocess ()
t = Threading. Thread (target = Self.commonprocess,args = ())
T.start ()
T.join (5)
def do_post (self):
Logging.info (' Received url is%s '% Self.path)
Logging.info (' This is a POST method! ')
#self. Commonprocess ()
t = Threading. Thread (target = Self.commonprocess,args = ())
T.start ()
T.join (5)
def do_put (self):
Logging.info (' Received url is%s '% Self.path)
Logging.info (' This is a PUT method! ')
#self. Commonprocess ()
t = Threading. Thread (target = Self.commonprocess,args = ())
T.start ()
T.join (5)
In the main () function, you declare the object of this class to create the server:
Https_server = Securehttpserver (Server_address,securehttphandler)
The following is the test code for the client:
Import Httplib
def main ():
conn = Httplib. Httpsconnection (host = "127.0.0.1", port = 8443, key_file= './server.key ', cert_file= './server.crt ', source_address = (' 1 27.0.0.1 ', 8080))
Print "Requesting ..."
Conn.request (' PUT ', '/test_body.txt ')
R1 = Conn.getresponse ()
#打印响应码和响应状态信息
Print R1.status, R1.reason
In addition, the twisted framework in Python seems powerful when it comes to working with Web servers, and can be looked into later.
Python builds a simple Web server