Quickly implement system prototype using Python
[Summary] A quick prototype constructs a prototype before developing a real system. Based on the prototype, the entire system is developed gradually. Python is very easy to use and supports Windows/MAC/Unix/Linux/Solaris multi-operating system platforms, which can help developers complete tasks more quickly on these platforms. At the same time, Python has a powerful basic class library and a large number of third-party extension libraries, so it is also widely used. This article provides an example to illustrate how to use python to quickly implement an asynchronous multi-thread front-end machine system.
[Keywords] Dynamic Programming Language rapid prototype development front-end Simulation System
I. system Background
When developing a cross-platform business system, to ensure the data security of the backend server, the client usually communicates with the front-end transaction machine, sends transaction requests, receives transaction requests from the front-end transaction machine, and then interacts with the back-end server, obtain the returned data of the transaction from the background, and then return the data to the client in the format of the transaction message.
The operating system used by the transaction front-end server is complex. Generally, it depends on the specific situation of the customer unit. Some adopt Windows systems, and some adopt Unix/Linux or Solaris systems. However, before going to the customer's organization for project implementation, developers need to debug client transactions at any time during the development process. This requires a system to simulate the front-end transaction, during the debugging process, you can easily modify the definition of the transaction message and simulate the transaction message returned by the background. In the development of some systems, this simulation system can be used as a complete system prototype. The process of developing the system is to gradually improve the transaction type and transaction return data based on this prototype, finally, the entire system is developed.
Simulation System Development can be implemented in multiple ways, while Dynamic Language Python is easy to use, rich class libraries, and easy to modify. This article describes how to develop a simulation system using python to quickly implement the most common functions of a transaction front-end machine: receiving transaction requests, organizing returned data, and sending returned data.
Ii. Differences between PythonStep(Non-blocking) Communication
The asyncore library is a standard library of Python, which is an asynchronous socket package. We can directly use socket and other underlying libraries for network communication, but asyncore makes it easier for us to communicate over the network, avoiding direct use of socket, select, poll and other tools need to face complex processing.
The asyncore library is simple and contains only one loop () function and one Dispatcher base class. Every class Object inherited from dispatcher can be considered as a socket to be processed, which can be a TCP connection or UDP.
The asyncore library is easy to use. We only need to define a class, which inherits the dispatcher and then rewrite (overwrite) Some methods. The methods we need to override are generally headers with handle.
The loop () function is used to detect an instance of dispatcher stored in a dictionary, which is called a channel. Every time you create a dispatcher object, you will add yourself to a default dictionary. When an object is added to the channel, the socket behavior has been defined. The program only needs to call loop (), and the asynchronous multi-thread communication function is ready.
Iii. Focus on Business Processing
In our simulation system, a main communication service class is defined to inherit from asyncore because multiple client services are required at the same time. dispatcher class, override the handle_accept method of this class, obtain the client connection from here, output the Client IP address and port information to the console, and forward it to the processing Thread class.
The processing Thread class inherits from asyncore. dispatcher_with_send. This class can receive and send data, and only needs to override the handle_read method.
In this way, an asynchronous multi-thread transaction simulation system can run.
The handle_read method is triggered whenever the client sends data. In this method, you can determine the validity of the transaction data, extract the transaction category, extract the transaction data, organize the transaction return data, and send the data to the client, the entire transaction process is complete.
Here, you can easily add new transactions by judging the transaction type.
Iv. Code Summary
1. import warehouse receiving File
import asyncore import socketimport sys
2. Main Communication Service
During class initialization, create a socket connection, bind it to the specified port, and set the maximum number of concurrent connections. The default value is 10, which can serve up to 10 clients at the same time.
When the client calls, the handle_accept method is triggered. Here, the Client IP address and port information are output, and the processing Thread class secondaryserversocket is started.
When the client is disconnected, the handle_colse method is triggered. This method also calls the close method of asyncore. Dispatcher class to handle the problem.
Class mainserversocket (asyncore. dispatcher): def _ init _ (self, Port): asyncore. dispatcher. _ init _ (Self) self. create_socket (socket. af_inet, socket. sock_stream) self. BIND ('', Port) # You can set the maximum number of connections in the configuration file. Currently, 10 connections are self. listen (10) # Up to N client services can be simultaneously def handle_accept (Self): newsocket, address = self. accept () print ("new connection, from {}". format (Address) secondaryserversocket (newsocket) def handle_close (Self): asyncore. dispatcher. close (Self)
3. Processing Thread class
This class is inherited from asyncore. dispatcher_with_send. When the client sends a transaction message, the handle_read method is triggered.
In the handle_read method, the transaction packets are analyzed based on the specific communication protocol, and then processed separately for different transaction types. Finally, the processed transaction message is sent to the corresponding client.
Class secondaryserversocket (asyncore. dispatcher_with_send): def handle_read (Self): receivedhead = self. recv (4) if your edhead: If (LEN (your edhead) = 4) and (your edhead. isdigit (): Print ("packet header received successfully, packet length :{}... ". format (receivedhead) receiveddata = self. recv (INT (receivedhead) print ("the content of the specified length packet is successfully received... ") # -------------------- #0. special transaction processing: Server exit # -------------------- if (LEN (receiveddata) = 4) and (receive DData. Lower (). endswith ("exit"): Self. Close () print ("the server exits after receiving the exit command! ") Try: asyncore. close_all () returnexcept: SYS. Exit (0) return # -------------------- #... normal transaction processing #----------------------... Else: Self. Close () print ("illegal message header received! ") For X in range (LEN (random edhead): Print hex (ord (random edhead [x])," ", print () else: Self. close () def handle_close (Self): Print ("disconnected, from {}. ". format (self. getpeername ()))
4. Main Program Portal
The program starts from here. First, print the program help information, and then start the main communication service thread on the specified listening port.
If _ name _ = "_ main _": Print _ Doc _ mainserversocket (3555) print ("the server starts listening... ") asyncore. loop ()
[References]
1. Python Getting Started Guide release2.5b2, translated collectively by Guido van rosum, 2006.07.11, and Python China User Forum.
2. Version 2 of Python core programming, Author: (US) Chun (W. J.), translated by Song Jiguang, 2008.07, Beijing: People's post and telecommunications press.
3. Deep Python: Dive into Python Chinese Version 5.4b, Author: markpilgrim, collective translation of Python Chinese User Forum, updated review (5.4b): June to September 2007