-
命名:
项目/文件/函数 -> 小写+下划线
类 -> 驼峰 -
pycharm运行不起来
-
简单逻辑先处理
ret = {"code": 1000} try: user = request.data.get('user') pwd = request.data.get('pwd') user = Account.objects.filter(username=user, password=pwd).first() if not user: ret['code'] = 1001 ret['error'] = '用户名或密码错误' return Response(ret) uid = str(uuid.uuid4()) UserAuthToken.objects.update_or_create(user=user, defaults={'token': uid}) ret['token'] = uid except Exception as e: ret['code'] = 1003 return Response(ret)
-
特殊异常捕获
-
封装响应对象
class BaseResponse(object): def __init__(self): self.code = 1000 self.data = None self.error = None @property def dict(self): return self.__dict__
-
简单接口时,可以使用rest framework封装好的功能
class CourseViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin,GenericViewSet): queryset = models.Course.objects.all() serializer_class = CourseViewSetSerializers
-
接口如何编写?
业务:
返回所有:http://127.0.0.1:8088/api/v1/course/1/ 多个接口: http://127.0.0.1:8088/api/v1/course/1/ http://127.0.0.1:8088/api/v1/section/?course=1 http://127.0.0.1:8088/api/v1/chapter/?course=1
-
django查询
class AgreeView(ViewSetMixin, APIView): def post(self, request, *args, **kwargs): """ 点赞 :param request: :param args: :param kwargs: :return: """ ret = {'code': 1000, 'data': None} try: pk = kwargs.get('pk') # 方式一:更新赞数 obj = Article.objects.filter(id=pk).first() obj.agree_num = obj.agree_num + 1 obj.save() # 方式二:更新赞数 # F,更新数据库字段 # Q, 构造复杂条件 # from django.db.models import F,Q # v = Article.objects.filter(id=pk).update(agree_num=F("agree_num") + 1) # print(v) ret['data'] = obj.agree_num except Exception as e: ret['code'] = 1001 ret['error'] = '点赞失败' return Response(ret)
python笔记(写接口程序基本规范)
猜你喜欢
转载自blog.csdn.net/qq_41433183/article/details/89303582
今日推荐
周排行