Python Forum
One more issue with displaying API information
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
One more issue with displaying API information
#11
whenever i include the average. I tried making it a int and a float. I tried using different indexes. I just can't get it to show up. But I can get it to print to the console for some reason.
Reply
#12
What? How are you getting a value if the variable is None? I'm confused. Remember that we don't have the application and the state of the database, so you really need to give us more information.

As an aside, I hope you learn about automated testing at some point, as having a test case that demonstrates the problem would be ideal.

Oh, you possibly have scoping problems too. Consider whether your return statement is in the right place considering what your ifs are checking.
Reply
#13
This is the code and the error i'm getting.

@app.route("/api", methods=["GET", "POST"])
@app.route("/api/<isbn>")
def api(isbn=""):
    search = db.execute("SELECT * FROM books WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
    if search:
        title = search[1]
        author = search[2]
        year = search[3]
        isbn: search[0]
        ratingNum = ratingAvg = db.execute("SELECT COUNT(rating) FROM reviews WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
        ratingAvg = db.execute("SELECT AVG(rating) FROM reviews WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
        if ratingNum and ratingAvg:
            num1 = ratingNum[0]
            avg1 = ratingAvg[0]
            avg2 = float(avg1)
        else:
            return render_template("404.html")
    
    
    
    return {
        "title": title,
        "author": author,
        "year": year,
        "isbn": isbn,
        "review_count": num1,
        "average_score": avg2
    }
    
Error:
TypeError TypeError: float() argument must be a string or a number, not 'NoneType' Traceback (most recent call last) File "C:\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__ return self.wsgi_app(environ, start_response) File "C:\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app response = self.handle_exception(e) File "C:\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise raise value File "C:\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "C:\Python38\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Python38\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise raise value File "C:\Python38\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "C:\Python38\Lib\site-packages\flask\app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\school\project1\application.py", line 95, in api avg2 = float(avg1) TypeError: float() argument must be a string or a number, not 'NoneType'

i honestly have no clue why i can print it to console but not on the page.
Reply
#14
So as I asked before, under what circumstances are you getting the None? What's in the database and what request are you making?
Reply
#15
it's only when there's no reviews when i get the error...hmm that makes sense. I should put an if statment in there. I think I got it. Let's see.

OK now my code looks like this and it shows Null for books with no reviews but now it gives me an error when it does have reviews.

Here's what I'm getting.

@app.route("/api", methods=["GET", "POST"])
@app.route("/api/<isbn>")
def api(isbn=""):
    search = db.execute("SELECT * FROM books WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
    if search:
        title = search[1]
        author = search[2]
        year = search[3]
        isbn: search[0]
        ratingNum = ratingAvg = db.execute("SELECT COUNT(rating) FROM reviews WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
        ratingAvg = db.execute("SELECT AVG(rating) FROM reviews WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
        if ratingNum and ratingAvg:
            num1 = ratingNum[0]
            avg1 = ratingAvg[0]
            print(avg1)
        else:
            return render_template("404.html")
    
    
    
    return {
        "title": title,
        "author": author,
        "year": year,
        "isbn": isbn,
        "review_count": num1,
        "average_score": avg1
    }
Error:
TypeError TypeError: Object of type Decimal is not JSON serializable Traceback (most recent call last) File "C:\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__ return self.wsgi_app(environ, start_response) File "C:\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app response = self.handle_exception(e) File "C:\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise raise value File "C:\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "C:\Python38\Lib\site-packages\flask\app.py", line 1953, in full_dispatch_request return self.finalize_request(rv) File "C:\Python38\Lib\site-packages\flask\app.py", line 1968, in finalize_request response = self.make_response(rv) File "C:\Python38\Lib\site-packages\flask\app.py", line 2112, in make_response rv = jsonify(rv) File "C:\Python38\Lib\site-packages\flask\json\__init__.py", line 370, in jsonify dumps(data, indent=indent, separators=separators) + "\n", File "C:\Python38\Lib\site-packages\flask\json\__init__.py", line 211, in dumps rv = _json.dumps(obj, **kwargs) File "C:\Python38\Lib\json\__init__.py", line 234, in dumps return cls( File "C:\Python38\Lib\json\encoder.py", line 201, in encode chunks = list(chunks) File "C:\Python38\Lib\json\encoder.py", line 431, in _iterencode yield from _iterencode_dict(o, _current_indent_level) File "C:\Python38\Lib\json\encoder.py", line 405, in _iterencode_dict yield from chunks File "C:\Python38\Lib\json\encoder.py", line 438, in _iterencode o = _default(o) File "C:\Python38\Lib\site-packages\flask\json\__init__.py", line 100, in default return _json.JSONEncoder.default(self, o) File "C:\Python38\Lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} '

Got it working here's my code:

@app.route("/api", methods=["GET", "POST"])
@app.route("/api/<isbn>")
def api(isbn=""):
    search = db.execute("SELECT * FROM books WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
    if search:
        title = search[1]
        author = search[2]
        year = search[3]
        isbn: search[0]
        ratingNum = ratingAvg = db.execute("SELECT COUNT(rating) FROM reviews WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
        ratingAvg = db.execute("SELECT AVG(rating) FROM reviews WHERE isbn = :isbn", {'isbn':isbn}).fetchone()
        if ratingNum and ratingAvg:
            num1 = ratingNum[0]
            avg1 = ratingAvg[0]
            if avg1 != None:
                avg2 = int(avg1)
            else:
                avg2 = 0
        else:
            return render_template("404.html")
    

        return {
        "title": title,
        "author": author,
        "year": year,
        "isbn": isbn,
        "review_count": num1,
        "average_score": avg2
    }
Reply
#16
I solved it guys!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Displaying selected information from XML file in the Spyder console(weather forecast) JohnN_pl 6 3,459 Jun-20-2020, 01:36 PM
Last Post: JohnN_pl

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020