标准库 os、sys、logging、configparser、time、requests
os :
与操作系统交互的模块
- os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
- os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
- os.curdir 返回当前目录: ('.')
- os.pardir 获取当前目录的父目录字符串名:('..')
- os.makedirs('dirname1/dirname2') 可生成多层递归目录
- os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
- os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
- os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
- os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
- os.remove() 删除一个文件
- os.rename("oldname","newname") 重命名文件/目录
- os.stat('path/filename') 获取文件/目录信息
- os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
- os.linesep 输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
- os.pathsep 输出用于分割文件路径的字符串,win下为";", Linux下为":"
- os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
- os.system("bash command") 运行shell命令,直接显示
- os.environ 获取系统环境变量
- os.path.abspath(path) 返回path规范化的绝对路径
- os.path.split(path) # return tuple(head, tail) where tail is everything after the final slash, 即使为空
- os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
- os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
- os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
- os.path.isabs(path) 如果path是绝对路径,返回True
- os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
- os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
- os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
- os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
- os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
还有:
- l = os.path.split(r'D:\Users\yangxl\PycharmProjects\yangxl\yangxl.py')
- print(l) # ('D:\\Users\\yangxl\\PycharmProjects\\yangxl', 'yangxl.py')
- l = os.path.splitext(r'D:\Users\yangxl\PycharmProjects\yangxl\yangxl.py')
- print(l) # ('D:\\Users\\yangxl\\PycharmProjects\\yangxl\\yangxl', '.py')
- for dirpaths, dirnames, filenames in os.walk(r'D:\Users\yangxl\PycharmProjects\yangxl\datasets'):
- pass
示例,处理文件
- now = time.time() # 每次服务器重启时就会执行这段代码
- for abs_path, dirs, files in os.walk(path):
- for file_name in files:
- file_path = os.path.join(abs_path, file_name)
- try:
- st = os.stat(file_path)
- # 删除超过10天的文件
- if now - st.st_mtime > 3600 * 24 * 10:
- os.remove(file_path)
- except Exception, e:
- print e
sys:
与python解释器交互的模块
- sys.argv 命令行参数List,第一个元素是程序本身路径
- sys.exit(n) 退出程序,正常退出时exit(0)
- sys.version 获取Python解释器的版本信息
- sys.maxint 最大的Int值
- sys.path 返回模块的搜索路径,是个列表,初始化时使用PYTHONPATH环境变量的值
- sys.platform 返回操作系统平台名称,可以用于跨平台开发
- sys.stdout.write('please:')
- val = sys.stdin.readline()[:-1]
- 示例:
- if sys.platform == 'win32':
- os.system('dir')
- else:
- os.system('ls')
示例:日志打印
- # city.py
- import sys, os
- def print_log():
- f = sys._getframe(1) # depth
- rv = (os.path.normcase(f.f_code.co_filename), f.f_code.co_name, f.f_lineno) # 文件、调用者、调用者在文件中的行数
- print(rv)
- # gogo.py
- from province.city import print_log
- def gogo():
- print_log()
- gogo()
- # ('/home/yangxl/PycharmProjects/meng/province/city.py', 'print_log', 5)
- # ('/home/yangxl/PycharmProjects/meng/gogo.py', 'gogo', 4)
添加环境变量,
- 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。
日志配置方法:
- import logging
- logging.basicConfig(level=logging.DEBUG,
- format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
- datefmt='%a, %d %b %Y %H:%M:%S',
- filename='test.log', # 不配置的话,默认输出到屏幕,二选一
- filemode='a')
- logging.debug('debug message')
- logging.info('info message')
- logging.warning('warning message')
- logging.error('error message')
- logging.critical('critical message')
format的格式:
- format参数中可能用到的格式化串:
- %(name)s Logger的名字
- %(levelno)s 数字形式的日志级别
- %(levelname)s 文本形式的日志级别
- %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
- %(filename)s 调用日志输出函数的模块的文件名
- %(module)s 调用日志输出函数的模块名
- %(funcName)s 调用日志输出函数的函数名
- %(lineno)d 调用日志输出函数的语句所在的代码行
- %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
- %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
- %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
- %(thread)d 线程ID。可能没有
- %(threadName)s 线程名。可能没有
- %(process)d 进程ID。可能没有
- %(message)s用户输出的消息
使用logger对象配置日志:
- import logging
- logger = logging.getLogger()
- # 创建一个handler,用于写入日志文件
- fh = logging.FileHandler('test.log')
- # 再创建一个handler,用于输出到控制台
- ch = logging.StreamHandler()
- formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
- fh.setFormatter(formatter)
- ch.setFormatter(formatter)
- logger.addHandler(fh) # logger对象可以添加多个fh和ch对象
- logger.addHandler(ch)
- logger.setLevel(logging.DEBUG) # 设置日志水平,(在打印日志之前)
- logger.debug('logger debug message')
- logger.info('logger info message')
- logger.warning('logger warning message')
- logger.error('logger error message')
- logger.critical('logger critical message')
configparser:
生成配置文件:
- import configparser
- config = configparser.ConfigParser()
- config["DEFAULT"] = {'ServerAliveInterval': '',
- 'Compression': 'yes',
- 'CompressionLevel': ''}
- config['bitbucket.org'] = {'User': 'hg'}
- config['topsecret.server.com'] = {'Host Port': '', 'ForwardX11': 'no'}
- config['DEFAULT']['ForwardX11'] = 'yes'
- with open('example.ini', 'w') as configfile:
- config.write(configfile)
对配置项进行基本操作:
- import configparser
- config = configparser.ConfigParser()
- # --------查
- config.read('example.ini')
- # 没列出'DEFAULT',它的数据会列在其他的键值对中,当作默认配置
- print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
- print('bytebong.com' in config) # False
- print(config['bitbucket.org']['User']) # hg
- print(config['DEFAULT']['Compression']) # yes
- print(config['topsecret.server.com']['ForwardX11']) # no
- for key in config['bitbucket.org']:
- print(key)
- print(config.options('bitbucket.org')) # ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
- print(config.items('bitbucket.org')) # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
- # 读了默认配置
- print(config.get('bitbucket.org', 'compression')) # yes
- # -------删,改,增(config.write(open('i.cfg', "w")))
- config.add_section('yangxl')
- config.remove_section('topsecret.server.com')
- config.remove_option('bitbucket.org', 'user')
- config.set('bitbucket.org', 'k1', '')
- config.write(open('example.ini', "w")) # 覆盖原文件
time:
- import time
- import datetime
- # 时间戳到字符串, local_time --> strftime
- timestamp = time.time()
- struct_time = time.localtime(timestamp)
- strftime = time.strftime('%Y-%m-%d %H:%M:%S', struct_time) # 2019-04-26 11:53:50
- # print(strftime)
- # 字符串到时间戳, strptime --> mktime
- struct_time = time.strptime('2019-04-26 11:53:50', '%Y-%m-%d %H:%M:%S')
- timestamp = time.mktime(struct_time) # 1556250830.0
- # print(timestamp)
- # 时间戳到datetime
- dt = datetime.datetime.fromtimestamp(1556250830.0) # 2019-04-26 11:53:50
- # datetime到时间戳, timetuple --> mktime
- struct_time = dt.timetuple()
- timestamp = time.mktime(struct_time) # 1556250830.0
- # print(timestamp)
- # datetime到date
- dte = dt.date() # 2019-04-26
- # print(type(dte))
- # 给定数字生成datetime
- dt = datetime.datetime(2019, 4, 26, 12, 23, 34) # 2019-04-26 12:23:34
- # 添加timedelta
- timedelta = datetime.timedelta(3, hours=3, seconds=60) # 3 days, 3:01:00
- dt = dt + timedelta # 2019-04-29 15:24:34
- # print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) # 2019 4 29 15 24 34
- # 获取当天0点的时间戳
- SECONDS_ONE_DAY = 3600*24
- timestamp_day = timestamp // SECONDS_ONE_DAY * SECONDS_ONE_DAY # 1556236800.0
- # print(timestamp_day)
- # 计算两个时间戳相差的天数,天数不是按照24小时计算
- # 分两步:计算当天0点时间戳,
- # 0点时间戳到datetime
- time_1 = 1556250830.0
- time_2 = 1556451820.0
- days = (datetime.datetime.fromtimestamp(time_2 // SECONDS_ONE_DAY * SECONDS_ONE_DAY) - datetime.datetime.fromtimestamp(time_1 // SECONDS_ONE_DAY * SECONDS_ONE_DAY)).days
- # print(days)
- print time.strftime('%Y%m%d') # 20190426
- time.monotonic() # 这个貌似是从开机到当前的时间戳啊
types:
dir():
- # coding:utf8
- import sys
- import types
- print type(sys) == types.ModuleType # 模块类型
- print dir(sys)
- print dir('yangxl')
- # 示例:摘自tornado.Application
- def _load_ui_modules(self, modules):
- if isinstance(modules, types.ModuleType):
- self._load_ui_modules(dict((n, getattr(modules, n))
- for n in dir(modules)))
- elif isinstance(modules, list):
- for m in modules:
- self._load_ui_modules(m)
- else:
- assert isinstance(modules, dict)
- for name, cls in modules.items():
- try:
- if issubclass(cls, UIModule):
- self.ui_modules[name] = cls
- except TypeError:
- pass
inspect:
- def ismodule(object):
- """Return true if the object is a module."""
- return isinstance(object, types.ModuleType)
- def isclass(object):
- """Return true if the object is a class."""
- return isinstance(object, type)
- def ismethod(object):
- """Return true if the object is an instance method."""
- return isinstance(object, types.MethodType)
itertools:
- import itertools
- s = itertools.count() # 这可不是计数器,有参数的哦
- print s.next()
- print s.next()
- print s.next()
hashlib:
1、
- >>> import hashlib
- >>> m = hashlib.md5()
- >>> m.update(b"Nobody inspects") # bytes类型
- >>> m.update(b" the spammish repetition")
- >>> m.digest()
- b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
2、
- hasher = hashlib.sha1()
- for part in self._write_buffer:
- hasher.update(part)
- return '"%s"' % hasher.hexdigest()
socket:
- buf = bytearray(self.read_chunk_size)
- self.socket.recv_into(buf) # A version of recv() that stores its data into a buffer rather than creating a new string.
- socket.gethostname() # 'yangxl-Lenovo-ideapad-330C-15IKB'
re:
- re.compile('([\x00-\x7f]+)') # 十六进制, 匹配ASCII表前128个
- >>> s = '%E7%BE%8A%E5%B0%8F%E7%BE%9A'
- >>> s
- '%E7%BE%8A%E5%B0%8F%E7%BE%9A'
- >>> import re
- >>> _asciire = re.compile('([\x00-\x7f]+)')
- >>> _asciire.split(s)
- ['', '%E7%BE%8A%E5%B0%8F%E7%BE%9A', '']
带br的,
- re.findall(br'\*|(?:W/)?"[^"]*"', "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d")
urllib:
- from urllib import request, parse
- # s = request.urlopen('http://127.0.0.1:9999/login/?name=羊小羚A&age=26')
- # print(s.read())
- d = parse.urlencode([
- ('name', '羊小羚'),
- ('age', ''),
- ])
- data = request.urlopen('http://127.0.0.1:9999/login/', d.encode('utf8'))
- print(data.read())
collections:
- >>> from collections import Mapping
- >>> dis = {'name': 'yangxl', 'age': 26}
- >>> isinstance(dis, Mapping) # 无法理解
- True
collections.queue,
- self.queue = collections.deque()
- self.queue.append(key)
- self.queue.popleft()
- 。。。很多方法呢。。。
collections.namedtuple,
- SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data']) # 定义
- key = SelectorKey(1, 2, 3, 4) # 赋值
- print(key.fd) # 取值
- 不能修改
collections.defaultdict,
- from collections import defaultdict
- CLIENT_EXCEPTION_CACHES = defaultdict(int)
- had_num = CLIENT_EXCEPTION_CACHES[content_md5] + 1 # 默认是0,然后加1
- CLIENT_EXCEPTION_CACHES[content_md5] += 1
- # 就是个字典
heapq:
- heapq.heappush(self._scheduled, timer)
asyncio.base_events.py中的函数call_at(scheduler.start)
resource:
查看系统资源消耗,
- import resource
- resource.getrusage(resource.RUSAGE_SELF)[2]
traceback:
- import traceback
- tb = traceback.format_exc() # tb = 'NoneType\n'
pickle、cPickle:
- >>> import pickle
- >>> d = {'name': 'yangxl', 'age': 18}
- >>> d
- {'age': 18, 'name': 'yangxl'}
- >>> s = pickle.dumps(d)
- >>> s
- b'\x80\x03}q\x00(X\x03\x00\x00\x00ageq\x01K\x12X\x04\x00\x00\x00nameq\x02X\x06\x00\x00\x00yangxlq\x03u.'
- >>> type(s)
- <class 'bytes'>
- >>> import cPickle as pickle # 只有py2才有
- >>> d = {'name': 'yangxl', 'age': 18}
- >>> s = pickle.dumps(d)
- >>> s
- "(dp1\nS'age'\np2\nI18\nsS'name'\np3\nS'yangxl'\np4\ns."
- >>> type(s)
- <type 'str'>
zlib:
- # py2
- >>> d
- {'age': 18, 'name': 'yangxl'}
- >>> zlib.compress(d)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: compress() argument 1 must be string or read-only buffer, not dict
- >>>
- >>> zlib.compress('d')
- 'x\x9cK\x01\x00\x00e\x00e'
- >>> zlib.compress(b'd')
- 'x\x9cK\x01\x00\x00e\x00e'
- # py3
- >>> d
- {'age': 18, 'name': 'yangxl'}
- >>> zlib.compress(d)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: a bytes-like object is required, not 'dict'
- >>>
- >>> zlib.compress('d')
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: a bytes-like object is required, not 'str'
- >>>
- >>> zlib.compress(b'd')
- b'x\x9cK\x01\x00\x00e\x00e'
- 到了py3中,即使是字符串类型也不行了
weakref:
- temp = property_class.get(self.uid, server) # 对象
- setattr(temp, 'weak_user', weakref.proxy(self)) # 弱引用外部传入user,避免循环引用
- setattr(self, "_%s" % property_name, temp) # 还有个下划线
requests模块
requests中的方法:
- import requests
- # res = requests.get('http://dig.chouti.com')
- # 等同于
- res = requests.request(
- url='http://dig.chouti.com',
- method='get'
- )
- print(res)
requests模块基本参数:
url、method、params、data、json、headers、cookies
get方法
- import requests
- res = requests.request(
- url='https://www.sogou.com/web',
- method='get',
- params={'query':'羊小羚'} #会拼接成https://www.sogou.com/web?query=羊小羚&...
- )
- print(res.text)
- # 'https://www.sogou.com/web?query=羊小羚' #搜狗
- # 'https://www.baidu.com/s?wd=羊小羚' #百度
post方法
- form_data = {'phone':8615313144407,'password':'123456','oneMonth':1}
- res = requests.post(
- url = 'http://dig.chouti.com/login',
- data = form_data
- )
- print(res.text) # {"result":{"code":"9999", "message":"", "data":{"complateReg":"0","destJid":"cdu_48196352125"}}}
data和json
- res = requests.post(
- url = 'http://127.0.0.1:8000/pachong',
- # data = {'phone':8615313144406,'password':'chouti123456','oneMonth':1},
- # content-type: application/x-www-form-urlencoded,数据传到request.body中然后继续传到request.port中。
- # request.POST: <QueryDict: {'oneMonth': ['1'], 'phone': ['8615313144406'], 'password': ['chouti123456']}>
- # request.body: b'oneMonth=1&password=chouti123456&phone=8615313144406'
- json = json.dumps("{'phone':8615313144406,'password':'chouti123456','oneMonth':1}'")
- # content-type: application/json,数据只传到request.body中。
- # request.POST: <QueryDict: {}>
- # request.body: b'"\\"{\'phone\':8615313144406,\'password\':\'chouti123456\',\'oneMonth\':1}\'\\""'
- )
- print(res.text)
headers
- res = requests.get(
- url='https://www.zhihu.com/',
- headers={
- 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
- # 'Referer' : 'https://www.zhihu.com/',
- # 如果使用浏览器可以正常访问,但是使用爬虫就不行,那可能就遇到反爬虫策略了,需要添加以下两个参数:
- # User-Agent,代表使用什么设备访问,(伪造浏览器)
- # Referer,从哪里跳转过来的,一般情况下都是从首页跳转
- },
- )
- print(res.text) #An internal server error occured.
cookies
- res = requests.get(
- url='https://i.cnblogs.com/Configure.aspx',
- # headers={
- # 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
- # 'Referer' : 'https://www.zhihu.com/',
- # 如果使用浏览器可以正常访问,但是使用爬虫就不行,那可能就遇到反爬虫策略了,需要添加以下两个参数:
- # User-Agent,代表使用什么设备访问,(伪造浏览器)
- # Referer,从哪里跳转过来的,一般情况下都是从首页跳转
- # },
- # 当需要登录才能访问时,可能需要cookies或session
- cookies={
- '.CNBlogsCookie' : '886F4CA84CC7BC01EF975E3F27EAF9CC3D894702B2EDD7F2A8C373A603E1CECB1013D7B7BA5734628DFE8091863906995C70C0AB1F9A57B4C7F7A47C29286B9D25139D87A5A96B06438933A87E63790AF63AD83A'
- }
- )
- print(res.text)
requests模块的其他参数:
- def request(method, url, **kwargs):
- """Constructs and sends a :class:`Request <Request>`.
- :param method: method for the new :class:`Request` object.
- :param url: URL for the new :class:`Request` object.
- :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
- :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
- :param json: (optional) json data to send in the body of the :class:`Request`.
- :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
- :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
- ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
- or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
- defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
- to add for the file.
- :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
- :param timeout: (optional) How long to wait for the server to send data
- before giving up, as a float, or a :ref:`(connect timeout, read
- timeout) <timeouts>` tuple.
- :type timeout: float or tuple
- :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
- :type allow_redirects: bool
- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
- :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
- :param stream: (optional) if ``False``, the response content will be immediately downloaded.
- :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
- :return: :class:`Response <Response>` object
- :rtype: requests.Response
- Usage::
- >>> import requests
- >>> req = requests.request('GET', 'http://httpbin.org/get')
- <Response [200]>
- """
实例:
- def param_method_url():
- # requests.request(method='get', url='http://127.0.0.1:8000/test/')
- # requests.request(method='post', url='http://127.0.0.1:8000/test/')
- pass
- def param_param():
- # - 可以是字典
- # - 可以是字符串
- # - 可以是字节(ascii编码以内)
- # requests.request(method='get',
- # url='http://127.0.0.1:8000/test/',
- # params={'k1': 'v1', 'k2': '水电费'})
- # requests.request(method='get',
- # url='http://127.0.0.1:8000/test/',
- # params="k1=v1&k2=水电费&k3=v3&k3=vv3")
- # requests.request(method='get',
- # url='http://127.0.0.1:8000/test/',
- # params=bytes("k1=v1&k2=k2&k3=v3&k3=vv3", encoding='utf8'))
- # 错误
- # requests.request(method='get',
- # url='http://127.0.0.1:8000/test/',
- # params=bytes("k1=v1&k2=水电费&k3=v3&k3=vv3", encoding='utf8'))
- pass
- def param_data():
- # 可以是字典
- # 可以是字符串
- # 可以是字节
- # 可以是文件对象
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # data={'k1': 'v1', 'k2': '水电费'})
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # data="k1=v1; k2=v2; k3=v3; k3=v4"
- # )
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # data="k1=v1;k2=v2;k3=v3;k3=v4",
- # headers={'Content-Type': 'application/x-www-form-urlencoded'}
- # )
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # data=open('data_file.py', mode='r', encoding='utf-8'), # 文件内容是:k1=v1;k2=v2;k3=v3;k3=v4
- # headers={'Content-Type': 'application/x-www-form-urlencoded'}
- # )
- pass
- def param_json():
- # 将json中对应的数据进行序列化成一个字符串,json.dumps(...)
- # 然后发送到服务器端的body中,并且Content-Type是 {'Content-Type': 'application/json'}
- requests.request(method='POST',
- url='http://127.0.0.1:8000/test/',
- json={'k1': 'v1', 'k2': '水电费'})
- def param_headers():
- # 发送请求头到服务器端
- requests.request(method='POST',
- url='http://127.0.0.1:8000/test/',
- json={'k1': 'v1', 'k2': '水电费'},
- headers={'Content-Type': 'application/x-www-form-urlencoded'}
- )
- def param_cookies():
- # 发送Cookie到服务器端
- requests.request(method='POST',
- url='http://127.0.0.1:8000/test/',
- data={'k1': 'v1', 'k2': 'v2'},
- cookies={'cook1': 'value1'},
- )
- # 也可以使用CookieJar(字典形式就是在此基础上封装)
- from http.cookiejar import CookieJar
- from http.cookiejar import Cookie
- obj = CookieJar()
- obj.set_cookie(Cookie(version=0, name='c1', value='v1', port=None, domain='', path='/', secure=False, expires=None,
- discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False,
- port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=False)
- )
- requests.request(method='POST',
- url='http://127.0.0.1:8000/test/',
- data={'k1': 'v1', 'k2': 'v2'},
- cookies=obj)
- def param_files():
- # 发送文件
- # file_dict = {
- # 'f1': open('readme', 'rb')
- # }
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # files=file_dict)
- # 发送文件,定制文件名
- # file_dict = {
- # 'f1': ('test.txt', open('readme', 'rb'))
- # }
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # files=file_dict)
- # 发送文件,定制文件名
- # file_dict = {
- # 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf")
- # }
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # files=file_dict)
- # 发送文件,定制文件名
- # file_dict = {
- # 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf", 'application/text', {'k1': '0'})
- # }
- # requests.request(method='POST',
- # url='http://127.0.0.1:8000/test/',
- # files=file_dict)
- pass
- def param_auth():
- from requests.auth import HTTPBasicAuth, HTTPDigestAuth
- ret = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('wupeiqi', 'sdfasdfasdf'))
- print(ret.text)
- # ret = requests.get('http://192.168.1.1',
- # auth=HTTPBasicAuth('admin', 'admin'))
- # ret.encoding = 'gbk'
- # print(ret.text)
- # ret = requests.get('http://httpbin.org/digest-auth/auth/user/pass', auth=HTTPDigestAuth('user', 'pass'))
- # print(ret)
- #
- def param_timeout():
- # ret = requests.get('http://google.com/', timeout=1) # 如果只有一个,表示发送请求的时间。
- # print(ret)
- # ret = requests.get('http://google.com/', timeout=(5, 1)) # 如果有两个,第一个表示发送请求的时间,第二个表示读取返回内容的时间。
- # print(ret)
- pass
- def param_allow_redirects():
- ret = requests.get('http://127.0.0.1:8000/test/', allow_redirects=False)
- print(ret.text)
- def param_proxies():
- # proxies = {
- # "http": "61.172.249.96:80", # 使用http协议访问网页时,使用'61.172.249.96:80'代理。
- # "https": "http://61.185.219.126:3128", # 使用https协议访问网页时,使用'https://61.185.219.126:3128'代理。
- # }
- # proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'} # 访问'http://10.20.1.128'时,使用'http://10.10.1.10:5323'代理。
- # ret = requests.get("http://www.proxy360.cn/Proxy", proxies=proxies) # 代理,让别人来发送请求
- # print(ret.headers)
- # from requests.auth import HTTPProxyAuth
- #
- # proxyDict = {
- # 'http': '77.75.105.165',
- # 'https': '77.75.105.165'
- # }
- # auth = HTTPProxyAuth('username', 'mypassword') #使用代理,需要登录
- #
- # r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)
- # print(r.text)
- pass
- def param_stream():
- ret = requests.get('http://127.0.0.1:8000/test/', stream=True)
- print(ret.content)
- ret.close()
- # from contextlib import closing
- # with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
- # # 在此处理响应。
- # for i in r.iter_content():
- # print(i)
- def requests_session():
- import requests
- session = requests.Session()
- ### 1、首先登陆任何页面,获取cookie
- i1 = session.get(url="http://dig.chouti.com/help/service")
- ### 2、用户登陆,携带上一次的cookie,后台对cookie中的 gpsd 进行授权
- i2 = session.post(
- url="http://dig.chouti.com/login",
- data={
- 'phone': "8615131255089",
- 'password': "xxxxxx",
- 'oneMonth': ""
- }
- )
- i3 = session.post(
- url="http://dig.chouti.com/link/vote?linksId=8589623",
- )
- print(i3.text)
标准库 os、sys、logging、configparser、time、requests的更多相关文章
- A Byte of Python 笔记(12)python 标准库:sys、os,更多内容
第14章 python 标准库 Python标准库是随Python附带安装的,它包含大量极其有用的模块. sys 模块 sys 模块包含系统对应的功能.如 sys.argv 列表包含命令行参数. # ...
- 介绍下Python的两个标准库 os 和 sys
import sysprint(sys.path) #python 2 中报错 ....,打印的是绝对路径(***\\python\\lib\\site-packages# 第三方库,后退一级为标准库 ...
- 标准库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 ...
- Python标准库之Sys模块使用详解
sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. 处理命令行参数 在解释器启动后, argv 列表包含了传递给脚本的所有参数, 列表的第一个元素为脚本自身的名称. 使用sy ...
- Python标准库--os模块
这个模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行.一个例 ...
- Python标准库_ sys,random,time
一.sys 1. sys这个模块让你能够访问与Python解释器联系紧密的变量和函数 2. sys模块中一些重要的函数和变量 argv 命令行参数,包括脚本名称 exi ...
- python 标准库 -- os
os os.getcwd() os.getcwd() # 获取当前工作目录 os.listdir(path) os.listdir('/tmp') # 列出指定目录下的文件和目录 os.mkdir(p ...
- Python3 标准库:os
1.重命名 import os os.rename('test.txt','x.txt') #重命名文件或目录 import os os.renames('a/123.txt','a/b/h.txt' ...
- Python标准库 os
(掌握os模块,你需要了解Linux或类Unix系统下常用命令的操作) os.name 指示你正在使用的平台.比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix' ...
随机推荐
- linux centos 7上运行teamviewer与找不到ID问题处理办法
以前在raspberryPi上搞过teamviewer,现在用了CentOS服务器,搞了一个vpn,访问还有点问题,时间紧张,就先给teamviewer. 而centos7 上安装也比较简单,几条命令 ...
- Python之道(一)之安装Python
"Python之道"首先介绍一下在windows系统下怎样安装Python开发环境. (1)下载MSI安装文件 进入网址www.python.org,点击Downloads进入下载 ...
- Charles for Mac(HTTP 监视器和网络抓包工具)破解版安装
1.软件简介 Charles 是在 Mac.Linux 或 Windows 下常用的 http 协议网络包截取工具,在平常的测试与调式过程中,掌握此工具就基本可以不用其他抓包工具了.Charle ...
- hexo + Github Page 0元建立博客攻略
传送门: 5分钟 0元搭建个人独立博客网站(一):https://mp.weixin.qq.com/s/69isJE191WV2gaVbjrwTtw 5分钟 0元搭建个人独立博客网站(二):https ...
- Docker 以 docker 方式运行 jenkins
https://testerhome.com/topics/5798 Docker 以 docker 方式运行 jenkins jmcn · 2016年08月26日 · 最后由 blueshark 回 ...
- Hexo NexT 博客与Github page 关联指南
上篇文章 Hexo 博客框架NexT主题搭建指南 我们已经在本地搭建好了Hexo博客框架NexT 主题的博客程序,但是这感觉还是远远不够. 我们还想把它部署到我们的Github上,让其他人可以看到我们 ...
- Atitit php vs node.js attilax总结
Atitit php vs node.js attilax总结 1.1. 上手度 还是php 1 1.2. Node.js最大的缺点 异步回调导致可读性差..特别嵌套的时候.. 1 1.1. 上手 ...
- 【C语言】两个指针(地址)相减
两个指针相减,为两个指针之间间隔这两个指针类型的数目. 如:int *p,*q; p-q=(p地址-q地址)/sizeof(int) #include <stdio.h> int main ...
- ElasticStack系列之九 & master、data 和 client 节点
在生产环境下,如果不修改elasticsearch节点的角色信息,在高数据量,高并发的场景下集群容易出现脑裂等问题. 默认情况下,elasticsearch 集群中每个节点都有成为主节点的资格,也都存 ...
- Pitch detection algorithm(基音搜索算法)PDA相关链接
第一:维基百科 http://en.wikipedia.org/wiki/Pitch_estimation 简要系统介绍了基音估计算法的分类和一些链接,论文 第二:http://ws2.bingham ...