首页 > 解决方案 > 如何使用flask从html表单获取测试输入到另一个python脚本?

问题描述

我正在尝试启动并运行一个仅要求 URL 的简单 Web 表单。

这是 HTML 代码 (index.html)

<!DOCTYPE html>
<html>
    <body>
        <form name = 'test' action = "." method = "post">
            <form action="test.php" method="get">
                URL <input type="text" link="link" name = "URL"/>
                <input type="submit" />
        </form>
    </body>
</html>

我正在使用 Flask 运行简单的 Web 应用程序,这是 Flask 代码:(app.py)

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")

def index():
    return render_template('index.html')

@app.route("/", methods = ["POST"])

def get_value():
    url = request.form["URL"]
    return 'The url is ' + url

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

我正在尝试将输入的 URL 获取到另一个 python 脚本,以便我可以用它做一些事情,这是另一个 python 脚本:(url.py)

from app import get_value

print(get_value())

但是,每当我运行 python3 url.py 时,它都会给我这个错误:

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

知道如何打印成功获取 URL 吗?最好有很多细节,因为我对 Flask 很陌生。

标签: pythonhtmlflask

解决方案


发生错误是因为您调用了一个需要来自请求的数据来获取用户输入的函数。您应该调用 url 处理函数,而不是让处理函数调用 url 的检索。

考虑这个答案https://stackoverflow.com/a/11566296/5368402以确保您正确传递 url。现在你有了你的 url,只需将它传递给你的其他脚本。

import url # your url.py module

@app.route("/", methods = ["POST"])

def get_value():
    input_url = request.form["URL"]
    url.handle_url(input_url) #call a function inside url.py
    

推荐阅读