0

I'm new to programming with Python. I'd like to set a variable for the Python requests method (.get, .post, etc.).

Something like:

import requests

method = 'get'
url = 'https://google.com'

response = requests.method(url)

This of course results in an error because requests does not have a .method option.

It feels like the answer lies with getattr, but I don't understand what parameters to pass getattr.

Any advice?

Thank you

SeaDude
  • 3,725
  • 6
  • 31
  • 68

1 Answers1

-1

You can use the following code:

import requests

get = requests.get
post = requests.post
put = requests.put
patch = requests.patch
delete = requests.delete

url = 'https://google.com'

google = get(url)

If you would like it as a class you can use the following code:

import requests


class Methods:
    def __init__(self):
        self.get = requests.get
        self.post = requests.post
        self.put = requests.put
        self.patch = requests.patch
        self.delete = requests.delete


methods = Methods()
url = 'https://google.com'
method = "get"

google = getattr(methods, method)(url)
abhigyanj
  • 2,355
  • 2
  • 9
  • 29