Py学习  »  davidism  »  全部回复
回复总数  3
6 年前
回复了 davidism 创建的主题 » 在python中的HTML文件之间跳转

url_for 生成应用程序中定义的路由的URL。没有(或者可能不应该有)原始html文件被提供,尤其是在templates文件夹之外。每个模板都应该由Jinja呈现。要显示或发布表单的每个位置都应该通过应用程序上的路由进行处理和生成。

在这种情况下,您可能希望有一条路径,既可以在GET时呈现表单,也可以在POST时处理表单提交。

__init__.py :

from flask import Flask, request, url_for, redirect, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
    if request.method == 'POST':
        # do stuff when the form is submitted

        # redirect to end the POST handling
        # the redirect can be to the same route or somewhere else
        return redirect(url_for('index'))

    # show the form, it wasn't submitted
    return render_template('cool_form.html')

templates/index.html :

<!doctype html>
<html>
<body>
    <p><a href="{{ url_for('cool_form') }}">Check out this cool form!</a></p>
</body>
</html>

templates/cool_form.html :

<!doctype html>
<html>
<body>
    <form method="post">
        <button type="submit">Do it!</button>
    </form>
</html>

我不知道你的表单和路由实际上是做什么的,所以这只是一个例子。


如果需要链接静态文件,请将它们放在 static 文件夹,然后使用:

url_for('static', filename='a_picture.png')
8 年前
回复了 davidism 创建的主题 » 为什么pycharm没有看到sqlalchemy模块?

您已将第三方库安装到virtualenv中,但PyCharm默认情况下不知道这一点。如果未指定任何内容,它将选择系统Python安装作为解释器。您需要进入项目设置,并将解释器配置为指向virtualenv。PyCharm将为解释器编制索引,并允许您自动完成。

Project interpreter settings

可以在左侧的下拉菜单中自动检测到virtualenv。如果不是,请单击右侧的档位,单击“添加本地”,然后选择 /path/to/virtualenv/bin/python (或 \Path\to\virtualenv\Scripts\python.exe 在Windows上)。

7 年前
回复了 davidism 创建的主题 » 使用Python、Flask和SQLAlchemy获取Postgresql数据库中的双条目

如果你用的是现代的 flask run 命令,没有任何选项 app.run --no-reload :

FLASK_DEBUG=1 flask run --no-reload

也, __name__ == '__main__' 永远不会是真的,因为应用程序不是直接执行的。使用相同的想法 Martijn's answer __main__ 封锁。

if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
    # do something only once, before the reloader

if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
    # do something each reload