在htmlfi中的PythonAnywhere上运行脚本

2024-04-20 09:13:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Flask框架运行一个python脚本。 主要目标是:

  • 提交数据(关键字)+单击按钮
  • 将关键字放在python脚本上
  • 在服务器上运行它
  • 返回响应
  • 请求结果(Json)
  • 在html页面上打印结果

一些注意事项:

API是来自第三方的请求 我想在html页面中打印的结果只是一个数字。在

API脚本:

import indicoio
indicoio.config.api_key = 'YOUR_API_KEY'

# single example
print.indicoio.sentiment("Keyword")

经过一番研究,我找到了两个解决问题的方法,但我不知道如何实现代码。我是个初学者,请放轻松。在

我的应用程序副本

^{pr2}$

第一种方法:

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>

如果我需要添加更多信息,请告诉我。谢谢!在


Tags: 方法nameimport脚本apijsonappflask
1条回答
网友
1楼 · 发布于 2024-04-20 09:13:39

我建议使用fetch它是纯javascript在js中进行url调用。您可以像fetch('/my-link')那样执行GET调用

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)输出/

相关问题 更多 >