This series of tutorials we will use python achieve some simple testing tools as simple as possible for our tools to the command-line based tools.
Python version of this tutorial series is 3.6.3 .
background
In this section we achieve a simple command-line tool get a request to send, used as follows:
python get.py www.v2ex.com/api/nodes/show.json\?name\=python
接口地址: http://www.v2ex.com/api/nodes/show.json?name=python
状态码: 200
Headers:
Date : Tue, 10 Jul 2018 07:06:12 GMT
Content-Type : application/json;charset=UTF-8
Transfer-Encoding : chunked
Connection : keep-alive
Vary : Accept-Encoding
X-Rate-Limit-Remaining : 119
Expires : Tue, 10 Jul 2018 08:03:49 GMT
Server : Galaxy/3.9.8.1
Etag : W/"76a33d25372411dc6fa4190a5cf9679caa0edc2a"
X-Rate-Limit-Reset : 1531209600
Cache-Control : max-age=3600
X-Rate-Limit-Limit : 120
Google : XY
Content-Encoding : gzip
Strict-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"
}
The main usage scenario is to quickly access the http api interface to view the status codes, response headers and response content.
Code
For simplicity, we will use requests library. The setup documentation here .
import requests
from sys import argv
USAGE = '''
USAGE:
python get.py https://api.github.com
'''
if len(argv) != 2:
print(USAGE)
exit()
script_name, url = argv
if url[:4] != 'http':
url = 'http://' + url
r = 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)
Time for action
- Copy the code again, you can not see up and running
- Each line of code to add comments, understand the code done
- If you need to add the default when sending requests get
Content-Type: application/json
the headers, how to modify the code