django API 中接口的互相调用实例
我就废话不多说了,还是直接上代码吧!
url="http://%s:%s/api-token-auth/"%(ip,port) query_args={ "username":username, "password":password } resp=requests.post(url=url,data=query_args) token=json.loads(resp.text)["token"] headers={"Authorization":"JWT"+""+token}#拿到token,拼成headers post_url="http://%s:%s/message/message-level-two/"%(ip,port) data={ "app":app, "url":url, "message_id":message_id, "head":head, "title":title, "userprofile_id_list":userprofile_id_list } headers=self.headers requests.post(url=post_url,data=data,headers=headers)
获取当前请求的ip和端口
host_ip,host_port=self.request.META.get("HTTP_HOST").split(':')[0],\ self.request.META.get("HTTP_HOST").split(':')[1]
常见的请求头如下:
CONTENT_LENGTH–Thelengthoftherequestbody(asastring).
CONTENT_TYPE–TheMIMEtypeoftherequestbody.
HTTP_ACCEPT–Acceptablecontenttypesfortheresponse.
HTTP_ACCEPT_ENCODING–Acceptableencodingsfortheresponse.
HTTP_ACCEPT_LANGUAGE–Acceptablelanguagesfortheresponse.
HTTP_HOST–TheHTTPHostheadersentbytheclient.
HTTP_REFERER–Thereferringpage,ifany.
HTTP_USER_AGENT–Theclient'suser-agentstring.
QUERY_STRING–Thequerystring,asasingle(unparsed)string.
REMOTE_ADDR–TheIPaddressoftheclient.
REMOTE_HOST–Thehostnameoftheclient.
REMOTE_USER–TheuserauthenticatedbytheWebserver,ifany.
REQUEST_METHOD–Astringsuchas"GET"or"POST".
SERVER_NAME–Thehostnameoftheserver.
SERVER_PORT–Theportoftheserver(asastring).
获取请求头内容的用META
示例:
defindex(request): ip=request.META.get("REMOTE_ADDR") returnHttpResponse("你的ip地址是%s"%ip)
http://10.254.30.27/1
self.kwargs[‘pk']#可以拿到后边的1
补充知识:django使用requests请求相关接口
1、如果是get请求接口,并且需要带相关参数的话,可以借鉴下面的代码:
importrequests fromdjango.httpimportJsonResponse defget_info(request): url='http://www.baidu.com' params={'id':1,'user':'lin'} response=requests.get(url=url,params=params) returnJsonResponse(response.text,safe=False)
这样将会返回一串json的字符串数据。
2、如果是post请求接口,并且需要带相关参数的话,可以借鉴下面的代码:
importrequests fromjsonimportdumps fromdjango.httpimportJsonResponse defget_info(request): url='http://www.baidu.com' data={'id':1,'user':'lin'} response=requests.post(url=url,data=dumps(data)) returnJsonResponse(response.text,safe=False)
注:
(1)、其中必须注意的为data这个参数,必须要用dumps(data)转换一下,不然会报错,response状态码为400,badrequesterror400whileusingpythonrequests.postfunction。
(2)、如果需要在post请求底下加相关请求头的话,可以借鉴下面的代码:
importrequests fromjsonimportdumps fromdjango.httpimportJsonResponse defget_info(request): url='http://www.baidu.com' data={'id':1,'user':'lin'} headers={'content-Type':'application/json','Accept':'*/*'} response=requests.post(url=url,data=dumps(data),headers=headers) returnJsonResponse(response.text,safe=False)
这里如果response的状态码报415错误的话,即HTTP请求415错误–不支持的媒体类型(Unsupportedmediatype),这就是content-Type可能写错了,就要注意一下了,因为通常接口会封装一些参数到请求头底下。
以上这篇djangoAPI中接口的互相调用实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。