一、动态菜单API的生成
1、API
#菜单信息 url(r‘^menus$‘, views.MenuModelView.as_view({"get": "list", }), name="menus-list"),
2、MenuModelView
from collections import OrderedDictclass MenuModelView(GenericViewSet): authentication_classes = [AuthToken] def list(self,request,*args,**kwargs): ret = {"data": {}, "meta": {"message": "获取菜单成功", "code": 2000}} try: user = request.user menus_dict = InitPermission(request, user).init_menus_dict() od = OrderedDict() if menus_dict: for key in sorted(menus_dict): od[key] = menus_dict[key] ret["data"] = {"menus_list":od.values()} except Exception as e: ret["meta"]["message"] = "获取菜单失败" ret["meta"]["code"] = 2001 return Response(ret)
在restframework框架的认证组件中通过 authentication_classes = [AuthToken]进行认证,获得user,从而传入user,从而初始化菜单数据,然后根据数据库中的positionid可以进行菜单排序。
认证参考:https://www.cnblogs.com/shenjianping/p/11387324.html
初始化菜单参考:https://www.cnblogs.com/shenjianping/p/11448427.html
二、权限API生成
1、API
#前端获取权限,用于按钮级别的权限检验 url(r‘^roles/rights$‘,views.RightsView.as_view({"get": "list"}), name="roles-rights-list"),
2、RightsView
class RightsView(GenericViewSet): def list(self,request,*args,**kwargs): """ 从redis中获取权限相关,用于前台按钮级别权限检验 {‘/crm/dept$‘: [‘get‘], ‘rights/(?P<type>\\w+)$‘: [‘get‘], ‘/crm/menus‘: [‘get‘] :param request: :param args: :param kwargs: :return: """ #从redis中获取permission_dict ret = {"data": {}, "meta": { "message": "获取权限信息成功", "code": 2000}} try: permission_bytes = SessionStore().get_session(settings.PERMISSION_SESSION_KEY) permission_dict = eval(permission_bytes) ret["data"] = permission_dict except Exception as e: ret["meta"]["message"] = "获取权限信息失败" ret["meta"]["code"] = 2001 return Response(ret)
在用户权限初始化后会将其保存在redis中,这里返回的就是在redis中存储的用户权限。