我在调用外部api时遇到问题。这是我的观点:
class TestView(APIView):
def call_api(self, request, *args, **kwargs):
headers = {}
url = 'http://jsonplaceholder.typicode.com/users/'
method = request.method.lower()
method_map = {
'get': requests.get,
'post': requests.post,
'put': requests.put,
'patch': requests.patch,
'delete': requests.delete
}
return Response(method_map[method](url, headers=headers, data=json.dumps(request.data)).json())
def get(self, request, *args, **kwargs):
return self.call_api(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.call_api(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.call_api(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.call_api(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.call_api(request, *args, **kwargs)
这是我的urls.py:
url(r'^test/(?P<pk>[0-9]+)/$', TestView.as_view()),
如何更新我的网址和call_api()以获取用户之一:test / 1 / - 转到http://jsonplaceholder.typicode.com/users/1,test / 2 - 转到http://jsonplaceholder.typicode.com/users//2。现在我拥有urls.py中的所有用户。我还需要这个用于所有REST请求。感谢。
答案 0 :(得分:1)
将call_api
更新为
def call_api(self, request, *args, **kwargs):
headers = {}
url = 'http://jsonplaceholder.typicode.com/users/'+args[0]
# args[0] = pk