【问题标题】:Run a script on PythonAnywhere within a html file在 html 文件中的 PythonAnywhere 上运行脚本
【发布时间】: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


【解决方案1】:

我建议使用 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)输出/

【讨论】:

  • 我应该创建一个特定页面(my_link)来处理帖子和获取吗?
  • 您已经创建了 my-link url 处理程序并且现在返回单击右键?
  • 我所做的只是使用flask部署一个静态html,我已经学习python 1周了:(
  • 哦,太好了。所以你必须知道如何创建网站(包括模板和静态和渲染视图)
  • 您现在的具体问题是什么?
猜你喜欢
  • 2021-01-07
  • 2014-05-16
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2020-11-11
相关资源
最近更新 更多