Python Django 使用requests库请求相关接口

Python Django 使用requests库请求相关接口,第1张

1.安装requests库,cmd下执行
pip install requests
2.创建一个Demo项目

创建过程可以参考Django安装_grfstc的博客-CSDN博客

3.在本地搭建json-server本地模拟后端数据

搭建过程可以参考react前端调试时使用json-server本地模拟后端数据_grfstc的博客-CSDN博客

 的1~3步骤,cmd进入db.json目录下启动服务

json-server --watch db.json --port 3004
4. 修改urls.py文件,添加路由
from django.urls import path
from App import views

urlpatterns = [
    path('user/post/', views.post_test, name='post'),
    path('user/get/', views.get_test, name='get'),
]
5. 修改应用下的视图文件views.py
#coding:utf-8
import requests
import json
from json import dumps
from django.http import JsonResponse
from django.shortcuts import render


def post_test(request):
    header = {
        "Content-Type": "application/json"
    }
    url = 'http://localhost:3004/records'  # api链接
    data = {"date": "2022-05-05", "title": "收入", 'amount': 315}
    response = requests.post(url=url, data=dumps(data), headers=header)
    response.encoding = response.apparent_encoding
    return JsonResponse(response.json(), safe=False)      # .json()以字典格式显示


def get_test(request):
    url = 'http://localhost:3004/records'  # api链接
    params = {"id": 6, }
    wb_data = requests.get(url=url, params=params)  # 引入requests库来请求数据
    wb_data.encoding = "utf-8"
    return JsonResponse(wb_data.json(), safe=False)

注意requests.post()中data这个参数,必须要用dumps(data)转换一下,不然会报错,response状态码为"GET /user/post/ HTTP/1.1" 500 104404

 6.运行Django服务,查看效果

http://127.0.0.1:8000/user/post/

且db.json增加一条数据

 http://127.0.0.1:8000/user/get/

能获取id为6的数据 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/868801.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存