时间:2020-11-20 17:36:34 | 栏目:Python代码 | 点击:次
步骤
根据之前的文章已经搭建好 Django的目录
开始流程
运行 manage.py 文件
# 创建一个app startapp ulb_manager settings.py 文件中 设置 INSTALLED_APPS = [ # 加入这句话 'apps.ulb_manager', ] MIDDLEWARE_CLASSES = [ # 关闭掉跨域的一些验证,注释掉下面这句话 # 'django.middleware.csrf.CsrfViewMiddleware', ]
urls.py 文件中 注册接口
from django.conf.urls import url from django.contrib import admin from apps.ulb_manager.views import apis urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api', apis), ]
编写接口返回
在 ulb_manager 目录下 的 views.py 文件 编写代码
# Create your views here. from apps.message.models import UserMessage def apis(request): if request.method == "POST": name = request.POST.get("name", "") all_messages = UserMessage.objects.filter(name=name) else: # 例子 name = request.GET.get("name", "") all_messages = UserMessage.objects.all() resultList = [] for message in all_messages: resultList += [{ "username": message.name, "address": message.address, }] # 返回值 response = JsonResponse(resultList, safe=False) # response.status_code = 500 自定义响应码 return response