美文网首页
Django POST

Django POST

作者: Yating_Yang | 来源:发表于2017-04-23 14:04 被阅读1183次

    第一步

    在case中的views.py中添加下面的函数来实现HTTP POST 请求。目的是提供一个HTTP POST Request的接口来向数据库中插入新的数据。

    def post_case(request):
        if request.method == 'POST':
            print 'we are in POST request'
    
            received_json_data = json.loads(request.body)
            print received_json_data
    
            name1 = received_json_data['name']
            result1 = received_json_data['result']
    
            case_one = case(name=name1, result=result1)
            case_one.save()
            return HttpResponse(json.dumps(received_json_data), content_type="application/json")
    
        else:
            return HttpResponse('It is not a POST request!!!')
    

    第二步

    修改case文件夹下面的urls.py, 添加最后一行。

    from django.conf.urls import url
    from . import views
    
    urlpatterns = [
        url(r'get_case', views.get_case, name='get_case'),
        url(r'post_case', views.post_case, name='post_case'),
    ]
    

    第三步

    如果出现POST 请求出错403文件,请修改settings.py文件中的内容,注释‘django.middleware.csrf.CsrfViewMiddleware', CSRF是跨站点请求伪造。
    [02/Dec/2016 03:05:28] "POST /case/post_case HTTP/1.1" 403 2629

    MIDDLEWARE_CLASSES = (    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',    #'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',    'django.middleware.security.SecurityMiddleware',)
    

    第四步

    在mysite文件夹内,创建一个python文件send_requests.py,内容如下。调用python的request来发送post request。运行该文件,在Pycharm中点击运行。
    也可以利用一下其他工具来发HTTP POST请求,比如Jmeter等。

    import json
    import requests
    
    if __name__=="__main__":
        url = 'http://127.0.0.1:8080/case/post_case'
        case_new = {'name':'live2','result':'PASS'}
        r = requests.post(url, data=json.dumps(case_new))
    

    相关文章

      网友评论

          本文标题:Django POST

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