亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

互聯網斷開后如何繼續請求發布

互聯網斷開后如何繼續請求發布

米琪卡哇伊 2021-12-29 10:44:26
with open("student.csv", "r") as csv_ledger:    r = csv.DictReader(csv_ledger)    data = [dict(d) for d in r ]    groups = {}    for k, g in groupby(data, lambda r: (r['name'])):        items = []        for i in g:        #data processing        try:           post_api = requests.post(ENDPOINT_URL, json=groups, headers=headers)        except requests.ConnectionError:              print("Something went wrong")        finally:              print("resume post request")目前,當互聯網連接斷開時,我的代碼將無法恢復發布請求。如果我使用 try 和 exception,它就不起作用。
查看完整描述

2 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

不確定您是否可以在沒有服務器端實現的情況下隨意恢復,但您可以從客戶端恢復。這是一個簡單的阻塞示例,但您可能希望將其放入線程中。


import csv

import socket

from time import sleep


import requests



def is_internet_on():

    try:

        socket.setdefaulttimeout(3)

        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(('1.1.1.1', '8080'))

        return True

    except:

        return False



def do_call_later(url, headers, body):

    while not is_internet_on():

        sleep(5)

    requests.post(url, headers=headers, body=body)



with open("student.csv", "r") as csv_ledger:

    r = csv.DictReader(csv_ledger)

    data = [dict(d) for d in r]

    groups = {}


    for k, g in groupby(data, lambda r: (r['name'])):

        items = []

        for i in g:

            # data processing

            pass

        try:

            timeout_arg = (

                # first tuple value is the connection timeout,

                # how long to wait before initial connection is established

                1.0,

                # second tuple value is the read timeout, this is how long

                # the client will wait after the initial connection

                # before dropping the connection because no response was sent

                1.0

            )

            post_api = requests.post(ENDPOINT_URL, json=groups, headers=headers, timeout=timeout_arg)

        except requests.ConnectionError:

            do_call_later(ENDPOINT_URL, headers, groups)

        finally:

            print("resume post request")

編輯:超時調用的文檔:https : //github.com/kennethreitz/requests/blob/master/requests/api.py#L34


查看完整回答
反對 回復 2021-12-29
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

不確定,它是否可以像這樣工作。

可恢復請求的思想是將數據分塊發送,然后組裝為后端。因此,如果中間請求失敗,它可以稍后通過發送其他塊來恢復。后端也應該能夠接受塊并組裝它們

看一個python庫可恢復


查看完整回答
反對 回復 2021-12-29
  • 2 回答
  • 0 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號