15.1sys模块15.2datatime模块15.3logging模块15.4request15.5crm实战15.6参数介绍15.7token接口

15.1sys模块

import sys

print(sys.modules)#描述当前执行代码的位置,解释器中导入的所有模块都会被放在字典中
import time
print(time.time())
print(sys.modules['time'].time())
print(time==sys.modules['time'])


# import requests
#
# res=requests.get('http://www.baidu.com')
# print(res.text)

print(sys.path)

# 1.能不能导入一个模块,就要看导入的这个模块所在的路径在不在sys.path当中,命名的时候不能以模块命名
# 如果sys.path 寻找数据的时候,从左往右去找,如果找到一个文件就不会继续找了
#
# sys.argv 通过sys.argv从程序的外部进行输入
# print(sys.argv)拿到当前py文件的路径列表
# 可以通过sys.argv从程序的外部进行输入,通过python调
# 代码上线,进行调试

try:
if sys.argv[1]=='wind'and sys.argv[2]=='666':
print('登陆成功')
else:
print('登陆失败')
except Exception as e:
print(e)

15.2datatime模块
from datetime import datetime


dt=datetime.now()#直接获取当前的时间
print(datetime.now())#直接获取当前时间
print(datetime.utcnow())#格林威治时间

print(dt.day)
print(dt.month)
print(dt.year)
print(dt.hour)

dt1=datetime(2022,7,8,11,0)
dt2=datetime(2019,11,6,12,0)
print(dt1-dt2)# 计算时间差
print(type(dt1))


s1='2022/9/30'
ret1=datetime.strptime(s1,'%Y/%m/%d')# 把字符串转为datetime时间类型
print(ret1,type(ret1))


#把datetime时间类型 转为字符串
dt2=datetime(2019,11,6,12,0)
ret3=dt2.strftime('%Y-%m-%d %H:%M:%S')
print(ret3,type(ret3))






dt2.strftime('%Y-%m-%d %H/%M:%s')


15.3logging模块
import logging


# logging 日志分为5个等级,默认只显示warning和warning等级以上的信息
logging.debug('调试模式')
logging.info('基础信息')
logging.warning('警告')
logging.error('错误')
logging.critical('严重的错误')

# 设置日志等级
# 日志写入文件中

fh=logging.FileHandler(filename='../log/test.log',encoding='utf-8')指定中文格式
logging.basicConfig(level=logging.DEBUG,
handlers=[fh])#显示DEBUG和DEBUG级别以上所有的日志信息

logging.debug('调试模式')
logging.info('基础信息')
logging.warning('警告')
logging.error('错误')
logging.critical('严重的错误')

日志既写入文件中,又显示在屏幕上

fh=logging.FileHandler(filename='../log/test.log',encoding='utf-8')指定中文格式
sh=logging.StreamHandler()
logging.basicConfig(level=logging.DEBUG,
handlers=[fh,sh])#显示DEBUG和DEBUG级别以上所有的日志信息



logging.debug('调试模式1')
logging.info('基础信息1')
logging.warning('警告1')
logging.error('错误1')
logging.critical('严重的错误1')


优化日志,设置日志的格式
fh=logging.FileHandler(filename='../log/test.log',encoding='utf-8')指定中文格式
sh=logging.StreamHandler()
logging.basicConfig(
format='%(asctime)s-%(name)s[%(lineno)d]-%(levelname)s-%(module)s-%(message)s',
level=logging.DEBUG,
handlers=[fh,sh])#显示DEBUG和DEBUG级别以上所有的日志信息


logging.debug('调试模式1')
logging.info('基础信息1')
logging.warning('警告1')
logging.error('错误1')
logging.critical('严重的错误1')


日志切割
import time
from logging import handlers

sh=logging.StreamHandler()
rh=handlers.RotatingFileHandler('../log/test.log',maxBytes=1024,backupCount=5,encoding='utf-8')#根据大小切
maxBytes 最大的字节数超过就切 backupCount=5 最多备份5个,切到第六个就删掉,把第6个命名第5个
fh=handlers.TimedRotatingFileHandler(filename='../log/test2.log',when='s',interval=5,encoding='utf-8')#根据时间切
interval=5 按5秒切一次,when='s' when='M'按分停 when='H'按小时 when='D'按天切 when='W'按周切

logging.basicConfig(
format='%(asctime)s-%(name)s-%(levelname)s-%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[sh,rh,fh],
level=logging.INFO
)

while True:
logging.info('zhangsan666')












logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:

filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

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用户输出的消息
15.4 request模块
import requests

# response=requests.get('http://www.baidu.com')
# print(response.status_code)#返回的状态码
# response.encoding='utf-8'#指定编码格式
# print(response.text)#返回文本类型的格式
# print(response.cookies)#返回的cookies
# print(response.encoding)#返回的编码格式
# print(response.url)#返回的url
# print(response.content)#返回是byte类型的数据
# print(response.headers)#返回的响应头,根据响应头,选择
# print(response.json())#获取json类型的数据
#

#爬取图片
# response=requests.get('https://t7.baidu.com/it/u=4036010509,3445021118&fm=193&f=GIF')
# print(response.content)#返回是byte类型的数据
# with open('图片.png','wb')as f:
# f.write(response.content)


response=requests.get('https://haokan.baidu.com/v?pd=wisenatural&vid=14756353705742823396')
# print(response.content)#返回是byte类型的数据
with open('视频.MP4','wb')as f:
for i in response.iter_content(chunk_size=1024):
f.write(i)

15.5 crm 实战

import requests

data={
"userAccount":"admin",
"loginPwd":"123456"
}

res=requests.request(method='post',url='http://124.220.179.221:8081/cms/manage/loginJump.do',data=data)
print(res.status_code)
print(res.json())
cookie=res.cookies

def add_user(cookie):
url2="http://124.220.179.221:8081/cms/manage/saveSysUser.do"
data2={
"id":"",
"username":"1111111",
"usersex":"1",
"userMobile":"15212341234",
"userEmail":"123@qq.com",
"userAccount":"123455",
"loginPwd":"123456",
"confirmPwd":"123456"
}
ret=requests.request('post',url2,data=data2,cookies=cookie)
print(ret.status_code)
print(ret.headers)
print(ret.json())

add_user(cookie)


def delete_user(cookie):
url3="http://124.220.179.221:8081/cms/manage/deleteByIds.do"
data3={
"id":"",
"username":"1111111",
"usersex":"1",
"userMobile":"15212341234",
"userEmail":"123@qq.com",
"userAccount":"123455",
"loginPwd":"123456",
"confirmPwd":"123456"
}
ret=requests.request('post',url3,data=data3,cookies=cookie)
print(ret.status_code)
print(ret.headers)
print(ret.json())

delete_user(cookie)


# requests.post()
# requests.post(url, data=None, json=None, **kwargs)发送POST请求,相关参数:
#
# url:请求的URL。
# data:可选参数,请求中携带表单编码的字典、bytes或者文件对象。
# json:请求中携带json类型的数据。
# **kwargs:参见requests.request中的kwargs。
# 在post请求中,data与json既可以是str类型,也可以是dict类型。
#
# 区别:
#
# 不管json是str还是dict,如果不指定headers中的content-type,默认为application/json
# data为dict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式
# data为str时,如果不指定content-type,默认为textain
# 用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式
# 实际应用时候,需要根据后端服务处理的方式来确定
15.6参数介绍
import requests

response=requests.get(url='http://www.httpbin.org/get?k1=v1&k2=v2' )
print(response.status_code)#http://www.httpbin.org/get?k1=v1&k2=v2
print(response.headers)
print(response.json())

# params 参数

data={
"k1":"v1",
"k2":'v2'
}
response=requests.get(url='http://www.httpbin.org/get',params=data)
print(response.json())


# 1.登录,获取cookies值
data={
"userName":"admin",
"password":"1234"
}
response=requests.post(url="http://www.neeo.cc:6002/pinter/bank/api/login",data=data)
print(response.json())#用json去取响应头,查看接口
print(response.cookies)
print(response.cookies.get_dict())

# 2.在需要cookies验证的时候,携带上刚才获取到的cookies值
response=response.get(url='http://www.neeo.cc:6082/pinter/bank/api/query?userName=admin',cookies=cookie)
print(response.status_code)
print(response.json())


import requests
import webbrowser

url='http://img2.baidu.com/it/u=3908142881,2459234098&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500'

response=requests.get(url=url)
f=open('a.jpeg','wb')
f.write(response.content)
f.close()

webbrowser.open('a.jpeg')


# requests.post()
# requests.post(url,data=None,json=None,**kwargs)发送POST请求,相关参数:
#
# url:请求的URL
# data:可选参数,请求中携带表单编码的字典、bytes或者文件对象
# json:请求中携带json类型的数据
# **kwargs:参见request.request中的kwargs
# 在post请求中,data与json既可以是str类型,也可以是dict类型
#
# 区别:
#
# 不管json是str还是dict,如果不指定headers中的content-type,默认为application/json
# data为dict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式
# data为str时,如果不指定content-type,默认为text/plain
# 用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为a
# 实际应用时候,需要根据后端服务处理的方式来确定
#

# token 接口



15.7token接口
import requests

#用户登录
def login():
url='http://49.234.14.39:5001/user/login'
data={
"password":"123456",
"username":"admin"
}
ret=requests.request('post',url,json=data)
print(ret.status_code)#状态码
print(ret.headers)#主要看类型
return ret.json()['access_token']
token=login()

#查询用户
def select(token):
url='http://49.234.14.39:5001/user/query'
header={'Content-Type':'application/json'}
data={
"access_token":token
}
ret=requests.post(url,json=data)
print(ret.json())
select(token)

#初始化用户
def select(token):
url='http://49.234.14.39:5001/user/init'
header={'Content-Type':'application/json'}
data={
"access_token":token
}
ret=requests.post(url,json=data)
print(ret.json())
select(token)

#删除用户
def select(token):
url='http://49.234.14.39:5001/user/delete'
header={'Content-Type':'application/json'}
data={
"access_token":token,
"username":"user6"
}
ret=requests.post(url,json=data)
print(ret.json())
select(token)


















































































posted @   海棠花未眠0125  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示