【问题标题】:Flask, html and javascript desktop appFlask、html 和 javascript 桌面应用程序
【发布时间】:2012-07-12 11:12:28
【问题描述】:

我想使用 python、html 和 javascript 构建一个桌面应用程序。到目前为止,我已经按照烧瓶上的 tuts 并有一个 hello world 工作示例。我现在应该怎么做才能让它工作? html 文件如何与它们下面的 python 脚本“对话”?

这是我目前的代码:

from flask import Flask, url_for, render_template, redirect
app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

@app.route('/')
def index():
    return redirect(url_for('init'))

@app.route('/init/')
def init():
    css = url_for('static', filename='zaab.css')
    return render_template('init.html', csse=css)

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

【问题讨论】:

  • HTML 文件从不与 Python 脚本“对话”。 Python(通过 Flask)将使用 Jinja2 使用您传递给 render_template() 的任何信息来呈现 HTML 文件。你应该在这里完成教程:flask.pocoo.org/docs/tutorial/introduction 之后事情会变得更有意义。
  • 好吧,这是有道理的,但我怎么能传递数据呢?例如。从表单传递一些数据

标签: javascript python html flask


【解决方案1】:

您可以像在 Jinja 模板中一样使用 HTML 表单 - 然后在您的处理程序中使用以下内容:

from flask import Flask, url_for, render_template, redirect
from flask import request # <-- add this

# ... snip setup code ...

# We need to specify the methods that we accept
@app.route("/test-post", methods=["GET","POST"])
def test_post():
    # method tells us if the user submitted the form
    if request.method == "POST":
        name = request.form.name
        email = request.form.email
    return render_template("form_page.html", name=name, email=email)

如果您想使用GET 代替POST 提交表单,您只需检查request.args 而不是request.form(有关更多信息,请参阅flask.Request's documentation)。不过,如果您打算对表单做很多事情,我建议您查看出色的 WTForms 项目和 Flask-WTForms extension。

【讨论】:

  • 首先感谢您的回答,我是flask和jinja的新手,所以我想知道除了flask是否还需要安装ninja
  • @MpampinosHolmens - 如果你运行pip install Flask(假设你已经安装了 pip 并且在你的PATH 上可用)那么 Flask 将连同它的依赖项(Jinja2 和 Werkzeug)一起安装。
猜你喜欢
  • 2011-06-03
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
相关资源
最近更新 更多