您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将输入从html传递到python并返回

将输入从html传递到python并返回

您是否正在运行像apache setup这样的Web服务器?如果您不这样做,我不确定这是否行得通,所以您可能需要看一下Mamp要使其执行您的python脚本,您还需要编辑该httpd.conf文件

从:

<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>

至:

  <Directory "/var/www/cgi-bin">
  Options +ExecCGI
  AddHandler cgi-script .cgi .py
  Order allow,vdeny
  Allow from all
  </Directory>

如果您只是想在不设置服务器的情况下制作实际的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()

它将yourfile.html在与您的python项目相同的目录中创建一个HTML文档。

我不建议这样做,但是我意识到由于这是一项任务,因此您可能无法选择使用库。如果您愿意的话,一种更优雅的方法是使用像yattag这样的东西,它将使它更易于维护。

从他们的网站复制Hello World示例。

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('h1'):
    text('Hello World!')

print(doc.getvalue())

如果没有本地Web服务器设置,另一种替代方法是将Flask 用作Web服务器。您需要像下面这样构建项目:

    /yourapp  
    basic_example.py  
    /static/  
        /test.css
    /templates/  
        /test.html

蟒蛇:

__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:

<!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(如果要样式化表单?)

p {
    font-family: verdana;
    font-size: 20px;
}
h2 {
    color: navy;
    margin-left: 20px;
    text-align: center;
}

这里根据您的问题做了一个基本的例子, 希望这可以帮助您走上正确的道路,祝您好运。

python 2022/1/1 18:44:01 有291人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶