Cómo obtener un objeto JSON en Python (Flask Framework). A continuación se muestra mi fragmento de código `
var hotel=$( "#listHotel option:selected" ).val(); if(hotel!="select") { $.ajax({ url: '/getHotels', data: {'hotel':hotel}, type: 'POST', success: function(response){ alert(response); var r= JSON.parse(response); var rating =r.message $("#rate").html("Ratings : "+rating); $("#rate").show('slow'); console.log(response); }, error: function(error){ alert(response); console.log(error); } }); }`
¿Cómo puedo obtener el hotel
valor JSON en mi Flask Framework
Python script?
from flask import Flask, render_template, json, request app = Flask(__name__) @app.route('/') def main(): return render_template('index.html') @app.route('/getHotels',methods=['POST','GET']) def getHotels(): try: _hotel=request.POST['hotel'] print _hotel
Este es mi código en Python
En su javascript, transforme los datos a JSON y establezca contentType
en "application/json"
:
data: JSON.stringify({'hotel':hotel}), contentType : "application/json",
En su función de flask obtenga el JSON usando request.json
:
@app.route('/getHotels') def getHotels(): hotel = request.json['hotel'] .....