将输入从 html 传递到 python 并返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43677564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing input from html to python and back
提问by RnRoger
I need to make a webpage for an assignment, it doesn't have to be uploaded to the web, I am just using a local .html file. I did some reading up and came up with the following html and python:
我需要为作业制作一个网页,它不必上传到网络,我只是使用本地 .html 文件。我做了一些阅读并想出了以下 html 和 python:
<!DOCTYPE html>
<html>
<head>
<title>
CV - Rogier
</title>
</head
<body>
<h3>
Study
</h3>
<p>
At my study we learn Python.<br>
This is a sall example:<br>
<form action="/cgi-bin/cvpython.py" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</p>
</body>
</html>
Python:
Python:
import cgi
import cgitb #found this but isn't used?
form = cgi.FieldStorage()
first_name = form.getvalue('first_name').capitalize()
last_name = form.getvalue('last_name').capitalize()
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2>Your name is {}. {} {}</h2>".format(last_name, first_name, last_name))
print ("</body>")
print ("</html>")
However this just gives the prints as text and not as a proper html file with the 1 line that I want.
然而,这只是将打印作为文本而不是作为我想要的 1 行的正确 html 文件。
采纳答案by Kai
Do you have a web server like apache setup this is running on?
If you don't I'm not sure this will work so you may want to have a look at MampTo allow it to execute your python script you will also need to edit the httpd.conf
file
你有一个像 apache setup 这样的 web 服务器正在运行吗?如果你不这样做,我不确定这会起作用,所以你可能想看看Mamp要让它执行你的 python 脚本,你还需要编辑httpd.conf
文件
From:
从:
<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>
To:
到:
<Directory "/var/www/cgi-bin">
Options +ExecCGI
AddHandler cgi-script .cgi .py
Order allow,vdeny
Allow from all
</Directory>
Alternatively
或者
If you simply want to make an actual HTML file without setting up a server a very basic but crude way of doing this would be to simply write everything to a HTML file you create like:
如果你只是想在不设置服务器的情况下制作一个实际的 HTML 文件,一个非常基本但粗略的方法是简单地将所有内容写入你创建的 HTML 文件,如下所示:
fo.write("Content-type:text/html\r\n\r\n")
fo.write("<html>")
fo.write("<head>")
fo.write("<title>Hello - Second CGI Program</title>")
fo.write("</head>")
fo.write("<body>")
fo.write("<h2>Your name is {}. {} {}</h2>".format("last_name", "first_name", "last_name"))
fo.write("</body>")
fo.write("</html>")
fo.close()
Which will create a HTML document called yourfile.html
in the same directory as your python project.
这将yourfile.html
在与您的 python 项目相同的目录中创建一个 HTML 文档。
I don't recommend doing this, but I realise since it's an assignment you may not have the choice to use libraries. In case you, are a more elegant way would be to use something like yattagwhich will make it much more maintainable.
我不建议这样做,但我意识到因为这是一项任务,您可能无法选择使用库。万一你,更优雅的方法是使用像yattag这样的东西,这将使它更易于维护。
To copy the Hello World example from their website.
从他们的网站复制 Hello World 示例。
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('h1'):
text('Hello world!')
print(doc.getvalue())
Update:
更新:
Another alternative if you don't have a local web server setup is to use Flaskas your web server. You'll need to structure your project like:
如果您没有本地 Web 服务器设置,另一种选择是使用Flask作为您的 Web 服务器。你需要像这样构建你的项目:
/yourapp
basic_example.py
/static/
/test.css
/templates/
/test.html
Python:
Python:
__author__ = 'kai'
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test.html')
@app.route('/hello', methods=['POST'])
def hello():
first_name = request.form['first_name']
last_name = request.form['last_name']
return 'Hello %s %s have fun learning python <br/> <a href="/">Back Home</a>' % (first_name, last_name)
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 3000)
HTML:
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="static/test.css">
<title>
CV - Rogier
</title>
</head>
<body>
<h3>
Study
</h3>
<p>
At my study we learn Python.<br>
This is a sall example:<br>
<form action="/hello" method="post">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" name= "form" value="Submit" />
</form>
</p>
</body>
</html>
CSS (If you want to style your form?)
CSS(如果您想设置表单样式?)
p {
font-family: verdana;
font-size: 20px;
}
h2 {
color: navy;
margin-left: 20px;
text-align: center;
}
Made a basic example based on your question hereHopefully this helps get you on the right track, good luck.
在这里根据您的问题制作了一个基本示例 希望这有助于您走上正轨,祝您好运。
回答by Nani Chintha
Change the below in apache/conf/httpd.conf file:
在 apache/conf/httpd.conf 文件中更改以下内容:
<Directory "C:/xampp/cgi-bin">
AllowOverride All
Options None
Require all granted
</Directory>
To:
到:
<Directory "C:/xampp/cgi-bin">
Options ExecCGI
AddHandler cgi-script .cgi .py
Order allow,deny
Allow from all
</Directory>
otherwise run html form also using python script:(No need to change above http.conf file)
否则也使用 python 脚本运行 html 表单:(无需更改上面的 http.conf 文件)
#!C:\Users\DELL\AppData\Local\Programs\Python\Python36\Python.exe
print("Content-type:text/html \r\n\r\n")
print('<html>')
print('<body>')
print('<form action="/cgi-bin/hello_get.py">')
print('First Name:<input type = "text" name = "first_name"><br/>')
print('Last Name:<input type = "text" name = "last_name" />')
print('<input type = "submit" value = "submit">')
print('</form>')
print('</body>')
print('</html>')`
回答by Tamás Novák
I'm new to both HTML and Python, but as far as I know HTML doesn't have to be indented. This means that you can pass a lot of HTML code in one python print. You can actually print a whole HTML code in one line.
我是 HTML 和 Python 的新手,但据我所知,HTML 不必缩进。这意味着您可以在一次 Python 打印中传递大量 HTML 代码。您实际上可以在一行中打印整个 HTML 代码。
I'm printing lists into html tables with for loops. The HTML code is not nice, but it's working. I guess you only need them to be temporary, as I do.
我正在使用 for 循环将列表打印到 html 表中。HTML 代码不是很好,但它可以工作。 我想你只需要它们是暂时的,就像我一样。
Cheers!
干杯!
回答by Lalit Thaware
firstly check browser url like that it looks like file:///C:/xampp/htdocs/cgi_python/form.html
首先检查浏览器网址,它看起来像 file:///C:/xampp/htdocs/cgi_python/form.html
that means your code is correct and no error but output show as a python script code because "code work in console not in browser"
这意味着您的代码是正确的,没有错误,但输出显示为 python 脚本代码,因为“代码在控制台中工作而不是在浏览器中工作”
i.e mean you directly open a file in htdocs folder and click filename.html and execute then output from in text format For open a browser
即意味着您直接在 htdocs 文件夹中打开一个文件并单击 filename.html 并执行然后以文本格式输出 For open a browser
Solution is
解决方案是
- open browser type in url
- localhost/filepath eg. http://localhost/cgi_python/form.htmlthen get the answer
- 打开浏览器输入网址
- 本地主机/文件路径例如。http://localhost/cgi_python/form.html然后得到答案