从同一项目中的另一个应用程序调用一个应用程序的基于类的视图

从同一项目中的另一个应用程序调用一个应用程序的基于类的视图

本文介绍了从同一项目中的另一个应用程序调用一个应用程序的基于类的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有基于此类的视图:

class Browse(APIView):
'''
Browse associations

'''
permission_classes = [TokenHasReadWriteScope]

def get(self,request,format=None):
    reply={}
    status=200


    try:
        filter_options={}
        name=request.query_params.get('name','').strip()
        if name:
            filter_options['name__icontains']=name


        associations=Association.objects.filter(**filter_options)values('id','name')
        page=request.query_params.get('page',1)
        paginator=Paginator(associations,20)
        data=paginator.page(page)
    except PageNotAnInteger:
        data=paginator.page(1)
    except EmptyPage:
        data=paginator.page(paginator.num_pages)

    except:
        status=400
        reply['detail']=(_('ErrorProcessingRequest'))

    if status==200:
        reply['associations']=list(data)
        reply['total_num_of_pages']=paginator.num_pages
        reply['total_rows_found']=paginator.count

    return JsonResponse(reply,status=status)

现在,我有另一个面向内部用户的应用程序(不同的登录名和所有用户名),但我仍要列出关联.上面的代码很短,我不介意将其粘贴到那里,只是想知道是否可以通过调用另一个应用程序的views.py中的Browse来避免DRY.

Now I have another app that is oriented towards internal users (different login and all) but I want to list the associations still. The above code is short and i don't mind pasting it there but just wondering if I can avoid DRY by calling the Browse from views.py of another app.

当前,我尝试从应用2中进行尝试:

Currently, I trie this from app 2:

      from app1.views import Browse
      b=Browse()
      #but I cant serialize it as it returns <app1.views.Browse object at 0x0000000006CE0E80> is not JSON serializable

推荐答案

按照以下.我要做的就是:

Solved it following this SO Answer. All I had to do was:

view = Browse.as_view()
return view(request)

这篇关于从同一项目中的另一个应用程序调用一个应用程序的基于类的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 18:48