首页 > 解决方案 > 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()

错误信息

标签: pythonhtmlflask

解决方案


您需要使用请求上下文。

RuntimeError:在请求上下文之外工作。

这通常意味着您尝试使用需要活动 HTTP 请求的功能。有关如何避免此问题的信息,请参阅有关测试的文档。

[...]
with app.test_request_context(
        '/url/', data={'format': 'short'}):
    username = app.gfg()[0]
    password = app.gfg()[1]
    TestLogin(username, password)
    [...] 

你可以看看文档


推荐阅读