美文网首页
python+django 设计一个接口返回json

python+django 设计一个接口返回json

作者: 一大碗面丶 | 来源:发表于2018-10-30 12:53 被阅读0次

    废话不多说,今天介绍一个用来写json接口的第三方库djangorestframework
    下载地址:http://www.django-rest-framework.org
    终端指令安装:

    pip install djangorestframework
    

    修改settings.py文件

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        "tcapp",
        'rest_framework_swagger',//新增
        'rest_framework',//新增
    ]
    

    数据库里的模型转json
    python3.5自带json包 import json即可
    也可以用模型序列化django-simple-serializer这个库来做Model->Json
    终端指令:

    pip install django-simple-serializer
    

    接下来开始写一个返回json的接口
    在项目中,打开views.py文件。

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from rest_framework.views import APIView
    from dss.Serializer import serializer
    from django.http import HttpResponse, HttpRequest
    from tcapp.models import itemsPost
    
    # Create your views here.
    
    def response_as_json(data, foreign_penetrate=False):
        jsonString = serializer(data=data, output_type="json", foreign=foreign_penetrate)
        response = HttpResponse(
                # json.dumps(dataa, cls=MyEncoder),
                jsonString,
                content_type="application/json",
        )
        response["Access-Control-Allow-Origin"] = "*"
        return response
    
    def json_response(data, code=200, foreign_penetrate=False, **kwargs):
        data = {
            "code": code,
            "msg": "成功",
            "data": data,
        }
        return response_as_json(data, foreign_penetrate=foreign_penetrate)
    
    def json_error(error_string="", code=500, **kwargs):
        data = {
            "code": code,
            "msg": error_string,
            "data": {}
        }
        data.update(kwargs)
        return response_as_json(data)
    
    JsonResponse = json_response
    JsonError = json_error
    class ReturnJson(APIView):
    
        def get(self, request, *args, **kwargs):
            return JsonResponse(itemsPost.objects.all())
    

    逻辑写好, 在urls.py中添加此接口

    from django.conf.urls import url
    from django.contrib import admin
    from tcapp.views import ReturnJson
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^api', ReturnJson.as_view()),
    ]
    

    运行项目
    游览器中输入

    http://127.0.0.1:8000/api
    

    游览器中会返回数据库模型转换的json数据

    报错:ImportError: No module named rest_framework_swagger
    解决:缺少插件,指令安装:

    sudo pip install django-rest-swagger
    

    感觉对你有帮助,点下订阅再走哦!

    相关文章

      网友评论

          本文标题:python+django 设计一个接口返回json

          本文链接:https://www.haomeiwen.com/subject/ytxgtqtx.html