'InlineResponse2002' object is not subscriptable | How do I manipulate the API response? - python

Code:
import time
import giphy_client
from giphy_client.rest import ApiException
from pprint import pprint
def giphyapi():
api_instance = giphy_client.DefaultApi()
api_key = '################################'
tag = 'test'
rating = 'pg-13'
fmt = 'json'
try:
# Search Endpoint
api_response = api_instance.gifs_random_get(api_key, tag = tag, rating = rating, fmt = fmt)
## here’s where I want to do stuff with the data
except ApiException as exc:
print("Exception when calling DefaultApi->gifs_random_get: %s\n" % exc)
return None
giphyapi()
Hi! How do I convert api_instance into something manipulatable, such as a dict?
This is the same problem as this, but the solution that the question author found sadly did not work for me.
I have tried print(api_response.data[0].images.type), but that threw this error:
TypeError: 'RandomGif' object is not subscriptable
I also tried this:
for block in api_response["data"]:
giftype = block["type"]
But that threw this error:
TypeError: 'InlineResponse2002' object is not subscriptable
I’m using Python 3.8.1, and I’m also using giphy-python-client. Here is a list of RandomGif models. The one I’m trying to fetch in the two examples of what I tried above is type.
Any help is greatly appreciated! 🙂

I solved it thanks to shoot2thr1ll284 on Reddit.
You just use api_response.data.type and replace type with the property that you want to fetch.

Related

How to extract required information using GPT-3 API

I tried the steps mentioned in this article.
https://matthewbilyeu.com/blog/2022-09-01/responding-to-recruiter-emails-with-gpt-3
There is a screenshot that says: Here's an example from the OpenAI Playground.
I typed all the text in "playground" but do not get similar response as shown in that image. I expected similar text like {"name":"William", "company":"BillCheese"} I am not sure how to configure the parameters in openAI web interface.
Update:
I used this code:
import json
import re, textwrap
import openai
openai.api_key = 'xxx'
prompt = f"""
Hi Matt! This is Steve Jobs with Inforation Edge Limited ! I'm interested in having you join our team here.
"""
completion = openai.Completion.create(
model="text-davinci-002",
prompt=textwrap.dedent(prompt),
max_tokens=20,
temperature=0,
)
try:
json_str_response = completion.choices[0].text
json_str_response_clean = re.search(r".*(\{.*\})", json_str_response).groups()[0]
print (json.loads(json_str_response_clean))
except (AttributeError, json.decoder.JSONDecodeError) as exception:
print("Could not decode completion response from OpenAI:")
print(completion)
raise exception
and got this error:
Could not decode completion response from OpenAI:
AttributeError: 'NoneType' object has no attribute 'groups'
You're running into this problem: Regex: AttributeError: 'NoneType' object has no attribute 'groups'
Take a look at this line:
json_str_response_clean = re.search(r".*(\{.*\})", json_str_response).groups()[0]
The regex can't find anything matching the pattern, so it returns None. None does not have .groups() so you get an error. I don't have enough details to go much further, but the link above might get you there.
I don't know why both the questioner as well as one reply above me are using RegEx. According to the OpenAI documentation, a Completion will return a JSON object.
No need to catch specific things complexly - just load the return into a dictionary and access the fields you need:
import json
# ...
# Instead of the try ... except block, just load it into a dictionary.
response = json.loads(completion.choices[0].text)
# Access whatever field you need
response["..."]
this worked for me:
question = "Write a python function to detect anomlies in a given time series"
response = openai.Completion.create(
model="text-davinci-003",
prompt=question,
temperature=0.9,
max_tokens=150,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.6,
stop=[" Human:", " AI:"]
)
print(response)
print("==========Python Code=========")
print(response["choices"][0]["text"])

"KeyError: 'added' "when importing different lists of json

I'm getting a "KeyError: 'added'" Error when i try to import one of my three lists inside a json file. The list i'm trying to import is the one called "added". I had this working when it was just one list without the name "added" on top but now it seems like i can't access the list anymore. I want to individually import them basically.
This is my code to get the Json parts before i import them into the database:
import requests
import json
from users.models import Facility, FacilityAddress, FacilityInspectionInfo, FacilityComplaints
from django.core.management.base import BaseCommand
IMPORT_URL = 'https://url/imports.json'
class Command(BaseCommand):
def import_facility_from_file(self, data):
UUID = data.get('UUID', None)
Name = data.get('Name', None)
PrimaryAddress = data["AddressInfo"]["PrimaryAddress"]
""" This is what happens after the database entry related code """
def handle(self, *args, **options):
"""
Call the function to import data from json url
"""
headers = {'Content-Type': 'application/json'}
response = requests.get(
url=IMPORT_URL,
headers=headers,
)
response.raise_for_status()
data = response.json()
for key, data_object in data.items():
self.import_facility_from_file(data_object)
The new version of the Json File that im trying to use but thats causing the error:
{
"added":
{"125hk24h5kjh43k5":
{
"UUID":"125hk24h5kjh43k5",
"Name":"Test Facility 1",
"AddressInfo":
{"PrimaryAddress":"1234 Drive RD"},
"ImporterLastModifiedTimestamp":1643721420}},
"deleted":["235hk24h5kjh43k5,235hk345789h43k5"],
"modified":{"995hk24h5kjh43k5":
{
"UUID":"995hk24h5kjh43k5",
"Name":"Test Facility 2",
"AddressInfo":
{"PrimaryAddress":"2345 Test RD"},
"ImporterLastModifiedTimestamp":1643721420}
}
}
The old version of the json file that worked perfectly with the code i intially wrote:
{"00016ed7be4872a19d6e16afc98a7389b2bb324a2":
{"UUID":"00016ed7be4872a19d6e1ed6f36b647f3eb41cadedd2130b103a5851caebc26fbbbf24c2f1a64d2cf34ac4e03aaa30309816f58c397e6afc98a7389b2bb324a2","Name":"Test Facility","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test#example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}},
"00016ed7be4872a15435435435b2bb324a2":
{"UUID":"000c93dcb7a0b3d5783bb330892aff6abdb9fb57a7d3701c2d903f3640877579f3173ecd8a80532f6c3d53dbacde78a6a54ae42fef321a5793f5a01934f8de7a","Name":"Test Facility 2","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test#example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}},
"00234324324343243afc98a7389b2bb324a2":
{"UUID":"fffd4dec10054e6e1deb2a2266a7c6bb0136ba46222e734ceed5855651f735cfbe0bb66cfaf27c3d175ae261a8f6df0c36b5390d15c70b07d67e35e1081aaf6d","Name":"Test Facility 3","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test#example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}}
So i tried it like this to get the UUID and other information from the modified json file:
UUID = data["added"]["UUID"]
but i'm getting this error:
KeyError: 'added'
It sounds like the json format has changed underneath you and you need to adapt.
How about processing all the items in both the "added" and "modified" sections?
for key, data_object in data.items():
if key in ["added", "modified"]:
for key, data in data_object.items():
self.import_facility_from_file(data)
AttributeError: 'list' object has no attribute 'get' because you've list data type in between your dictionary so you can add check for type like this
for key, data_object in data.items():
if type(data_object) == dict:
for data in data_object.values():
self.import_facility_from_file(data)

Strava API Python - AttributeError object has no attribute

For those of you who have experience with Strava API - I used the documentation on their developer site: https://developers.strava.com/docs/reference/#api-Activities-getLoggedInAthleteActivities
However, copying their code over I get an attribute error-
AttributeError: 'ActivitiesApi' object has no attribute 'getActivityById'
AttributeError: 'ActivitiesApi' object has no attribute 'getLoggedInAthleteActivities'
Any idea why? Obviously inputted my ID/secret/token as from their website. Code below:
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
STRAVA_CLIENT_ID = MY_CLIENT_ID
STRAVA_CLIENT_SECRET = 'MY_CLIENT_SECRET'
STRAVA_ACCESS_TOKEN = 'MY_ACCESS_TOKEN'
swagger_client.configuration.access_token = STRAVA_ACCESS_TOKEN
api_instance = swagger_client.ActivitiesApi()
def get_activity_data():
activity_id = 3307145226
includeAllEfforts = True # Boolean | To include all segments efforts. (optional)
try:
# Get Activity
api_response = api_instance.getActivityById(id,
includeAllEfforts=includeAllEfforts)
pprint(api_response)
except ApiException as e:
print("Exception when calling ActivitiesApi->getActivityById: %s\n" % e)
return
Looks like you have an error for passing the id to getActivityById. Your activity id variable is activity_id but you're passing in id. Not sure if that will fix your issue or not but it's a start.

Twython' object has no attribute 'getUserTimeline'

I'm trying to create a bot that will retweet and promote some of my other accounts. But i receive the below error
AttributeError: 'Twython' object has no attribute 'getUserTimeline'
my code is:
search_results = twitter.getUserTimeline(sreen_name="SCREENNAME", count = 2,)
try:
for tweet in search_results["statuses"]:
twitter.retweet(id = tweet["id_str"])
except TwythonError as e:
print e
Can anyone help?
According to the twithon documentation there is no getUserTimeline function there is however a get_user_timeline function.
You should change the following call:
twitter.getUserTimeline
to be:
twitter.get_user_timeline

Getting Django object "is not JSON serializable"

I have a webservice that reads a JSON object and it was giving me unicodeEncodeError exception. After googling a little bit, I saw How can I convert a dict to a unicode JSON string?
(I followed other questions that were related to unicodeEncodeError but I was still getting AttributeError: 'dict' object has no attribute 'content')
I did what was mentioned in that particular question and now I am getting ..... is not JSON serializable
Can anyone tell me what do I have to do now?
Following is my code:
def someMethod()
some_data = request.data
json_string1 = json.dumps(some_data) #GETTING ERROR ON THIS LINE
json_string2 = get_string(json_string1)
archive = call.send_json(json_string2)
def get_string(value):
find_unicode = re.compile('\\\\u([\da-f]{4})')
def get_parsed_unicode(x):
return chr(int(x.group(1), 16))
return find_unicode.sub(get_parsed_unicode, str(value))
Thanks for the help !!
When you're passing the object to the method, use foo.serealize(true). Include JQUERY to use this.

Categories

Resources