如何修改views.py和urls.py以启用Django应用程序的端点?

时间:2019-02-12 19:59:55

标签: python django

在我的Django应用中,我想修改urls.py以便将端点users添加为localhost:8000/users

from rest_framework import routers

# ...

router = routers.DefaultRouter()
router.register(r'users', ???)

urlpatterns = [
    path('admin/', admin.site.urls),    
    path(r'', include(router.urls))
]

但是我不知道如何修改views.py以启用端点。我应该在views.py内创建一个类吗?

from django.http import HttpResponse
import pandas as pd
import datetime
import json

def index(request):
    #...

    response_data = {}
    response_data['prediction'] = y_pred
    response_data['probability'] = round(y_prob,2)
    response_json = json.dumps(response_data)

    return HttpResponse(response_json)

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,并且只想让URL返回一些JSON,则只需按照常规方式更改urls.py

urls.py

from [app-name] import views

urlpatterns = [
    #...,    
    path("users", views.users_endpoint, name='users_endpoint'),
    #...,
]

views.py

# ...
def users_endpoint(request):
    #...

    response_data = {}
    response_data['prediction'] = y_pred
    response_data['probability'] = round(y_prob,2)
    response_json = json.dumps(response_data)

    return HttpResponse(response_json)

因此urls.py中的条目说:

  

当路径为ROOT_URL/users时,从应用程序中的users_endpoint文件调用视图views.py[app-name]