惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
H
Heimdal Security Blog
T
Tenable Blog
Webroot Blog
Webroot Blog
Cisco Talos Blog
Cisco Talos Blog
NISL@THU
NISL@THU
Help Net Security
Help Net Security
W
WeLiveSecurity
量子位
Stack Overflow Blog
Stack Overflow Blog
Schneier on Security
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
Recorded Future
Recorded Future
Martin Fowler
Martin Fowler
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
L
Lohrmann on Cybersecurity
SecWiki News
SecWiki News
Blog — PlanetScale
Blog — PlanetScale
F
Full Disclosure
Recent Commits to openclaw:main
Recent Commits to openclaw:main
小众软件
小众软件
Cyberwarzone
Cyberwarzone
S
Security Affairs
L
LangChain Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
V
V2EX
WordPress大学
WordPress大学
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
Scott Helme
Scott Helme
H
Help Net Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Cyber Attacks, Cyber Crime and Cyber Security
有赞技术团队
有赞技术团队
IT之家
IT之家
G
Google Developers Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
S
Schneier on Security
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
O
OpenAI News
宝玉的分享
宝玉的分享

Django

请教下 哪款 vscode 插件可以通过点击跳转 urls 定义 - V2EX Django 一文告诉你 all 懒加载的机制 - V2EX 大家学习编程做项目的时候一开始会容易卡壳吗?比如我今天一个下午才弄出来了博客当中的文章评论加回复功能,有时候会因为一个小点卡壳,稍微复杂点的逻辑就感觉脑子不够用,甚至是给 html 的 div 取变量名的时候脑子也会不够 - V2EX 请教在 ubuntu23 中如何 让 Django runserver 开机自启动 - V2EX 请教 Django runserver 开机自启动的问题 - V2EX 不知道开发的流媒体合租平台有没有意义… - V2EX 公司自主招聘(远程)后端 Go 开发,想要远程岗位抓紧啦 - V2EX [求助] Mediacms 接入 Keycloak - V2EX 有没有好的 drf 项目可以学习下的? - V2EX django 快速开发明明 drf 更好,为啥还是很多人更推荐 fast.api 和忍者 - V2EX django 的同步机制有性能瓶颈为什么还是有很多人用? - V2EX 大家怎么处理开发时 Migration 一大堆,修修改改啰啰嗦嗦,同步到生产之前还得检查合并下这个问题的? - V2EX Django 模型自定义 Manager 自定义 filter 如何支持链式调用? - V2EX python3 manage.py build_index 这条 Django 命令到底啥意思啊?官方文档找不到说明,谢谢 - V2EX 前后端分离项目, Django 良好的项目结构是怎么样的 - V2EX Django get_max_test_processes - V2EX Django makemigrations 生成的 migrations 文件,如何放在代码当前目录的文件夹中? - V2EX 请教下大家,Django 的 tests 测试模块,如何不创建新从测试数据库,而是直接操作生产环境数据库谢谢! - V2EX django 好像对于 ios 打不开 admin page - V2EX Django 模板中变量的嵌套 - V2EX 早起把网站的友链网页和自主添加友链功能撸出来了,过来收集一波友链 - V2EX 用 django 调用长时间执行的脚本,如何返还输出呢? - V2EX Django 中递归分类 model 用什么组件显示比较合适? - V2EX django 一开始没用 restfulapi 开发, 还能自动生成文档吗? - V2EX 求推 django 数据可视化插件 - V2EX django 用 docker 部署,要不要每次部署到服务器的时候改改 image 的 settings 配置 - V2EX 有没有使用 django 国际化模块的,针对 django.po 国际化文件写了一个 vscode 的插件 - V2EX Django 访问 relation 时,如何得知是谁访问的? - V2EX django admin 部分自带的 css 文件 collectstatic,生成的文件大小为 0? - V2EX Django 怎么做同一个 url,对应不同的 view 函数? - V2EX django 里面的原生的 sql 查询,会一直占用数据库连接吗 - V2EX Django ORM 如何才能在 save_model 插入数据库完成后,再次更新数据库? - V2EX django 定时触发任务 - V2EX 请问 django 怎么高效的获取范围内一条随机数据 - V2EX 请问 Django ORM 如何实现 left join? - V2EX [求助] Django 图片路径的问题 - V2EX 为什么 django ORM 的更新时间字段选择在程序内部生成(auto_now),而不使用 MYSQL 的 on update? - V2EX 有基于 django 的开源博客系统吗? - V2EX Django admin 当中动态显示外键的相关属性 - V2EX Django 如何获取 apscheduler 的 scheduler 实例? - V2EX django3 的 i18n 汉化求救 - V2EX 你们公司的 django 项目如何 - V2EX Django 的 ORM 的 exclude 和 filter 的区别到底是啥? - V2EX 关于如何根据 Accept 的 media_type 返回不同类型序列化数据的想法 - V2EX 请问 Django 在启动的时,如何执行一次性业务代码? - V2EX 推荐一本 django 源码解析的书《深入理解 Django 框架内幕与实现原理》 - V2EX 请问 Django 的 JSONField 字段有没有必要进行索引? - V2EX 分享一个在 Django 的 model 里,使用元类动态添加相似的带自定义中间表的多对多关系字段的方法 - V2EX 咨询个 django 处理耗时任务的问题,顺便找个兼职完成个 demo - V2EX
请教 drf 全局封装 response 的优雅实现 - V2EX
HashV2 · 2022-08-18 · via Django
passerby233

3

passerby233      2022 年 8 月 18 日

1.全局异常
```python
from rest_framework.exceptions import ValidationError
from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
"""
自定义异常,需要在 settings.py 文件中进行全局配置
1.在视图中的 APIView 中使用时,需要在验证数据的时候传入 raise_exception=True 说明需要使用自定义异常
2.ModelViewSet 中非自定义 action 已经使用了 raise_exception=True,所以无需配置
"""
response = exception_handler(exc, context)
if response is not None:
# 字段校验错误处理
if isinstance(exc, ValidationError):
if isinstance(response.data, dict):
# 取错误信息中的一组数据返回
error_data = list(dict(response.data).items())[0]
# 该组数据的 key ,对应模型中的某个字段
error_key = error_data[0]
# 该组数据的 value ,有可能是多个错误校验提示信息,这里只取第一条
error_value = error_data[1][0]
response.data['message'] = f"{error_key}: {error_value}"
for key in dict(response.data).keys():
# 删除多余错误信息
if key != 'message':
response.data.pop(key)
response.data['code'] = 40000
response.data['data'] = None
if isinstance(response.data, list):
response.data = {'code': 40000, 'message': response.data[0], 'data': None}
return response
if 'detail' in response.data:
response.data = {'code': 40000, 'message': response.data.get('detail'), 'data': None}
else:
# 未知错误
response.data = {'code': 40000, 'message': str(response.data), 'data': None}
return response
return response
```
2.自定义 response
```python
from rest_framework.response import Response
from rest_framework import serializers

class JsonResponse(Response):
"""
自定义接口响应数据格式类
1.在视图类中的 APIView 中使用该 JsonResponse 返回响应数据
2.ModelViewSet 、Mixin 下派生的 APIView 类、views.APIView 都需要自己重写并返回 JsonResponse 格式的数据
"""

def __init__(self, data=None, code=None, msg=None,
status=None,
template_name=None, headers=None,
exception=False, content_type=None):
super().__init__(None, status=status)

if isinstance(data, serializers.Serializer):
msg = (
'You passed a Serializer instance as data, but '
'probably meant to pass serialized `.data` or '
'`.error`. representation.'
)
raise AssertionError(msg)
self.data = {'code': code, 'message': msg, 'data': data}
self.template_name = template_name
self.exception = exception
self.content_type = content_type

if headers:
for name, value in headers.items():
self[name] = value
```
ModelViewSet 子类中重写 action 返回值
```python
from utils.drf_utils.custom_json_response import JsonResponse
def create(self, request, *args, **kwargs):
"""
create task
"""
res = super().create(request, *args, **kwargs)
return JsonResponse(data=res.data, msg='success', code=20000, status=status.HTTP_201_CREATED,
headers=res.headers)
```