不要将此请求http保存在Django的数据库中

时间:2018-11-14 23:24:29

标签: django database python-3.x http

客户: 我在Django上发帖

import requests
payload = {'datax':['12', '15'], 'datay':['22', '23'], 'timestamp':['1', '2'], 'data':['20', '19'], 'timestamp1':['1', '2'], 'mission':['Mission01', 'Mission01']}
r = requests.post("http://127.0.0.1:8000", data=payload)

服务器(Django):我从客户端收到http帖子,并将数据保存在数据库中。 这是我的模特 home / models.py

from django.db import models

class Mission(models.Model):
    name = models.CharField(max_length=250)
    description = models.CharField(max_length=1000)
    type = models.CharField(max_length=500)
    date = models.DateField()

    def __str__(self):
        return self.name + '-' + self.description

class SensorLog (models.Model):
    mission = models.ForeignKey(Mission, on_delete=models.CASCADE)
    data = models.CharField(max_length=50)
    timestamp = models.CharField(max_length=50)

class PositionLog(models.Model):
    mission = models.ForeignKey(Mission, on_delete=models.CASCADE)
    datax = models.CharField(max_length=50)
    datay = models.CharField(max_length=50)
    timestamp = models.CharField(max_length=50)

这是我的看法 home / view.py

from django.shortcuts import render
from django.http import Http404, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Mission, SensorLog, PositionLog

@csrf_exempt
def home(request):
    if request.method == 'POST':
        data = request.POST.getlist('datax')
        datass = request.POST.getlist('datay')
        timestampss = request.POST.getlist('timestamp')
        datas = request.POST.getlist('data')
        timestamps = request.POST.getlist('timestamp1')
        missions = request.POST.getlist('mission')
        for i in range(len(data)):
            mission = Mission.objects.get(name=missions[i])
            post1 = PositionLog.objects.create(datax=data[i], datay=datass[i], timestamp=timestampss[i], mission=mission)
            post = SensorLog.objects.create(data=datas[i], timestamp=timestamps[i], mission=mission)
    return HttpResponse()

def index(request):
    all_mission = Mission.objects.all()
    context = {'all_mission': all_mission}
    return render(request, 'mission/index.html', context)

def detail(request, mission_id):
    try:
        mission = Mission.objects.get(pk=mission_id)
    except Mission.DoesNotExist:
        raise Http404("Mission dose not exist")
    return render(request, 'mission/detail.html', {'mission': mission})

我的urls.py

from django.contrib import admin
from django.urls import path, include
from home import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name ='home'),
    path('mission/', include('home.urls'))
]

这是我在home / urls.py

中的网址中
from django.conf.urls import url
from . import views

urlpatterns = [

    #/mission/
    url(r'^$', views.index, name='index'),

    #/mission/712/
    url(r'(?P<mission_id>[0-9]+)/$', views.detail, name='detail'),
]

我收到了我的http帖子,但没有保存数据。我有(“ POST / HTTP / 1.1” 200 0) 为什么不保存数据?我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

这里的问题是您要传递值列表作为requests.post()的有效负载,但是不应以常规格式编码的帖子请求以这种方式传递多个值。数据到达视图时,方括号不会转换为列表。

如果希望保持相同的数据结构,则需要通过指定json参数来切换为以JSON格式发送有效载荷:

r = requests.post("http://127.0.0.1:8000", json=payload)  # Use json 

在您看来,您需要加载JSON有效负载,并使用常规get()检索每个列表:

import json

@csrf_exempt
def home(request):
    if request.method == 'POST':
        # Load the JSON payload
        payload = json.loads(request.body)

        # Retrieve the lists
        data = payload.get('datax')
        datass = payload.get('datay')
        timestampss = payload.get('timestamp')
        datas = payload.get('data')
        timestamps = payload.get('timestamp1')
        missions = payload.get('mission')
        ...