python3 實現 get 和 post 請求

用 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 羣內領取相關資料
相關文章
相關標籤/搜索