<commit_before>import json

from functools import update_wrapper
from admino.utils import import_from_string
from admino.views import ChangeListRetrieveAPIView

from django import http
from django.conf import settings
from django.contrib.admin import AdminSite, ModelAdmin
from django.contrib.admin.options import IncorrectLookupParameters
from django.conf.urls import url, include
from django.core.serializers.json import DjangoJSONEncoder
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from .constants import HTTP_METHOD_VIEWS


class AdminoMixin(ModelAdmin):

    http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']

    def get_api_urls(self):

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            wrapper.model_admin = self
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            url(r'^$',
                wrap(self.admin_site.admin_view(self.dispatch)),
                name='%s_%s_api_list' % info),
            url(r'^(?P<pk>[-\d]+)/$',
                wrap(self.admin_site.admin_view(self.dispatch)),
                name='%s_%s_api_detail' % info),
        ]
        return urlpatterns

    def api_urls(self):
        return self.get_api_urls()
    api_urls = property(api_urls)

    def _allowed_methods(self):
        return [m.upper() for m in self.http_method_names if hasattr(self, "api_" + m)]

    def http_method_not_allowed(self, request, *args, **kwargs):
        if settings.DEBUG and self._allowed_methods():
            raise Exception("Only" + str(self._allowed_methods()))
        return http.HttpResponseNotAllowed(self._allowed_methods())

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        if not request.method.lower() in self.http_method_names:
            return self.http_method_not_allowed(request, *args, **kwargs)

        handler = self.http_method_not_allowed
        if request.method.lower() == "get":
            handler = getattr(self, "api_get", self.http_method_not_allowed)

        api_view_name = HTTP_METHOD_VIEWS.get(request.method.lower())
        if api_view_name:
            handler = getattr(self, "api_" + api_view_name, self.http_method_not_allowed)

        return handler(request, *args, **kwargs)

    def api_get(self, request, *args, **kwargs):
        if kwargs.get("pk"):
            return self.api_detail(request, *args, **kwargs)
        else:
            return self.api_list(request, *args, **kwargs)

    def get_admin_cl(self, request):
        ChangeList = self.get_changelist(request)
        try:
            cl = ChangeList(request, self.model, self.list_display,
                self.list_display_links, self.list_filter, self.date_hierarchy,
                self.search_fields, self.list_select_related, self.list_per_page,
                self.list_max_show_all, self.list_editable, self)
            return cl

        except IncorrectLookupParameters:
            raise Exception("IncorrectLookupParameters")

    def obj_as_dict(self, request, obj):
        bundle = dict()
        model_fields = self.model._meta.get_fields()

        field_names = [f.name for f in model_fields]
        readonly_fields = self.get_readonly_fields(request, obj)
        field_names.extend(readonly_fields)
        field_names.extend(self.list_display)

        for field in model_fields:
            if field.rel and field.rel.many_to_many:
                data = []
                rel_model = field.rel.model
                f_val = getattr(obj, field.name)
                rel_field_names = [f.name for f in rel_model._meta.get_fields() if not f.is_relation]
                print rel_field_names
                for m in f_val.all():
                    d = dict()
                    for f_name in rel_field_names:
                        d[f_name] = getattr(m, f_name)
                    data.append(d)
                bundle[field.name] = data
                field_names.remove(field.name)

        for field in field_names:
            if hasattr(obj, field):<commit_msg>added todo comment added for obj_as_dict, print clean<commit_after>import json

from functools import update_wrapper
from admino.utils import import_from_string
from admino.views import ChangeListRetrieveAPIView

from django import http
from django.conf import settings
from django.contrib.admin import AdminSite, ModelAdmin
from django.contrib.admin.options import IncorrectLookupParameters
from django.conf.urls import url, include
from django.core.serializers.json import DjangoJSONEncoder
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from .constants import HTTP_METHOD_VIEWS


class AdminoMixin(ModelAdmin):

    http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']

    def get_api_urls(self):

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            wrapper.model_admin = self
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            url(r'^$',
                wrap(self.admin_site.admin_view(self.dispatch)),
                name='%s_%s_api_list' % info),
            url(r'^(?P<pk>[-\d]+)/$',
                wrap(self.admin_site.admin_view(self.dispatch)),
                name='%s_%s_api_detail' % info),
        ]
        return urlpatterns

    def api_urls(self):
        return self.get_api_urls()
    api_urls = property(api_urls)

    def _allowed_methods(self):
        return [m.upper() for m in self.http_method_names if hasattr(self, "api_" + m)]

    def http_method_not_allowed(self, request, *args, **kwargs):
        if settings.DEBUG and self._allowed_methods():
            raise Exception("Only" + str(self._allowed_methods()))
        return http.HttpResponseNotAllowed(self._allowed_methods())

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        if not request.method.lower() in self.http_method_names:
            return self.http_method_not_allowed(request, *args, **kwargs)

        handler = self.http_method_not_allowed
        if request.method.lower() == "get":
            handler = getattr(self, "api_get", self.http_method_not_allowed)

        api_view_name = HTTP_METHOD_VIEWS.get(request.method.lower())
        if api_view_name:
            handler = getattr(self, "api_" + api_view_name, self.http_method_not_allowed)

        return handler(request, *args, **kwargs)

    def api_get(self, request, *args, **kwargs):
        if kwargs.get("pk"):
            return self.api_detail(request, *args, **kwargs)
        else:
            return self.api_list(request, *args, **kwargs)

    def get_admin_cl(self, request):
        ChangeList = self.get_changelist(request)
        try:
            cl = ChangeList(request, self.model, self.list_display,
                self.list_display_links, self.list_filter, self.date_hierarchy,
                self.search_fields, self.list_select_related, self.list_per_page,
                self.list_max_show_all, self.list_editable, self)
            return cl

        except IncorrectLookupParameters:
            raise Exception("IncorrectLookupParameters")

    def obj_as_dict(self, request, obj):
        # todo implement a serializer class
        bundle = dict()
        model_fields = self.model._meta.get_fields()

        field_names = [f.name for f in model_fields]
        readonly_fields = self.get_readonly_fields(request, obj)
        field_names.extend(readonly_fields)
        field_names.extend(self.list_display)

        for field in model_fields:
            if field.rel and field.rel.many_to_many:
                data = []
                rel_model = field.rel.model
                f_val = getattr(obj, field.name)
                rel_field_names = [f.name for f in rel_model._meta.get_fields() if not f.is_relation]
                for m in f_val.all():
                    d = dict()
                    for f_name in rel_field_names:
                        d[f_name] = getattr(m, f_name)
                    data.append(d)
                bundle[field.name] = data
                field_names.remove(field.name)

        for field in field_names:
            if hasattr(obj, field):
{'fraction_non_alphanumeric': 0.09800741427247452, 'fraction_numerical': 0.0, 'mean_word_length': 2.5265522875816995, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2680728', 'n_tokens_mistral': 2573, 'n_tokens_neox': 2503, 'n_words': 555}