2012-08-07 13 views
12

Ho un gestore per un URL,Flask non ottenere tutti i dati provenienti da dati di richiesta jQuery

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

Il conduttore non può retrive la parte di dati della richiesta. Quando si utilizzano jQuery:

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

nulla viene restituito

+0

umm Forse qualcosa viene restituito, ma non stanno facendo nulla con esso –

+0

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. –

+0

ma lo sto testando con alert (xhr.responseText), non c'è nulla nella rispostaText – Noor

risposta

18

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

4

Ho lavorato con funzionalità simili e dopo un po 'di fare in giro con l'Ajax e pitone, questo è ciò che mi è venuta in pitone lettura dei dati 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) 
0

Hmm, ricevo richieste AJAX tramite request.form.Sto usando DataTables e specificare in questo modo: la funzione

<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 }} ], 
     }); 
}); 

L'XHR() è semplice:

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

usersview è un'istanza dell'oggetto mia griglia(). In questo caso, interessa solo su come ottenere di ai dati ajax che DataTable inviati con:

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 
Problemi correlati