用 python3 写脚本发送 get 或 post 请求已经不下一次了,但是每次写都不能随心顺手,总得要百度一下,然后照搬过来,测试才能使用,这里记下使用 demo,方便以后使用。get 请求
#获取git仓库信息
def get_git_info():
params = parse.urlencode({"repo":repo,"git_url":git_url})
response = request.urlopen(conf.git_info_url + '?%s' % params)
result = json.loads(response.read().decode('utf-8'))
global git_info
if result['status']:
print('获取仓库信息成功')
git_info = result['data']
global code_run_path
if code_run_path == '':
code_run_path = git_info['code_run_path'].rstrip('/')
else:
msg = result['msg']
print(msg)
raise Exception('获取git仓库信息失败')
return git_info当然,这里前提是要导入模块 from urllib import parse,request,parse.urlencode({"repo":repo,"git_url":git_url}) 对参数进行编码,request.urlopen(conf.git_info_url + '?%s' % params) 发送拼接请求,response.read().decode('utf-8') 读取返回内容并用 utf-8 编码方式解析出来
post 请求
def log_release(success_servers,fail_servers,error_msg,status):
deploy_file = source_dir + '/post-deploy-script.sh'
deploy_script=''
if os.path.isfile(deploy_file):
with open(deploy_file,'r') as f:
deploy_script = f.read()
exclude_file = source_dir + '/.deploy-exclude.list'
exclude_content = ''
if os.path.isfile(exclude_file):
with open(exclude_file, 'r') as f:
exclude_content = f.read()
deploy_version_log = get_version()
data = {"env":env,"mode":mode,"git_url":git_url,"source_dir":source_dir,"is_sync_delete":str(is_sync_delete),"repo_dir":repo,
"code_run_path":code_run_path,"success_servers":success_servers,"fail_servers":fail_servers,"error_msg":error_msg,
"status":str(status),"deploy_script":deploy_script,"deploy_version_log":deploy_version_log,"exclude_content":exclude_content}
text_data = json.dumps(data)
text_data = bytes(text_data,'utf-8')
response = request.Request(conf.log_release_url, text_data)
res = request.urlopen(response)
定义 json 参数
data =
{"env":env,"mode":mode,"git_url":git_url,"source_dir":source_dir,"is_sync_delete":str(is_sync_del
ete),"repo_dir":repo,
"code_run_path":code_run_path,"success_servers":success_servers,"fail_servers":fail_servers,"erro
r_msg":error_msg,
"status":str(status),"deploy_script":deploy_script,"deploy_version_log":deploy_version_log,"exclu
de_content":exclude_content}
将 json 转为 字符串text_data = json.dumps(data)
将参数转化字节流text_data = bytes(text_data,'utf-8')
发送请求response = request.Request(conf.log_release_url, text_data) res = request.urlopen(response)
这里需要注意的是,post 过去的数据如果是 php 接收的话需要 使用以下方式接收并处理
$data = file_get_contents('php://input');
$data = json_decode($data, true);笔者在这里踩过几次坑了,直接用框架的 post 取出来的是整个字符串,用 json 又解析不出来参数数组
话还是不多说,如果还有问题未能解决,可加技术群887934385 群内领取相关资料