基础使用

数据类型

  1. '''
  2. 函数不定数量的参数传递
  3. *args 传入的只能是元祖,列表
  4. **kwargs 传入的只能是键值对,字典类型
  5. '''
  6. coll_list = ('1','2')
  7. coll_map = {"a":1,"b":2}
  8. def showCollList(*args):
  9. for arg in args:
  10. print("{}的值为{}".format(arg,arg))
  11. def showCollMap(**kwargs):
  12. for key,value in kwargs.items():
  13. print("{}的值为{}".format(key,value))
  14. showCollList(*coll_list)
  15. showCollMap(**coll_map)
  16. 输出为:
  17. 1的值为1
  18. 2的值为2
  19. b的值为2
  20. a的值为1

日志-同时输出到前台和文件

  1. import sys
  2. import logging
  3. LOG_FORMAT = "%(asctime)s - %(message)s"
  4. LOG_NAME="script"
  5. logger = logging.getLogger(LOG_NAME)
  6. logger.setLevel(logging.INFO)
  7. console_handler = logging.StreamHandler(sys.stderr) # 默认是sys.stderr
  8. console_handler.setLevel(logging.INFO)
  9. console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
  10. file_handler = logging.FileHandler(LOG_NAME+'.log')
  11. file_handler.setLevel(logging.INFO)
  12. file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
  13. logger.addHandler(console_handler)
  14. logger.addHandler(file_handler)
  15. logger.info("info")

数据库操作

pymongo

  1. import pymongo
  2. client = pymongo.MongoClient(host="mongodb://root:pass@127.0.0.1:27017/?authSource=admin")
  3. db=client.dbname
  4. collection = db.collectionName

pyredis

  1. import redis
  2. from urllib import parse
  3. redis_url = 'redis://:{}@localhost:6379/1'.format(parse.quote('myredispass'))
  4. pool = redis.ConnectionPool.from_url(redis_url,None,decode_components=True)
  5. r = redis.Redis(connection_pool=pool)
  6. # 批量操作
  7. values=(1,2,3)
  8. with r.pipeline(transaction=False) as pipe:
  9. for value in values:
  10. pipe.sadd("redis-set-key", value)
  11. pipe.execute()
  12. # OR
  13. pipe.sadd("redis-set-key", *values) #这里要使用*args格式,否则会将整个作为一个值存储
  14. '''
  15. 增量迭代命令
  16. scan - no keys
  17. sscan - no smembers
  18. hscan - no hgetall
  19. zscan - no zrange
  20. '''
  21. #
  22. print("------set------")
  23. r.sadd("set","004")
  24. r.sadd("set","003")
  25. for item in r.sscan_iter("set"):
  26. print("item=",item)
  27. #
  28. print("------hash------")
  29. r.hset("hash","a","1")
  30. r.hset("hash","b","2")
  31. r.hset("hash","c","3")
  32. for k,v in r.hscan_iter("hash"):
  33. print(k,v)
  34. #
  35. print("------zset------")
  36. r.zadd("zset",'a',11,'b',21)
  37. r.zadd("zset",cdef=66,hijk=77)
  38. for k,s in r.zscan_iter("zset"):
  39. print(k,s)

pymysql

  1. import pymysql.cursors
  2. # 连接数据库
  3. connection = pymysql.connect(host='localhost',
  4. user='user',
  5. password='passwd',
  6. db='db',
  7. charset='utf8mb4',
  8. cursorclass=pymysql.cursors.DictCursor)
  9. try:
  10. with connection.cursor() as cursor:
  11. # 创建一条新的记录
  12. sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
  13. cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
  14. # 连接完数据库并不会自动提交,所以需要手动 commit 你的改动
  15. connection.commit()
  16. with connection.cursor() as cursor:
  17. # 读取单条记录
  18. sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
  19. cursor.execute(sql, ('webmaster@python.org',))
  20. result = cursor.fetchone()
  21. print(result)
  22. finally:
  23. connection.close()