【问题标题】:Python HTML writing form data to a filePython HTML将表单数据写入文件
【发布时间】:2017-08-02 21:10:11
【问题描述】:

尝试编写一个简单的应用程序:

  1. 提供一个 html 表单以获取输入数据(问候语和姓名)。

  2. 在浏览器中显示数据,然后(这里是我想不通的部分)

  3. 将输入表单数据保存到一个简单的 .txt 文件中

这里是python代码:

import web

urls = (
    '/hello', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/', base='layout')


class Index(object):
    def GET(self):
        return render.hello_form() # returns form to browser

    def POST(self): # gets name and greeting data back
        form = web.input(name="Nobody", greet="Hello")
        greeting = "%s ... %s" % (form.greet, form.name)
        return render.index(greeting = greeting) #displays index.html
        with open ('projects/forms/ninja.txt)', 'w') as out_file:
        out_file.write(form.getValue("greet"))
        out_file.write(form.getValue("name"))

if __name__ == "__main__":
    app.run()

这里是hmtl格式:

<h1>this is hello_form</h1>

<form action="/hello" method="POST">
    A Greeting: <br>
    <input type="text" name="greet">
    <br/>
    Your Name: <br>
    <input type="text" name="name">
    <br/>
   <input type="submit">
</form>

我已经搜索过其他答案,包括这个:

how to store html form data into file

但我似乎无法找到进行此操作的信息。

【问题讨论】:

  • return 语句后不能做任何事情。

标签: python html forms input


【解决方案1】:

您正在使用此行对 /hello 执行 POST 请求。

<form action="/hello">

但是,您尚未为此路由定义控制器。结果,什么也没有发生。

要么在 /Index 上发布 POST,要么为 /hello 创建一个处理程序

另外,我强烈推荐一个框架。一些小东西,比如Flask

【讨论】:

  • 同意。有些框架让简单的事情变得更加困难,但 Flask 真的很容易使用。
  • 他们显然已经在使用 web.py 框架,并且同样清楚地将 /hello 路由设置为指向索引处理程序。
猜你喜欢
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 2015-01-21
  • 1970-01-01
  • 2015-03-15
  • 2014-08-14
  • 2015-01-27
相关资源
最近更新 更多