Python中的多个意外POST请求

时间:2015-07-03 07:30:06

标签: python python-requests

我有这个程序使用请求库发送GET请求,然后将POST请求发送到另一个服务器。

import requests 

# inside the loop : 
headers = {'charset':'utf-8','Content-Type':'application/json'}
url = "http://someurl/_get_v2.php"
data = jenal

try :
    resp = requests.post(url,json=data,headers=headers, timeout=(connect_timeout,read_timeout))

    print "Post request sent" 
# If a connection error occurs, start from the beginning of the loop
except requests.exceptions.ConnectionError as e: 
    continue 
# If a read_timeout error occurs, start from the beginning of the loop
except requests.exceptions.ReadTimeout as e:  
    continue
time.sleep(10)

这是主循环中的POST部分。我尝试使用,除非程序遇到延迟,我不希望它停止任何错误,但是从循环开始刷新并继续,依此类推。从逻辑上讲,程序应该没问题,但是当突然出现多个延迟时,程序会同时发送多个POST请求。

例如:日志应该是这样的: 10发送。 20发送。 30发送。 45发送(延迟5秒)。 55发送

但是会发生什么: 10发送 20发送 30发送 延迟..
45发送 45发送 发送了45(同时发送了几个数据副本,这会破坏我的数据库) 55发送

我该如何阻止额外的副本?

这是该计划的第一部分。如果帖子中有任何内容,这部分会重复,每次都可以看到打印件:

connect_timeout = 3.05
read_timeout = 2

while True:
loop_time_start = time.time()
# GET

url_source = 'http://something/api_json.asp?cmd=list_metering&auth=YWRtaW46YWRtaW4='
try: 
    url = requests.get(url_source)
    print "GET request sent" 
except requests.exceptions.ConnectionError as e: continue

2 个答案:

答案 0 :(得分:1)

如果您在代码中添加计时器,该怎么办?

import requests 
from datetime import datetime, time

posting = False

# inside the loop :

if not posting:
    posting = True

    headers = {'charset':'utf-8','Content-Type':'application/json'}
    url = "http://someurl/_get_v2.php"
    data = jenal

    start = datetime.now()
    try :
        resp = requests.post(url,json=data,headers=headers,timeout=(connect_timeout,read_timeout))

        print "Post request sent" 

        posting = False

    except requests.exceptions.ConnectionError as e:
        # If you continue here, then there will be no sleep.
        # If your POST fails straight away, it tries again straight away. 

        # You should print/log here so you know which exception is being caught.

        # Add Timer
        end = datetime.combine(start.date(), time(0))

        ShouldISleep(start, end)

        posting = False

        continue

    except requests.exceptions.ReadTimeout as e:
        # If you continue here, then there will be no sleep.
        # If your POST fails straight away, it tries again straight away.

        # You should print/log here so you know which exception is being caught.

        # Add Timer
        end = datetime.combine(start.date(), time(0))

        ShouldISleep(start, end)

        posting = False

        continue

    time.sleep(10)

创建一个功能

def ShouldISleep(t1, t2):
    passed = (t1 - t2).seconds
    if passed < 10:
        time.sleep(10 - passed)

答案 1 :(得分:0)