2017-06-06 67 views
0

我试图运行一个使用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> 

让我知道,如果我需要增加更多的信息。谢谢!

+0

我看你正试图AJAX方法调用服务器。好,现在停止什么? –

+0

@ raja-simon我从来没有与阿贾克斯合作过,我真的不知道从哪里开始。 –

回答

1

我建议使用抓取它的纯JavaScript来在js中调用url。你可以做的GET调用,比如fetch('/my-link')

fetch('/my-link') 
    .then(function(response) { 
    return response.json() 
    }).then(function(json) { 
    console.log('parsed json', json) 
    }).catch(function(ex) { 
    console.log('parsing failed', ex) 
    }) 

您认为做一些处理和return jsonify(dict)输出/

+0

我应该创建一个处理帖子并获取的特定页面(my_link)吗? –

+0

下面是一个示例:https://tone-analyzer-demo.mybluemix.net –

+0

您已经创建了my-link网址处理程序,并且现在返回点击右键? –