程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python interface automation core module - database operations and logs

編輯:Python

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
MysqlDB

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

MysqlClient

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

Pymysql

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

SQLAlchemy

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

We use pymysql For example

01
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


Code implementation :

Create database connection object

connect =

pymysql.Connect(

 host='xxxxx',
port=3306,
user='root',
password='XXXX',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor

)

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

cursor.close()

Close the connection

conn.close()

Query order Library

Get a cursor object

cursor = connect.cursor()

Query database name plus table name

mtxshop_trade.es_order

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

02
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 .

DEBUG

INFO

WARNING

ERROR

CRITICAL

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

01
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

logger.setLevel(logging.INFO)

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

stream_handler.setFormatter(formatter)

file_handler.setFormatter(formatter)

Add controller to logger

logger.addHandler(stream_handler)

logger.addHandler(file_handler)

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

logging_init()

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved