【发布时间】:2017-11-07 08:11:40
【问题描述】:
我正在尝试使用 Flask 框架运行 python 脚本。 主要目标是:
- 提交数据(关键字)+点击按钮
- 将关键字放在python脚本上
- 在服务器上运行
- 返回响应
- 请求结果(Json)
- 在html页面上打印结果
一些注意事项:
脚本是来自第三方 API 的请求 我想在 html 页面中打印的结果只是一个数字。
API 脚本:
import indicoio
indicoio.config.api_key = 'YOUR_API_KEY'
# single example
print.indicoio.sentiment("Keyword")
经过一些研究,我找到了 2 个解决我的问题的方法,但我不知道如何实现代码。我是初学者,请放轻松。
我的 App.py
from flask import Flask
app = Flask(__name__, static_url_path="/static", static_folder='/home/dubspher/mysite/static')
@app.route('/')
def static_file():
return app.send_static_file('index.html')
if __name__ == "__main__":
app.run()
第一种方法:
pip install requests
import requests
data = {"keyword":"LoremIpsum"}
r = requests.put("Request_Page_Link/",data = data )
data = r.json
print("data")
第二种方法:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/my-link/')
def my_link():
print 'I got clicked!'
return 'Click.'
if __name__ == '__main__':
app.run(debug=True)
处理 POST 和 GET 请求的代码:
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){
$.ajax({
type:'get',
url:<YOUR SERVERSIDE PAGE URL>,
cache:false,
data:<if any arguments>,
async:asynchronous,
dataType:json, //if you want json
success: function(data) {
<put your custom validation here using the response from data structure >
},
error: function(request, status, error) {
<put your custom code here to handle the call failure>
}
});
});
</script>
如果我需要添加更多信息,请告诉我。谢谢!
【问题讨论】:
-
我看到您正在尝试使用 ajax 方法来调用服务器。好的,现在停止什么?
-
@raja-simon 我从未使用过 ajax,而且我真的不知道从哪里开始。
标签: javascript python ajax web-applications flask