Skip to content Skip to sidebar Skip to footer

Multiple Accidental Post Requests In Python

I have this program that sends a GET request using requests library and then sends a POST request to another server. import requests # inside the loop : headers = {'charset':'u

Solution 1:

What if you add a timer to the code.

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 = Falsecontinue

    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 = Falsecontinue

    time.sleep(10)

Create a function

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

Solution 2:

Post a Comment for "Multiple Accidental Post Requests In Python"