python实现http get pos download

python实现http get post download

使用requests, 加上重试机制,超时机制.

python 复制代码
#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import requests
import sys
import json
import os
import logging
import time

def httpGet(urlStr, headers = None, params = None, data = None, isRaiseNone200=False):
    print('url:' + urlStr)
    print('params:', params)

    MAX_RETRY_COUT = 5
    # 加个重试次数,可根据需要定制哪些情况下进行重试,如果不重试就把raise的注释去掉
    for retTryPos in range(MAX_RETRY_COUT):
        try:
            # 这里timeout要加,设置连接与访问超时时间,否则可能遇到http卡死挂住的情况
            res = requests.request('get', urlStr, params=params, headers=headers, data=data, timeout=(15, 20))
            content = res.text
            print(content)

            if res.status_code != 200:
                if isRaiseNone200:
                    raise ValueError('http不是200')
                else:
                    print('重试')
                    time.sleep(5)
                    continue
            else:
                return content
        except requests.exceptions.ConnectionError as e:
            logging.error('网络连接异常: ', e)
            print('重试')
            time.sleep(5)
            #raise
        except requests.exceptions.Timeout as e:
            logging.error('连接超时: ', e)
            print('重试')
            time.sleep(5)
            #raise
        except requests.exceptions.RequestException as e:
            logging.error('请求异常: ', e)
            time.sleep(5)
            #raise
        except requests.exceptions.HTTPError as e:
            logging.error(f'HTTP错误, 状态码: {e.response.status_code}, {e}')
            time.sleep(5)
            #raise
        except ValueError as e:
            logging.error('响应解析异常: ', e)
            print('重试')
            time.sleep(5)
            #raise

    raise ValueError('超出重试次数')

def httpDownload(urlStr, saveFile):
    print('download url:' + urlStr)
    savePath = os.path.dirname(saveFile)
    if not os.path.exists(savePath):
        print('mkdir:', savePath)
        os.makedirs(str(savePath))

    r = requests.get(urlStr, timeout=(15, 30))
    if r.status_code != 200:
        print('http返回:', r.content)
        print('http code:', r.status_code)
        raise ValueError('code不是200')

    tmpFile = saveFile + '.tmp'
    with open(tmpFile, 'wb') as f:
        f.write(r.content)
        f.close()
        os.rename(tmpFile, saveFile)

def httpPost(urlStr, headers, postData):
    print('url:' + urlStr)
    try:
        token = getToken()
        datas = json.dumps(postData)
        rc = requests.post(url=urlStr, data=datas, headers=headers, timeout=(8, 20))
        print('post:' + str(datas))
        content = (rc.text)
        print(content)
        if rc.status_code != 200:
            raise ValueError('code不是200')
        return content
    except requests.exceptions.ConnectionError as e:
        logging.error('网络连接异常: ', e)
        time.sleep(5)
        #raise
    except requests.exceptions.Timeout as e:
        logging.error('连接超时: ', e)
        time.sleep(5)
        #raise
    except requests.exceptions.RequestException as e:
        logging.error('请求异常: ', e)
        time.sleep(5)
        #raise
    except requests.exceptions.HTTPError as e:
        logging.error(f'HTTP错误, 状态码: {e.response.status_code}, {e}')
        time.sleep(5)
        #raise
    except ValueError as e:
        logging.error('响应解析异常: ', e)
        time.sleep(5)
        #raise

    raise ValueError('超出重试次数')


if __name__ == '__main__':
    httpGet('http://www.baidu.com')

作者:帅得不敢出门 csdn原创谢绝转载收录

相关推荐
aifannihao1 小时前
AI 学习第 14 课:CNN 训 6 轮卡在 0.5352,数据没打乱
pytorch·python·深度学习·cnn·学习路线
yuyuxun12 小时前
协同过滤的校园二手物品智能推荐系统的设计与实现 毕业设计-附源码40082
javascript·vue.js·spring boot·python·数据分析·django·课程设计
如夏倾城2 小时前
百度文心(容易被忽略的好用AI)使用方式
人工智能·python·百度·语言模型·dubbo
用户019027581613 小时前
quotes 实时价和 klines 最新收盘价为什么对不上?
python
another heaven3 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
少司府3 小时前
嵌入式入门篇(二):初识STM32F103ZET6
linux·python·stm32·单片机·嵌入式硬件·mcu·嵌入式软件
打工仔折腾 AI4 小时前
Changedetection.io 网页变动监控:Docker 部署、通知配置与公网暴露实践
运维·人工智能·后端·python·docker·容器·性能优化
火云代理4 小时前
Python 使用代理 IP 前,先弄清 Requests 的配置来源与验证方法
网络·python·网络协议·tcp/ip·ip
SomeOtherTime4 小时前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
如夏倾城5 小时前
QUIC——HTTP/3 的唯一底层传输协议 及 0-RTT恢复
网络·网络协议·tcp/ip·安全·http