创建项目
$ django-admin startproject server
运行项目
$ cd server
$ python manage.py runserver
创建一个模块
$ python manage.py startapp api
设置控制器
api/views.py:
import json
from django.http import HttpResponse, JsonResponse
def main(request):
return HttpResponse('hello world.')
def cat(request):
return JsonResponse({'message': 'cat.'})
def dog(request):
return HttpResponse(json.dumps({'message': "dog."}), content_type='application/json')
配置api模块的路由(Urls)
api/urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.main, name='main'),
path('cat', views.cat, name='cat'),
path('dog', views.dog, name='dog')
]
将api控制器导入主模块中
server/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
]
启动服务器后访问: http://127.0.0.1:8000/api
http://127.0.0.1:8000/api/cat
http://127.0.0.1:8000/api/dog