json - 如何在 DjangoRestFramework UI 中获得格式更好的 JSON 响应
问题描述
我在 DRF 中有一个 APIVIEW,我在其中写了一些视图以获得一些响应,我想获得一个格式更好的 JSONResponse。
视图.py
class Pay(APIView):
def get(self, request):
url = "https://api.paystack.co/transaction/verify/262762380"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
这是我想要改进的格式错误的 JSONResponse 的图形表示。谢谢
解决方案
因此,如果您没有模型,而是您以其他方式获得的某些数据结构(如来自第三方 API 的响应),则只需返回一个带有此数据结构作为参数的响应。
在这种情况下,您实际上是在 3rd 方 API 和您的客户端之间充当一种代理,如果这是您想要的(确保不要泄露私人数据!)
例子:
class Pay(APIView):
def get(self, request):
url = "https://api.paystack.co/transaction/verify/262762380"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
# no need for 'data' and 'files' arguments with method GET
response = requests.get(url, headers=headers)
# do some validation, at least check for response.status_code
if response.status_code == 200:
data = response.json()
return Response(data)
使用requests 库时还有更多的可能性。
推荐阅读
- javascript - 在 Heroku 上重新启动后,Better-SQLite3 数据库重置
- angular - Angular - 如何在下拉列表中设置默认选项
- mysql - 如何优化 mysql 查询
- java - 内容下载在 chrome for Web App 中占用太多
- apache - 在 Github 页面上重定向 zip 文件
- php - PHP表单值导致数组
- ember.js - 用于 Ember 注入服务的 Intellisense
- python - 将变量传递给索引函数 - Python
- flutter - Flutter - Persisting BottomNavigationBar - 如何不在某些页面上显示?
- postgresql - SQLAlchemy Core - 生成 PostgreSQL SUBSTRING 表达式?