我是python Web开发的新手,正在使用流行的框架烧瓶版本1.0.3。我想知道是否可以在用户输入时以html形式(使用python 3.7.2版)捕获用户输入,例如使用google搜索表单或spotify搜索栏。
我一直在研究此主题,并且遇到过javascript解决方案,但不幸的是,我对javascript不熟悉。我还遇到了像键盘和msvcrt这样的python模块(仅Windows的python模块),它们在终端中都可以正常工作,但是当在flask的render_template函数中作为关键字arg返回并使用jinja2将该函数传递给oninput属性时在这种形式的情况下,键盘模块不起作用,msvcrt仅在捕获用户输入(有时会键入)时起作用。
#code in app.py
from flask
import Flask, request, render_template
import msvcrt
app = Flask(__name__)
app.secret_key = "nate"
@app.route('/input')
def render_input():
def func():
x = []
while True:
kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
if '\\r' in kp or '\\n' in kp:
print(x)
break
else :
print(kp)
x.append(kp)
continue
return render_template("input.html", func = func)
if __name__ == "__main__":
app.run(debug = True)
<form action="/results" method="post">
<input type="search" name="search" id="search" oninput="{{ func() }}" autocomplete="off">
<button>Submit</button>
</form>
当我在终端中运行python app.py并导航到127.0.0.1:5000/input并开始输入时,有时输入会打印到终端上,而其他时候当我重新加载页面时,我必须按Enter在终端中完成页面加载。我在这里缺少什么吗?我要问的是只能在python中做吗?非常感谢您的帮助。
答案 0 :(得分:0)
使用Javascript,如果不熟悉^^,则早晚需要使用它。
JS是您唯一的解决方案,因为您想捕获浏览器中与UI的使用交互,并且浏览器不了解python,因此,一旦呈现了模板,js便是依赖的模板。
对于您的情况,JS将允许您监听事件(键入内容),检索键入的内容,通过ajax调用将其发送到flask应用程序,flask将发挥其魔力并将结果发送回页面。(我认为那毕竟是你想要的)