import os
import shutil
import time
source_dir = 'D:/源文件夹' # 源文件夹路径
target_dir = 'E:/目标文件夹' # 目标文件夹路径
# 遍历源文件夹中的所有文件
for filename in os.listdir(source_dir):
source_path = os.path.join(source_dir, filename)
# 判断文件是否为普通文件(排除文件夹等非文件类型)
if os.path.isfile(source_path):
mod_time = os.path.getmtime(source_path) # 获取文件修改时间
# 将创建时间转换为星期和时分
mod_time_weekday = int(time.strftime('%w', time.localtime(mod_time)))
mod_time_hour = int(time.strftime('%H', time.localtime(mod_time)))
mod_time_minute = int(time.strftime('%M', time.localtime(mod_time)))
# 判断文件创建时间是否符合要求
if mod_time_weekday == 3 and mod_time_hour == 18 and mod_time_minute >= 20 :
target_path = os.path.join(target_dir, filename) # 构造目标文件路径
shutil.copy(source_path, target_path) # 复制文件到目标文件夹
elif mod_time_weekday == 3 and mod_time_hour == 19 and mod_time_minute <= 20 :
target_path = os.path.join(target_dir, filename) # 构造目标文件路径
shutil.copy(source_path, target_path) # 复制文件到目标文件夹
elif mod_time_weekday == 5 and mod_time_hour == 18 and mod_time_minute >= 20 :
target_path = os.path.join(target_dir, filename) # 构造目标文件路径
shutil.copy(source_path, target_path) # 复制文件到目标文件夹
elif mod_time_weekday == 5 and mod_time_hour == 19 and mod_time_minute <= 20 :
target_path = os.path.join(target_dir, filename) # 构造目标文件路径
shutil.copy(source_path, target_path) # 复制文件到目标文件夹
print("完成")
本来应该是复制所有符合条件的文件,但只复制一个就结束了,是哪里错了( p′︵‵。)
哪位帮忙指点下੭ ᐕ)੭*⁾⁾
谢谢大师指出错误(=^▽^=)
你有循环,有判断,而且你没贴报错信息,你也没有中断循环的代码,那么我们假定代码正常运行了,但很可能符合条件就只有一个文件。
好好看看每次循环出来的数据,看看是不是那个判断和你的意愿不符合
你有循环,有判断,而且你没贴报错信息,你也没有中断循环的代码,那么我们假定代码正常运行了,但很可能符合条件就只有一个文件。
好好看看每次循环出来的数据,看看是不是那个判断和你的意愿不符合
工欲善其事必先利其器,废话不多说。我们先开始搭建环境。
# 创建项目目录
mkdir InterfaceTesting
# 切换到项目目录下
cd InterfaceTesting
# 安装虚拟环境创建工具
pip install virtualenv
# 创建虚拟环境,env代表虚拟环境的名称,可自行定义
virtualenv env
# 启动虚拟环境,执行下面命令后会发现路径上有 (env) 字样的标识
source env/Scripts/activate
# 查看 (env) 环境下使用的 Python 和 pip 工具版本
ls env/Scripts/
# *** 安装 requests ***
pip install requests
# 退出虚拟环境,退出后路径上的 (env) 字样的标识消失
cd env/Scripts/
deactivate
# 导出环境所需要的模块的清单
pip freeze >> requirements.txt
# 上传 GitHub 时,将下面项忽略上传
echo env/ >> .gitignore
echo InterfaceTesting.iml >> .gitignore
echo __pycache__/ >> .gitignore
# 将代码传至 GitHub
# 本地仓初始化
git init
# 创建本地仓与 GitHub 仓的远程链接
git remote add github 你的github仓的地址
# 将代码添加到暂存区
git add .
# 将代码提交到
git commit -m "init environment"
# 将代码上传到GitHub仓中
git push github master
复制代码
初始化环境的项目结构示例如下:
接口一般来说有两种,一种是程序内部的接口,一种是系统对外的接口。
(1) webservice接口:走soap协议通过http传输,请求报文和返回报文都是xml格式的,我们在测试的时候都要通过工具才能进行调用,测试。
(2) http api 接口:走http协议,通过路径来区分调用的方法,请求报文都是key-value形式的,返回报文一般都是json串,有get和post等方法。
复制代码
根据接口的请求方法,常用的几种接口请求方式:
(1) GET:从指定资源获取数据
(2) POST:向指定的资源请求被处理的数据(例如用户登录)
(3) PUT:上传指定的URL,一般是修改,可以理解为数据库中的 update
(4) DELETE:删除指定资源
复制代码
所有的数据测试目标以一个开源的接口模拟网站【HTTPBIN】为测试对象。
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : requests_send_request.py
@Time : 2019/9/2 11:54
@Author : Crisimple
@Github : https://crisimple.github.io/
@Contact : Crisimple@foxmail.com
@License : (C)Copyright 2017-2019, Micro-Circle
@Desc : None
"""
import requests
# 1.requests请求方式
# (1) GET请求方式
httpbin_get = requests.get('http://httpbin.org/get', data={'key': 'value'})
print('httpbin_get: ', httpbin_get.text)
# (2) POST请求方式
httpbin_post = requests.post('https://httpbin.org/post', data={'key': 'value'})
print('httpbin_post: ', httpbin_post.text)
# (3) PUT请求方式
httpbin_put = requests.put('https://httpbin.org/put', data={'key': 'value'})
print('httpbin_put: ', httpbin_put.text)
# (4) DELETE请求方式
httpbin_delete = requests.delete('https://httpbin.org/delete', data={'key': 'value'})
print('httpbin_delete', httpbin_delete)
# (5) PATCH亲求方式
httpbin_patch = requests.patch('https://httpbin.org/patch', data={'key': 'value'})
print('httpbin_patch', httpbin_patch)
复制代码
常用的参数传递形式有四种:【GitHub示例】
(1)字典形式的参数:payload = {'key1': 'value1', 'key2': 'value2'}
(2) 元组形式的参数:payload = (('key1', 'value1'), ('key2', 'value2'))
(3) 字符串形式的参数:payload = {'string1', 'value1'}
(4) 多部份编码的文件:files = {
# 显示设置文件名、文件类型和请求头
'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})
}
复制代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : requests_transfer_parameter.py
@Time : 2019/9/2 12:39
@Author : Crisimple
@Github : https://crisimple.github.io/
@Contact : Crisimple@foxmail.com
@License : (C)Copyright 2017-2019, Micro-Circle
@Desc : 参数传递:字典、元组、字符串、文件
"""
import requests
# 2. 参数传递
# (1) 传参参数为字典形式: 数据字典会在发送请求时会自动编码为表单形式
def transfer_dict_parameter():
payload = {
'key1': 'value1',
'key2': 'value2'
}
transfer_dict_parameter_result = requests.post('https://httpbin.org/post', params=payload)
print("transfer_dict_parameter_url: ", transfer_dict_parameter_result.url)
print("transfer_dict_parameter_text: ", transfer_dict_parameter_result.text)
transfer_dict_parameter()
# (2) 传参参数为元组形式: 应用于在表单中多个元素使用同一 key 的时候
def transfer_tuple_parameter():
payload = (
('key1', 'value1'),
('key1', 'value2')
)
transfer_tuple_parameter_result = requests.post('https://httpbin.org/post', params=payload)
print('transfer_tuple_parameter_url: ', transfer_tuple_parameter_result.url)
print('transfer_tuple_parameter_text: ', transfer_tuple_parameter_result.text)
transfer_tuple_parameter()
# (3) 传参参数形式是字符串形式
def transfer_string_parameter():
payload = {
'string1': 'value'
}
transfer_string_parameter_result = requests.post('https://httpbin.org/post', params=payload)
print('transfer_string_parameter_url: ', transfer_string_parameter_result.url)
print('transfer_string_parameter_text: ', transfer_string_parameter_result.text)
transfer_string_parameter()
# (4) 传参参数形式:一个多部分编码(Multipart-Encoded)的文件
def transfer_multipart_encoded_file():
interface_url = 'https://httpbin.org/post'
files = {
# 显示设置文件名、文件类型和请求头
'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})
}
transfer_multipart_encoded_file_result = requests.post(url=interface_url, files=files)
print('transfer_multipart_encoded_file_result_url: ', transfer_multipart_encoded_file_result.url)
print('transfer_multipart_encoded_file_result_url: ', transfer_multipart_encoded_file_result.text)
transfer_multipart_encoded_file()
复制代码
给接口传递参数,请求接口后,接口会给我们我们响应返回,接口在返回的时候,会给我们返回一个状态码来标识当前接口的状态。
(1)状态码
【GitHub示例】
状态码 | 状态 | 描述 |
---|---|---|
1xx | ---- | **信息类的状态码 ** |
100 | Continue | 服务器仅接收到部分请求,但是一旦服务器并没有拒绝该请求,客户端应该继续发送其余的请求。 |
101 | Switching Protocols | 服务器转换协议,服务器将遵从客户的请求转换到另外一种协议 |
2xx | ---- | **成功类的状态码 ** |
200 | OK | 请求成功(是对 GET 或 POST 的请求应答文档) |
201 | Created | 请求被创建完成,同时信的资源被创建 |
202 | Accepted | 供处理的请求已被接收,但是处理未完成 |
203 | Non-authoritative Information | 文档已正常地返回,但一些应答头可能不正确,以为使用的式文档的拷贝 |
204 | No Content | 没有新文档。浏览器应该继续显示原来的文档。如果用户定期地刷新页面,而Servlet可以确定用户文档足够新,这个状态代码是很有用的。 |
205 | Reset Content | 没有新文档。但浏览器应该重置它所显示的内容。用来强制浏览器清除表单输入内容。 |
206 | Partial Content | 客户发送了一个带有Range头的GET请求,服务器完成了它。 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : response_code.py
@Time : 2019/9/2 15:41
@Author : Crisimple
@Github : https://crisimple.github.io/
@Contact : Crisimple@foxmail.com
@License : (C)Copyright 2017-2019, Micro-Circle
@Desc : None
"""
import requests
# 1. 返回接口状态码:200
def response_200_code():
interface_200_url = 'https://httpbin.org/status/200'
response_get = requests.get(interface_200_url)
response_get_code = response_get.status_code
print('response_get_code: ', response_get_code)
response_200_code()
# 2.返回接口状态码:400
def response_400_code():
interface_400_url = 'https://httpbin.org/status/400'
response_get = requests.get(interface_400_url)
response_get_code = response_get.status_code
print('response_get_code: ', response_get_code)
response_400_code()
复制代码
(2)响应头
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : response_content.py
@Time : 2019/9/2 15:41
@Author : Crisimple
@Github : https://crisimple.github.io/
@Contact : Crisimple@foxmail.com
@License : (C)Copyright 2017-2019, Micro-Circle
@Desc : None
"""
import requests
# 1. 返回接口状态码:
# (1). 返回接口状态码:200
def response_200_code():
interface_200_url = 'https://httpbin.org/status/200'
response_get = requests.get(interface_200_url)
response_get_code = response_get.status_code
print('response_get_code: ', response_get_code)
response_200_code()
# (2).返回接口状态码:400
def response_400_code():
interface_400_url = 'https://httpbin.org/status/400'
response_get = requests.get(interface_400_url)
response_get_code = response_get.status_code
print('response_get_code: ', response_get_code)
response_400_code()
# (3) 重定向接口返回状态码:301
def response_301_code():
interface_url = 'https://butian.360.cn'
response_get = requests.get(interface_url)
response_get_code = response_get.status_code
print('response_get_code: ', response_get_code)
response_301_code()
# ------------------------------------------------------
# 2. 响应内容
  响应内容的请求头、查看文本、编码方式、二进制响应、原始响应。
def response_contents():
url = 'https://httpbin.org/get'
response_get = requests.get(url=url)
# 响应头
print('response_get_headers', response_get.headers)
# 响应文本
print('response_get_text: ', response_get.text)
# 文本编码方式
print('response_get_encoding: ', response_get.encoding)
# 二进制响应内容
print('response_get_content: ', response_get.content)
# 原始响应内容
origin_content = response_get.raw
origin_content_read = origin_content.read(10)
print('origin_content: ', origin_content)
print('origin_content_read: ', origin_content_read)
response_contents()
复制代码
【GitHub示例】
(1) 操作cookies
import requests
import time
url = 'https://httpbin.org/get'
def operator_cookies():
r = requests.get(url)
print('r.cookies: ', r.cookies)
jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
r2 = requests.get(url=url, cookies=jar)
print('r2.text', r2.text)
operator_cookies()
复制代码
(2) 请求历史
import requests
url = 'https://httpbin.org/get'
def request_history():
r = requests.get(url=url)
print('r.history: ', r.history)
request_history()
复制代码
(3) 超时请求
requests 在经过 timeout 参数设定的秒数时间之后停止等待响应。
import requests
import time
def timeout():
print(time.time())
url = 'https://httpbin.org/get'
print(time.time())
r = requests.get(url, timeout=5)
print(time.time())
timeout()
复制代码
(4) 错误与异常
常见的错误异常有:
· 遇到网络问题(如:DNS 查询失败、拒绝连接等时),requests 会抛出一个 ConnectionError 异常。
· 如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError异常。
· 若请求超时,则超出一个 Timeout 异常。
· 若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
· 所有 Requests 显式抛出的异常都继承自 requests.exceptions.RequestsException。
复制代码
理论千千万万,实战才是真理。百度翻译提供了一套成熟的翻译接口(不是恰饭😂),我们就用此接口对前面理论进行实战。【GitHub示例】
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : baidu_translate.py
@Time : 2019/9/2 20:05
@Author : Crisimple
@Github : https://crisimple.github.io/
@Contact : Crisimple@foxmail.com
@License : (C)Copyright 2017-2019, Micro-Circle
@Desc : None
"""
import requests
import random
import hashlib
import urllib
import json
class BaiduTranslate(object):
def __init__(self, word):
# 你要翻译的元素
self.q = word
self.fromLang = 'en'
self.toLang = 'zh'
self.baidu_translate = 'https://api.fanyi.baidu.com'
self.translate_api_url = '/api/trans/vip/translate'
# 百度开发者配置信息
self.appid = 'XXXXXXXX'
self.secretKey = 'XXXXXXXX'
# 开发配置
self.salt = random.randint(32768, 65536)
self.sign = self.appid + self.q + str(self.salt) + self.secretKey
m1 = hashlib.md5()
m1.update(self.sign.encode('utf-8'))
self.sign = m1.hexdigest()
self.my_url = self.translate_api_url + '?appid=' + self.appid + '&q=' + urllib.request.quote(self.q) + '&from=' + self.fromLang + '&to=' + self.toLang + '&salt=' + str(self.salt) + '&sign=' + self.sign
def en_translate_zh(self):
re = requests.request('post', self.baidu_translate + self.translate_api_url)
print('\n\t re.text', re.text)
re_json = json.loads(re.text)
print('\n\t re_json', re_json)
if __name__ == "__main__":
bt = BaiduTranslate('test')
bt.en_translate_zh()
复制代码
有了requests库请求接口了,为什么要再用urllib来请求接口呢?因为urllib是python的基础库,不需要下载安装,在对环境要求甚高的环境下,在不破坏原来的环境下,依然可以让自动化代码依然运行。【GitHub示例】
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : urllib_request.py
@Time : 2019/9/2 20:49
@Author : Crisimple
@Github : https://crisimple.github.io/
@Contact : Crisimple@foxmail.com
@License : (C)Copyright 2017-2019, Micro-Circle
@Desc : None
"""
from urllib import request
from urllib import parse
def urllib_request():
base_url = 'http://www.tuling123.com/openapi/api'
payload = {
'key1': 'Your',
'key2': '你好'
}
ur = request.Request(url=base_url)
ur_response = request.urlopen(ur)
print('\n ur_response: \n\t', ur_response)
print('\n ur_response_getcode: \n\t ', ur_response.getcode)
print('\n ur_response_headers: \n\t ', ur_response.headers)
data = parse.urlencode(payload).encode('utf-8')
url_payload = request.Request(url=base_url, data=data)
url_payload_response = request.urlopen(url_payload)
print('\n url_payload_response: \n\t', url_payload_response)
print('\n url_payload_response_getcode: \n\t ', url_payload_response.getcode)
print('\n url_payload_response_headers: \n\t ', url_payload_response.headers)
print('\n url_payload_response_msg: \n\t ', url_payload_response.msg)
print('\n url_payload_response_read: \n\t ', url_payload_response.read)
urllib_request()
复制代码
自搭建的接口平台使用Django框架进行开发,基于当前接口的需求(接口的增、删、改、查)功能,搭建一个满足需要的接口测试平台。