标准库 os、sys、logging、configparser、time、requests

os :

  与操作系统交互的模块

 1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
 2 os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
 3 os.curdir  返回当前目录: ('.')
 4 os.pardir  获取当前目录的父目录字符串名:('..')
 5 os.makedirs('dirname1/dirname2')    可生成多层递归目录
 6 os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 7 os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
 8 os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir 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 
11 # gogo.py
12 
13 from province.city import print_log
14 
15 def gogo():
16     print_log()
17 
18 gogo()
19 # ('/home/yangxl/PycharmProjects/meng/province/city.py', 'print_log', 5)
20 # ('/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的格式:

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对象配置日志:

 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': '45',
 6                      'Compression': 'yes',
 7                      'CompressionLevel': '9'}
 8 
 9 config['bitbucket.org'] = {'User': 'hg'}
10 config['topsecret.server.com'] = {'Host Port': '50022', '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 
19 for key in config['bitbucket.org']:
20     print(key)
21 
22 print(config.options('bitbucket.org'))  # ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
23 print(config.items('bitbucket.org'))  # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
24 
25 # 读了默认配置
26 print(config.get('bitbucket.org', 'compression'))  # yes
27 
28 
29 # -------删,改,增(config.write(open('i.cfg', "w")))
30 config.add_section('yangxl')
31 
32 config.remove_section('topsecret.server.com')
33 config.remove_option('bitbucket.org', 'user')
34 
35 config.set('bitbucket.org', 'k1', '11111')
36 
37 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)
print time.strftime('%Y%m%d')  # 20190426
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', '26'),
 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 
12 >>> import cPickle as pickle  # 只有py2才有
13 >>> d = {'name': 'yangxl', 'age': 18}
14 >>> s = pickle.dumps(d)
15 >>> s
16 "(dp1\nS'age'\np2\nI18\nsS'name'\np3\nS'yangxl'\np4\ns."
17 >>> type(s)
18 <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 
16 # py3
17 
18 >>> d
19 {'age': 18, 'name': 'yangxl'}
20 >>> zlib.compress(d)
21 Traceback (most recent call last):
22   File "<stdin>", line 1, in <module>
23 TypeError: a bytes-like object is required, not 'dict'
24 >>>
25 >>> zlib.compress('d')
26 Traceback (most recent call last):
27   File "<stdin>", line 1, in <module>
28 TypeError: a bytes-like object is required, not 'str'
29 >>> 
30 >>> zlib.compress(b'd')
31 b'x\x9cK\x01\x00\x00e\x00e'
32 
33 到了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中的方法:

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)

  

posted @ 2017-05-15 19:56  羊小羚  阅读(394)  评论(0编辑  收藏  举报