我們使用Django構建web-app後端,爲Ember應用程序提供RESTful API。Django REST框架 - 多個模型/ API?
所以(進化上)我們開始下面的簡單結構:
project root
|
|-app1/models.py .... no views.py
|
|-app2/models.py .... no views.py
|
|-app3/models.py .... no views.py
|
\- restapi - provides REST API for app*: huge views.py, huge serializers.py, huge test.py
這是很容易使用,尤其是與DRF的可瀏覽視圖:
@api_view(['GET'])
def api_root(request, format=None):
return Response(
{
'users': reverse('current-user-detail', request=request),
'interfacesettings': reverse('interface-settings', request=request),
............................................................
'preferences': reverse('preferences', request=request),
}
)
不久,我們已經有足夠的模型/ API讓我們的restapi.app方式過於複雜和混亂,我們開始考慮使用更合理的東西:
project root
|
|-app1/models.py .... views.py, serializers.py, tests.py
|
|-app2/models.py .... views.py, serializers.py, tests.py
|
|-app3/models.py .... views.py, serializers.py, tests.py
|
\- we do not need rest api anymore (but where will we put our api_root?)
另一方面,我們現在所有複雜的測試(涉及少數模型)在一個方便的地方。我們重複使用了序列化器的功能。我們有一個api_root。所以可能我們可能有這樣的事情:
project root
|
|-app1/models.py .... views.py (app1 API), serializers.py, tests.py
|
|-app2/models.py .... views.py (app2 API), serializers.py, tests.py
|
|-app3/models.py .... views.py (app3 API), serializers.py, tests.py
|
\- restapi - views.py (api_root), tests.py for complicated tests and serializers.py for common functions
哪種方法更好?這裏常見的最佳實踐是什麼? 有沒有我們可以看一看的開放項目?