我有以下python脚本:
from flask import Flask, render_template, json, request
from flask import Flask, request, abort, jsonify
from flaskext.mysql import MySQL
import MySQLdb
app = Flask(__name__)
@app.route("/")
def main():
return render_template('testFirst.html')
@app.route("/form_submit/", methods=['POST'])
print ("outside function")
def connect():
import json
dtb = request.select['value'] #i want the selected drop down value to be set here which will be used to connect to the database
db = MySQLdb.connect("localhost","root","",dtb)
cursor = db.cursor()
cursor.execute("SELECT * FROM REPORT_SUITE")
results = cursor.fetchall()
json_return_value =[]
for result in results:
table_data = {'REPORTSUITE_ID' : result[0], 'REPORTSUITE_NAME' : result[1], 'STAGING_DATABASE' : result[2], 'DWH_DATABASE' : result[3], 'TRANS_TABLE' : result[4]}
json_return_value.append(table_data)
print ("hi")
print json.dumps(json_return_value)
return json.dumps(json_return_value)
connect()
if __name__ == "__main__":
app.run(debug = True)
它呈现以下html文件: $(文件)。就绪(函数(){ $( “按钮”)。点击(函数(){ $就({ url:“/ form_submit /”, data:$('#databases')。val(), 类型:'POST', 成功:警惕(“亲爱的伯爵”) }); }); });
<body>
<select id ="databases">
<option value = "">--Select From following--</option>
<option value = "OMTSL_QBO">OMTSL_QBO</option>
<option value = "OMTSL_SBG">OMTSL_SBG</option>
<option value = "OMTSL_PTX">OMTSL_PTX</option>
</select>
<br><br>
<button type = "button"> Click Me!!</button>
<div id ="placeholder"></div>
</body>
</html>
HTML表单应该通过ajax调用调用python脚本,方法是将选定的值从下拉列表传递给connect()方法。
当我运行main.py时,我收到以下错误
Traceback (most recent call last):
File "main.py", line 31, in <module>
connect()
File "main.py", line 16, in connect
dtb = request.select['value']
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Library/Python/2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
我不知道如何将下拉值传递给被调用的python fucntion。我试图寻找它,但我仍然没有找到方法 做到这一点。请帮我完成这个
答案 0 :(得分:0)
你不应该有一个单独的“Python脚本”。它应该是Flask应用程序中的另一个处理程序,带有一个Ajax脚本调用的路径。
答案 1 :(得分:0)
Ajax使用HTTP,因此您无法直接调用python脚本(除非您专门构建了以这种方式工作的设置)。
你的ajax应该是这样的:
$(document).ready(function(){ $("button").click(function(){ $.ajax({ url : "/form_submit/", data : $('#databases').val(), type : 'POST', //success : alert("Hi "+ $('#databases').val()) success : alert("Hi dear count ") }); }); });
然后有一个用@app.router('/form_submit/')
装饰的Flask函数,然后根据Flask教程处理表单数据。
答案 2 :(得分:0)
在你的第二个代码中,你是使用POST从ajax发送呼叫,而在你的Flask代码中你有
@app.route("/form_submit/", methods=['GET'])
将此行更改为:
@app.route("/form_submit/", methods=['GET', 'POST'])