【问题标题】:Create Resource on Django Tastypie with a Java POST request but getting 500 error code使用 Java POST 请求在 Django Tastypie 上创建资源但收到 500 错误代码
【发布时间】:2012-12-19 04:29:18
【问题描述】:

我正在尝试使用 Java 客户端将新资源发布到 django sweetpie 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 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("penalty",reservation.isPenalty());
    return obj;
}

json: {
"product": "\/api\/reservation\/product\/12\/",
"id": "7",
"reserv_finish": "2013-01-05T23:11:51+00:00",
"resource_uri": "\/api\/reservation\/reservation\/7\/",
"penalty": false,
"reserv_date_start": "2013-01-05T23:11:51+00:00"

}


我的客户发布代码:

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/”

【问题讨论】:

    标签: java django json rest tastypie


    【解决方案1】:

    您的 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
    }
    

    ISO-8601 日期时间应如下所示:

    "2013-01-04T17:31:57+00:00"
                        ^^^^^^^
    

    另外,您安装了哪个python-dateutil 版本?你能检查一下吗?

    pip freeze | grep dateutil
    

    其他值得一看的东西:

    【讨论】:

    • 我为 date util 执行了您的命令并得到“警告:找不到用于分发的 svn 位置==0.6.24dev-r0 python-dateutil==1.5”。现在将尝试您建议的更改。如果可行,会通知您
    • 用您的想法更改了我上面的代码,但我仍然收到 500 错误。我的新 json 已编辑。即使有反斜杠,网址也可以吗?
    • 我不认为反斜杠可以,但错误消息显然与日期时间有关。添加 +00:00 部分后,您是否收到相同的错误消息?
    • 我希望你意识到在生产代码中最后一部分应该是实际的时区,例如-03:00如果你在巴西..
    • 刚刚尝试了一个大致相同的 POST(使用curl),似乎解析出多余的斜线没有问题。
    【解决方案2】:

    知道了。问题出在我的 json 不完整。我有一个未添加的用户资源外键。这是解决方案:

    json:

    {
        "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()
    

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多