python - 如何使用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 很陌生。
解决方案
发生错误是因为您调用了一个需要来自请求的数据来获取用户输入的函数。您应该调用 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
推荐阅读
- sql - 使用 VTL Velocity,如何创建 VALUES 数组以在 SQL 语句中使用
- java - 通过 Eclipse 下载和使用 ICS 文件
- arrays - Powershell将数组传递给其他脚本,转向系统hastable?使固定?
- javascript - ajax后的jQuery不运行
- python - 对跨越几年的 pandas DataFrame 重新采样
- r - 如何在 R studio 中循环重复创建 NetCDF 文件中的动态名称?
- ios - 从 CLI 配置 Xcode 项目以支持 Apple 通用版本控制
- html - 如何设置滚动条可见?
- asp.net-mvc - 在 ADFS 身份验证中获取 AD(域详细信息)
- spring - Spring事件可能通知所有范围内的bean吗?