Django REST framework函数使用

  1. request

# request 使用
# 1
request.POST  # 只能处理表单(form)数据,只能处理“POST”方法.
 - a = request.POST.get('a', 0) 获取提交表单的a的数据
 - 客户端:curl -X POST  -d "a=11" -d "b=12"  http://127.0.0.1:8000/report/post_an_apple   
 - 客户端:-d (or --data) sends the Content-Type application/x-www-form-urlencoded
 - 客户端:调试信息
Request Headers
Content-Type: application/x-www-form-urlencoded
Content-Length: 3
Request Body
  a: "a"



# 2
request.body  # 处理任意数据.可以处理'POST', 'PUT' 和 'PATCH'方法.
 - res = json.loads(request.body.decode()) 获取提交的数据
 - 客户端:curl --header "Content-Type: application/json" --request POST --data "{\"a\":\"xyz\",\"b\":\"xyz\"}" http://127.0.0.1:8000/report/post_an_apple
 - 客户端:-d (or --data) sends the Content-Type application/x-www-form-urlencoded, 所以需要--header "Content-Type: application/json"
 - 客户端: -request POST is optional if you use -d, as the -d flag implies a POST request.
 - 客户端:调试信息
Request Headers
Content-Type: application/json
Request Body
    {
        "a": 1234,
        "b": 2222
    }
  1. post模板【application/x-www-form-urlencoded】
from django.http import HttpResponse
import json


def post_an_apple(request):
    if request.method == 'POST':
        dic = {}
        # 判断是否传参
        if request.POST:
            a = request.POST.get('a', 0)
            b = request.POST.get('b', 0)
            # 判断参数中是否含有a和b
            if a and b:
                res = add_args(a, b)
                dic['number'] = res
                dic = json.dumps(dic)
                return HttpResponse(dic)
            else:
                return HttpResponse('输入错误')
        else:
            return HttpResponse('输入为空')

    else:
        return HttpResponse('方法错误')


# 测试数据
import requests

res = requests.post('http://127.0.0.1:8000/report/post_an_apple', data={'a': 3, 'b': 4})
print(res.text)
  1. post模板【application/json】
def post_an_apple(request):
    if request.method == 'POST':
        # print(request.body)
        if isinstance(request.body, str):
            try:
                req_dic = json.loads(request.body, encoding='utf-8')
                print(req_dic)
            except ValueError:
                return HttpResponse('格式错误')
            return HttpResponse('OK')
        else:
            return HttpResponse('格式错误')



# 测试数据
import requests

headers = {
    'Content-Type': 'application/json',
}

data = '{"a":"xyz","b":"xyz"}'

response = requests.post('http://127.0.0.1:8000/report/post_an_apple', headers=headers, data=data)
print(response.text)
  1. ListCreateAPIView


# 1 settings.py
INSTALLED_APPS = [
'rest_framework'
]

# 2 urls.py
url(r'^publisher_list2/', views.reportInfoListView.as_view()),


# 3 views.py
from rest_framework.generics import ListCreateAPIView
from rest_framework import serializers


class ReportInfoSerializer(serializers.ModelSerializer):
    """
    测试报告详情序列化
    """
    def to_representation(self, instance):
        """
        将更新时间变成天
        :param instance:
        :return:
        """
        ret = super(ReportInfoSerializer, self).to_representation(instance)
        # ret["case_date"] = ret["case_date"].split("T")[0]
        return ret

    # 不能省略
    class Meta:
        model = models.Publisher
        fields = ("name", "addr", )


class reportInfoListView(ListCreateAPIView):
    """
    测试报告统计信息
    """
    def get_queryset(self):
        queryset = models.Publisher.objects.all().order_by("id")
        return queryset

    serializer_class = ReportInfoSerializer



# 4 html
# a
   <script>

    function update_info()
    {
        var form_data = $("#form_data");
        update_data_ajax(form_data, '/publisher_list2')
    }

    function update_data_ajax(id, url) {
        {#var data = $(id).serializeJSON();#}
        var data = $(id).serialize();
        $.ajax({
            type: 'post',
            url: url,
            data: JSON.stringify(data),
            contentType: "application/json",
            success: function (data) {
                if (data !== 'ok') {
                    alert(data);
                }
                else {
                    window.location.reload();
                }
            },
            error: function () {
                alert('Sorry请重试!');
            }
        });
    }

    </script>


# b
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">新增</button>

# c
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    模态框(Modal)标题
                </h4>
            </div>
            <form id="form_data">
            <div class="modal-body">
                <textarea v-model="input_text" name="mytextarea"  cols="70" rows="10" placeholder="输入……"></textarea><br><br>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
                <button type="button" onclick="update_info()" class="btn btn-primary">
                    提交更改
                </button>
            </div>
            </form>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

posted @ 2020-12-06 10:47  该显示昵称已被使用了  阅读(98)  评论(0编辑  收藏  举报