主要思路:

  1. 连接mysql数据库,这里数据库需要使用Proxifier来设置代理,然后才能正常连接
  2. 获取mysql数据库中某一数据,作为接口的参数信息
  3. 将接口返回结果保存至csv数据表中
# -*- coding:utf-8 -*-
'''
主要功能:
1、连接mysql数据库
2、将返回结果保存至本地文件
''' import pymysql
import urllib.request
import requests
import json class TestMysql(): def __int__(self):
self.address = "mysql://127.0.0.1/" #连接mysql
def connect(self):
flag_init = 0
error_init = 0
error_fail_init = 0
# 初始化接口参数
login_url = 'https://api.ty.com/oauth2/token?grant_type=password&sms_verify=true'
login_header = {"Authorization": "Basic E23werredW3uY243hY5guaXBob76lOrdfREWdfZtrFtfYtfggREWDYTE="}
login_data = {
"username": "15012345678",
"password": "123456",
"appName": "hea-by",
"grant_type": "password",
"sms_verify": "true"
}
# 登录请求接口
r_login = requests.post(url=login_url, data=login_data, headers=login_header) # api_token = '785f510b-95d1-4bfe-8b4b-faa7fdbc8c23' #连接mysql
conn = pymysql.connect(host = 'mysql.beta.ty.net',
port = 3306,
user = 'root',
password = '123456',
db = 'test',charset='utf8')
# conn.set_character_set('utf-8')
# 通过获取到的数据库连接conn下的cursor()方法来创建游标
cur = conn.cursor()
# cur.execute("set NAMES gbk") # 一般到这一步就行了
# cur.execute('SET CHARACTER SET gbk;')
# cur.execute('SET character_set_connection=gbk;') # 打印查询数据库的表中符合的数据数目
test_name_count=cur.execute("select `name` from t_test_nutrition_info;")
print(test_name_count)
# 打印表中的多少数据
test_name_info = cur.fetchmany(test_name_count)
for i in test_name_info:
print(i)
print(type(i))
x = list(i)
print(x) #接口调用 food_data = {
"msg": x[0]
} print(x[0])
# list转换为str,下面响应无结果使用
food_string = "".join(x[0])
print(type(food_string)) print("请求食材名称:" + food_string) print(food_data) # 获取响应报文
print(r_login.text)
print(type(r_login))
response = json.loads(r_login.text) access_token = response['access_token']
food_headers = {"Authorization": "Bearer " + access_token}
food_url = 'https://api.ty.com/food_detect' r_food = requests.post(url = food_url,json= food_data,headers = food_headers) #发送请求接口
# 获取响应报文 # 转换为dict格式
food_response = json.loads(r_food.text)
print(r_food)
print(r_food.json())
print(type(r_food.json()))
print(type(food_response)) # 判断响应结果是否为空,不为空,则获取dict中的第一个
if food_response:
print(food_response[0])
food_response_one = food_response[0]
# 取得AI识别的食物名称
cal_name = food_response_one['properties']['cal_name']
print(cal_name)
# 取得输入的食物名称
food_name = food_response_one['properties']['name']
print(food_name)
# 判断食物和AI是否一致
if cal_name == food_name:
flag_init = flag_init + 1
print("食材匹配成功:%d" %flag_init)
# 首先将字符串转换为list或dict
print(type(cal_name))
food_dict = eval("{'cal_name':cal_name,'name':food_name}")
print(food_dict)
print(type(food_dict))
# 将字典转换为json格式
food_json =json.dumps(food_dict,ensure_ascii= False)
# 识别成功的食材追加保存在文件success_food.json中
file_save = open('success_food.json','a')
file_save.write(food_json)
file_save.close() else:
print(food_name)
error_init = error_init + 1
print("食材匹配失败:%d" %error_init)
# 写入本地保存匹配失败的食材名称
food_error_dict = eval("{'cal_name':cal_name,'name':food_name}")
#将字典转换为json格式
food_error_json = json.dumps(food_error_dict,ensure_ascii=False)
# 识别识别的食材保存在fail_food.json文件中
file_error_save = open('error_food.json','a')
file_error_save.write(food_error_json)
file_error_save.close() else:
error_fail_init = error_fail_init + 1
print("食材没有找到%d"%error_fail_init )
# 写入本地保存没有找到的食材名称
food_fail_dict = eval("{'name':food_string}")
# 将字典转换为json格式
food_fail_json = json.dumps(food_fail_dict,ensure_ascii= False)
file_fail_save = open('fail_food.json','a')
file_fail_save.write(food_fail_json)
file_fail_save.close() # 重新保存文件success_food.json、error_food.json、fail_food.json # food_response_one = food_response[0]
# cal_name = food_response_one['properties']['cal_name']
# print(cal_name)
#
# # 获取食物名称
# food_name = food_response_one['properties']['name']
# print(food_name)
# # 判断食物和AI是否一致
# if cal_name == food_name :
# flag_init = flag_init + 1
# print("食材匹配成功:%d" %flag_init )
# else:
# print(food_name)
# error_init = error_init + 1
# print("食材匹配失败:%d" %error_init)
# #获取响应状态码
# print(r_food.status_code) # 关闭游标
cur.close()
# 关闭连接
conn.commit()
conn.close() if __name__ == '__main__': tm = TestMysql()
tm.connect() print("----------测试结束----------")

该代码主要实现了连接数据库,将数据库中的某一数据保存为接口的一个参数,同时保存响应结果到本地文件。

python requests接口测试系列:连接mysql,获取mysql查询的值作为接口的入参的更多相关文章

  1. Python+requests 发送简单请求--》获取响应状态--》获取请求响应数据

    Python+requests 发送简单请求-->获取响应状态-->获取请求响应数据 1.环境:安装了Python和vscode编译器(Python自带的编译器也ok).fiddler抓包 ...

  2. Python+Requests+Xpath实现动态参数获取实战

    1.古诗文网直接登录时,用浏览器F12抓取登录接口的入参,我们可以看到框起来的key对应的value是动态参数生成的,需获取到: 2.登录接口入参的值一般是登录接口返回的原数据值,若刷新后接口与对应源 ...

  3. Python+Requests接口测试教程(1):Fiddler抓包工具

    本书涵盖内容:fiddler.http协议.json.requests+unittest+报告.bs4.数据相关(mysql/oracle/logging)等内容.刚买须知:本书是针对零基础入门接口测 ...

  4. Python+Requests接口测试教程(2):

    开讲前,告诉大家requests有他自己的官方文档:http://cn.python-requests.org/zh_CN/latest/ 2.1 发get请求 前言requests模块,也就是老污龟 ...

  5. Python+Requests接口测试教程(2):requests

    开讲前,告诉大家requests有他自己的官方文档:http://cn.python-requests.org/zh_CN/latest/ 2.1 发get请求 前言requests模块,也就是老污龟 ...

  6. python requests 接口测试

    1.get方法请求接口 url:显而易见,就是接口的地址url啦 headers:请求头,例如:content-type = application/x-www-form-urlencoded par ...

  7. Python+Django+SAE系列教程12-----配置MySQL数据库

    由于SAE上支持的是Mysql,首先我们要在本地配置一个Mysql的环境 ,我在网上找到MySQL-python-1.2.4b4.win32-py2.7.exe,并双击 安装 选择典型安装 安装结束后 ...

  8. python requests接口测试

    Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作,甚至包括各种方法覆盖,来完成最 ...

  9. python 模块 wmi 远程连接 windows 获取配置信息

    测试工具应用: https://ask.csdn.net/questions/247013 wmi连接不上报错问题集 https://blog.csdn.net/xcntime/article/det ...

随机推荐

  1. 写这篇博客之前,我又忘了“==”和equals的区别。

    没错.嘟嘟又把==号和equals 的区别给忘掉了 ==号比较基本类型的时候比的是值,比较引用类型的时候比较的是地址.equals比较基本类型的时候.... 脑子里关于这道题的答案好模糊好没有安全感 ...

  2. IOS应用无法下载、此时无法安装应用程序

    无法安装应用 app开发者,进行程序测试,重试还不行,就重新打包, 个人,更改wifi的dns 在“设置” –> “WiFi” –> 进入当前的WiFi 进入之后点击旁边的叹号,然后进入之 ...

  3. 【iOS】The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods install

    从 github 下载的项目经常会遇到这个问题, 如图所示: 参考: iOS 'The sandbox is not sync with the Podfile.lock'问题解决 尚未解决…………

  4. MyBatis框架之关联查询

    概述:关联查询主要在<resultMap>元素中,用<association>配置一对一.用<collection> 配置一对多 一.一对一查询       1.使 ...

  5. Guitar Pro如何更改五线谱的符杆方向

    可能有的小伙伴不知道Guitar Pro是什么软件,我先稍微给大家介绍一下~ Guitar Pro是专为帮助所有吉他爱好者学习.绘谱.创作的多功能软件.它包含所有吉他的现有指法和音色,可以帮助我们了解 ...

  6. go 学习之路(三)

    一.strings和strconv使用 1.strings.HasPrefix(s string,prefix string) bool :判断字符串s是否以prefix开头 2.stings.Has ...

  7. containerd与kubernetes集成

    kubernetes集群三步安装 概念介绍 cri (Container runtime interface) cri is a containerd plugin implementation of ...

  8. Windows 下安装 Python + Django

    Django是Python的一个Web开发框架,以下是介绍的是windows下的安装步骤, 作者的环境是Win10 ,Windows Server 也是一样的 以下是作者整理的步骤,也可以参考官方教程 ...

  9. 【Kubernetes 系列一】Kubernetes 概述

    以下内容还可以通过 Google Slide 查看:https://docs.google.com/presentation/d/1eYP4bkVBojI_e6PqdpxIf0hvWO-JwAf-fy ...

  10. mongoDB的CRUD的总结

    今天开始接触非关系型数据库的mongoDB,现在将自己做的笔记发出来,供大家参考,也便于自己以后忘记了可以查看. 首先,mongoDB,是一种数据库,但是又区别与mysql,sqlserver.orc ...