Python Requests Tutorial: GET, POST, HTTPS, File Upload/Download, Timeout, Authentication, Session, Token, and Test Automation Framework
This article provides a comprehensive Python tutorial covering how to send GET and POST requests, handle HTTPS verification, perform file uploads and downloads, set request timeouts, use basic and token authentication, manage sessions, generate signatures, and organize a test automation framework with configuration, common utilities, test data, test cases, reporting, and execution scripts.
This guide demonstrates practical usage of the requests library for various HTTP operations and shows how to structure a Python‑based API test automation framework.
1. Send a GET request
#导包
import requests
#定义一个url
url = "http://xxxxxxx"
#传递参数
payload = "{\"head\":{\"accessToken\":\"\",\"lastnotice\":0,\"msgid\":\"\"},\"body\":{\"user_name\":\"super_admin\",\"password\":\"b50c34503a97e7d0d44c38f72d2e91ad\",\"role_type\":1}}"
headers = {
'Content-Type': 'text/plain',
'Cookie': 'akpsysessionid=bafc0ad457d5a99f3a4e53a1d4b32519'
}
#发送get请求
r = requests.get(url=url, headers=headers, data=payload)
print(r.text)
print(r.encoding)
print(r.text.encode('utf-8').decode('unicode_escape'))2. Send a POST request
#导包
import requests
#定义一个url
url = "http://xxxxxxx"
#传递参数
payload = "{\"head\":{\"accessToken\":\"\",\"lastnotice\":0,\"msgid\":\"\"},\"body\":{\"user_name\":\"super_admin\",\"password\":\"b50c34503a97e7d0d44c38f72d2e91ad\",\"role_type\":1}}"
headers = {
'Content-Type': 'text/plain',
'Cookie': 'akpsysessionid=bafc0ad457d5a99f3a4e53a1d4b32519'
}
#发送post请求
r = requests.post(url=url, headers=headers, data=payload)
print(r.text)3. Send an HTTPS request (ignore certificate verification)
import requests
url = 'https://www.ctrip.com/'
# ignore certificate
r = requests.post(url=url, verify=False)
print(r.text)
# use a certificate file
r = requests.post(url=url, verify='path/to/cert')
print(r.text)4. File upload
import requests
file = {'filename': open('文件名称', 'rb')}
response = requests.post("网址", files=file)
print(response.text)5. File download
# Small file download
import requests
r = requests.get("https://img.sitven.cn/Tencent_blog_detail.jpg")
with open("D:\a.jpg", "wb") as f:
f.write(r.content)
# Large file download
import requests
def test_downloads(url, file):
s = requests.session()
r = s.get(url, stream=True, verify=False)
with open(file, "wb") as f:
for chunk in r.iter_content(chunk_size=512):
f.write(chunk)
if __name__ == "__main__":
url = "https://www.url.com/test/export"
file = "D:\a.xlsx"
test_downloads(url=url, file=file)6. Request timeout handling
#导包
import requests
for i in range(0,10):
try:
url = "http://xxxxxxxxxxxxxxxx"
data = {"head":{...}, "body":{...}}
# timeout set to 0.03 seconds
r = requests.post(url=url, json=data, timeout=0.03)
print(r.text)
print(r.cookies)
except:
print('error')7. Authentication and session usage
# Basic auth
import requests
url = 'http://192.168.1.1'
headers = {}
r = requests.get(url, auth=('admin','123456'), headers=headers, timeout=10)
print(r.text)
# Session
session = requests.session()
response = session.post(url, headers=req_header, data=form_data)
# Token example
import requests
url = "http://xxxxxxxxxxxxxxx"
json = {"head":{...}, "body":{...}}
r = requests.post(url=url, json=json)
print(r.text)
print(r.cookies)8. Signature generation (WeChat Pay example)
# appid, mch_id, device_info, body, nonce_str defined
import hashlib
stringA = "appid=wxd930ea5d...&nonce_str=ibuaiVcKdpRxkhJA"
md = hashlib.md5()
md.update(stringA.encode())
AES = md.hexdigest().upper()
print(AES)9. Automation framework structure
config: configuration files (Python packages)
common: shared utility methods
testdata: test data files (xls, txt, csv)
test_case: test case scripts
report: generated HTML/XML reports
run_case: test execution script
log: logging
9.1 Example config functions
def server_ip():
# return different server addresses based on environment
server_add = {
'dev_ip': 'http://his.xxxxxxxxxxx.com',
'sit_ip': 'http://his.xxxxxxxxxxxx.comm'
}
return server_add['dev_ip']
def sql_conf():
host = 'localhost'
user = 'root'
password = '123456'
database = 'mysql'
port = 3306
charset = 'utf8'
return host, user, password, database, port, charset9.2 Common utilities (Excel reading, MySQL query)
# Read Excel
import xlrd
def get_excel_value(i):
filename = r"../testdata/jiekou.xls"
book = xlrd.open_workbook(filename)
sheet = book.sheet_by_index(0)
return sheet.cell_value(i,1), sheet.cell_value(i,2)
# MySQL query
import pymysql
from config.sql_conf import *
def get_sql(sql):
host, user, password, database, port, charset = sql_conf()
db = pymysql.connect(host=host, user=user, password=password, database=database, port=port, charset=charset)
cursor = db.cursor()
cursor.execute(sql)
data = cursor.fetchall()
cursor.close()
db.close()
return data9.3 Sample test case
def test_aokao_login():
url = server_ip() + '/service/user/login'
username, password = get_excel_value(1)
json = {
"head": {"accessToken":"", "lastnotice":0, "msgid":""},
"body": {"username": username, "password": password, "forceLogin":0}
}
r = requests.post(url=url, json=json)
print(r.text)
assert r.status_code == 200
assert '"accessToken":"89a08bff-15d7-4d7a-9967-0b5f4fb699ce",' in r.text
def test_aokao_registadd():
url = server_ip() + '/service/registration/registadd'
data = {"head":{...}, "body":{...}}
r = requests.post(url=url, json=data, timeout=0.09)
print(r.text)
print(r.cookies)
assert r.status_code == 2009.4 Test execution script
import pytest
if __name__ == "__main__":
pytest.main([
'../test_case/',
'--html=../report/report.html',
'--junitxml=../report/report.xml'
])The article concludes with references to the original tutorial and illustrative diagrams.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
