您的位置:首页技术文章
文章详情页

python实现测试工具(一)——命令行发送get请求

【字号: 日期:2022-07-07 17:21:58浏览:6作者:猪猪

本系列教程我们将使用python实现一些简单的测试工具,为了尽可能的简单,我们的工具以命令行工具为主。

本系列教程使用的python版本是3.6.3。

背景

这一节我们实现简单的命令行发送get请求的工具,使用方式如下:

python get.py www.v2ex.com/api/nodes/show.json?name=python接口地址: http://www.v2ex.com/api/nodes/show.json?name=python状态码: 200Headers:Date : Tue, 10 Jul 2018 07:06:12 GMTContent-Type : application/json;charset=UTF-8Transfer-Encoding : chunkedConnection : keep-aliveVary : Accept-EncodingX-Rate-Limit-Remaining : 119Expires : Tue, 10 Jul 2018 08:03:49 GMTServer : Galaxy/3.9.8.1Etag : W/'76a33d25372411dc6fa4190a5cf9679caa0edc2a'X-Rate-Limit-Reset : 1531209600Cache-Control : max-age=3600X-Rate-Limit-Limit : 120Google : XYContent-Encoding : gzipStrict-Transport-Security : max-age=31536000{ 'id' : 90, 'name' : 'python', 'url' : 'https://www.v2ex.com/go/python', 'title' : 'Python', 'title_alternative' : 'Python', 'topics' : 9530, 'stars' : 6601, 'header' : '这里讨论各种 Python 语言编程话题,也包括 Django,Tornado 等框架的讨论。这里是一个能够帮助你解决实际问题的地方。', 'footer' : null, 'created' : 1278683336, 'avatar_mini' : '//cdn.v2ex.com/navatar/8613/985e/90_mini.png?m=1531131631', 'avatar_normal' : '//cdn.v2ex.com/navatar/8613/985e/90_normal.png?m=1531131631', 'avatar_large' : '//cdn.v2ex.com/navatar/8613/985e/90_large.png?m=1531131631'}

主要使用场景是快速访问http的api接口,查看状态码,响应头以及响应内容。

代码实现

简单起见,我们会用到requests库。

import requestsfrom sys import argvUSAGE = ’’’USAGE:python get.py https://api.github.com’’’if len(argv) != 2: print(USAGE) exit()script_name, url = argvif url[:4] != ’http’: url = ’http://’ + urlr = requests.get(url)print(f'接口地址: {url}n')print(f'状态码: {r.status_code}n')print(f'Headers:')for key, value in r.headers.items(): print(f'{key} : {value}')print(r.text)

动手时间

抄一遍代码,看自己能不能运行起来 给这段代码每一行都加上注释,理解代码做了些什么 如果需要在发送get请求的时候默认加上Content-Type: application/json的headers,这段代码该如何修改

源码地址

https://github.com/easonhan007/simple_test_tools

以上就是python实现测试工具(一)——命令行发送get请求的详细内容,更多关于python 命令行发送get请求的资料请关注好吧啦网其它相关文章!

标签: Python 编程
相关文章: