在浏览器(HTML)查询中从SQLite返回多个结果

oymdgrw7  于 2023-06-23  发布在  SQLite
关注(0)|答案(1)|浏览(121)

我是Flask和Python的新手。我正在使用SQLite创建露营日志。我创建了一个html文件,将用户输入保存到SQLite数据库中。用户可以基于2个不同的参数(月份和/或位置)调用1个条目“行”。我希望能够召回所有满足所用参数的条目。
为了澄清,用户记录露营旅行,其包括:start_dateend_datelocationcamping_siteweathernotespictures。在浏览器的底部有一个搜索,将允许用户按月份,地点或两者查看露营旅行。当前,用户仅具有对该月份、位置或两者的最近条目的访问权。我相信这是一个简单的解决办法,但我已经搜索了互联网,并没有找到一个解决我的具体困境。
下面是我的Flask应用程序的代码:

@app.route('/past-trips', methods=['GET'])
def get_past_trips(): 
    # Fetch past trip information from the database
    db = get_db()
    cursor = db.cursor()
    cursor.execute("SELECT * FROM past_trips")
    rows = cursor.fetchall()

    # Convert the rows into a list of dictionaries
    past_trips = []
    for row in rows:
        trip = {
            'start_date': row['start_date'],
            'end_date': row['end_date'],
            'location': row['location'],
            'camping_site': row['camping_site'],
            'weather': row['weather'],
            'notes': row['notes'],
            'pictures': row['pictures']
        }
        past_trips.append(trip)

    # Retrieve query parameters for filtering
    location = request.args.get('location')
    month = request.args.get('month')
    
    # Filter past trips based on query parameters
    filtered_trips = past_trips  # Initialize the filtered trips list with all past trips

    if location:
        # Perform case-insensitive comparison
        location = location.lower()
        filtered_trips = [trip for trip in filtered_trips if trip['location'].lower() == location]

    if month:
        # Convert month name to YYYY-MM format
        month_names = {
            'january': '01',
            'february': '02',
            'march': '03',
            'april': '04',
            'may': '05',
            'june': '06',
            'july': '07',
            'august': '08',
            'september': '09',
            'october': '10',
            'november': '11',
            'december': '12'
        }

        if month in month_names:
            month = month_names[month]
            filtered_trips = [trip for trip in filtered_trips if
                              datetime.datetime.strptime(trip['start_date'], '%Y-%m-%d').strftime('%m') == month]

    print(filtered_trips)  # Print the filtered past trips

    # Return the filtered past trip information as a JSON response
    return jsonify(filtered_trips)

if __name__ == '__main__':
    app.teardown_appcontext(close_db)
    app.run()

相关camping_ui.html代码

<div class="my-5">
      <h2 class="text-center mb-3">Most Recent Trip by Month or Location</h2>
      <div class="row mb-3">
        <label for="month" class="col-sm-2 col-form-label">Month</label>
        <div class="col-sm-10">
          <select class="form-select" id="month">
            <option value=""></option>
            <option value="january">January</option>
            <option value="february">February</option>
            <option value="march">March</option>
            <option value="april">April</option>
            <option value="may">May</option>
            <option value="june">June</option>
            <option value="july">July</option>
            <option value="august">August</option>
            <option value="september">September</option>
            <option value="october">October</option>
            <option value="november">November</option>
            <option value="december">December</option>
          </select>
        </div>
      </div>
      <div class="row mb-3">
        <label for="past-location" class="col-sm-2 col-form-label">Location</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="past-location">
        </div>
      </div>
      <div class="text-center">
        <button type="button" class="btn btn-primary" onclick="searchPastTrips()">Search</button>
      </div>
      <div class="my-5">
        <h3 class="text-center">Results</h3>
        <table class="table table-striped">
          <thead>
            <tr>
              <th scope="col">Start Date</th>
              <th scope="col">End Date</th>
              <th scope="col">Location</th>
              <th scope="col">Camping Site ID</th>
              <th scope="col">Weather</th>
              <th scope="col">Notes</th>
              <th scope="col">Pictures</th>
            </tr>
          </thead>
          <tbody id="past-trips">
            <!-- past trips will be populated here -->
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
  // Function to fetch and display past trips based on month and location
  function searchPastTrips() {
    const monthSelect = document.getElementById('month');
    const locationInput = document.getElementById('past-location');

    const selectedMonth = monthSelect.value.toLowerCase();
    const selectedLocation = locationInput.value.toLowerCase();

    const url = `/past-trips?month=${selectedMonth}&location=${selectedLocation}`;

    fetch(url)
      .then(response => response.json())
      .then(data => {
        const pastTripsContainer = document.getElementById('past-trips');
        pastTripsContainer.innerHTML = '';

        data.forEach(trip => {
          const row = document.createElement('tr');

          const pastTripsContainer = document.getElementById('past-trips');
          pastTripsContainer.innerHTML = '';

          const startDateCell = document.createElement('td');
          startDateCell.textContent = trip.start_date;
          row.appendChild(startDateCell);

          const endDateCell = document.createElement('td');
          endDateCell.textContent = trip.end_date;
          row.appendChild(endDateCell);

          const locationCell = document.createElement('td');
          locationCell.textContent = trip.location;
          row.appendChild(locationCell);

          const campingSiteCell = document.createElement('td');
          campingSiteCell.textContent = trip.camping_site;
          row.appendChild(campingSiteCell);

          const weatherCell = document.createElement('td');
          weatherCell.textContent = trip.weather;
          row.appendChild(weatherCell);

          const notesCell = document.createElement('td');
          notesCell.textContent = trip.notes;
          row.appendChild(notesCell);

          const picturesCell = document.createElement('td');
          const pictureImage = document.createElement('img');
          // pictureImage.src = trip.pictures; // Assuming the picture field contains the image URL
          picturesCell.appendChild(pictureImage);
          row.appendChild(picturesCell);

          pastTripsContainer.appendChild(row);
        });
      })
      .catch(error => console.error(error));
  }

  // Call the function to fetch and display past trips when the page loads
  document.addEventListener('DOMContentLoaded', searchPastTrips);
</script>
</body>
</html>
czq61nw1

czq61nw11#

pastTripsContainer在循环中被清空

fetch(url)
      .then(response => response.json())
      .then(data => {
        const pastTripsContainer = document.getElementById('past-trips');
        pastTripsContainer.innerHTML = '';

        data.forEach(trip => {
          const row = document.createElement('tr');

          const pastTripsContainer = document.getElementById('past-trips');
          pastTripsContainer.innerHTML = '';

相关问题