Flask没有从jQuery请求数据中获取任何数据

时间:2012-08-07 05:37:39

标签: jquery python flask

我有一个URL的处理程序,

@app.route("/", methods=['POST'])
@crossdomain(origin='*')
def hello():
    ss=str(request.data)
    print ss
    return ss

处理程序无法检索请求的数据部分。使用jQuery时:

jQuery.ajax(
   {
      type: "POST",
      dataType: "json",
      data:"adasdasd",
      url: 'http://127.0.0.1:5000/',
      complete: function(xhr, statusText)
      {  alert(xhr.responseText) }})

没有返回任何内容

4 个答案:

答案 0 :(得分:19)

有趣的是,事实证明你只能使用request.data如果数据是使用烧瓶无法处理的mimetype发布的,否则它是一个空字符串""我认为,文档不是'非常清楚,我做了一些测试,似乎是这种情况,你可以看一下测试时控制台产生的控制台输出。

  

传入请求数据

     

数据
  包含传入的请求数据作为字符串,以防它带有Flask无法处理的mimetype。

取自http://flask.pocoo.org/docs/api/

但由于我们使用json POST执行标准flask可以很好地处理此问题,因此您可以访问标准request.formss=str(request.form)应该执行的数据我测试过它的技巧。

作为旁注@crossdomain(origin='*'),这似乎很危险,这是我们不允许跨站点ajax请求的原因,但我确定你有理由。

这是我用于测试的完整代码:

from flask import Flask
app = Flask(__name__)

from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper


def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator



@app.route("/", methods=['POST'])
@crossdomain(origin='*')
def hello():
    ss=str(request.form)

    print 'ss: ' + ss + ' request.data: ' + str(request.data)
    return ss


@app.route("/test/")
def t():
    return """
<html><head></head><body>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript'>
jQuery.ajax(
   {
      type: "POST",
      dataType: "json",
      data: "adasdasd",
    url: 'http://127.0.0.1:5000/',
complete: function(xhr, statusText)
      {  alert(xhr.responseText) }})

var oReq = new XMLHttpRequest();
oReq.open("POST", "/", false);
oReq.setRequestHeader("Content-Type", "unknown");
oReq.send('sync call');
alert(oReq.responseXML);
</script></body></html>
"""

if __name__ == '__main__':
    app.run()

输出:

$ python test.py 
 * Running on http://127.0.0.1:5000/
127.0.0.1 - - [07/Aug/2012 02:45:28] "GET /test/ HTTP/1.1" 200 -
ss: ImmutableMultiDict([('adasdasd', u'')]) request.data: 
127.0.0.1 - - [07/Aug/2012 02:45:28] "POST / HTTP/1.1" 200 -
ss: ImmutableMultiDict([]) request.data: sync call
127.0.0.1 - - [07/Aug/2012 02:45:28] "POST / HTTP/1.1" 200 -
127.0.0.1 - - [07/Aug/2012 02:45:29] "GET /favicon.ico HTTP/1.1" 404 -

和我的系统:

$ python --version
Python 2.6.1

$ python -c 'import flask; print flask.__version__;'
0.8

$ uname -a
Darwin 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386

使用谷歌浏览器Version 20.0.1132.57

答案 1 :(得分:5)

我一直在使用类似的功能,在使用了ajax和python之后,这就是我为python读取ajax数据而提出的

JavaScript的:

var data = {
      data: JSON.stringify({
                        "value":'asdf'
                    })
   }
};

$.ajax({
   url:"/",
   type: 'POST',
   data: data,
   success: function(msg){
              alert(msg);
            }
})

Python:

from flask import json
@app.route("/", methods=['POST'])
def get_data():
    data = json.loads(request.form.get('data'))
    ss = data['value']
    return str(ss)

答案 2 :(得分:0)

嗯,我通过request.form收到了AJAX请求。我使用DataTables并将其指定为:

<script type="text/javascript">
$(document).ready( function() {
        $('#mgmtdata').dataTable( {
                "bServerSide": true,
                "sAjaxSource": "{{url_for('.xhr')|safe}}",
                "sServerMethod": "POST",
                "bDeferRender": true,  
                "bFilter": {{ info.filter if info.filter else "false" }},
                "aoColumnDefs": [ {{ info.columndefs|safe if info.columndefs }} ],
        } );
} );

xhr()函数很简单:

@usersview.route('/xhr', methods=["POST"])
def xhr():
    if not 'usersview' in g:   
        g.usersview = UsersDatatableView()
    return g.usersview.render()

usersview是我的Grid()对象的一个​​实例。在这种情况下,它只对它如何获得DataTables发送的ajax数据感兴趣:

def render(self):
    q = self.getQuery()

    # add filtering
    if 'sSearch' in request.form and request.form['sSearch']:
        q = self.applyFilter(q, request.form['sSearch'])

    # add sorting
    if 'iSortingCols' in request.form:
       # and so on

答案 3 :(得分:0)

这对我有用。

在Java语言中:

$.ajax({
  type: 'POST',
  url: "enter your correct url",
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify({title: 'My Title', article: 'My article'}),
  success: function(result){
    console.log(result)
  }
});

在Python中(烧瓶):

 from flask import request
 import json

 @app.route("/", methods=['POST'])
 def home():
   json_data = json.loads(request.data)
   print(json_data)
   return json_data

注意:要点是;

  • JSON.stringify()
  • contentType:“ application / json; charset = utf-8”
  • json.loads
  • request.data