1.安装rest_framework
pip install djangorestframework
2.配置rest_framework
## 将rest_framework加入项目app列表 INSTALLED_APPS = [ ‘rest_framework‘, ] ## 其他配置 # ======rest api====== REST_FRAMEWORK = { # Use Django‘s standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. # 自定义异常处理方法 ‘EXCEPTION_HANDLER‘: ‘api_core.exception.api_exception_handler‘, # ‘EXCEPTION_HANDLER‘: ‘tennis_api.exception.api_exception_handler‘, # 全局权限控制 ‘DEFAULT_PERMISSION_CLASSES‘: [ # ‘rest_framework.permissions.DjangoObjectPermissions‘ # ‘api_core.permission.AppApiPermission‘, ‘rest_framework.permissions.AllowAny‘, # ‘tennis_api.permission.AppApiPermission‘ ], # 授权处理 ‘DEFAULT_AUTHENTICATION_CLASSES‘: ( ‘rest_framework.authentication.SessionAuthentication‘, ‘rest_framework.authentication.BasicAuthentication‘, # ‘rest_framework.authentication.TokenAuthentication‘, ‘api_core.authentication.ExpiringTokenAuthentication‘, # ‘tennis_api.authentication.ExpiringTokenAuthentication‘, ), # 全局级别的过滤组件,查找组件,排序组件 ‘DEFAULT_FILTER_BACKENDS‘: (‘rest_framework.filters.SearchFilter‘, ‘rest_framework.filters.DjangoFilterBackend‘, ‘rest_framework.filters.OrderingFilter‘,), # 分页每页大小 ‘PAGE_SIZE‘: 5, ‘DEFAULT_PARSER_CLASSES‘: ( ‘rest_framework.parsers.JSONParser‘, ‘rest_framework.parsers.FormParser‘, ), ‘DEFAULT_RENDERER_CLASSES‘: ( ‘rest_framework.renderers.JSONRenderer‘, ‘rest_framework.renderers.BrowsableAPIRenderer‘, ) }
3.urls.py配置
urlpatterns = [ # 接口浏览登录 url(r‘^api-auth/‘, include(‘rest_framework.urls‘, namespace=‘rest_framework‘)), ]
4.应用
## 引入rest_framework装饰器 from rest_framework.decorators import api_view @csrf_exempt @require_customer_login @api_view(["GET", "POST", "REQUEST"]) def user_address_list(request): """ 获取用户地址列表 请求参数: { # 要求用户登录 } 返回数据:{ "code": code, # 业务状态:1为成功0为失败 "data": { "address_list": [ { "id", "is_default", # 是否默认地址 "customer_name", # 客户名称 "phone_no", # 手机号 "province__province_name", # 省份名称 "province_id", # 省份ID "city__city_name", # 城市名 "city_id", # 城市ID "district__district_name", # 县乡名 district_id", # 县乡ID "address" # 用户地址信息 }], for_select: False # 是否下单中 }, "message": "" } """ curr_customer = get_current_customer() if curr_customer is None: return {"code": constants.RESULT_NOT_LOGIN, "message": u"您还未登陆"} # 地址 customer_address = CustomerAddress.objects.filter(customer_id=curr_customer.id, available=True, deleted=False).values("id", "is_default", "customer_name", "phone_no", "province__province_name", "province_id", "city__city_name", "city_id", "district__district_name", "district_id", "address") address_list = [] if customer_address: address_list = list(customer_address) data_dict = {‘address_list‘: address_list, "for_select": False} if emall_constants.SESSION_VSHOP_ADD_ORDER_INFO in request.session: data_dict[‘for_select‘] = True return Response({"code": constants.RESULT_SUCCESS, "data": data_dict, "message": ""})
原文地址:https://www.cnblogs.com/konglingxi/p/9435723.html
时间: 2024-10-03 23:03:55