Python interface automation core module - database operations and logs

Code classmate software test 2022-06-23 17:05:20 阅读数:706


When carrying out interface test , We need to connect to the database , Back up the data source 、 Restore 、 Verification and other operations .

Python Common modules for connecting to databases

python2 The hottest driver library of the times . be based on C Development , Yes windows Platform unfriendly . Now it has entered python3 Time , Basically no longer use


It is a heavyweight Web Development framework Django in ORM Function dependent tools


pure Python The driver of implementation , Performance ratio MysqlDb Bad , But the installation is simple , Easy to use


That is, it supports native SQL Also support ORM The library of

We use pymysql For example

Pymysql Usage method

Installation method :pip install pymysql

Pymsyql Usage flow
Get the connection

To obtain the cursor -- The function of cursor is to traverse the records returned by query database , In order to carry out the corresponding operation

perform SQL sentence

Close cursor

Close the connection

 Insert picture description here
 Insert picture description here

Code implementation :

Create database connection object

connect =




connect: receive Pymysql.connect Object returned by method , Establish connection object

pymysql.Connect Establish connection method

host=XXXX Connect to the database server

port=3306 Connection database port number

password=“xxxxx”: password

charset=“utf8mb4”: The code for establishing the connection

cursorclass=pymysql.cursors.DictCursor: Set the return data type Return dictionary

Create cursors

cursor = conn.cursor()

Executive core SQL sentence

Close cursor


Close the connection


Query order Library

Get a cursor object

cursor = connect.cursor()

Query database name plus table name


cursor.execute(“SELECT order_id,trade_sn FROM mtxshop_trade.es_order WHERE order_id=47050 OR order_id=47049”)

data = cursor.fetchall() # Get all the results of the query

cursor.close()# Close cursor object

The basic concept of log

Mention log , Whether it's writing framework code or business code , Are inseparable from the log records , He can bring us great help in locating the problem , The best practice is to use built-in logging modular , because logging The module provides developers with very rich functions .

The level of logging

The log level is used to control the information level of the printed log

First , When configuring the log module , You need to set the log level of the log module first

for example , If set to INFO Level , Then print the log with DEBUG The log will not be output .






Log output mode

Output to console

output to a file

Log format

Specify the format and content of the output log. Common formats are :

%(levelno)s: Print log level values

%(levelname)s: Print log level name

%(pathname)s: Print the path of the currently executing program , In fact, that is sys.argv[0]

%(filename)s: Print the name of the currently executing program

%(funcName)s: Print the current function of the log

%(lineno)d: Print the current line number of the log

%(asctime)s: Time to print the log

%(thread)d: Print thread ID

%(threadName)s: Print thread name

%(process)d: Printing process ID

%(message)s: Print log information

logging Usage flow

First step : Instantiation logging modular

The second step : Set log level

The third step : Configure the log processor 、 Log format ; Log processor : Control the printing mode of the log

Step four : Print log

logging Module processing flow


The interface test framework implements the log collection function

Write the log configuration function code

This function configures the output log to the console and file , And set the log printing format

def logging_init():

Initialize the logger

logger = logging.getLogger()

Set log level


Add controller

stream_handler = logging.StreamHandler()

file_handler = logging.handlers.TimedRotatingFileHandler(config.BASE_DIR + “/logs/lagou_log.log”, when=‘h’,

interval=1,backupCount=3, encoding=“utf-8”)

Format log

fmt = "%(asctime)s %(levelname)s [%(name)s] [ %(filename)s %(funcName)s % (lineno)d ] %(message)s "

formatter = logging.Formatter(fmt)

Add the log format to the controller



Add controller to logger



return logger

And then in api. init .py This function is called , Complete the initialization of the log

from utils import logging_init

Initialize the log configuration function


Test print log

import logging

logging.debug(“ test debug Level of log printing ”) # Don't print

stay api. init .py Reason for initializing log configuration :

execute perform script Use case in ,script The use case in is to call api Interface implementation interface testing , Follow the module syntax , When calling a module , It will automatically execute the... Under the module init .py Code

follow-up , Only need to print the log in the module , Import logging Installation package , You can output the log information of the configured log format and log level


版权声明:本文为[Code classmate software test]所创,转载请带上原文链接,感谢。