Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java POST请求在Django Tastypie上创建资源,但得到500个错误代码_Java_Django_Json_Rest_Tastypie - Fatal编程技术网

使用Java POST请求在Django Tastypie上创建资源,但得到500个错误代码

使用Java POST请求在Django Tastypie上创建资源,但得到500个错误代码,java,django,json,rest,tastypie,Java,Django,Json,Rest,Tastypie,我试图用Java客户机向django tastypie API发布一个新资源,但得到一个Http 500错误代码。 基本上,我只是试图从客户端对我的api进行新的预订 型号: class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() def __unicode__(self): return self.name class

我试图用Java客户机向django tastypie API发布一个新资源,但得到一个Http 500错误代码。 基本上,我只是试图从客户端对我的api进行新的预订

型号:

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __unicode__(self):
        return self.name

class Product(models.Model):
    author = models.ForeignKey(Author)

    name = models.CharField(max_length=100)
    genre = models.CharField(max_length=100)
    pub_date = models.DateTimeField()

class Reservation(models.Model):
    user = models.ForeignKey(User)
    product = models.ForeignKey(Product)

    reserv_date_start = models.DateTimeField()
    reserv_finish = models.DateTimeField()
    penalty = models.BooleanField()

    def __unicode__(self):
        return self.product.name
资源:

class AuthorResource(ModelResource):
    #user = fields.ForeignKey(UserResource, 'user')
    class Meta:
        queryset = Author.objects.all()
        resource_name = 'author'
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

class ProductResource(ModelResource):
    author = fields.ForeignKey(AuthorResource, 'author')
    class Meta:
        queryset = Product.objects.all()
        resource_name = 'product'
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

class ReservationResource(ModelResource):
    product = fields.ForeignKey(ProductResource, 'product')
    class Meta:
        queryset = Reservation.objects.all()
        resource_name = 'reservation'
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
我发布的json(我使用的是java simple json,我得到了反斜杠,我不知道如何去掉它):


}


我的客户发送代码:

public void apacheHttpClientPost(String url, String user, char[] pass, JSONObject data) {
     try {

    DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(user, new String(pass)));
    HttpPost postRequest = new HttpPost(url);
    StringEntity input = new StringEntity(data.toJSONString());
    input.setContentType("application/json");
    postRequest.setEntity(input);

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 201) {
        throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatusLine().getStatusCode());
    }

    BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();

  } catch (MalformedURLException e) {

    e.printStackTrace();

  } catch (IOException e) {

    e.printStackTrace();

  }

}
调试错误之一:

/usr/local/lib/python2.7/dist-packages/django/db/models/fields/init.py:808: RuntimeWarning:DateTimeField接收到原始日期时间(2013-01-04 17:31:57),时区支持处于活动状态。运行时警告)

我正在发邮件到

"http://localhost:8000/api/reservation/reservation/"


JSON中的日期时间缺少时区部分:

json: {
    "product": "\/api\/reservation\/product\/9\/",
    "id": "6",
    "reserv_finish": "2013-01-04T17:31:57",                 // <-- Here
    "resource_uri": "\/api\/reservation\/reservation\/6\/",
    "penalty": false,
    "reserv_date_start": "2013-01-04T17:31:57"              // <-- And here
}
另外,您安装了哪个
python-dateutil
版本?请检查一下这个好吗

pip freeze | grep dateutil
其他值得一看的东西:
  • 在Tastypie文档中
  • 在Django文档中

    • 明白了。问题在于我的json不完整。我没有添加用户资源的外键。以下是解决方案:

      json:

      资源:

      class ReservationResource(ModelResource):
          user = fields.ForeignKey(UserResource, 'user')
          product = fields.ForeignKey(ProductResource, 'product')
          class Meta:
              queryset = Reservation.objects.all()
              resource_name = 'reservation'
              authentication = BasicAuthentication()
              authorization = DjangoAuthorization()
      
      java客户端代码:

      public JSONObject encodeJsonObject(Reservation reservation){
          JSONObject obj=new JSONObject();
          obj.put("id",String.valueOf(reservation.getId()));  
          obj.put("product","/api/reservation/product/"+reservation.getProduct().getId()+"/");      
          obj.put("reserv_date_start",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+00:00'").format(reservation.getReserv_date_start()));
          obj.put("reserv_finish",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+00:00'").format(reservation.getReserv_finish()));        
          obj.put("resource_uri", "/api/reservation/reservation/"+reservation.getId()+"/");
          obj.put("user", "/api/reservation/auth/user/1/"); //not dynamic yet
          obj.put("penalty",reservation.isPenalty());
          return obj;
      }
      

      我对dateutil执行了您的命令,并得到“警告:无法找到distribute==0.6.24dev-r0 python dateutil==1.5的svn位置”。现在,我将尝试您建议的更改。我会让您知道它是否有效。我用您的想法更改了上面的代码,但我仍然收到500个错误。我的新json已编辑。即使有反斜杠,URL也可以吗?我不认为反斜杠可以,但错误消息显然与日期时间有关。添加
      +00:00
      部分后,您是否会收到相同的错误消息?我希望您认识到,在生产代码中,最后一部分应该是实际时区,例如
      -03:00
      ,如果您在巴西..刚刚尝试了一篇大致相同的帖子(使用
      curl
      )另外,似乎额外的斜杠在解析时没有问题。
      pip freeze | grep dateutil
      
      {
          "product": "\/api\/reservation\/product\/12\/",
          "id": "7",
          "reserv_finish": "2013-01-06T15:26:15+00:00",
          "resource_uri": "\/api\/reservation\/reservation\/7\/",
          "penalty": false,
          "reserv_date_start": "2013-01-06T15:26:15+00:00",
          "user": "\/api\/reservation\/auth\/user\/1\/"
      }
      
      class ReservationResource(ModelResource):
          user = fields.ForeignKey(UserResource, 'user')
          product = fields.ForeignKey(ProductResource, 'product')
          class Meta:
              queryset = Reservation.objects.all()
              resource_name = 'reservation'
              authentication = BasicAuthentication()
              authorization = DjangoAuthorization()
      
      public JSONObject encodeJsonObject(Reservation reservation){
          JSONObject obj=new JSONObject();
          obj.put("id",String.valueOf(reservation.getId()));  
          obj.put("product","/api/reservation/product/"+reservation.getProduct().getId()+"/");      
          obj.put("reserv_date_start",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+00:00'").format(reservation.getReserv_date_start()));
          obj.put("reserv_finish",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+00:00'").format(reservation.getReserv_finish()));        
          obj.put("resource_uri", "/api/reservation/reservation/"+reservation.getId()+"/");
          obj.put("user", "/api/reservation/auth/user/1/"); //not dynamic yet
          obj.put("penalty",reservation.isPenalty());
          return obj;
      }