【问题标题】:I am storing data in MongoDB and want to fetch that data based on user query我将数据存储在 MongoDB 中,并希望根据用户查询获取该数据
【发布时间】:2022-02-09 20:03:28
【问题描述】:

我在 MongoDB 中存储数据,现在我创建了一个烧瓶网页,它允许用户提交一个 ID 并基于 ID(存储在数据库中)它应该返回该数据。我的要求是在输入 ID 并单击提交按钮后,Flask 应显示包含数据的消息或提示。我有点卡住了。下面是代码。

app.py

@app.route('/status', methods = ["GET", "POST"])
def status():
    
    return render_template("status.html")

status.html

<h1 id="title">Check Status</h1>
<div id="form-outer">
  <p id="description">
    Enter Complaint ID
  </p>
  <form id="survey-form" method="get">
    <div class="rowTab">
      <div class="labels">
        <label id="name-label" for="name">Enter Complaint ID: </label>
      </div>
      <div class="rightTab">
        <input autofocus type="text" name="id" id="id" class="input-field" placeholder="Enter ID" required>
      </div>
    </div>
    
    <button id="submit" type="submit">Submit</button>
    <button id="reset" type="reset">Reset</button>
  </form>
</div>
</body>
</html>

ID 已存储在数据库中。简单来说,我希望代码搜索该特定 ID 并返回该 ID 的关联数据。我应该如何编写状态函数来做到这一点?

【问题讨论】:

    标签: python html python-3.x mongodb flask


    【解决方案1】:

    在您的情况下,您必须这样做:
    首先,您必须将方法更改为POST,因为您要发布数据。
    然后,您需要使用要将数据发送到的 URL 添加操作,在您的情况下,它将是 status

    <h1 id="title">Check Status</h1>
    <div id="form-outer">
      <p id="description">
        Enter Complaint ID
      </p>
      <form id="survey-form" action="{{ url_for('status')}}" method="POST">
        <div class="rowTab">
          <div class="labels">
            <label id="name-label" for="name">Enter Complaint ID: </label>
          </div>
          <div class="rightTab">
            <input autofocus type="text" name="id" id="id" class="input-field" placeholder="Enter ID" required>
          </div>
        </div>
        
        <button id="submit" type="submit">Submit</button>
        <button id="reset" type="reset">Reset</button>
      </form>
    </div>
    </body>
    </html>
    

    在 app.py 中你需要从你需要使用request模块的表单中接收var

    from flask import request
    

    那么你的函数需要看起来像这样

    @app.route('/status', methods=['POST', 'GET'])
    def status():
        if request.method == 'POST':
            your_var = request.form['id']
        return render_template('status.html')
    

    希望这能解决您的问题

    【讨论】:

    • 然后你可以将 your_var 插入 mongo db 你可以检查这个link
    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多