【问题标题】:How to Execute Python Code on Server from an HTML Form Button如何从 HTML 表单按钮在服务器上执行 Python 代码
【发布时间】:2017-07-12 13:19:42
【问题描述】:

我想在用户单击 HTML 表单按钮时执行 python 代码。怎么可能?用户是否可能无法查看服务器上的 python 代码?表单输入将是 Python 代码中的变量。我正在使用 Flask 框架和 python 2.7。安全性还不是问题。

我的 route.py 文件:

from pytube import YouTube
from moviepy.editor import *
import os

app = Flask(__name__)

@app.route("/",methods=['GET','POST'])
def landing():
    return render_template("index.html",ytdir=ytdir,ytlink=ytlink)

if __name__ == "__main__":
    app.run(debug=True)

Template 文件夹中的 index.html:

<form method="POST" action="/">
<input type="text" class="form-control" name="ytdir" placeholder="Example: C:\Downloads">

<h4>The YouTube Video that you want to download</h4>
<textarea class="form-control" rows="3" name="ytlink" placeholder="Example: https://www.youtube.com/watch?v=HipaBLsGB_Y"></textarea>
</form>
<input class="btn btn-primary" type="submit" value="Download">

基本上,我有一个使用ytdirytlink 将YouTube 视频下载到本地驱动器的python 代码。

我应该将python代码放在​​哪里,以便在单击按钮时执行它。

【问题讨论】:

  • 您希望客户端计算机执行 python 脚本?
  • 我希望客户端的计算机向我的服务器提交一个 Post 请求。然后我的服务器获取输入字段并运行 python 脚本。在此示例中,客户端的计算机输入了一个 youtube 链接。然后,我的服务器有一个 python 脚本来下载 youtube 视频。我有一个工作 python 脚本。单击提交按钮后,我只是不知道如何让我的服务器执行此 python 代码。
  • 我理解,这是一个非常常见的使用模式。事实上,Flask 在how to do AJAX with jQuery and Flask 上有一个教程很常见。

标签: python ajax button flask forms http-post


【解决方案1】:

我建议你做一个“api call”

@app.route("/ytdl", methods=["GET"])
def download_video(link):
 # call your download code here 
 # and return the video as an input stream
 # read the flask tutorial on how to do that

在 javascript 中使用 axios 或其他东西使用 jquery 下载文件 喜欢$button.click(() =&gt; axios.get(http://&lt;localhost url&gt;:&lt;port&gt;/ytdl) 去再次阅读文档如何进行ajax调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 2019-07-03
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2016-04-21
    • 2016-03-03
    相关资源
    最近更新 更多