python - Flask - 从 HTML 页面获取输入并将输入传递给另一个 Python 文件中的函数
问题描述
我试图从 html 文件中获取用户输入并将其传递给位于同一目录中另一个 python 文件中的函数。
用户应该在 html 网页中输入他们的用户名和密码,输入将被传递到另一个 python 文件中以运行许多验证功能。
一些帮助或指导将不胜感激:)
谢谢
form.html 文件
<form action="{{ url_for("gfg")}}" method="post">
<label for="username">username:</label>
<input type="text" id="username" name="username" placeholder="username">
<label for="password">password:</label>
<input type="text" id="password" name="password" placeholder="password">
<button type="submit">Login</button>
应用程序.py 文件
# importing Flask and other modules
from flask import Flask, request, render_template
# Flask constructor
app = Flask(__name__)
# A decorator used to tell the application
# which URL is associated function
@app.route('/', methods=["GET", "POST"])
def gfg():
if request.method == "POST":
# getting input with name = fname in HTML form
username = request.form.get("username")
# getting input with name = lname in HTML form
password = request.form.get("password")
return username + password
return render_template("form.html")
if __name__ == '__main__':
app.run()
主 python 文件(函数所在的位置)
def main():
username = app.gfg()[0]
password = app.gfg()[1]
TestLogin(username, password)
if __name__ == "__main__":
main()
解决方案
您需要使用请求上下文。
RuntimeError:在请求上下文之外工作。
这通常意味着您尝试使用需要活动 HTTP 请求的功能。有关如何避免此问题的信息,请参阅有关测试的文档。
[...]
with app.test_request_context(
'/url/', data={'format': 'short'}):
username = app.gfg()[0]
password = app.gfg()[1]
TestLogin(username, password)
[...]
你可以看看文档
推荐阅读
- c++ - 现代 CMake 应该如何添加 SSE 标志?
- docker - 从 docker 映像访问本地主机时出错
- java - 如何编写不带括号的 ArrayList
- r - 在第三列 R 数据框中获取较小的值
- javascript - 传递 PHP 数组以填充多个 ChartJS 图表的有效过程是什么?
- graphql - 在 GraphQL .NET 中,如何指定查询可以采用可选参数?
- angular - 如何使用 SharePointOnline 上的 OData 查询创建每周定期事件?
- networking - 如何从外部网络访问本地计算机上的 Openstack?
- mysql - SELECT n 行 WHERE n-1 行在日期之前存在
- c++ - GetDC ReleaseDC 特定上下文中 CPU 使用率高