• Django的RestfulAPI框架RestFramework


    Django的Restful-API框架


    安装框架

    #sudo pip3 install django
    #sudo pip3 install markdown
    #sudo pip3 install djangorestframework 
    

    启动项目

    #django-admin.py startproject MyRestSite
    #cd MyRestSite
    #python manage.py makemigrations
    #python manage.py migrate
    #python manage.py createsuperuser
    

    配置文件settings.py

    # Application definition
    
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
    )
    
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
        ]
    }
    

    编写模型

    models.py

    class TableName(models.Model):
        xxx = xxxx(xxx=xxx)
        class Meta:
            xxxxxxx
    

    模型序列化

    serializers.py

    from rest_framework import serializers
    class TableNameSerializer(serializers.ModelSerializer):
        class Meta:
            model = TableName
            fields = ('xxxx', 'xxxxx', 'xxxx', 'xxxxx')
    

    视图路由

    views.py

    from rest_framework.renderers import JSONRenderer
    from rest_framework import serializers
    class JSONResponse(HttpResponse):
        """
        用于返回JSON数据.
        """
    
        def __init__(self, data, **kwargs):
            content = JSONRenderer().render(data)
            kwargs['content_type'] = 'application/json'
            content='{"xxxxx":'+content+'}'
            super(JSONResponse, self).__init__(content, **kwargs)
    
    @csrf_exempt
    def xxxxxxxxx(request,xxxxxxxxxx):
    
        if request.method == 'GET':
           ...
            return JSONResponse(serializer.data)
    

    路由转发

    urlpatterns = [
        ...
        url(r'^api/x/xxxxx/xxxxx$', xxxxxxxs),
    ]
    

    测试运行

    #python3 ./manage.py runserver
    # curl -H 'Accept: application/json; indent=4' -u username:password http://127.0.0.1:8000/apiurls/
    

  • 相关阅读:
    js人工智能对话框
    html 实现相册
    thinkphp5 三种重定向(跳转)
    thinkphp5 分页实现
    常用的Mysql数据库操作语句大全
    FormData之file图片上传
    FormData对象
    input file 上传图片时限制格式
    form 中Enctype=multipart/form-data 的作用
    thinkphp5 不刷新退出
  • 原文地址:https://www.cnblogs.com/KevinGeorge/p/9102435.html
Copyright © 2020-2023  润新知