我对Flask很新。尝试构建一个烧瓶应用程序,它从后端neo4j获取数据并以JSON格式发布。最终的目标是使用d3.js进行可视化。但对于初学者,我想将其发布为JSON。
以下是我的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)
在views.py中,Customer(Galactic_ID).find()和Customer(Galactic_ID).get_relationships()在models.py中调用Customer类下的函数find(self)和get_relationships(self):
当我尝试运行以下是HTTP呼叫:
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 -
答案 0 :(得分:0)
以下是工作解决方案:
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)
答案 1 :(得分:0)
我遇到了类似的问题,但已通过 flask-cors
模块修复。
首先需要安装在终端$ pip install flask-cors
然后添加到您的应用中:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/", methods=['POST'])
def helloWorld():
return "Hello, cross-origin-world!"