使用Appengine对python进行解码 [英] Decoding JSON with python using Appengine

查看:84
本文介绍了使用Appengine对python进行解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码从一个简单的3输入表单中检索值:

  //从表单中检索数据
var $ form = $(this),
prgname = $ form.find('input [name =prg]')。val(),
startDate = $(#startdate ).datepicker({dateFormat:'yy-mm-dd'})。val(),
endDate = $(#enddate)。datepicker({dateFormat:'yy-mm-dd'}) .VAL();

以下代码将请求发送到服务器:

  var request = $ .ajax({
url:/ prg /,
type:post,
data:JSON .stringify({prg:prgname,start:startDate,end:endDate}),
contentType:'application / json',
dataType:'json',
success:function(){ },
error:function(jqXHR,textStatus,errorThrown){};

服务器端使用python和webapp2我做了以下,(这里是我不确定的事情)

  import json 

class PrgHandler(webapp2.RequestHandler):
def post(self):
prg = cgi.escape(self.request.POST ['prg'])
start_date = cgi.escape(self.request.POST ['start'])
end_date = cgi.escape(self.request.POST ['end'])

#some code to write to db这里
....
#if成功返回成功messa ge
如果成功:
success_msg = [{'class':'success','msg':'成功保存到数据库'}]
else:
success_msg = [ {'class':'error','msg':'无法保存到数据库'}]

data_string = json.dumps(success_msg)
self.response.headers.add_header ('content-type','application / json',charset ='utf-8')
self.response.write(data_string)

当我得到响应时,它会跳过成功函数并直接进入错误。



记录错误值im没有任何意义:

 错误是:
文本状态是:错误
jqXHR是:[object object]

Chrome的控制台给我的错误:

 将资源解释为Document,但使用MIME类型application / json传输:

我查了一下,SO上的解决方案无效,我认为这是服务器端代码的错误:

  self.response.headers.add_header('content-type','application / json',charset ='utf-8')

如果我注释掉上面的代码,我在chrome中没有发现任何错误,我只是在空白页面上返回响应以下格式的正确值:

  [{msg:成功保存到数据库,class: success}] 

在上面的例子中,它保存到数据库中,所以我似乎无法找到

编辑
这个错误看起来是来自于服务器端我已经删除了以下行:
event.preventDefault();



从我的脚本中,它至少导致所有问题,至少我得到一个清晰的指示哪里pr会徽是。这是由于错误地获取发布的数据,我如何以正确的方式做到这一点?我试过以下内容:

  json_data = self.request.GET.items()
decode = json.loads( json_data)

但是我得到一个TypeError:期望的字符串或缓冲区在下面一行:
json_data = self.request.GET.items()

解决方案

好吧,我设法弄清楚了这一点,并认为我会发布回答这对我帮助寻找这些信息的人很有帮助,因为webapp2文档对于'获取'发布的json数据没有什么帮助。

在客户端上的

我做了以下内容:

  var request = $ .ajax({
url:/ some / url / ,
type:POST,
data:JSON.stringify([{someval:val1,someval2:val2,someval3:val3}]),
contentType:application / json,
dataType:'json',
beforeSend:function(){
$('#loading-div')。show();
},
complete:函数(){
$(#装载-DIV)隐藏();
},
success:function(response,textStatus,jqXHR){}
});

我之所以无法找出问题的原因是因为我删除了以下行一些注释掉的行阻止页面在发布后重定向。这是所有奇怪的,无关的和无用的错误消息的来源:

  event.preventDefault(); 

在服务器端获取将json数据发布到appengine中,执行以下操作:

  jdata = json.loads(cgi.escape(self.request.body))
用于jdata中的vals:
val1 = vals ['someval']
val2 = vals ['someval2']
val3 = vals ['someval3']

以上是问题的根源,我没有做到这一点,如果客户端没有上一行,就没有办法弄清楚。



无论如何,一旦你有数据做你需要做的任何处理,一旦你完成,并需要发回一个JSON响应添加以下行:

  //数据看起来像这样
data = {'return_value':val1,'return_value2':val2,
'return_value3 ':val3,'return_value4':val4}

return_data = json.dumps(data)
self.response.headers.add_h eader('content-type','application / json',charset ='utf-8')
self.response.write(return_data)

几乎忘记了在客户端再次访问使用jquery从服务器发送回来的变量,它非常简单...执行如下操作:

  success:function(response,textStatus,jqXHR){
console.log(response.return_value);
console.log(response.return_value2);
console.log(response.return_value3);
}

希望这可以帮助有人寻找这些信息。


I have the following code which retrieves values from a simple 3 input form:

//retrieves data from a form
var $form = $( this ),
    prgname= $form.find('input[name="prg"]').val(),
    startDate = $("#startdate").datepicker({ dateFormat: 'yy-mm-dd' }).val(),
    endDate = $("#enddate").datepicker({ dateFormat: 'yy-mm-dd' }).val();

The following code sends the request to the server:

var request = $.ajax({
      url: "/prg/",
      type: "post",
  data: JSON.stringify({prg:  prgname, start:startDate, end:endDate}),
  contentType: 'application/json',
  dataType: 'json',
      success: function() {},
      error: function (jqXHR, textStatus, errorThrown){};

on the server end using python and webapp2 Im doing the following, (here is where I am unsure of things)

import json

class PrgHandler(webapp2.RequestHandler):
    def post(self):
        prg= cgi.escape(self.request.POST['prg'])
        start_date = cgi.escape(self.request.POST['start'])
        end_date = cgi.escape(self.request.POST['end'])

        #some code to write to db here
        ....
        #if successful return a success message
        if success:
            success_msg = [{'class': 'success', 'msg': 'Successfully saved to the database'}]
        else:
            success_msg = [{'class': 'error', 'msg': 'Could not saved to the database'}]

        data_string = json.dumps(success_msg)
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')   
        self.response.write(data_string)

When I get the response it is skipping the success function and going directly to the error.

Logging the error values im not getting any thing meaningful:

the error is:
The text status is:error
The jqXHR is:[object Object] 

Chrome's console is giving me the error:

Resource interpreted as Document but transferred with MIME type application/json:

I looked that up and the solutions on SO did not work, I think this is an error with the server side code:

self.response.headers.add_header('content-type', 'application/json', charset='utf-8')

If I comment out the above line I get no error in chrome and I just get back the response on a blank page with the correct values in the following format:

[{"msg": "Successfully saved to the database", "class": "success"}]

In the above case it does save to the database so I cannot seem to find anything wrong except for the header and simply don't know how to proceed!

EDIT The error it seems is from the server side I had removed the following line: event.preventDefault();

from my script and it caused all the problems now at least Im getting a clear indication of where the problem is. It's from incorrectly getting the posted data, how would I do it the correct way? I tried the following:

json_data = self.request.GET.items()
decoded = json.loads(json_data)

but Im getting a TypeError: expected string or buffer on the following line: json_data = self.request.GET.items()

解决方案

OK so I managed to figure this out and thought I will post the answer that worked for me to help anyone looking for this information because the webapp2 docs are not that helpful when it comes to 'getting' posted json data.

on the client side I did the following:

var request = $.ajax({
    url: "/some/url/",
    type: "POST",
    data: JSON.stringify([{someval: val1, someval2:val2, someval3:val3}]),
    contentType: "application/json",
    dataType: 'json',
    beforeSend: function() {
        $('#loading-div').show();
    },
    complete: function(){
        $('#loading-div').hide();
    },
    success: function(response, textStatus, jqXHR){}
});

The reason I couldnt figure out the problem straight away was because of the following line which I deleted along with some commented out line which prevented the page from redirecting after posting. This was the source of all the weird, unrelated and unhelpful error messages:

event.preventDefault();

on the server side to get the json data being posted to appengine do the following:

jdata = json.loads(cgi.escape(self.request.body))
    for vals in jdata:
        val1 = vals['someval']
        val2 = vals['someval2']
        val3 = vals['someval3']

The above was the root of the problem I wasn't doing it right and without the previous line on the client side there was no way to figure it out.

Anyways once you have the data do whatever processing you need to do with it and once you are done and need to send back a json response add the following lines:

//the data would look something like this 
data = {'return_value': val1, 'return_value2': val2,
        'return_value3': val3, 'return_value4': val4}

        return_data = json.dumps(data)
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.write(return_data)

Almost forgot on the client side again to access the variables sent back from the server with jquery its very straight forward...do something like:

 success: function(response, textStatus, jqXHR){
        console.log(response.return_value);
        console.log(response.return_value2);
        console.log(response.return_value3);
 }

Hope this will help someone seeking this information.

这篇关于使用Appengine对python进行解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆