我试图运行一个使用Flask框架的python脚本。 的主要目标是:在Python文件中的PythonAnywhere上运行脚本
- 提交数据(关键字)+点击一个按钮
- 把关键字上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我从来没有与阿贾克斯合作过,我真的不知道从哪里开始。 –