python小知识点汇总
一 写mysql
场景:自动化用例中需要构造数据,写入redis
- 表中已有该primary_key的记录,在现有基础上更新字段
- 表中无该记录,需要插入
# 请求传入table字段,db.table,context为要添加的字段等,一般为json或dict def add_table(context,table): # 获取db table及primary_id table_name = table db_name = 'default' #默认的库名 if "." in table: db_name = table.split('.')[0] table_name = table.split('.')[1] else: table = 'advert_dsp.'+table_name
# 得到该表的primary_key sql = "select column_name from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where table_name = '%s' and constraint_name = 'PRIMARY'" % (table_name) primary_key = command(db_name,sql)[0].get("column_name") # 若请求字段有primary_key,则指定记录操作 result = 0 context.text = eval(context.text) if context.text else None primary_value = context.text.get(primary_key) if (primary_key in context.text) else 0 if primary_value: result = command(db_name,'select * from %s where %s=%s'%(table_name,primary_key,primary_value))
"""
# 替换一些常量,可有可无 for k,v in context.text.items(): if v in AutoTest: context.text[k] = AutoTest.get(v)
"""
# 场景1,表中已有对应记录,现有基础上更新 if result: param = dict_to_set(context.text,",") #param = urllib.unquote(urllib.parse.urlencode(context.text).replace("&", ",")) if param: sql_update = 'update %s set %s where %s=%s'%(table_name,param,primary_key,primary_value) command(db_name,sql_update) # 场景2,表中无对应记录,插入新数据 else: context.params = DbData(**context.text).params[table] #与默认值列表整合一下,补充默认值
# 要插入的value中的双引号需要转义,dict.values是会单双引号配合,所以手动处理一下 value_list = [] for k, v in context.params.items(): v = v.replace('"', '\\\"') if isinstance(v, str) else v value_list.append(str(v)) values = '"' + '", "'.join(value_list) + '"'
qmarks = ', '.join(['%s'] * len(context.params)) cols = ', '.join(context.params.keys())
# 可行方案 sql = 'insert into '+table_name+'(%s) values(%s)' % (cols, values) command(db_name,sql)
# 报错方案
sql = 'insert into '+table_name+'(%s) values(%s)' % (cols, qmarks)
command(db_name,sql,values)
报错方案:用的是msyql的execute(sql, param)
不知道为什么会报错,一样的key和value,方案1就正常,方案2就报错了:not enough arguments for format string
二 使用 flask mock 一个小服务
场景:要写一个mock服务或者其他
# -*- coding:utf-8 -*- from flask import Flask from flask import request import sys,json,md5 reload(sys) sys.setdefaultencoding("utf-8") app = Flask(__name__) @app.route('/others/getSignature',methods=['GET']) //域名后的path,是个GET服务 def get_sig(): project = request.args.get('project') # 处理查询 path = request.args.get('path') reqValue = eval(request.args.get('reqValue')) sig = '' str_request = '' timestamp = '' if project == 'meipai': secret_key = "bdaefd747c7d594f" request_value = sorted(reqValue.iteritems(),key = lambda asd:str(asd[1])) for key in request_value: str_request = str_request + str(key[1]) str_temp = path + str_request + secret_key + timestamp m = md5.new() m.update(str_temp) tmp = m.hexdigest() for i in range(16): pos = i*2 sig += tmp[pos+1]+tmp[pos] return sig if __name__ == '__main__': app.run(debug=True,host='192.168.99.31',port=8002)