python3 實現 get 和 post 請求

雪花飄發表於2019-02-12

用 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,requestparse.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_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}

    將 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 又解析不出來引數陣列

本作品採用《CC 協議》,轉載必須註明作者和本文連結

雪花飄

相關文章