【问题标题】:How to I route to an MySQL ID in Flask based on the entry selected?如何根据选择的条目路由到 Flask 中的 MySQL ID?
【发布时间】:2017-03-12 00:54:43
【问题描述】:

我是 Python 新手,目前正在使用 Flask 和 MySQL 创建一个页面,该页面允许将信息(名字、姓氏和电子邮件)提交到数据库并显示在我的 index.html 上。

我面临的挑战是每个条目都有一个编辑按钮,以将用户带到一个 URL(在本例中为“/friends/id/edit”),该 URL 将显示一个编辑页面特定用户。如何以一种允许它转到正确的 URL 并编辑数据库中的正确信息的方式编写它?

我的 server.py 文件:

    @app.route('/', methods=["GET"])
def index():
    query = "SELECT * FROM friends"
    friends = mysql.query_db(query)
    return render_template('index.html', all_friends=friends)

@app.route('/friends', methods=["POST"])
def create():
        if len(request.form['email']) < 1:
            flash("Email cannot be blank.", "error")
            return redirect('/')
        if not EMAIL_REGEX.match(request.form['email']):
            flash("Invalid email address", "error")
            return redirect('/')
        else:
            query = "INSERT INTO friends (first_name, last_name, email, created_at) VALUES (:first_name, :last_name, :email, NOW())"
            data = {
                    'first_name': request.form['first_name'],
                    'last_name': request.form['last_name'],
                    'email': request.form['email']
                    }

            mysql.query_db(query, data)    
            query= "SELECT * FROM friends"
            friend = mysql.query_db(query)
            return render_template('index.html', all_friends=friend)

@app.route('/friends/<id>/edit', methods=["GET"])
def edit(id):
        return render_template('/edit.html')

index.html:

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Full Friends</title>
  </head>
  <body>
    <h1>Full Friends</h1>
    {% for friend in all_friends: %}
       <p>ID: {{ friend['id'] }} First Name: {{ friend['first_name'] }} Last Name: {{ friend['last_name'] }} Email: {{ friend['email'] }} Timestamp: {{ friend['timestamp'] }} <form action="/friends/<id>/edit" method=["GET"]><input id="edit" type="submit" value="Edit"></form> <form action="/friends/<id>/delete"><input id="delete" type="submit" method="POST" value="Delete"></form></p>
    {% endfor %}

    <div id="add_contact">
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          <ul class=flashes>
          {% for category, message in messages %}
            <li class="{{ category }}">{{ message }}</li>
          {% endfor %}
          </ul>
        {% endif %}
      {% endwith %}

      <form action="/friends" method="POST">
        <p class="titles">First Name:</p><input type="text" name="first_name">
        <p class="titles">Last Name:</p><input type="text" name="last_name">
        <p class="titles">Email:</p><input type="text" name="email"><br>
        <input type="submit" value="Add Friend">
      </form>
    </div>
  </body>
</html>

【问题讨论】:

    标签: python mysql url flask


    【解决方案1】:

    我相信您希望在模板中创建“编辑”链接,您可以像下面这样实现。您不需要“表单”。您可以使用 css 为链接设置样式,使其看起来像一个按钮。

    {% for friend in all_friends: %}
         <p>
        <a href="/friends/{{friend['id']}}/edit">Edit</a>
        </p>
    {% endfor %}
    

    【讨论】:

    • 谢谢!这比我想象的要简单得多。
    【解决方案2】:

    只要您不关心安全性。你可以这样做。

    server.py 文件:

    @app.route('/friends/<id>/edit', methods=["GET"])
    def edit(id):
        return render_template('/edit.html', id=id)
    
    @app.route('/friends/<id>/edit', methods=["POST"])
    def edit(id):
        # Do anything with the POST data
        # and modify database
        return render_template('/edit.html', id=id)
    

    edit.html 文件:

    <html>
    <head>
        <meta charset="utf-8">
        <title>Full Friends</title>
    </head>
    <body>
      <span> friend id: {{ id }} </span>
      <form action="/friends/{{ id }}/edit" method="POST">
        <p class="titles">First Name:</p><input type="text" name="first_name">
        <p class="titles">Last Name:</p><input type="text" name="last_name">
        <p class="titles">Email:</p><input type="text" name="email"><br>
        <input type="submit" value="Modify Friend">
      </form>
    </body>
    </html>
    

    这里的想法是,您只有一个模板,您可以使用数据库中的数据填充一个模板,并且您可以通过他们的 ID 区分发布请求中的用户。

    [编辑] 我误读了你的问题。您还必须在 index.html 中将 /friends/&lt;id&gt;/edit 替换为 /friends/{{ friend['id'] }}/edit 。这样,您就可以为每个用户提供唯一的链接。并且您可以使用 ID 搜索数据库并使用用户信息填充模板。

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 2021-07-16
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2019-12-18
      相关资源
      最近更新 更多