Flask 将 kwargs 传递到例程

问题描述 投票:0回答:1

我需要一些建议

在以下代码中,如果指定了 record_id,WTF 表单将填充信息。

@app.route('/settings', methods=['GET', 'POST'])
def settings(**kwargs):

 ...

    record_id_ = kwargs.pop('rec_id', 0)

  if record_id_ != 0:  # if focus record is spesified
      data = find_sql_data...
 
      # insert values into licence form
      form1.field1.data = lic_data[0][1]
      ...

  else:   # No focus record is spesified
      form1.field8.data = datetime(2000, 1, 2)
      ...

     return render_template(template_name_or_list='setup.html',
                            form1=form1, data=data, )

问题是,当未指定记录时,“settings.html”会完美呈现,但如果指定了记录,则信息会正确传递,但 Flask 路径错误并且未应用 CSS

Flask 路径更改为

GET /static/assets/....
GET /settings/static/assets/....

如何修复 CSS(和其他)文件的路径

谢谢 埃弗特

我尝试将

return redirect(url_for('settings', record_id=record_id))
更改为
return setting(record_id=record_id)
但这也没有达到预期的结果。

阻止表单数据也不能解决问题

python flask
1个回答
0
投票

在我看来,您已经在模板中为 CSS 文件指定了相对路径。这就是路径根据路线而变化的原因。如果您使用

url_for('static', filename=...)
包含该文件,问题应该可以解决,因为会自动使用绝对路径。

以下示例向您展示了如果您要使用评论中提到的 URL 参数,您的应用程序可能会是什么样子。该示例使用 Flask-SQLAlchemy 的旧版查询接口。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Settings</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='assets/main.css') }}">
</head>
<body>
    <form method="post" action="{{ url_for('settings', record_id=obj_id) }}">
        {{ form.csrf_token }}
        <div>
            {{ form.field1.label() }}
            {{ form.field1() }}
        </div>
        <div>
            {{ form.field2.label() }}
            {{ form.field2() }}
        </div>
        <button type="submit">Submit</button>
    </form>
</body>
</html>
from flask import (
    Flask, 
    redirect, 
    render_template, 
    request, 
    url_for
)
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import DateTimeField, StringField

app = Flask(__name__)
app.config.from_mapping(
    SECRET_KEY='your secret here', 
    SQLALCHEMY_DATABASE_URI='sqlite:///example.db'
)
db = SQLAlchemy(app)

class Settings(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    field1 = db.Column(db.String)
    field2 = db.Column(db.DateTime)

with app.app_context():
    db.drop_all()
    db.create_all()

class SettingsForm(FlaskForm):
    field1 = StringField()
    field2 = DateTimeField()

@app.route('/settings', methods=['GET', 'POST'])
def settings():
    obj_id = request.args.get('record_id', 0, type=int)
    obj = Settings.query.get(obj_id)
    data = { 'field2': datetime(2000, 1, 2) }
    form = SettingsForm(request.form, obj=obj, data=data)
    if form.validate_on_submit():
        if not obj: 
            obj = Settings()
            db.session.add(obj)
        form.populate_obj(obj)
        db.session.commit()
        return redirect(url_for('settings', record_id=obj.id))
    return render_template('settings.html', **locals())

如果您喜欢可变规则,可以使用以下实现。

@app.route('/settings', methods=['GET', 'POST'], defaults={ 'obj_id': 0 })
@app.route('/settings/<int:obj_id>', methods=['GET', 'POST'])
def settings(obj_id=0):
    obj = Settings.query.get(obj_id)
    data = { 'field2': datetime(2000, 1, 2) }
    form = SettingsForm(request.form, obj=obj, data=data)
    if form.validate_on_submit():
        if not obj: 
            obj = Settings()
            db.session.add(obj)
        form.populate_obj(obj)
        db.session.commit()
        return redirect(url_for('settings', obj_id=obj.id))
    return render_template('settings.html', **locals())
© www.soinside.com 2019 - 2024. All rights reserved.