我如何使用python打印输出到html页面? [英] how do i print outputs to html page using python?
问题描述
我希望用户输入一个句子,然后我将这个句子分解成一个列表。我得到了html页面,但我无法将该句子传递给python。
如何正确发送要由python处理的用户输入并将其输出到新的页面?
Python web框架。例如,要使用 bottle
:
break-sentence.py
:
<$
@route('/',method = pre $'$'$'$' ('GET','POST'])
@view('form_template')
def index():
return dict(parts = request.forms.sentence.split(),#分割空白
show_form = request.method =='GET')#show form获取请求
run(host ='localhost',port = 8080)
模板文件 form_template.tpl
用于显示表单和句法部分在Python中处理后(参见上面的 index()
函数):
<!DOCTYPE html>
< title>分解句子< / title>
%if show_form:
< form action =/method =post>
< label for =句子>输入要分解的句子< / label>
< input type =textname =sentence/>
< / form>
%else:
句子部分:< ol>
%部分零件:
< li> {{part}}
%end
< / ol>
%end
request.forms.sentence
在Python中用于访问来自< input name =句子/>
字段的用户输入。
要试用它,您可以下载 bottle.py 并运行:
$ python break-sentence.py
启动Bottle服务器(使用WSGIRefServer())...
听取http:// localhost:8080 /
按Ctrl-C退出。
现在您可以访问 http:// localhost:8080 /
。
I want user to enter a sentence then I break up that sentence into a list. I got the html page down but i have trouble passing that sentence to python.
How do I properly send the user input to be processed by python and output it to a new page?
解决方案 There are many Python web frameworks. For example, to break up a sentence using bottle
:
break-sentence.py
:
#!/usr/bin/env python
from bottle import request, route, run, view
@route('/', method=['GET', 'POST'])
@view('form_template')
def index():
return dict(parts=request.forms.sentence.split(), # split on whitespace
show_form=request.method=='GET') # show form for get requests
run(host='localhost', port=8080)
And the template file form_template.tpl
that is used both to show the form and the sentence parts after processing in Python (see index()
function above):
<!DOCTYPE html>
<title>Break up sentence</title>
%if show_form:
<form action="/" method="post">
<label for="sentence">Input a sentence to break up</label>
<input type="text" name="sentence" />
</form>
%else:
Sentence parts:<ol>
%for part in parts:
<li> {{ part }}
%end
</ol>
%end
request.forms.sentence
is used in Python to access user input from <input name="sentence"/>
field.
To try it you could just download bottle.py and run:
$ python break-sentence.py
Bottle server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
Now you can visit http://localhost:8080/
.
这篇关于我如何使用python打印输出到html页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!