Git Product home page Git Product logo

Comments (5)

dreammelter avatar dreammelter commented on August 10, 2024

So it seems one step of the instructions wanted to use the web action URL instead of the API to get all the dealers...
The link includes my email in it, so I'd rather not. (It'd also require an extra step to authenticate when there's a perfectly good public API link setup for it already.)

from agfzb-cloudappdevelopment_capstone.

dreammelter avatar dreammelter commented on August 10, 2024

BUG: Actually Calling the API in view

def get_dealers_from_cf(url, **kwargs):
"""
This function:
1. Parses the json data returned from the request / "get-all-dealers" Cloud function
2. Puts it into a proxy CarDealers obj.
3. Creates and returns a list of those proxies.
At this moment it takes kwargs (state filter), but doesn't do anything with it.
"""
results = [] # we're gonna stuff each obj into a list
json_result = get_request(url)
if json_result:
# Get the row list from the obj and save it as our dealers
# dealers = json_result['rows']
dealers = json_result['entries'] # this is a list of dicts
for d in dealers:
# we are now accessing each individual dict
# Reincarnate the dict as a CarDealer obj
dealer_obj = CarDealer(address=d['address'], city=d["city"], full_name=d["full_name"],
db_id=d["id"], lat=d["lat"], long=d["long"], short_name=d["short_name"],
st=d["st"], db_zip=d["zip"])
# stick the obj into our results list
results.append(dealer_obj)
return results

For whatever reason, Django throws a KeyError when I try to access the Dealer info from the list of Dealership JSON objects received. (After calling the API method in the view)

def get_dealerships(request):
context = {}
if request.method == "GET":
# My API is currently setup to allow the following link to run the "get-all-dealers" Function
url = "https://1984d932.us-south.apigw.appdomain.cloud/api/dealership"
dealerships = get_dealers_from_cf(url) # should be a list of CarDealer objs.
#dealer_names = ' '.join([dealer.short_name for dealer in dealerships]) # dot-access cuz it should be an object...
dealer_names = []
for dealer in dealerships:
print(dealer.short_name)
dealer_names.append(dealer.short_name)
#dealer_names = set(pull_dealer_names)
context['dealers'] = dealer_names
return render(request, 'djangoapp/index.html', context)

Which, I see we are receiving....
i'm looking right at it

I can print each dealer (instead of creating new CarDealer) and the whole dictionary is returned, as expected.
we have dealer dicts

I tried recreating something similar outside the project and it works as expected:

#test ways to unpack dictionaries stored in lists...

# our dictionary list:
# this is essentially what our "dealers" list looks like.
d_list = [
    {'a':1,'b':"two",'c': False},
    {'a':"one", 'b':True, 'c':3},
    {'a':True,'b':2, 'c':"three"}
]

# this is what our plain CarModel class looks like
class Model:
    def __init__(self, a, b ,c) -> None:
        self.a = a
        self.b = b
        self.c = c
    
    def __str__(self) -> str:
        return self.a

d_list.items() # Error: this is a list object

for d in d_list:
    d.items()


for d in d_list:
    for k, v in d.items():
        # here making some sort of factory/higher order func would be useful...
        # or use a constructor method, yeah
        dict(k=v) # this ends up making a bunch of little dictionaries that all have a key of 'k'


o_list = []

for d in d_list:
    # d is accessing the individual dict entry, right?
    new_obj = Model(a=d['a'], b=d['b'], c=d['c'])
    o_list.append(new_obj)

# that works as expected...
# o_list is now a collection of objects.
# objs, whose properties we can access with a .
o_list[0].a
o_list[2].b
o_list[1].c

# this creates a (dict length ** 2) number of objects... so 9 in our case.
# however this was one solution that Django accepted at one point
# except I can't seem to replicate it now since I didn't keep the code.
x_list = []
for d in d_list:
    for i in d:
        new_obj = Model(a=d['a'], b=d['b'], c=d['c'])
        x_list.append(new_obj)

Not sure what's going on here... (wrong type? Data suddenly disappears?)
This practically crashes the whole front page.

from agfzb-cloudappdevelopment_capstone.

dreammelter avatar dreammelter commented on August 10, 2024

test_access = dealers[0]['address'] works as expected. 🙃

from agfzb-cloudappdevelopment_capstone.

dreammelter avatar dreammelter commented on August 10, 2024

Since Django worked fine with a second for-loop being used to access each key in the dict, used a while loop to short circuit it before making a new obj per key.

I could also be wrong about my assumption that each dealer obj is in fact a dictionary, but IDK... it was half working and the mockup also worked.

for dealer in dealers:
i = 0
for key in dealer: #Get KeyError without this...
while i < 1: # prevent it from actually doing this for every key
# reincarnate it as a CarDealer obj
dealer_obj = CarDealer(address=dealer['address'], city=dealer["city"], full_name=dealer["full_name"],
db_id=dealer["id"], lat=dealer["lat"], long=dealer["long"], short_name=dealer["short_name"],
st=dealer["st"], db_zip=dealer["zip"])
results.append(dealer_obj)
i += 1 # i++ is not a thing in Python lol...

from agfzb-cloudappdevelopment_capstone.

dreammelter avatar dreammelter commented on August 10, 2024

Still need a separate "get dealers by state" method (and thus a new API link.)

from agfzb-cloudappdevelopment_capstone.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.