os :

  与操作系统交互的模块

  1. os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
  2. os.chdir("dirname") 改变当前脚本工作目录;相当于shellcd
  3. os.curdir 返回当前目录: ('.')
  4. os.pardir 获取当前目录的父目录字符串名:('..')
  5. os.makedirs('dirname1/dirname2') 可生成多层递归目录
  6. os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
  7. os.mkdir('dirname') 生成单级目录;相当于shellmkdir dirname
  8. os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shellrmdir dirname
  9. os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
  10. os.remove() 删除一个文件
  11. os.rename("oldname","newname") 重命名文件/目录
  12. os.stat('path/filename') 获取文件/目录信息
  13. os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
  14. os.linesep 输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
  15. os.pathsep 输出用于分割文件路径的字符串,win下为";", Linux下为":"
  16. os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
  17. os.system("bash command") 运行shell命令,直接显示
  18. os.environ 获取系统环境变量
  19. os.path.abspath(path) 返回path规范化的绝对路径
  20. os.path.split(path) # return tuple(head, tail) where tail is everything after the final slash, 即使为空
  21. os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
  22. os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
  23. os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
  24. os.path.isabs(path) 如果path是绝对路径,返回True
  25. os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
  26. os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
  27. os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
  28. os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
  29. os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间

  还有:

  1. l = os.path.split(r'D:\Users\yangxl\PycharmProjects\yangxl\yangxl.py')
  2. print(l) # ('D:\\Users\\yangxl\\PycharmProjects\\yangxl', 'yangxl.py')
  3.  
  4. l = os.path.splitext(r'D:\Users\yangxl\PycharmProjects\yangxl\yangxl.py')
  5. print(l) # ('D:\\Users\\yangxl\\PycharmProjects\\yangxl\\yangxl', '.py')
  6.  
  7. for dirpaths, dirnames, filenames in os.walk(r'D:\Users\yangxl\PycharmProjects\yangxl\datasets'):
  8. pass

示例,处理文件

  1. now = time.time() # 每次服务器重启时就会执行这段代码
  2. for abs_path, dirs, files in os.walk(path):
  3. for file_name in files:
  4. file_path = os.path.join(abs_path, file_name)
  5. try:
  6. st = os.stat(file_path)
  7. # 删除超过10天的文件
  8. if now - st.st_mtime > 3600 * 24 * 10:
  9. os.remove(file_path)
  10. except Exception, e:
  11. print e

sys:

  与python解释器交互的模块

  1. sys.argv 命令行参数List,第一个元素是程序本身路径
  2. sys.exit(n) 退出程序,正常退出时exit(0)
  3. sys.version 获取Python解释器的版本信息
  4. sys.maxint 最大的Int
  5. sys.path 返回模块的搜索路径,是个列表,初始化时使用PYTHONPATH环境变量的值
  6. sys.platform 返回操作系统平台名称,可以用于跨平台开发
  7. sys.stdout.write('please:')
  8. val = sys.stdin.readline()[:-1]
  9.  
  10. 示例:
  11. if sys.platform == 'win32':
  12. os.system('dir')
  13. else:
  14. os.system('ls')

示例:日志打印

  1. # city.py
  2.  
  3. import sys, os
  4.  
  5. def print_log():
  6. f = sys._getframe(1) # depth
  7. rv = (os.path.normcase(f.f_code.co_filename), f.f_code.co_name, f.f_lineno) # 文件、调用者、调用者在文件中的行数
  8. print(rv)
  9.  
  10. # gogo.py
  11.  
  12. from province.city import print_log
  13.  
  14. def gogo():
  15. print_log()
  16.  
  17. gogo()
  18. # ('/home/yangxl/PycharmProjects/meng/province/city.py', 'print_log', 5)
  19. # ('/home/yangxl/PycharmProjects/meng/gogo.py', 'gogo', 4)

添加环境变量,

  1. sys.path.insert(0, os.path.split(os.path.split(os.path.split(os.path.abspath(__file__))[0])[0])[0]) # 把根目录添加到环境变量

logging:

  日志级别等级:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET。

  日志配置方法:

  1. import logging
  2. logging.basicConfig(level=logging.DEBUG,
  3. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  4. datefmt='%a, %d %b %Y %H:%M:%S',
  5. filename='test.log', # 不配置的话,默认输出到屏幕,二选一
  6. filemode='a')
  7.  
  8. logging.debug('debug message')
  9. logging.info('info message')
  10. logging.warning('warning message')
  11. logging.error('error message')
  12. logging.critical('critical message')

  format的格式:

  1. format参数中可能用到的格式化串:
  2. %(name)s Logger的名字
  3. %(levelno)s 数字形式的日志级别
  4. %(levelname)s 文本形式的日志级别
  5. %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
  6. %(filename)s 调用日志输出函数的模块的文件名
  7. %(module)s 调用日志输出函数的模块名
  8. %(funcName)s 调用日志输出函数的函数名
  9. %(lineno)d 调用日志输出函数的语句所在的代码行
  10. %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
  11. %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
  12. %(asctime)s 字符串形式的当前时间。默认格式是 2003-07-08 16:49:45,896”。逗号后面的是毫秒
  13. %(thread)d 线程ID。可能没有
  14. %(threadName)s 线程名。可能没有
  15. %(process)d 进程ID。可能没有
  16. %(message)s用户输出的消息

  使用logger对象配置日志:

  1. import logging
  2.  
  3. logger = logging.getLogger()
  4. # 创建一个handler,用于写入日志文件
  5. fh = logging.FileHandler('test.log')
  6.  
  7. # 再创建一个handler,用于输出到控制台
  8. ch = logging.StreamHandler()
  9.  
  10. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  11.  
  12. fh.setFormatter(formatter)
  13. ch.setFormatter(formatter)
  14.  
  15. logger.addHandler(fh) # logger对象可以添加多个fh和ch对象
  16. logger.addHandler(ch)
  17.  
  18. logger.setLevel(logging.DEBUG) # 设置日志水平,(在打印日志之前)
  19.  
  20. logger.debug('logger debug message')
  21. logger.info('logger info message')
  22. logger.warning('logger warning message')
  23. logger.error('logger error message')
  24. logger.critical('logger critical message')

configparser:

  生成配置文件:

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4.  
  5. config["DEFAULT"] = {'ServerAliveInterval': '',
  6. 'Compression': 'yes',
  7. 'CompressionLevel': ''}
  8.  
  9. config['bitbucket.org'] = {'User': 'hg'}
  10. config['topsecret.server.com'] = {'Host Port': '', 'ForwardX11': 'no'}
  11. config['DEFAULT']['ForwardX11'] = 'yes'
  12.  
  13. with open('example.ini', 'w') as configfile:
  14. config.write(configfile)

  对配置项进行基本操作:

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4.  
  5. # --------查
  6. config.read('example.ini')
  7.  
  8. # 没列出'DEFAULT',它的数据会列在其他的键值对中,当作默认配置
  9. print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
  10.  
  11. print('bytebong.com' in config) # False
  12.  
  13. print(config['bitbucket.org']['User']) # hg
  14. print(config['DEFAULT']['Compression']) # yes
  15.  
  16. print(config['topsecret.server.com']['ForwardX11']) # no
  17.  
  18. for key in config['bitbucket.org']:
  19. print(key)
  20.  
  21. print(config.options('bitbucket.org')) # ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
  22. print(config.items('bitbucket.org')) # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
  23.  
  24. # 读了默认配置
  25. print(config.get('bitbucket.org', 'compression')) # yes
  26.  
  27. # -------删,改,增(config.write(open('i.cfg', "w")))
  28. config.add_section('yangxl')
  29.  
  30. config.remove_section('topsecret.server.com')
  31. config.remove_option('bitbucket.org', 'user')
  32.  
  33. config.set('bitbucket.org', 'k1', '')
  34.  
  35. config.write(open('example.ini', "w")) # 覆盖原文件

time:

  1. import time
  2. import datetime
  3.  
  4. # 时间戳到字符串, local_time --> strftime
  5. timestamp = time.time()
  6. struct_time = time.localtime(timestamp)
  7. strftime = time.strftime('%Y-%m-%d %H:%M:%S', struct_time) # 2019-04-26 11:53:50
  8. # print(strftime)
  9.  
  10. # 字符串到时间戳, strptime --> mktime
  11. struct_time = time.strptime('2019-04-26 11:53:50', '%Y-%m-%d %H:%M:%S')
  12. timestamp = time.mktime(struct_time) # 1556250830.0
  13. # print(timestamp)
  14.  
  15. # 时间戳到datetime
  16. dt = datetime.datetime.fromtimestamp(1556250830.0) # 2019-04-26 11:53:50
  17.  
  18. # datetime到时间戳, timetuple --> mktime
  19. struct_time = dt.timetuple()
  20. timestamp = time.mktime(struct_time) # 1556250830.0
  21. # print(timestamp)
  22.  
  23. # datetime到date
  24. dte = dt.date() # 2019-04-26
  25. # print(type(dte))
  26.  
  27. # 给定数字生成datetime
  28. dt = datetime.datetime(2019, 4, 26, 12, 23, 34) # 2019-04-26 12:23:34
  29.  
  30. # 添加timedelta
  31. timedelta = datetime.timedelta(3, hours=3, seconds=60) # 3 days, 3:01:00
  32. dt = dt + timedelta # 2019-04-29 15:24:34
  33. # print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) # 2019 4 29 15 24 34
  34.  
  35. # 获取当天0点的时间戳
  36. SECONDS_ONE_DAY = 3600*24
  37. timestamp_day = timestamp // SECONDS_ONE_DAY * SECONDS_ONE_DAY # 1556236800.0
  38. # print(timestamp_day)
  39.  
  40. # 计算两个时间戳相差的天数,天数不是按照24小时计算
  41. # 分两步:计算当天0点时间戳,
  42. # 0点时间戳到datetime
  43. time_1 = 1556250830.0
  44. time_2 = 1556451820.0
  45. days = (datetime.datetime.fromtimestamp(time_2 // SECONDS_ONE_DAY * SECONDS_ONE_DAY) - datetime.datetime.fromtimestamp(time_1 // SECONDS_ONE_DAY * SECONDS_ONE_DAY)).days
  46. # print(days)
  1. print time.strftime('%Y%m%d') # 20190426
  1. time.monotonic() # 这个貌似是从开机到当前的时间戳啊

types:

dir():

  1. # coding:utf8
  2.  
  3. import sys
  4. import types
  5.  
  6. print type(sys) == types.ModuleType # 模块类型
  7.  
  8. print dir(sys)
  9. print dir('yangxl')
  10.  
  11. # 示例:摘自tornado.Application
  12. def _load_ui_modules(self, modules):
  13. if isinstance(modules, types.ModuleType):
  14. self._load_ui_modules(dict((n, getattr(modules, n))
  15. for n in dir(modules)))
  16. elif isinstance(modules, list):
  17. for m in modules:
  18. self._load_ui_modules(m)
  19. else:
  20. assert isinstance(modules, dict)
  21. for name, cls in modules.items():
  22. try:
  23. if issubclass(cls, UIModule):
  24. self.ui_modules[name] = cls
  25. except TypeError:
  26. pass

inspect:

  1. def ismodule(object):
  2. """Return true if the object is a module."""
  3. return isinstance(object, types.ModuleType)
  4.  
  5. def isclass(object):
  6. """Return true if the object is a class."""
  7. return isinstance(object, type)
  8.  
  9. def ismethod(object):
  10. """Return true if the object is an instance method."""
  11. return isinstance(object, types.MethodType)

itertools:

  1. import itertools
  2.  
  3. s = itertools.count() # 这可不是计数器,有参数的哦
  4. print s.next()
  5. print s.next()
  6. print s.next()

hashlib:

1、

  1. >>> import hashlib
  2. >>> m = hashlib.md5()
  3. >>> m.update(b"Nobody inspects") # bytes类型
  4. >>> m.update(b" the spammish repetition")
  5. >>> m.digest()
  6. b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'

2、

  1. hasher = hashlib.sha1()
  2. for part in self._write_buffer:
  3. hasher.update(part)
  4. return '"%s"' % hasher.hexdigest()

socket:

  1. buf = bytearray(self.read_chunk_size)
  2. self.socket.recv_into(buf) # A version of recv() that stores its data into a buffer rather than creating a new string.
  1. socket.gethostname() # 'yangxl-Lenovo-ideapad-330C-15IKB'

re:

  1. re.compile('([\x00-\x7f]+)') # 十六进制, 匹配ASCII表前128个
  1. >>> s = '%E7%BE%8A%E5%B0%8F%E7%BE%9A'
  2. >>> s
  3. '%E7%BE%8A%E5%B0%8F%E7%BE%9A'
  4. >>> import re
  5. >>> _asciire = re.compile('([\x00-\x7f]+)')
  6. >>> _asciire.split(s)
  7. ['', '%E7%BE%8A%E5%B0%8F%E7%BE%9A', '']

带br的,

  1. re.findall(br'\*|(?:W/)?"[^"]*"', "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d")

urllib:

  1. from urllib import request, parse
  2.  
  3. # s = request.urlopen('http://127.0.0.1:9999/login/?name=羊小羚A&age=26')
  4. # print(s.read())
  5.  
  6. d = parse.urlencode([
  7. ('name', '羊小羚'),
  8. ('age', ''),
  9. ])
  10. data = request.urlopen('http://127.0.0.1:9999/login/', d.encode('utf8'))
  11. print(data.read())

collections:

  1. >>> from collections import Mapping
  2. >>> dis = {'name': 'yangxl', 'age': 26}
  3. >>> isinstance(dis, Mapping) # 无法理解
  4. True

collections.queue,

  1. self.queue = collections.deque()
  2. self.queue.append(key)
  3. self.queue.popleft()
  4. 。。。很多方法呢。。。

collections.namedtuple,

  1. SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data']) # 定义
  2. key = SelectorKey(1 2 3 4) # 赋值
  3. print(key.fd) # 取值
  4. 不能修改

collections.defaultdict,

  1. from collections import defaultdict
  2. CLIENT_EXCEPTION_CACHES = defaultdict(int)
  3. had_num = CLIENT_EXCEPTION_CACHES[content_md5] + 1 # 默认是0,然后加1
  4. CLIENT_EXCEPTION_CACHES[content_md5] += 1
  5. # 就是个字典

heapq:

  1. heapq.heappush(self._scheduled, timer)

asyncio.base_events.py中的函数call_at(scheduler.start)

resource:

查看系统资源消耗,

  1. import resource
  2. resource.getrusage(resource.RUSAGE_SELF)[2]

traceback:

  1. import traceback
  2. tb = traceback.format_exc() # tb = 'NoneType\n'

pickle、cPickle:

  1. >>> import pickle
  2. >>> d = {'name': 'yangxl', 'age': 18}
  3. >>> d
  4. {'age': 18, 'name': 'yangxl'}
  5. >>> s = pickle.dumps(d)
  6. >>> s
  7. b'\x80\x03}q\x00(X\x03\x00\x00\x00ageq\x01K\x12X\x04\x00\x00\x00nameq\x02X\x06\x00\x00\x00yangxlq\x03u.'
  8. >>> type(s)
  9. <class 'bytes'>
  10.  
  11. >>> import cPickle as pickle # 只有py2才有
  12. >>> d = {'name': 'yangxl', 'age': 18}
  13. >>> s = pickle.dumps(d)
  14. >>> s
  15. "(dp1\nS'age'\np2\nI18\nsS'name'\np3\nS'yangxl'\np4\ns."
  16. >>> type(s)
  17. <type 'str'>

zlib:

  1. # py2
  2.  
  3. >>> d
  4. {'age': 18, 'name': 'yangxl'}
  5. >>> zlib.compress(d)
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in <module>
  8. TypeError: compress() argument 1 must be string or read-only buffer, not dict
  9. >>>
  10. >>> zlib.compress('d')
  11. 'x\x9cK\x01\x00\x00e\x00e'
  12. >>> zlib.compress(b'd')
  13. 'x\x9cK\x01\x00\x00e\x00e'
  14.  
  15. # py3
  16.  
  17. >>> d
  18. {'age': 18, 'name': 'yangxl'}
  19. >>> zlib.compress(d)
  20. Traceback (most recent call last):
  21. File "<stdin>", line 1, in <module>
  22. TypeError: a bytes-like object is required, not 'dict'
  23. >>>
  24. >>> zlib.compress('d')
  25. Traceback (most recent call last):
  26. File "<stdin>", line 1, in <module>
  27. TypeError: a bytes-like object is required, not 'str'
  28. >>>
  29. >>> zlib.compress(b'd')
  30. b'x\x9cK\x01\x00\x00e\x00e'
  31.  
  32. 到了py3中,即使是字符串类型也不行了

weakref:

  1. temp = property_class.get(self.uid, server) # 对象
  2. setattr(temp, 'weak_user', weakref.proxy(self)) # 弱引用外部传入user,避免循环引用
  3. setattr(self, "_%s" % property_name, temp) # 还有个下划线

requests模块

requests中的方法:

  1. import requests
  2.  
  3. # res = requests.get('http://dig.chouti.com')
  4. # 等同于
  5. res = requests.request(
  6. url='http://dig.chouti.com',
  7. method='get'
  8. )
  9. print(res)

requests模块基本参数:

url、method、params、data、json、headers、cookies

get方法

  1. import requests
  2.  
  3. res = requests.request(
  4. url='https://www.sogou.com/web',
  5. method='get',
  6. params={'query':'羊小羚'} #会拼接成https://www.sogou.com/web?query=羊小羚&...
  7. )
  8. print(res.text)
  9. # 'https://www.sogou.com/web?query=羊小羚' #搜狗
  10. # 'https://www.baidu.com/s?wd=羊小羚' #百度

post方法

  1. form_data = {'phone':8615313144407,'password':'123456','oneMonth':1}
  2.  
  3. res = requests.post(
  4. url = 'http://dig.chouti.com/login',
  5. data = form_data
  6. )
  7. print(res.text) # {"result":{"code":"9999", "message":"", "data":{"complateReg":"0","destJid":"cdu_48196352125"}}}

data和json

  1. res = requests.post(
  2. url = 'http://127.0.0.1:8000/pachong',
  3. # data = {'phone':8615313144406,'password':'chouti123456','oneMonth':1},
  4. # content-type: application/x-www-form-urlencoded,数据传到request.body中然后继续传到request.port中。
  5. # request.POST: <QueryDict: {'oneMonth': ['1'], 'phone': ['8615313144406'], 'password': ['chouti123456']}>
  6. # request.body: b'oneMonth=1&password=chouti123456&phone=8615313144406'
  7. json = json.dumps("{'phone':8615313144406,'password':'chouti123456','oneMonth':1}'")
  8. # content-type: application/json,数据只传到request.body中。
  9. # request.POST: <QueryDict: {}>
  10. # request.body: b'"\\"{\'phone\':8615313144406,\'password\':\'chouti123456\',\'oneMonth\':1}\'\\""'
  11. )
  12. print(res.text)

headers

  1. res = requests.get(
  2. url='https://www.zhihu.com/',
  3. headers={
  4. 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
  5. # 'Referer' : 'https://www.zhihu.com/',
  6. # 如果使用浏览器可以正常访问,但是使用爬虫就不行,那可能就遇到反爬虫策略了,需要添加以下两个参数:
  7. # User-Agent,代表使用什么设备访问,(伪造浏览器)
  8. # Referer,从哪里跳转过来的,一般情况下都是从首页跳转
  9. },
  10. )
  11. print(res.text) #An internal server error occured.

cookies

  1. res = requests.get(
  2. url='https://i.cnblogs.com/Configure.aspx',
  3. # headers={
  4. # 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
  5. # 'Referer' : 'https://www.zhihu.com/',
  6. # 如果使用浏览器可以正常访问,但是使用爬虫就不行,那可能就遇到反爬虫策略了,需要添加以下两个参数:
  7. # User-Agent,代表使用什么设备访问,(伪造浏览器)
  8. # Referer,从哪里跳转过来的,一般情况下都是从首页跳转
  9. # },
  10. # 当需要登录才能访问时,可能需要cookies或session
  11. cookies={
  12. '.CNBlogsCookie' : '886F4CA84CC7BC01EF975E3F27EAF9CC3D894702B2EDD7F2A8C373A603E1CECB1013D7B7BA5734628DFE8091863906995C70C0AB1F9A57B4C7F7A47C29286B9D25139D87A5A96B06438933A87E63790AF63AD83A'
  13. }
  14. )
  15. print(res.text)

requests模块的其他参数:

  1. def request(method, url, **kwargs):
  2. """Constructs and sends a :class:`Request <Request>`.
  3.  
  4. :param method: method for the new :class:`Request` object.
  5. :param url: URL for the new :class:`Request` object.
  6. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
  7. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  8. :param json: (optional) json data to send in the body of the :class:`Request`.
  9. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
  10. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
  11. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
  12. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
  13. or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
  14. defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
  15. to add for the file.
  16. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
  17. :param timeout: (optional) How long to wait for the server to send data
  18. before giving up, as a float, or a :ref:`(connect timeout, read
  19. timeout) <timeouts>` tuple.
  20. :type timeout: float or tuple
  21. :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
  22. :type allow_redirects: bool
  23. :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
  24. :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
  25. :param stream: (optional) if ``False``, the response content will be immediately downloaded.
  26. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
  27. :return: :class:`Response <Response>` object
  28. :rtype: requests.Response
  29.  
  30. Usage::
  31.  
  32. >>> import requests
  33. >>> req = requests.request('GET', 'http://httpbin.org/get')
  34. <Response [200]>
  35. """

实例:

  1. def param_method_url():
  2. # requests.request(method='get', url='http://127.0.0.1:8000/test/')
  3. # requests.request(method='post', url='http://127.0.0.1:8000/test/')
  4. pass
  5.  
  6. def param_param():
  7. # - 可以是字典
  8. # - 可以是字符串
  9. # - 可以是字节(ascii编码以内)
  10.  
  11. # requests.request(method='get',
  12. # url='http://127.0.0.1:8000/test/',
  13. # params={'k1': 'v1', 'k2': '水电费'})
  14.  
  15. # requests.request(method='get',
  16. # url='http://127.0.0.1:8000/test/',
  17. # params="k1=v1&k2=水电费&k3=v3&k3=vv3")
  18.  
  19. # requests.request(method='get',
  20. # url='http://127.0.0.1:8000/test/',
  21. # params=bytes("k1=v1&k2=k2&k3=v3&k3=vv3", encoding='utf8'))
  22.  
  23. # 错误
  24. # requests.request(method='get',
  25. # url='http://127.0.0.1:8000/test/',
  26. # params=bytes("k1=v1&k2=水电费&k3=v3&k3=vv3", encoding='utf8'))
  27. pass
  28.  
  29. def param_data():
  30. # 可以是字典
  31. # 可以是字符串
  32. # 可以是字节
  33. # 可以是文件对象
  34.  
  35. # requests.request(method='POST',
  36. # url='http://127.0.0.1:8000/test/',
  37. # data={'k1': 'v1', 'k2': '水电费'})
  38.  
  39. # requests.request(method='POST',
  40. # url='http://127.0.0.1:8000/test/',
  41. # data="k1=v1; k2=v2; k3=v3; k3=v4"
  42. # )
  43.  
  44. # requests.request(method='POST',
  45. # url='http://127.0.0.1:8000/test/',
  46. # data="k1=v1;k2=v2;k3=v3;k3=v4",
  47. # headers={'Content-Type': 'application/x-www-form-urlencoded'}
  48. # )
  49.  
  50. # requests.request(method='POST',
  51. # url='http://127.0.0.1:8000/test/',
  52. # data=open('data_file.py', mode='r', encoding='utf-8'), # 文件内容是:k1=v1;k2=v2;k3=v3;k3=v4
  53. # headers={'Content-Type': 'application/x-www-form-urlencoded'}
  54. # )
  55. pass
  56.  
  57. def param_json():
  58. # 将json中对应的数据进行序列化成一个字符串,json.dumps(...)
  59. # 然后发送到服务器端的body中,并且Content-Type是 {'Content-Type': 'application/json'}
  60. requests.request(method='POST',
  61. url='http://127.0.0.1:8000/test/',
  62. json={'k1': 'v1', 'k2': '水电费'})
  63.  
  64. def param_headers():
  65. # 发送请求头到服务器端
  66. requests.request(method='POST',
  67. url='http://127.0.0.1:8000/test/',
  68. json={'k1': 'v1', 'k2': '水电费'},
  69. headers={'Content-Type': 'application/x-www-form-urlencoded'}
  70. )
  71.  
  72. def param_cookies():
  73. # 发送Cookie到服务器端
  74. requests.request(method='POST',
  75. url='http://127.0.0.1:8000/test/',
  76. data={'k1': 'v1', 'k2': 'v2'},
  77. cookies={'cook1': 'value1'},
  78. )
  79. # 也可以使用CookieJar(字典形式就是在此基础上封装)
  80. from http.cookiejar import CookieJar
  81. from http.cookiejar import Cookie
  82.  
  83. obj = CookieJar()
  84. obj.set_cookie(Cookie(version=0, name='c1', value='v1', port=None, domain='', path='/', secure=False, expires=None,
  85. discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False,
  86. port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=False)
  87. )
  88. requests.request(method='POST',
  89. url='http://127.0.0.1:8000/test/',
  90. data={'k1': 'v1', 'k2': 'v2'},
  91. cookies=obj)
  92.  
  93. def param_files():
  94. # 发送文件
  95. # file_dict = {
  96. # 'f1': open('readme', 'rb')
  97. # }
  98. # requests.request(method='POST',
  99. # url='http://127.0.0.1:8000/test/',
  100. # files=file_dict)
  101.  
  102. # 发送文件,定制文件名
  103. # file_dict = {
  104. # 'f1': ('test.txt', open('readme', 'rb'))
  105. # }
  106. # requests.request(method='POST',
  107. # url='http://127.0.0.1:8000/test/',
  108. # files=file_dict)
  109.  
  110. # 发送文件,定制文件名
  111. # file_dict = {
  112. # 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf")
  113. # }
  114. # requests.request(method='POST',
  115. # url='http://127.0.0.1:8000/test/',
  116. # files=file_dict)
  117.  
  118. # 发送文件,定制文件名
  119. # file_dict = {
  120. # 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf", 'application/text', {'k1': '0'})
  121. # }
  122. # requests.request(method='POST',
  123. # url='http://127.0.0.1:8000/test/',
  124. # files=file_dict)
  125.  
  126. pass
  127.  
  128. def param_auth():
  129. from requests.auth import HTTPBasicAuth, HTTPDigestAuth
  130.  
  131. ret = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('wupeiqi', 'sdfasdfasdf'))
  132. print(ret.text)
  133.  
  134. # ret = requests.get('http://192.168.1.1',
  135. # auth=HTTPBasicAuth('admin', 'admin'))
  136. # ret.encoding = 'gbk'
  137. # print(ret.text)
  138.  
  139. # ret = requests.get('http://httpbin.org/digest-auth/auth/user/pass', auth=HTTPDigestAuth('user', 'pass'))
  140. # print(ret)
  141. #
  142.  
  143. def param_timeout():
  144. # ret = requests.get('http://google.com/', timeout=1) # 如果只有一个,表示发送请求的时间。
  145. # print(ret)
  146.  
  147. # ret = requests.get('http://google.com/', timeout=(5, 1)) # 如果有两个,第一个表示发送请求的时间,第二个表示读取返回内容的时间。
  148. # print(ret)
  149. pass
  150.  
  151. def param_allow_redirects():
  152. ret = requests.get('http://127.0.0.1:8000/test/', allow_redirects=False)
  153. print(ret.text)
  154.  
  155. def param_proxies():
  156. # proxies = {
  157. # "http": "61.172.249.96:80", # 使用http协议访问网页时,使用'61.172.249.96:80'代理。
  158. # "https": "http://61.185.219.126:3128", # 使用https协议访问网页时,使用'https://61.185.219.126:3128'代理。
  159. # }
  160.  
  161. # proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'} # 访问'http://10.20.1.128'时,使用'http://10.10.1.10:5323'代理。
  162.  
  163. # ret = requests.get("http://www.proxy360.cn/Proxy", proxies=proxies) # 代理,让别人来发送请求
  164. # print(ret.headers)
  165.  
  166. # from requests.auth import HTTPProxyAuth
  167. #
  168. # proxyDict = {
  169. # 'http': '77.75.105.165',
  170. # 'https': '77.75.105.165'
  171. # }
  172. # auth = HTTPProxyAuth('username', 'mypassword') #使用代理,需要登录
  173. #
  174. # r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)
  175. # print(r.text)
  176.  
  177. pass
  178.  
  179. def param_stream():
  180. ret = requests.get('http://127.0.0.1:8000/test/', stream=True)
  181. print(ret.content)
  182. ret.close()
  183.  
  184. # from contextlib import closing
  185. # with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
  186. # # 在此处理响应。
  187. # for i in r.iter_content():
  188. # print(i)
  189.  
  190. def requests_session():
  191. import requests
  192.  
  193. session = requests.Session()
  194.  
  195. ### 1、首先登陆任何页面,获取cookie
  196.  
  197. i1 = session.get(url="http://dig.chouti.com/help/service")
  198.  
  199. ### 2、用户登陆,携带上一次的cookie,后台对cookie中的 gpsd 进行授权
  200. i2 = session.post(
  201. url="http://dig.chouti.com/login",
  202. data={
  203. 'phone': "8615131255089",
  204. 'password': "xxxxxx",
  205. 'oneMonth': ""
  206. }
  207. )
  208.  
  209. i3 = session.post(
  210. url="http://dig.chouti.com/link/vote?linksId=8589623",
  211. )
  212. print(i3.text)

  

标准库 os、sys、logging、configparser、time、requests的更多相关文章

  1. A Byte of Python 笔记(12)python 标准库:sys、os,更多内容

    第14章 python 标准库 Python标准库是随Python附带安装的,它包含大量极其有用的模块. sys 模块 sys 模块包含系统对应的功能.如 sys.argv 列表包含命令行参数. # ...

  2. 介绍下Python的两个标准库 os 和 sys

    import sysprint(sys.path) #python 2 中报错 ....,打印的是绝对路径(***\\python\\lib\\site-packages# 第三方库,后退一级为标准库 ...

  3. 标准库os

    os模块 提供对操作系统进行调用的接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 os ...

  4. Python标准库之Sys模块使用详解

    sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. 处理命令行参数 在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称. 使用sy ...

  5. Python标准库--os模块

    这个模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行.一个例 ...

  6. Python标准库_ sys,random,time

    一.sys 1.   sys这个模块让你能够访问与Python解释器联系紧密的变量和函数 2.  sys模块中一些重要的函数和变量 argv              命令行参数,包括脚本名称 exi ...

  7. python 标准库 -- os

    os os.getcwd() os.getcwd() # 获取当前工作目录 os.listdir(path) os.listdir('/tmp') # 列出指定目录下的文件和目录 os.mkdir(p ...

  8. Python3 标准库:os

    1.重命名 import os os.rename('test.txt','x.txt') #重命名文件或目录 import os os.renames('a/123.txt','a/b/h.txt' ...

  9. Python标准库 os

    (掌握os模块,你需要了解Linux或类Unix系统下常用命令的操作) os.name  指示你正在使用的平台.比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix' ...

随机推荐

  1. linux centos 7上运行teamviewer与找不到ID问题处理办法

    以前在raspberryPi上搞过teamviewer,现在用了CentOS服务器,搞了一个vpn,访问还有点问题,时间紧张,就先给teamviewer. 而centos7 上安装也比较简单,几条命令 ...

  2. Python之道(一)之安装Python

    "Python之道"首先介绍一下在windows系统下怎样安装Python开发环境. (1)下载MSI安装文件 进入网址www.python.org,点击Downloads进入下载 ...

  3. Charles for Mac(HTTP 监视器和网络抓包工具)破解版安装

    1.软件简介    Charles 是在 Mac.Linux 或 Windows 下常用的 http 协议网络包截取工具,在平常的测试与调式过程中,掌握此工具就基本可以不用其他抓包工具了.Charle ...

  4. hexo + Github Page 0元建立博客攻略

    传送门: 5分钟 0元搭建个人独立博客网站(一):https://mp.weixin.qq.com/s/69isJE191WV2gaVbjrwTtw 5分钟 0元搭建个人独立博客网站(二):https ...

  5. Docker 以 docker 方式运行 jenkins

    https://testerhome.com/topics/5798 Docker 以 docker 方式运行 jenkins jmcn · 2016年08月26日 · 最后由 blueshark 回 ...

  6. Hexo NexT 博客与Github page 关联指南

    上篇文章 Hexo 博客框架NexT主题搭建指南 我们已经在本地搭建好了Hexo博客框架NexT 主题的博客程序,但是这感觉还是远远不够. 我们还想把它部署到我们的Github上,让其他人可以看到我们 ...

  7. Atitit php vs node.js attilax总结

    Atitit php vs node.js attilax总结 1.1. 上手度  还是php 1 1.2. Node.js最大的缺点  异步回调导致可读性差..特别嵌套的时候.. 1 1.1. 上手 ...

  8. 【C语言】两个指针(地址)相减

    两个指针相减,为两个指针之间间隔这两个指针类型的数目. 如:int *p,*q; p-q=(p地址-q地址)/sizeof(int) #include <stdio.h> int main ...

  9. ElasticStack系列之九 & master、data 和 client 节点

    在生产环境下,如果不修改elasticsearch节点的角色信息,在高数据量,高并发的场景下集群容易出现脑裂等问题. 默认情况下,elasticsearch 集群中每个节点都有成为主节点的资格,也都存 ...

  10. Pitch detection algorithm(基音搜索算法)PDA相关链接

    第一:维基百科 http://en.wikipedia.org/wiki/Pitch_estimation 简要系统介绍了基音估计算法的分类和一些链接,论文 第二:http://ws2.bingham ...