python 程序接口_python笔记(写接口程序基本规范)

命名:

项目/文件/函数 -> 小写+下划线

类 -> 驼峰

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值