mysterious_guy mysterious_guy - 4 months ago 25
JSON Question

Flask 404 for POST request

I am very new to Flask. Trying to build a flask app which fetches data from the backend neo4j and posts it in JSON format. The eventual aim is to do visualisation using d3.js . But for starters, I want to post it as JSON.

Below is my views.py:

import models
from models import Customer
from flask import Flask, request, session, redirect, url_for, render_template, flash,json,jsonify
import os
app = Flask(__name__)
@app.route('/',methods = ['GET','POST'])
def enter_ID():
if request.method == 'POST':
Galactic_ID = request.form['Galactic_ID']
if Customer(Galactic_ID).find():
return redirect(url_for('Customer_relationships',Galactic_ID=request.form.get('Galactic_ID')))
else:
return "Wrong Galactic_ID"

else:
return render_template('Gal.html')

@app.route('/Customer_relationships/<Galactic_ID>')
def Customer_relationships(Galactic_ID):
data = Customer(Galactic_ID).get_relationships():
return render_template('rel.html',Galactic_ID=Galactic_ID,data =json.dumps(data))



if __name__ == '__main__':
host = os.getenv('IP','0.0.0.0')
port = int(os.getenv('PORT',5000))
app.secret_key = os.urandom(24)
app.run(host=host,port=port)


In views.py , Customer(Galactic_ID).find() and Customer(Galactic_ID).get_relationships() call the functions find(self) and get_relationships(self) under Customer class in models.py :

When I try and run this below are the HTTP Calls:

127.0.0.1 - - [29/Jul/2016 17:54:53] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [29/Jul/2016 17:54:56] "POST / HTTP/1.1" 302 -
127.0.0.1 - - [29/Jul/2016 17:54:56] "GET /Customer_relationships/2000000000084001287 HTTP/1.1" 200 -
127.0.0.1 - - [29/Jul/2016 17:54:56] "POST /Customer_relationships HTTP/1.1" 404 -

Answer

Below is the working solution:

import models
from models import Customer
from flask import Flask, request, session, redirect, url_for, render_template, flash,json,jsonify
import os
app = Flask(__name__)
@app.route('/',methods = ['GET','POST'])
def enter_ID():
    if request.method == 'POST':
        Galactic_ID = request.form['Galactic_ID']
        if Customer(Galactic_ID).find():
            return redirect(url_for('relationships',ID=request.form.get('Galactic_ID')))
        else:
            return "Wrong Galactic_ID"

   else:
       return render_template('Gal.html')
@app.route('/Customer_relationships',defaults={'ID':'Galactic_ID'},methods=['GET','POST'])
@app.route('/Customer_relationships/<ID>',methods=['GET','POST'])
def relationships(ID):
    data = Customer(ID).get_relationships()
    return  render_template('rel.html',data= json.dumps(data))





if __name__ == '__main__':
    host = os.getenv('IP','0.0.0.0')
    port = int(os.getenv('PORT',5000))
    app.secret_key = os.urandom(24)
    app.run(host=host,port=port)