api调用实例python_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 – The length of the request body (as a string).

CONTENT_TYPE – The MIME type of the request body.

HTTP_ACCEPT – Acceptable content types for the response.

HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.

HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.

HTTP_HOST – The HTTP Host header sent by the client.

HTTP_REFERER – The referring page, if any.

HTTP_USER_AGENT – The client's user-agent string.

QUERY_STRING – The query string, as a single (unparsed) string.

REMOTE_ADDR – The IP address of the client.

REMOTE_HOST – The hostname of the client.

REMOTE_USER – The user authenticated by the Web server, if any.

REQUEST_METHOD – A string such as "GET" or "POST".

SERVER_NAME – The hostname of the server.

SERVER_PORT – The port of the server (as a string).

获取请求头内容的用META

示例:

def index(request):

ip = request.META.get("REMOTE_ADDR")

return HttpResponse("你的ip地址是%s"%ip)

http://10.254.30.27/1

self.kwargs[‘pk'] # 可以拿到后边的 1

补充知识:django 使用requests请求相关接口

1、如果是get请求接口,并且需要带相关参数的话,可以借鉴下面的代码:

import requests

from django.http import JsonResponse

def get_info(request):

url = 'http://www.baidu.com'

params = {'id': 1, 'user': 'lin'}

response = requests.get(url=url, params=params)

return JsonResponse(response.text, safe=False)

这样将会返回一串json的字符串数据。

2、如果是post请求接口,并且需要带相关参数的话,可以借鉴下面的代码:

import requests

from json import dumps

from django.http import JsonResponse

def get_info(request):

url = 'http://www.baidu.com'

data = {'id': 1, 'user': 'lin'}

response = requests.post(url=url, data=dumps(data))

return JsonResponse(response.text, safe=False)

注:

(1)、其中必须注意的为data这个参数,必须要用dumps(data)转换一下,不然会报错,response状态码为400,bad request error 400 while using python requests.post function。

(2)、如果需要在post请求底下加相关请求头的话,可以借鉴下面的代码:

import requests

from json import dumps

from django.http import JsonResponse

def get_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)

return JsonResponse(response.text, safe=False)

这里如果response的状态码报415错误的话,即HTTP请求415错误 – 不支持的媒体类型(Unsupported media type),这就是content-Type可能写错了,就要注意一下了,因为通常接口会封装一些参数到请求头底下。

以上这篇django API 中接口的互相调用实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,您需要在Django创建一个API视图,该视图将处理来自Vue组件的请求。您可以使用Django REST框架来简化API的创建过程。 以下是一个使用Django REST框架创建API视图的示例: ```python from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import get_object_or_404 from .models import MyModel class MyModelView(APIView): def get(self, request, pk): my_model = get_object_or_404(MyModel, pk=pk) data = { 'id': my_model.id, 'name': my_model.name, 'description': my_model.description } return Response(data) ``` 在这个示例,我们创建了一个名为`MyModelView`的API视图,它处理`GET`请求,并返回`MyModel`模型的数据。我们使用`get_object_or_404`函数来获取指定ID的`MyModel`实例。 接下来,您需要在Vue组件使用`axios`库来发起HTTP请求并获取数据。以下是一个示例: ```javascript import axios from 'axios'; export default { data() { return { myModel: null } }, mounted() { axios.get('/api/my-model/1/') .then(response => { this.myModel = response.data; }) .catch(error => { console.log(error); }); } } ``` 在这个示例,我们使用`axios`库来发起`GET`请求,获取ID为1的`MyModel`实例的数据。我们将`response.data`赋值给`myModel`变量,以便在组件模板使用。 这就是一个简单的Vue组件调用Django接口的示例。当然,实际情况可能更加复杂,具体取决于您的应用程序的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值