gpt4 book ai didi

python - 将 html 表单值导入到 python 文件中

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:57 24 4
gpt4 key购买 nike

我有一个用 html5 开发的 python 操作前端,它从中获取必要的输入。我无法将输入传递给 python 代码。我尝试过使用 cgi,但它只是在浏览器上打印我的 python 代码。请帮忙。

我的html代码index.html:

`<body>
<form name="inputs" action="../testProj/testcgipy.py" method="get">
Enter name: <input type="text" name="tbox"> <input type="submit"
value="Submit">
</form>
</body>`

我的Python代码testcgipy.py:

import cgi
form= cgi.FieldStorage()
val= form.getvalue('tbox')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s </h2>" % (val)
print "</body>"
print "</html>"

最佳答案

您最好为您的应用程序使用适当的 HTTP 服务器。 Flask , bottle等等都是很棒的轻量级解决方案。

满足您需求的概念证明:

from bottle import request, route, template, redirect, run

@route('/')
def home():
html = '''
<form method='get' action='/query'>
Enter name: <input name='name'>
<br>
<button>Send</button>
</form>
'''
return template(html)

@route('/query')
def query():
name = request.query['name'] or None
if not name:
return redirect('/')
things = get_all_things(name)

html = '''
% for item in things:
<p>{{item}}</p>
% end
'''
return template(html, things=things)

def get_all_things(name: str):
return [name, 'another thing']


if __name__ == "__main__":
run()

这为您提供了一个可通过 localhost:8080 访问的服务器:
homepage

当您提交表单时:
result page

关于python - 将 html 表单值导入到 python 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56867755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com