基础使用
数据类型
'''函数不定数量的参数传递*args 传入的只能是元祖,列表**kwargs 传入的只能是键值对,字典类型'''coll_list = ('1','2')coll_map = {"a":1,"b":2}def showCollList(*args): for arg in args: print("{}的值为{}".format(arg,arg))def showCollMap(**kwargs): for key,value in kwargs.items(): print("{}的值为{}".format(key,value))showCollList(*coll_list)showCollMap(**coll_map)输出为:1的值为12的值为2b的值为2a的值为1
日志-同时输出到前台和文件
import sysimport loggingLOG_FORMAT = "%(asctime)s - %(message)s"LOG_NAME="script"logger = logging.getLogger(LOG_NAME)logger.setLevel(logging.INFO)console_handler = logging.StreamHandler(sys.stderr) # 默认是sys.stderrconsole_handler.setLevel(logging.INFO)console_handler.setFormatter(logging.Formatter(LOG_FORMAT))file_handler = logging.FileHandler(LOG_NAME+'.log')file_handler.setLevel(logging.INFO)file_handler.setFormatter(logging.Formatter(LOG_FORMAT))logger.addHandler(console_handler)logger.addHandler(file_handler)logger.info("info")
数据库操作
pymongo
import pymongoclient = pymongo.MongoClient(host="mongodb://root:pass@127.0.0.1:27017/?authSource=admin")db=client.dbnamecollection = db.collectionName
pyredis
import redisfrom urllib import parseredis_url = 'redis://:{}@localhost:6379/1'.format(parse.quote('myredispass'))pool = redis.ConnectionPool.from_url(redis_url,None,decode_components=True)r = redis.Redis(connection_pool=pool)# 批量操作values=(1,2,3)with r.pipeline(transaction=False) as pipe: for value in values: pipe.sadd("redis-set-key", value) pipe.execute()# ORpipe.sadd("redis-set-key", *values) #这里要使用*args格式,否则会将整个作为一个值存储'''增量迭代命令scan - no keyssscan - no smembershscan - no hgetallzscan - no zrange'''#print("------set------")r.sadd("set","004")r.sadd("set","003")for item in r.sscan_iter("set"): print("item=",item)#print("------hash------")r.hset("hash","a","1")r.hset("hash","b","2")r.hset("hash","c","3")for k,v in r.hscan_iter("hash"): print(k,v)#print("------zset------")r.zadd("zset",'a',11,'b',21)r.zadd("zset",cdef=66,hijk=77)for k,s in r.zscan_iter("zset"): print(k,s)
pymysql
import pymysql.cursors# 连接数据库connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)try: with connection.cursor() as cursor: # 创建一条新的记录 sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('webmaster@python.org', 'very-secret')) # 连接完数据库并不会自动提交,所以需要手动 commit 你的改动 connection.commit() with connection.cursor() as cursor: # 读取单条记录 sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('webmaster@python.org',)) result = cursor.fetchone() print(result)finally: connection.close()