V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
suueyoung
V2EX  ›  Python

flask, 如何处理 ponyorm 中的 update?

  •  
  •   suueyoung · 2016-09-05 17:35:29 +08:00 · 3014 次点击
    这是一个创建于 2789 天前的主题,其中的信息可能已经有所发展或是发生改变。

    正在使用ponyorm尝试弄出一个基于flask的网站. 但是在处理 update 的时候发现怎么弄都弄不好.

    处理 update 的 view 如下. 可是在实际情况中是点了 submit 之后, redirect 到的 index.html 页面上显示的数据信息根本就没有 update 到.

    目前的 active 是 False, 我想在通过选择 active 到 True 然后点击 submit:

    1. 把 active 保存到数据库;
    2. 之后重定向到 index.html.
    @app.route('/update/<int:id>', methods=('GET', 'POST'))
    @db_session
    def update(id):
        record = Tconfused.get(lambda p: p.id == id)
    
        form = UpdateForm()
        form.id.data = record.id
        form.active.data = record.active
        form.url.data = record.url
    
        if request.method == 'POST' and form.validate_on_submit():
            record.active = form.active.data
            record.url = form.url.data.strip()
            return redirect(url_for('index'))
        return render_template('update.html', record=record, form=form)
    

    从 f12 看见的 form data 也都没有错误

    csrf_token:1473071404##a662b5cd7428bb709b74372a0d12eed2d9c26b32
    active:1
    url:http://www.google.com
    

    请问, 要达到我的目的, 这个 view 里面有关数据库操作的部分要怎么写呢? 这里是完整的 3 个文件代码:

    • confused.py
    • templates/index.html
    • templates/update.html
    confused.py
    import os
    from pony.orm import Database, db_session, Required, Optional
    from flask import Flask, redirect, url_for, render_template, request
    from flask_wtf import Form
    from wtforms import SelectField, StringField, IntegerField
    from wtforms.validators import DataRequired
    
    ABS_DB_PATH = os.path.basename(__file__) + 'confuse.db'
    db = Database()
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'confused'
    
    
    class Tconfused(db.Entity):
        active = Required(bool, default=0)
        url = Optional(str)
    
    
    class UpdateForm(Form):
        id = IntegerField('ID')
        active = SelectField('Active', choices=[(1, 'True'),
                                                (0, 'False')])
        url = StringField('URL', validators=[DataRequired('url needed.')])
    
    
    @app.route('/')
    @db_session
    def index():
        records = Tconfused.select()[:]
        return render_template('index.html', records=records)
    
    
    @app.route('/update/<int:id>', methods=('GET', 'POST'))
    @db_session
    def update(id):
        record = Tconfused.get(lambda p: p.id == id)
    
        form = UpdateForm()
        form.id.data = record.id
        form.active.data = record.active
        form.url.data = record.url
    
        if request.method == 'POST' and form.validate_on_submit():
            record.active = form.active.data
            record.url = form.url.data.strip()
            return redirect(url_for('index'))
        return render_template('update.html', record=record, form=form)
    
    
    if __name__ == '__main__':
        db.bind('sqlite', ABS_DB_PATH, create_db=1)
        db.generate_mapping(create_tables=1)
    
        app.run(host='0.0.0.0', debug=1, port=5011)
    
    index.html
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <div>
        <table>
            <thead>
                <tr>
                    <td>edit</td>
                    <td>id</td>
                    <td>active</td>
                    <td>url</td>
            </tr>
            </thead>
            <tbody>
            {% for record in records %}
                <tr>
                    <td><a href="/update/{{ record.id }}">edit</a></td>
                    <td>{{ record.id }}</td>
                    <td>{{ record.active }}</td>
                    <td>{{ record.url }}</td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    </body>
    </html>
    

    update.html

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <div>
        <form action="" method="post">
            {{ form.hidden_tag() }}
            <div>{{ form.id.label(disabled=True) }} {{ form.id.data }}</div>
            <div>{{ form.active.label }} {{ form.active() }}</div>
            <div>{{ form.url.label }} {{ form.url(size=50) }}</div>
            <div><input type="submit"></div>
        </form>
    </div>
    <br>
    
    <div>
        <table>
            <thead>
            <tr>
                <td>id</td>
                <td>active</td>
                <td>url</td>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>{{ record.id }}</td>
                <td>{{ record.active }}</td>
                <td>{{ record.url }}</td>
            </tr>
            </tbody>
        </table>
    </div>
    </body>
    </html>
    
    2 条回复    2016-09-05 21:11:11 +08:00
    bjjvvv
        1
    bjjvvv  
       2016-09-05 17:52:07 +08:00
    form = UpdateForm()
    form.id.data = record.id
    form.active.data = record.active
    form.url.data = record.url

    这 4 句 POST 请求的时候同样会执行的,所以你把 POST 来的数据又赋值成原来的数据了
    所以你要把这 4 句放到 if 块的下面
    suueyoung
        2
    suueyoung  
    OP
       2016-09-05 21:11:11 +08:00
    @bjjvvv 太感谢了. 搞定了!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4461 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:10 · PVG 18:10 · LAX 03:10 · JFK 06:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.