interessante, come si scopre è possibile utilizzare solo request.data
se i dati è stato pubblicato con un mimetype che fiasco non può gestire, altrimenti la sua una stringa vuota ""
Penso che i documenti non fossero molto chiari, ho fatto alcuni test e, a quanto pare, è possibile dare un'occhiata all'output della console che il pallone genera quando si eseguono i miei test.
Incoming richiesta di dati
dati
contiene i dati di richiesta in arrivo come stringa nel caso in cui ne è venuto con un mimetype Flask non gestisce.
tratto da http://flask.pocoo.org/docs/api/
ma dato che stiamo facendo uno standard POST
utilizzando JSON flask
grado di gestire questo abbastanza bene in quanto tale, è possibile accedere ai dati dalla norma request.form
questo ss=str(request.form)
dovrebbe fare il trucco come ho testato.
Come nota a margine @crossdomain(origin='*')
questo sembra pericoloso, esiste un motivo per cui non è consentita la richiesta di cross site ajax, anche se sono sicuro che tu abbia i tuoi motivi.
questo è il codice completo che ho usato per la prova:
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()
uscita:
$ 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 -
e il mio sistema:
$ 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
utilizzando Google Chrome Version 20.0.1132.57
umm Forse qualcosa viene restituito, ma non stanno facendo nulla con esso –
Provate ad usare 'funzione di successo di ajax' e manipolare i dati come necessario anche 'funzione successo (data, textStatus, jqXHR), matrice Una funzione da chiamare se la richiesta ha esito positivo. La funzione ottiene tre argomenti: i dati restituiti dal server, formattati in base al parametro dataType; una stringa che descrive lo stato; e il jqXHR (nell'oggetto jQuery 1.4.x, XMLHttpRequest). A partire da jQuery 1.5, l'impostazione di successo può accettare una serie di funzioni. Ogni funzione sarà chiamata a turno. Questo è un Ajax Event. –
ma lo sto testando con alert (xhr.responseText), non c'è nulla nella rispostaText – Noor