Python Requests - Dynamically Pass HTTP Verb

前端 未结 2 1653
日久生厌
日久生厌 2021-02-19 02:33

Is there a way to pass an HTTP verb (PATCH/POST) to a function and dynamically use that verb for Python requests?

For example, I want this function to take a \'verb\' va

2条回答
  •  臣服心动
    2021-02-19 03:07

    With the request library, the requests.request method can be relied on directly (as Guillaume's answer suggested).

    However, when encountering against libraries that don't have a generic method for methods that have similar calling signatures, getattr can be supplied with the name of the desired method as a string with a default value. Maybe like

    action = getattr(requests, verb, None)
    if action:
        action(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
    else:
        # handle invalid action as the default value was returned
    

    For the default value it can be a proper action, or just leave it out and an exception will be raised; it's up to you how you want to handle it. I left it as None so you can deal with alternative case in the else section.

提交回复
热议问题