ValueError: [TypeError("'_cffi_backend.FFI' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')] in FastAPI - python

I am working with FastAPI and Firestore and I created a very basic endpoint to read all the documents in a collection. However, I get the following error when I run my code and I can't seem to figure out where it's coming from.
ValueError: [TypeError("'_cffi_backend.FFI' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
The code that I have used is below:
#router.get("/reviews/{review_id}")
def read_review(review_id: str):
# Get all documents in the Reviews collection
db = firestore.client()
reviews_ref = db.collection('Reviews')
docs = reviews_ref.stream()
output = {}
for doc in docs:
output[doc.id] = doc.to_dict()
return output
I am not sure why this error is being generated and I couldn't find anything related to the FastAPI for this error.

Related

Cannot (always) fetch an attribute in an object even though it exists

I'm currently developing locally an Azure function that communicates with Microsoft Sentinel, in order to fetch the alert rules from it, and more specifically their respective querys :
credentials = AzureCliCredential()
alert_rules_operations = SecurityInsights(credentials, SUBSCRIPTION_ID).alert_rules
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv('RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
The issue is that when I'm looping over list_alert_rules, and try to see each rule's query, I get an error:
Exception: AttributeError: 'FusionAlertRule' object has no attribute 'query'.
Yet, when I check their type via the type() function:
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv(
'RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
for rule in list_alert_rules:
print(type(rule))
##console: <class 'azure.mgmt.securityinsight.models._models_py3.ScheduledAlertRule'>
The weirder issue is that this error appears only when you don't print the attribute. Let me show you:
Print:
for rule in list_alert_rules:
query = rule.query
print('query', query)
##console: query YAY I GET WHAT I WANT
No print:
for rule in list_alert_rules:
query = rule.query
...
##console: Exception: AttributeError: 'FusionAlertRule' object has no attribute 'query'.
I posted the issue on the GitHub repo, but I'm not sure whether it's a package bug or a runtime issue. Has anyone ran into this kind of problems?
BTW I'm running Python 3.10.8
TIA!
EDIT:
I've tried using a map function, same issue:
def format_list(rule):
query = rule.query
# print('query', query)
# query = query.split('\n')
# query = list(filter(lambda line: "//" not in line, query))
# query = '\n'.join(query)
return rule
def main(mytimer: func.TimerRequest) -> None:
# results = fetch_missing_data()
credentials = AzureCliCredential()
alert_rules_operations = SecurityInsights(
credentials, SUBSCRIPTION_ID).alert_rules
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv(
'RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
list_alert_rules = list(map(format_list, list_alert_rules))
I have tried with same as you used After I changed like below; I get the valid response.
# Management Plane - Alert Rules
alertRules = mgmt_client.alert_rules.list_by_resource_group('<ResourceGroup>')
for rule in alertRules:
# Try this
test.query = rule.query //Get the result
#print(rule)
if mytimer.past_due:
logging.info('The timer is past due!')
Instead of this
for rule in list_alert_rules:
query = rule.query
Try below
for rule in list_alert_rules:
# Try this
test.query = rule.query
Sorry for the late answer as I've been under tons of work these last few days.
Python has an excellent method called hasattr that checks if the object contains a specific key.
I've used it in the following way:
for rule in rules:
if hasattr(rule, 'query'):
...
The reason behind using this is because the method returns object of different classes, however inherited from the one same mother class.
Hope this helps.

getting object has no attribute 'get' or object is not subscriptable when trying to access JSON response converted to DTO

I'm trying to access a JSON response, I've trying with get() method and I'm getting the "object has no attribute 'get'" error and when I tried it with [] I'm getting the "object is not subscriptable" error.
The response is valid, as I've printed it just before the get operation and all looks ok.
Did not had such problem parsing a response before.
def get_return_params_and_identifiers(return_params):
print("******** res start **********")
print(return_params)
print("******** res end **********")
return_parameters = return_params.get('return_parameters')
Here is part of a response:
******** res start **********
{'levels': None,
'return_parameters': [{'identifier_name': 'Premium',
'level': None,
'return_parameter_name_pk': 1258407,
'return_parameters_details': [{'base_parameter_name': 'Premium '
'Parameter',
'base_parameter_pk': 1149913,
'class_value': None,
....
....
Did anybody encountered such and have any idea what is happening.
EDIT:
Tried with json.loads() but the response is a DTO and not JSON anymore and thus getting the other error:
TypeError: the JSON object must be str, bytes or bytearray, not DTO
The DTO class is below:
class ReturnParametersContainerDTO(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'return_parameters': 'list[ReturnParameterDTO]',
'levels': 'LevelsDTO'
}
attribute_map = {
'return_parameters': 'returnParameters',
'levels': 'levels'
}
It clearly says that the items in the class are dictionary, but somehow it does not recognize it.
Ok, I solved the issue.
It was something in the implementation of the OpenApi's generated DTO class, that showed it as a dictionary (in to_str() method it called to_dict() and prints it as a dictionary) but in fact those were just properties, so used the method to_dict() (in swagger's generated class) to convert it to dictionary.
Now all works.

ROS2, TypeError when publishing custom message to Topic (python)

I have defined a custom message: uint8[] data
The custom message is imported in my Node class with no problems: from my_shared.msg import MyMessage
In the same Node, I create the publisher with: self.my_publisher = self.create_publisher(MyMessage, 'topic_in', 200)
and I publish the message with: self.my_publisher.publish(my_msg)
my_msg is built in the following way:
payload_bitstream = np.fromstring(my_data, np.uint8)
my_msg = payload_bitstream.tolist()
Sadly, I get a TypeError: File "/opt/ros/eloquent/lib/python3.6/site-packages/rclpy/publisher.py", line 68, in publish raise TypeError() TypeError
Could you help out with this if you know what I am doing wrong pls?
Thanks in advance, G.
The issue is in your assignment of my_msg, which is an instance of the class MyMessage containing attributes defined in the my_shared.msg file, namely my_msg.data which has type of uint8[]. It's correct that you did payload_bitstream.tolist() to get a list of native python ints with uint8 values, but you need to assign it to the data attribute. TL;DR:
my_msg.data = payload_bitstream.tolist()

Newbie in Python [2.7] function not working

I am using a script i've downloaded from the web to access our service API.
I am trying to run the function, but keep getting errors no matter what I am trying to do.
from PyBambooHR import PyBambooHR
bamboo = PyBambooHR(subdomain='domain', api_key='apicode')
changes = bamboo.get_employee_changes()
When I run this, I get the following error:
ValueError: Error: since argument must be a datetime.datetime instance
Now, no matter what I set as arguments, I still getting errors. I've also tried the syntax from: https://www.bamboohr.com/api/documentation/changes.php
The function is:
def get_employee_changes(self, since=None):
"""
Returns a list of dictionaries, each with id, action, and lastChanged keys, representing
the employee records that have changed since the datetime object passed in the since= argument.
#return List of dictionaries, each with id, action, and lastChanged keys.
"""
if not isinstance(since, datetime.datetime):
raise ValueError("Error: since argument must be a datetime.datetime instance")
url = self.base_url + 'employees/changed/'
params = {'since': since.strftime('%Y-%m-%dT%H:%M:%SZ')}
r = requests.get(url, params=params, headers=self.headers, auth=(self.api_key, ''))
r.raise_for_status()
return utils.transform_change_list(r.content)
Thanks for your help
As you see in that function is a parameter since of type datetime.datetime expected.
import datetime
changes = bamboo.get_employee_changes(since=datetime.datetime.now() - datetime.timedelta(days=365))
Should give you the changes since last year
Pass a variable of type datetime.datetime while calling the function bamboo.get_employee_changes()

Passing a variable to a JSON web service

I am accessing the class from the code api_service.py, which can be found here. When I call the first function, I have no problem, because no variables are passed:
from api_service import ApiService
import json
def main():
api_key = *removed*
access_token = *removed*
calling = ApiService(api_key,access_token)
survey_list = calling.get_survey_list()
But when I use the same type of routine as above to call a function from ApiService that requires a variable, I'm told that I should pass an object.
survey_details = calling.get_survey_details("1234")
survey_details = json.loads(json.dumps(survey_details))
print survey_details
The specific error message:
{u'status': 3, u'errmsg': u"Value '1234' for field '_data' is not of type object"}
Details for the get_survey_details aspect of the SurveyMonkey API are here, although I think a python-guru can solve this without knowing about the API.
This is a javascript/json object:
{field:'value'}
You have passed a string which, doesn't count as an "object" for these purposes.
Note that the error message is being generated by the service you are accessing. This question would be better directed to the creator of the service.

Categories

Resources