python生成随机数据导入数据库


生成伪数据用于各样的功能测试,压力测试。省去手动创建数据比较费时并且数据不够规范的麻烦

法一:采用faker库随机生成

1.关于faker

faker是python一个第三方模块,可以生成伪造数据的Python包,是一个github上的开源项目。通过内置的方法可以快速创建绝大多数类型的数据,比如姓名、地址、电话、身份证、时间、网络信息、文本信息等,并且结合python语法,可以向数据库批量构造压力测试数据。
gtihub仓库
官方文档
源码分析

2.常用方法

https://blog.csdn.net/weixin_43613890/article/details/102778436

3.生成数据,导入MySQL数据库

#常用方法查询:https://www.jianshu.com/p/d227d6522428

# Faker 是一个可以让你生成伪造数据的Python包

#pip3 install pymysql
import pymysql
#pip3 install faker
from faker import Faker


class Faker_mysql(object):
    def __init__(self,conn):
        self.conn = conn

    #建表语句函数,这里给出表结构,如果使用已存在的表,可以不创建表。
    def create_table(self):
        create_table_sql="""
        create table user(
        id int PRIMARY KEY auto_increment,
        username VARCHAR(20),
        password VARCHAR(20),
        address VARCHAR(35) 
        )
        """
        
        return create_table_sql

    #插入数据
    def insert_data(self):
        #创建游标
        cursor = self.conn.cursor()

        #调用建表函数
        # create_table = self.create_table()
        #执行sql语句
        # cursor.execute(create_table)

        
        #实例化Faker库,选择中文 zh-CN
        fake = Faker("zh-CN")
        while True:
            #使用Faker库生成假数据,将其转为字典格式,方便插入数据库
            ctx = {
                'username':fake.name(),
                'password':fake.password(special_chars=False),
                'address':fake.address()
            }
            print(ctx)
            sql="""
            insert into user(%s) value(%s)"""%(','.join([k for k,v in ctx.items()]),
            ','.join(['%s' for k,v in ctx.items()])
            )

            try:
                cursor.execute(sql,[v for k,v in ctx.items()])
                self.conn.commit()

            except:
                print('失败')
                self.conn.rollback()
        

if __name__ == "__main__":
    #连接数据库
    #host(ip地址),prot(端口号),user(用户),password(密码),database/db(数据库),charset='utf8'
    conn = pymysql.connect(host="localhost",
                            port=3306,
                            user="root",
                            password="python3..",
                            db="fakerceshi",
                            charset="utf8")
    print('链接成功')  
    
    faker_mysql = Faker_mysql(conn)   
    faker_mysql.insert_data()

法二:提供拟定的参数列表使用random随机

这是老师提供的一种思路,比较适合生成一些划定范围内的随机数据,记录一下。

参考:https://blog.csdn.net/m0_38139250/article/details/122055632

import random
import time
import shutil
import os
import faker
os.chdir("./") #切换工作路径为当前目录


#随机生成ip地址
ip_slices = [132, 156, 124, 10, 29, 167, 143, 187, 30, 100]
def sample_ip():
    slice = random.sample(ip_slices, 4)
    return ".".join([str(item) for item in slice])

#随机生成访问资源
url_paths = [
    "www/2",
    "www/1",
    "www/6",
    "www/4",
    "www/3",
    "pianhua/130",
    "toukouxu/821"
]

def sample_url():
    return random.sample(url_paths, 1)[0]



#随机生成状态码
status_code = [404, 302, 200]
def sample_status():
    return random.sample(status_code, 1)[0]



#随机生成来源地址
http_referers = [
    "https://www.baidu.com/s?wd={query}",
    "https://www.sogou.com/web?qu={query}",
    "http://cn.bing.com/search?q={query}",
    "https://www.so.com/s?q={query}"
]
search_keyword = [
    "我的祖国",
    "西游降魔篇",
    "阿甘正传",
    "扬名立万",
    "杨恩泽"
]
def sample_referer():
    if random.uniform(0, 1) > 0.2:
        return "-"
    refer_str = random.sample(http_referers, 1)
    # print refer_str[0]
    query_str = random.sample(search_keyword, 1)
    # print query_str[0]
    return refer_str[0].format(query=query_str[0])


#随机生成浏览器信息


#读取userAgentcopy文件并加载到列表中,代码如下:
# 读取userAgentcopy文件中的内容,生成一个userAgentlist列表
userAgentlist = []
with open("userAgentcopy",'r',encoding="UTF-8") as f:
    for line in f.readlines():
        line = line.replace("\"","")
        line = line.replace("\n","")
        userAgentlist.append(line)
# 随机useragent
def useragent():
    return random.sample(userAgentlist,1)

#生成log
# 生成当前时间
def get_timestamp():
    t = time.localtime()
    return time.strftime('%Y-%m-%d %H:%M:%S', t)


# 产生log
def generate_log(count=100, filepath="log", filename="log.txt"):
    # 日志目录
    log_path = os.path.join(os.getcwd(), filepath)
    # 日志文件路径
    log_name = os.path.join(log_path, filename)
    # 判断日志所在目录是否存在
    if not os.path.exists(log_path):
        os.mkdir(log_path)
        print(log_path, "已创建")
    elif os.path.exists(log_path) and os.path.exists(log_name):
        # 如果日志存在,先删除
        print(log_name, "已存在")
        # os.remove(log_name)
        # shutil.rmtree(log_name)
    # 打开日志
    with open(log_name, "a+") as f:
        # 生成日志
        while count >= 1:
            # 获取当前时间
            time_str = get_timestamp()
            # 定义日志格式
            log_format = "{ip}\t{localtime}\t\"GET {url} HTTP/1.0\"\t{referece}\t{status1}\t{useragent}"
            # 生成日志信息
            query_log = log_format.format(
                ip=sample_ip(),
                url=sample_url(),
                status1=sample_status(),
                referece=sample_referer(),
                localtime=time_str,
                useragent=useragent()
            )
            # 将日志写入文件
            f.write(query_log + "\n")
            count = count - 1;
            # 随机休眠
            #time.sleep(random.uniform(0, 2))
            # time.sleep(0.5)


if __name__ == '__main__':
    generate_log(count=1000000, filepath="log", filename="log1.txt")


  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值