python dynamic_urls_generator

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python dynamic_urls_generator相关的知识,希望对你有一定的参考价值。

from importlib import import_module
from django.apps import apps
from django.urls import path
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView


def get_patterns(app_name, filename):
    app_module = import_module('{}.{}'.format(app_name, filename))
    app_models = apps.get_app_config(app_name).get_models()
    model_names = [model.__name__ for model in app_models]
    patterns = []
    views = []

    for model in model_names:
        for key, value in app_module.__dict__.items():
            if isinstance(value, type):
                if value.__name__.startswith(model):
                    views.append({key: value})
    _views = set()
    for key in views:
        for key, value in key.items():
            for model_name in model_names:
                if value.__name__.startswith(model_name) and\
                            value.__name__ not in _views:
                    if isinstance(value, type):
                        if issubclass(value, ListView):
                            patterns += [path('{}/'.format(
                                model_name.lower()), value.as_view(),
                                name='{}-list'.format(model_name.lower()))]
                        if issubclass(value, DetailView):
                            patterns += [path('{}/<int:pk>/detail/'.format(
                                model_name.lower()), value.as_view(),
                                name='{}-detail'.format(model_name.lower()))]
                        if issubclass(value, CreateView):
                            patterns += [path('{}/create/'.format(
                                model_name.lower()), value.as_view(),
                                name='{}-create'.format(model_name.lower()))]
                        if issubclass(value, UpdateView):
                            patterns += [path('{}/<int:pk>/update/'.format(
                                model_name.lower()), value.as_view(),
                                name='{}-update'.format(model_name.lower()))]
                        if issubclass(value, DeleteView):
                            patterns += [path('{}/<int:pk>/delete/'.format(
                                model_name.lower()), value.as_view(),
                                name='{}-delete'.format(model_name.lower()))]
            _views.add(value.__name__)

    return patterns

# projects is the app name 
# views is the filename with the classbased views of your app 
urlpatterns = get_patterns('projects', 'views')

以上是关于python dynamic_urls_generator的主要内容,如果未能解决你的问题,请参考以下文章

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python

python初识