【发布时间】:2020-02-19 20:41:12
【问题描述】:
我正在尝试执行我的代码:
import json
import requests
class Request(object):
def __init__(self, method, path):
self.method = method
## Q1
self.url = ''.join([***MyClass.host***, path])
self.h = {
"Content-Type": "application/json;charset=UTF-8"
}
def __call__(self, f):
def wrapper(*args, **kwargs):
# Q2
getattr(requests, self.method)(url = self.url, headers = h***, data = json.dumps(body)***)
return wrapper
class MyClass(object):
def __init__(self, host):
self.host = host
@Request(method = "post", path = "/add_mission")
def AddMission(self, mission):
body = {
"mission_id": mission
}
@Request(method = "get", path = "/system_info")
def GetInfo(self):
print("I want get info")
有一些问题希望有人能解决我的问题:
1. 我的装饰器“Request”如何从“MyClass”中获取变量“host”? (在评论 ## Q1)
2.如何将函数的变量“body”传递给装饰器,可以吗? (在评论 ## Q2)
因为我需要使用 [post, get, delete] 访问不同的 url(host+path)。 我不确定这种情况下的装饰器是否匹配? 或者也许有更好的方法来处理这种情况?
【问题讨论】:
-
你不需要
getattr(requests, self.method)。requests.get已经只是requests.request("GET", ...)的包装。 -
@chepner 谢谢你的提醒。你的回复消除了我的困惑。 :)
标签: python python-requests decorator python-decorators