I can't figure out why my search function on pythonanywhere isn't working please help. Attached is the instructions and json file.  Here's my flask_app.py  from flask import Flask, render_template, jsonify, request import json app = Flask(__name__) @app.route('/') def index():     return render_template('apartmentsearch.html') @app.route('/catalog/') def catalog(search):     f = open('/home/pcasseus/data/apartments.json')     apartments = json.load(f)     query = request.args.get('searchField', '')     bedrooms = request.args.get('bedrooms', '')     sort = request.args.get('sort', '')     filtered_apartments = []     for apt in apartments:         if query.lower() in apt['Title'].lower() or query.lower() in apt['Description'].lower():             if bedrooms == '1+' and apt['Number of Bedrooms'] < 1:                 continue             if bedrooms == '2+' and apt['Number of Bedrooms'] < 2:                 continue             filtered_apartments.append(apt)     if sort == 'price-ascending':         filtered_apartments.sort(key=lambda x: x['Monthly Rent'])     elif sort == 'price-descending':         filtered_apartments.sort(key=lambda x: x['Monthly Rent'], reverse=True)     return jsonify(filtered_apartments) if __name__ == '__main__':     app.run(debug=True) Here's my script.js  function loadDoc(url, func) {     let xhttp = new XMLHttpRequest();     xhttp.onload = function() {         if (xhttp.status != 200) {             console.log("Error");         } else {             func(xhttp.response);         }     }     xhttp.open("GET", url);     xhttp.send(); } function apartment_search() {     let searchField = document.getElementById("searchField").value;     let bedrooms = document.getElementById("bedrooms").value;     let sort = document.getElementById("sort").value;     // Construct the URL with query parameters     let url = `http://pcasseus.pythonanywhere.com/catalog/${searchField}?bedrooms=${bedrooms}&sort=${sort}`;     loadDoc(url, apartment_search_results); }      function apartment_search_results(response) {     let data = JSON.parse(response);     let results = data["result"];      let temp = '';     for (let i = 0; i < results.length; i++) {         let apartment = results[i];         temp += "";         temp += "Title: " + apartment.Title + "";         temp += "Description: " + apartment.Description + ""         temp += "Number of Bedrooms: " + apartment['Number of Bedrooms'] + "";         temp += "Monthly Rent: " + apartment['Monthly Rent'];         temp += "";     }     temp += '';     let divResults = document.getElementById('divResults');     divResults.innerHTML = temp; } Here's my apartmentsearch.html     Apartment Search                       Search:         Number of Bedrooms:                                                             Sort By:                                                             Search                 Type in a search and hit search button...

Database System Concepts
7th Edition
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Chapter1: Introduction
Section: Chapter Questions
Problem 1PE
icon
Related questions
Question

I can't figure out why my search function on pythonanywhere isn't working please help. Attached is the instructions and json file. 

Here's my flask_app.py 

from flask import Flask, render_template, jsonify, request
import json

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('apartmentsearch.html')

@app.route('/catalog/<search>')
def catalog(search):
    f = open('/home/pcasseus/data/apartments.json')
    apartments = json.load(f)

    query = request.args.get('searchField', '')
    bedrooms = request.args.get('bedrooms', '')
    sort = request.args.get('sort', '')

    filtered_apartments = []
    for apt in apartments:
        if query.lower() in apt['Title'].lower() or query.lower() in apt['Description'].lower():
            if bedrooms == '1+' and apt['Number of Bedrooms'] < 1:
                continue
            if bedrooms == '2+' and apt['Number of Bedrooms'] < 2:
                continue
            filtered_apartments.append(apt)

    if sort == 'price-ascending':
        filtered_apartments.sort(key=lambda x: x['Monthly Rent'])
    elif sort == 'price-descending':
        filtered_apartments.sort(key=lambda x: x['Monthly Rent'], reverse=True)

    return jsonify(filtered_apartments)

if __name__ == '__main__':
    app.run(debug=True)

Here's my script.js 

function loadDoc(url, func) {
    let xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
        if (xhttp.status != 200) {
            console.log("Error");
        } else {
            func(xhttp.response);
        }
    }
    xhttp.open("GET", url);
    xhttp.send();
}

function apartment_search() {
    let searchField = document.getElementById("searchField").value;
    let bedrooms = document.getElementById("bedrooms").value;
    let sort = document.getElementById("sort").value;

    // Construct the URL with query parameters
    let url = `http://pcasseus.pythonanywhere.com/catalog/${searchField}?bedrooms=${bedrooms}&sort=${sort}`;

    loadDoc(url, apartment_search_results);
}
    
function apartment_search_results(response) {
    let data = JSON.parse(response);
    let results = data["result"]; 

    let temp = '<ul>';

    for (let i = 0; i < results.length; i++) {
        let apartment = results[i];

        temp += "<li>";
        temp += "<strong>Title:</strong> " + apartment.Title + "<br>";
        temp += "<strong>Description:</strong> " + apartment.Description + "<br>"
        temp += "<strong>Number of Bedrooms:</strong> " + apartment['Number of Bedrooms'] + "<br>";
        temp += "<strong>Monthly Rent:</strong> " + apartment['Monthly Rent'];
        temp += "</li>";
    }

    temp += '</ul>';

    let divResults = document.getElementById('divResults');
    divResults.innerHTML = temp;
}

Here's my apartmentsearch.html

<!DOCTYPE html>
<html>
<head>
    <title>Apartment Search</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
     <script src="{{ url_for('static', filename='script.js') }}"></script>
</head>
<body>
    <div>
        Search: <input type="text" id="searchField">
        <label for="bedrooms">Number of Bedrooms:</label>
        <select id="bedrooms-dropdown">
            <option value="">Any</option>
            <option value="1">1+</option>
            <option value="2">2+</option>
        </select>
        <label for="sort">Sort By:</label>
        <select id="sort-dropdown">
            <option value="none">None</option>
            <option value="price-ascending">Ascending</option>
            <option value="price-descending">Descending</option>
        </select>
        <button onclick="apartment_search()">Search</button>
    </div>

    <div id="divResults">
        Type in a search and hit search button...
    </div>
</body>
</html>

DAC: /home/pcasseus/data/apartments.json
Keyboard shortcuts: Normal
Share
H Save
Save as...
"Description": "Just painted alcove studio in a quiet, four story townhouse. World's best live in super (just ask the residents) keeps the public areas squeaky clean! Home
"Number of Bedrooms": 1,
"Monthly Rent": 1895
"Description": "This is a 3 separate bedroom apartment, 5th floor walk up, heat and hot water is included in your rent. Laundromat on site and there is a live in superinte
"Number of Bedrooms": 3,
"Monthly Rent": 2695
"Title": "Luxurious Waterfront Retreat",
"Description": "This beautiful two-bedroom 2, two-bathroom apartment welcomes floor-to-ceiling windows, ensuring rooms are bathed in natural light and offer captivating vi
"Number of Bedrooms": 2,
"Monthly Rent": 6325
1 [
2
{
3
"Title": "East Harlem Sunny Studio",
4
5
6
7
8
9
"Title": "Apartment Park Slope South",
10
11
12
13
14
15
16
17
18
19
24
25
26
27
28
29
1999 222222222222-23-201
},
"Title": "A Perfect Balance of Aesthetic and Practical Considerations",
"Description": "Welcome to the luxury of modern apartment! Prepare to be amazed by this spectacular residence, boasting a perfect blend of contemporary design and luxuriou
"Number of Bedrooms": 2,
"Monthly Rent": 7998
"Title":"Tribeca's Luxurious Apartment",
"Description": "This sunlit, beautiful 1-bedroom apartment with a home office boasts expansive windows, oak floors, and modern shades. The kitchen is a chef's dream, with
"Number of Bedrooms": 1,
"Monthly Rent": 5750
"Title": "Exquisite Tribeca Living: Corner 2 Bedroom Apartment with Views.",
"Description": "This cozy corner 2-bedroom, 2-bathroom apartment boasts expansive windows, oak floors, and modern shades. The kitchen is a chef's dream, with granite count
"Number of Bedrooms": 2,
"Monthly Rent": 7889
33
34
35
36
37
38
39
"Title": "Massive 2 Bed Penthouse w/ Private Terrace",
до
"Description": "Massive 3 Bed 1 Bath Penthouse unit with a private terrace. This incredible unit boasts large windows that fill the space with natural light. hardwood floo
Transcribed Image Text:DAC: /home/pcasseus/data/apartments.json Keyboard shortcuts: Normal Share H Save Save as... "Description": "Just painted alcove studio in a quiet, four story townhouse. World's best live in super (just ask the residents) keeps the public areas squeaky clean! Home "Number of Bedrooms": 1, "Monthly Rent": 1895 "Description": "This is a 3 separate bedroom apartment, 5th floor walk up, heat and hot water is included in your rent. Laundromat on site and there is a live in superinte "Number of Bedrooms": 3, "Monthly Rent": 2695 "Title": "Luxurious Waterfront Retreat", "Description": "This beautiful two-bedroom 2, two-bathroom apartment welcomes floor-to-ceiling windows, ensuring rooms are bathed in natural light and offer captivating vi "Number of Bedrooms": 2, "Monthly Rent": 6325 1 [ 2 { 3 "Title": "East Harlem Sunny Studio", 4 5 6 7 8 9 "Title": "Apartment Park Slope South", 10 11 12 13 14 15 16 17 18 19 24 25 26 27 28 29 1999 222222222222-23-201 }, "Title": "A Perfect Balance of Aesthetic and Practical Considerations", "Description": "Welcome to the luxury of modern apartment! Prepare to be amazed by this spectacular residence, boasting a perfect blend of contemporary design and luxuriou "Number of Bedrooms": 2, "Monthly Rent": 7998 "Title":"Tribeca's Luxurious Apartment", "Description": "This sunlit, beautiful 1-bedroom apartment with a home office boasts expansive windows, oak floors, and modern shades. The kitchen is a chef's dream, with "Number of Bedrooms": 1, "Monthly Rent": 5750 "Title": "Exquisite Tribeca Living: Corner 2 Bedroom Apartment with Views.", "Description": "This cozy corner 2-bedroom, 2-bathroom apartment boasts expansive windows, oak floors, and modern shades. The kitchen is a chef's dream, with granite count "Number of Bedrooms": 2, "Monthly Rent": 7889 33 34 35 36 37 38 39 "Title": "Massive 2 Bed Penthouse w/ Private Terrace", до "Description": "Massive 3 Bed 1 Bath Penthouse unit with a private terrace. This incredible unit boasts large windows that fill the space with natural light. hardwood floo
Project: Carmine's List
For this project, you will create a webpage and a web service that shows apartments for rent. You should have
this hosted on pythonanywhere.com however you should still submit your data and code files for the project.
Data
Create a JSON file with a list of 10 apartments. Each apartment should have the following fields:
- Title
Description
Number of Bedrooms
Monthly Rent
Feel free to find some actual ones that are on newyork.craigslist.org or newjersey.craigslist.org
Web Page
There is absolutely no chance that two students would have the same list.
Create a web page that has a the following:
search field
dropdown list of number of bedrooms: Any, 1+, 2+
- Sort: None, Price Ascending, Price Descending
Button to execute the search.
When the button is pressed, the web page must contact the Web Service with the above filters and then render
the JSON results formatted as HTML.
Web Service
The web service should receive the query from the web page and return JSON as a result. Do not return HTML.
It must return JSON.
- If the search field is not blank, filter if the search appears in the title or description.
If the dropdown list of bedrooms is used, filter by number of bedrooms.
For the sort, feel free to use a built-in python sorting method or write your own.
Keep in mind all of these can be used at the same time. Someone could search for "sunlight" with 2+ bedrooms
and sort by price ascending.
Transcribed Image Text:Project: Carmine's List For this project, you will create a webpage and a web service that shows apartments for rent. You should have this hosted on pythonanywhere.com however you should still submit your data and code files for the project. Data Create a JSON file with a list of 10 apartments. Each apartment should have the following fields: - Title Description Number of Bedrooms Monthly Rent Feel free to find some actual ones that are on newyork.craigslist.org or newjersey.craigslist.org Web Page There is absolutely no chance that two students would have the same list. Create a web page that has a the following: search field dropdown list of number of bedrooms: Any, 1+, 2+ - Sort: None, Price Ascending, Price Descending Button to execute the search. When the button is pressed, the web page must contact the Web Service with the above filters and then render the JSON results formatted as HTML. Web Service The web service should receive the query from the web page and return JSON as a result. Do not return HTML. It must return JSON. - If the search field is not blank, filter if the search appears in the title or description. If the dropdown list of bedrooms is used, filter by number of bedrooms. For the sort, feel free to use a built-in python sorting method or write your own. Keep in mind all of these can be used at the same time. Someone could search for "sunlight" with 2+ bedrooms and sort by price ascending.
Expert Solution
steps

Step by step

Solved in 3 steps

Blurred answer
Knowledge Booster
Linux
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Database System Concepts
Computer Science
ISBN:
9780078022159
Author:
Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:
McGraw-Hill Education
Starting Out with Python (4th Edition)
Starting Out with Python (4th Edition)
Computer Science
ISBN:
9780134444321
Author:
Tony Gaddis
Publisher:
PEARSON
Digital Fundamentals (11th Edition)
Digital Fundamentals (11th Edition)
Computer Science
ISBN:
9780132737968
Author:
Thomas L. Floyd
Publisher:
PEARSON
C How to Program (8th Edition)
C How to Program (8th Edition)
Computer Science
ISBN:
9780133976892
Author:
Paul J. Deitel, Harvey Deitel
Publisher:
PEARSON
Database Systems: Design, Implementation, & Manag…
Database Systems: Design, Implementation, & Manag…
Computer Science
ISBN:
9781337627900
Author:
Carlos Coronel, Steven Morris
Publisher:
Cengage Learning
Programmable Logic Controllers
Programmable Logic Controllers
Computer Science
ISBN:
9780073373843
Author:
Frank D. Petruzella
Publisher:
McGraw-Hill Education