Flask没有从jQuery请求数据中获取任何数据 [英] Flask not getting any data from jQuery request data

查看:308
本文介绍了Flask没有从jQuery请求数据中获取任何数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @ 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/',
完成:function(xhr,statusText)
{alert(xhr.responseText)}})

$ b

解决方案

有趣的是,如果数据被发布,你只能使用 request.data 与一个mimetype烧瓶不能处理,否则它是一个空字符串我认为,文档不是很清楚,我做了一些测试,似乎是在这种情况下,您可以看看在运行我的测试时,瓶子生成的控制台输出。


$ b


传入的请求数据



data

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


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



但是因为我们正在使用json flask 来执行标准的 POST ,所以可以很好地处理这个问题,来自标准 request.form 这个 ss = str(request.form)的数据应该会这样做,

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



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

  from flask import Flask 
app = Flask(__ name__)
$ b $ from datetime import timedelta
从flask进口make_response,request,current_app $ b $ from functools import upda te_wrapper

$ b def crossdomain(origin = None,methods = None,headers = None,
max_age = 21600,attach_to_all = True,
automatic_options = True):
如果方法不是None:
methods =','.join(对于方法中的x进行排序(x.upper()))
如果headers不是None而不是isinstance(headers,basestring ):
headers =','.join(x.upper()for x in header)
if isinstance(origin,basestring):
origin =','.join(origin )
如果isinstance(max_age,timedelta):
max_age = max_age.total_seconds()
$ b def get_methods():
如果方法不是无
返回方法

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

def decorator(f):
def wrapped_function(* args,** kwargs):
如果为automatic_options和request.method =='OPT IONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(* args,** kwargs))
如果不是attach_to_all和request.method! ='OPTIONS':
return resp

h = resp.headers
$ bh ['Access-Control-Allow-Origin'] = origin
h [''如果头文件不是$ b $ ['Access-Control-Allow-Methods'] = get_methods()
h ['Access-Control-Max-Age'] = str(max_age) -Control-Allow-Headers'] =标题
返回resp

f.provide_automatic_options = False
返回update_wrapper(wrapped_function,f)
返回修饰符


$ b $ 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.jstype =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 
*在http上运行://127.0.0.1:5000/
127.0.0.1 - [07 / Aug / 2012 02:45:28]GET / test / HTTP / 1.1200 -
ss:ImmutableMultiDict([ ('adasdasd',u'')])request.data:
127.0.0.1 - - [07 / Aug / 2012 02:45:28]POST / HTTP / 1.1200 -
ss :ImmutableMultiDict([])request.data:sync call
127.0.0.1 - - [07 / Aug / 2012 02:45:28]POST / HTTP / 1.1200 -
127.0.0.1 - - [07 / Aug / 2012 02:45:29]GET /favicon.ico HTTP / 1.1404 -

和我的系统:

  $ 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

使用谷歌浏览器版本在20.0.1132.57


I've a handler for a URL,

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

The handler cannot retrive the data part of the request. When using jQuery:

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

nothing is returned

解决方案

interesting, as it turns out you can only use request.data if the data was posted with a mimetype that flask can't handle, otherwise its an empty string "" I think, the docs weren't very clear, I did some tests and that seems to be the case, you can take a look at the console output the flask generates when you run my tests.

Incoming Request Data

data
  Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

taken from http://flask.pocoo.org/docs/api/

but since we are doing a standard POST using json flask can handle this quite well as such you can access the data from the standard request.form this ss=str(request.form) should do the trick as I've tested it.

As a side note @crossdomain(origin='*') this seems dangerous, theres a reason why we don't allow cross site ajax requests, though Im sure you have your reasons.

this is the complete code I used for testing:

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

output:

$ 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 -

and my system:

$ 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

using google chrome Version 20.0.1132.57

这篇关于Flask没有从jQuery请求数据中获取任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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