import os
import sys
import django
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 's2_day33_rbac_01_find_route.settings')
django.setup()
from django.conf import settings
from django.utils.module_loading import import_string
from django.urls import URLResolver, URLPattern
from utils.ext_url import RbacPattern
from importlib import import_module
from api import models
local_route_dict = {
# ("v1", "get"): "威1",
# ("v1", "post"): "威1",
# ("v2", "get"): "威1",
# ("v2", "post"): "威1",
}
root = import_module("s2_day33_rbac_01_find_route.urls")
resolver_list = [(root, None), ]
for resolver, pre_namespace in resolver_list:
patterns = getattr(resolver, "urlpatterns", None) or getattr(resolver, "url_patterns", None)
for item in patterns:
if type(item) == RbacPattern:
view_class = getattr(item.callback, 'view_class', None)
actions = getattr(item.callback, 'actions', None)
if view_class and not actions:
# 继承API定义视图
method_list = [m for m in ['get', 'post', 'put', 'patch', 'delete'] if hasattr(view_class, m)]
# print("API视图", item.name, item.text, method_list)
for m in method_list:
local_route_dict[(item.name, m)] = item.text
continue
if not view_class and actions:
# print("ViewSet视图", item.name, item.text, actions)
for m in actions:
local_route_dict[(item.name, m)] = item.text
continue
if type(item) == URLResolver:
namespace_list = [ele for ele in [pre_namespace, item.namespace] if ele]
total_namespace = ":".join(namespace_list) if namespace_list else None
resolver_list.append((item, total_namespace))
local_route_set = set(local_route_dict)
db_pers = models.Permission.objects.all()
db_pers_dict = {(item.route, item.method): item.name for item in db_pers}
db_pers_set = set(db_pers_dict)
# 新增
models.Permission.objects.bulk_create(
[models.Permission(route=route, method=method, name=local_route_dict[(route, method)]) for route, method in
local_route_set - db_pers_set]
)
# 删除
for route, method in db_pers_set - local_route_set:
models.Permission.objects.filter(route=route, method=method).delete()
# 更新
for group in db_pers_set & local_route_set:
# ("v1", "get")
if db_pers_dict[group] == local_route_dict[group]:
continue
route, method = group
models.Permission.objects.filter(route=route, method=method).update(name=local_route_dict[group])
标签:route,离线,django,item,dict,import,local,method,模板
From: https://www.cnblogs.com/cloud-2-jane/p/18423155