Home > Back-end >  Python script has function that have repetitive code
Python script has function that have repetitive code

Time:10-10

I have this piece of code in Python where functions are being used with a lot of the code lines doing the same thing. The only difference is the endpoint name differs from the rest. The endpoint are being called from a separate Flask app.

def add_latency(mbxIP, latency):
         url = f"http://{mbxIP}:5000/add_latency?ms={latency}"
         response = requests.get(url)
         if response.status_code // 100 == 2:
                print('OK')
                return True
         else:
                print(f"ERROR in add_latency. URL: {url}. Response code: {response.status_code}")
         return False

 def remove_latency(mbxIP, latency):
         url = f"http://{mbxIP}:5000/remove_latency?ms={latency}";response = requests.get(url)
         if response.status_code // 100 == 2:
                print('OK')
                return True
         else:
                print(f"ERROR in remove_latency. URL: {url}. Response code: {response.status_code}")
         return False

 def add_jitter(mbxIP, jitter):
         url = f"http://{mbxIP}:5000/add_jitter?ms={jitter}"
         response = requests.get(url)
         if response.status_code // 100 == 2:
                print('OK')
                return True
         else:
                print(f"ERROR in add_jitter. URL: {url}. Response code: {response.status_code}")
         return False

 def remove_jitter(mbxIP, jitter):
         url = f"http://{mbxIP}:5000/remove_jitter?ms={jitter}"
         response = requests.get(url)
         if response.status_code // 100 == 2:
                print('OK')
                return True
         else:
                print(f"ERROR in add_jitter. URL: {url}. Response code: {response.status_code}")
         return False

How can I reuse the code from one function and prevent repetition?

CodePudding user response:

do the following :

def url(a,b,function_name):
    url = f"http://{a}:5000/{function_name}?ms={b}"
    return url

def main_func(url,function_name):
         response = requests.get(url)
         if response.status_code // 100 == 2:
                print('OK')
                return True
         else:
                print(f"ERROR in {function_name}. URL: {url}. Response code: {response.status_code}")
         return False

def add_latency(mbxIP, latency):
    return main_func(url(mbxIP,latency),'add_latency')

def remove_latency(mbxIP, latency):
    return main_func(url(mbxIP,latency),'remove_latency')

def add_jitter(mbxIP, jitter):
     return main_func(url(mbxIP,jitter),'add_jitter')

def remove_jitter(mbxIP, jitter):
     return main_func(url(mbxIP,jitter),'remove_jitter')
  • Related