Object is not subscriptable in django - python

I have this function in django:
def get_customer(request):
resp = dict(succees=False, message='no se encontro clientes')
database = request.user.company_select.company_db
try:
customers = Customer.objects.using(database).get(id_customers=request.data['id_customer'])
if customers:
list_customers = list()
customers['subgroup_p'] = Customer_Subgroup.objects.using(database).values().filter(id_subgroup=customers['customers_subgroup'])
customers['group_p'] = Customer_Group.objects.using(database).values().filter(id_group=customers['subgroup_p']['group_id'])
customers['customers_subgroup_p'] = Catalog_Type_Customer.objects.using(database).values().filter(id_type_customer=customers['customers_type'])
customers['city_p'] = City.objects.values().filter(city_id=customers['city'])
customers['state_p'] = State.objects.values().filter(state_id=customers['city_p']['state_id'])
customers['country_p'] = Country.objects.values().filter(country_id=customers['state_p']['country_id'])
list_customers.append(customers)
resp.update(dict(success=True, message='', customers=list_customers))
except Exception as e:
print(e)
resp.update(dict(message='Error'))
return Response(resp)
But i get the error ´Customer´ is not subscriptable
What can i do to solve this?
Thanks!

You're trying to access a django model object property as dict but you need to access it as a property using .property_name like customers.subgroup_p.
try this:
def get_customer(request):
resp = dict(succees=False, message='no se encontro clientes')
database = request.user.company_select.company_db
try:
customers = Customer.objects.using(database).get(id_customers=request.data['id_customer'])
if customers:
list_customers = list()
customers.subgroup_p = Customer_Subgroup.objects.using(database).values().filter(id_subgroup=customers.customers_subgroup)
customers.group_p = Customer_Group.objects.using(database).values().filter(id_group=customers.subgroup_p.group_id)
customers.customers_subgroup_p = Catalog_Type_Customer.objects.using(database).values().filter(id_type_customer=customers.customers_type)
customers.city_p = City.objects.values().filter(city_id=customers.city)
customers.state_p = State.objects.values().filter(state_id=customers.city_p.state_id)
customers.country_p = Country.objects.values().filter(country_id=customers.state_p.country_id)
list_customers.append(customers)
resp.update(dict(success=True, message='', customers=list_customers))
except Exception as e:
print(e)
resp.update(dict(message='Error'))
return Response(resp)

Related

Django can't set attribute while changing media file url

I'm creating a function where I want the directory of the file changes if the image_type changes, for example if the image_type is aerial_view it should be in 1 folder and it if it is detailed_view it should move to another.
The file is able to move succesfully, however I'm facing can't set attribute while changing url of the image.
I'm not sure if this is the best way to change folder of a MEDIA file, I'd like suggestions if there's a better way.
def post(self, request):
image_ids = dict((request.data).lists())['image_id']
image_types = dict((request.data).lists())['image_type']
arr = []
for img_id, img_type in zip(image_ids, image_types):
image_qs = RoofImages.objects.get(id=img_id)
image_qs.image_type = img_type
print(BASE_DIR)
try:
if image_qs.image_type == 'detailed_view':
full_image_url = f'{BASE_DIR}{image_qs.image.url}'
full_new_image_url = full_image_url.replace('aerial_view', 'detailed_view')
shutil.move(full_image_url, full_new_image_url)
image_qs.image.url = str(image_qs.image.url).replace('aerial_view', 'detailed_view')
except Exception as e:
print(e)
try:
if image_qs.image_type == 'aerial_view':
full_image_url = f'{BASE_DIR}{image_qs.image.url}'
full_new_image_url = full_image_url.replace('detailed_view', 'aerial_view')
shutil.move(full_image_url, full_new_image_url)
image_qs.image.url = str(image_qs.image.url).replace('detailed_view', 'aerial_view')
except Exception as e:
print(e)
arr.append({img_id: img_type})
image_qs.save()
response_content = {
'status': True,
'message': 'Images type change successfully.',
'result': arr
}
return Response(response_content, status=status.HTTP_201_CREATED)
A little googling worked, we can change the attribute using instance.field.name instead of instance.field.url.
try:
if image_qs.image_type == 'detailed_view':
full_image_url = f'{BASE_DIR}{image_qs.image.url}'
full_new_image_url = full_image_url.replace('aerial_view', 'detailed_view')
shutil.move(full_image_url, full_new_image_url)
new_image_url = str(image_qs.image.url).replace('aerial_view', 'detailed_view')
image_qs.image.name = new_image_url
except Exception as e:
print(e)
try:
if image_qs.image_type == 'aerial_view':
full_image_url = f'{BASE_DIR}{image_qs.image.url}'
full_new_image_url = full_image_url.replace('detailed_view', 'aerial_view')
shutil.move(full_image_url, full_new_image_url)
new_image_url = str(image_qs.image.url).replace('detailed_view', 'aerial_view')
image_qs.image.name = new_image_url
except Exception as e:
print(e)

Cannot get the python test to assert an Exception was thrown

Code:
class ContributionHandler:
def __init__(self):
MetricsConfigurator.setup_metrics("ContributionMutationResolverLambda")
self.entity_linkage_authority_client_factory = EntityLinkageAuthorityClientFactory()
self.entity_linkage_authority_client = self.entity_linkage_authority_client_factory.get_client()
#retry(delay=0.5, tries=2)
def create_contribution(self, input_event):
"""
Calls Entity Linkage Authority to create a contribution between PEs
:return: the contribution created
"""
from_pe = input_event[constants.FROM_PE]
to_pe = input_event[constants.TO_PE]
logging.info(f"Creating contribution from PE: {from_pe} to PE: {to_pe}")
try:
response = self.__create_contribution_call(input_event)
return response
except Exception as e:
logging.info(f"Error creating the contribution from PE: {from_pe} to PE: {to_pe}")
raise e
#retry(delay=0.5, tries=2)
#metric_time
#metric_count
#metric_errors(verbose=True)
def __create_contribution_call(self, input_event):
"""
Separate retryable private function for api call with the client.
"""
relationship_contribution_info = RelationshipContributionInfo(input_event[constants.FROM_PE],
input_event[constants.TO_PE], input_event[constants.RELATIONSHIP_TYPE],
input_event[constants.INTENT], input_event[constants.IS_NEGATIVE])
audit_info = AuditInfo(input_event[constants.AUDIT_INFO][constants.CREATED_BY],
input_event[constants.AUDIT_INFO][constants.CREATED_AT])
try:
return self.entity_linkage_authority_client.create_relationship\
(CreateRelationshipRequest(relationship_contribution_info, audit_info))
except Exception as e:
logging.info("Recreating the client as Credentials expired1")
if isinstance(e, ClientError) and e.response['Error']['Code'] == 'ExpiredToken':
logging.info("Recreating the client as Credentials expired2")
self.entity_linkage_authority_client_factory = EntityLinkageAuthorityClientFactory()
self.entity_linkage_authority_client = self.entity_linkage_authority_client_factory.get_client()
raise e
Test case:
#mock.patch(METRICS_IMPORT_PATH + '.setup_metrics')
#mock.patch(ENTITY_LINKAGE_AUTHORITY_CLIENT_FACTORY_IMPORT_PATH + '.get_client')
#mock.patch(ENTITY_LINKAGE_AUTHORITY_CLIENT_FACTORY_IMPORT_PATH + '.__init__')
def test_create_contribution_handler_token_expiry(mock_client_factory_init, mock_get_client, mock_metrics):
mock_metrics.return_value = None
mock_client_factory_init.return_value = None
error_response = {"Error": {"Code": "ExpiredToken"}}
mock_get_client.return_value.create_relationship(mock.ANY).raiseError.side_effect = ClientError(error_response, "Expired Token")
contribution_handler = ContributionHandler()
with pytest.raises(ClientError) :
contribution_handler.create_contribution(CONTRIBUTION_INPUT)
# make sure we retried 3 times
# assert 3 == mock_client_factory_init.call_count
Output:
Test case is failing with following output:
[CPython36:setup:stdout] with pytest.raises(ClientError) :
[CPython36:setup:stdout] > contribution_handler.create_contribution(CONTRIBUTION_INPUT)
[CPython36:setup:stdout] E Failed: DID NOT RAISE

Getting Array keys in POST method using POSTMAN in Python 3 Flask-Restful API

How to get the value of array in postman using parser = reqparse.RequestParser() in flask api?
Im getting an error says: NoneType' object is not subscriptable
And here is my code:
class CreateUser(Resource):
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username', type = str)
args = parser.parse_args()
name = args['username'][0]
return name
except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
finally:
if conn is not None:
conn.close()
im getting error with this name = args['username'][0] and i also try to make this too name = args[0]['username'] and still error appears and when i just make this like name = args['username'] the postman replies null. please help me.
Use this
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username[0]', type = str)
parser.add_argument('username[1]', type = str)
args = parser.parse_args()
name = args['username[0]']
return name
except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
finally:
if conn is not None:
conn.close()
Editing for multiple params
form data should be like this
username: "user1"
username: "user2"
username: "user3"
Yes you can pass multiple values with same key
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username', type = str, action='append')
args = parser.parse_args()
name = args['username']
print(name) # ['user1', 'user2','user3'] you can traverse over this list

TypeError: Model constructor takes no positional arguments

While creating an answer for a question in the API (see code below), I got the following error:
TypeError: Model constructor takes no positional arguments
Can someone tell me how to solve this? I am using ndb model
import webapp2
import json
from google.appengine.ext import ndb
class AnswerExchange(ndb.Model):
answer=ndb.StringProperty(indexed=False,default="No Message")
class AnswerHandler(webapp2.RequestHandler):
def create_answer(self,question_id):
try:
query = StackExchange.query(StackExchange.questionId == question_id)
questions = query.fetch(1)
ans_json = json.loads(self.request.body)
answerObj = AnswerExchange(answer=ans_json["answer"])
answerObj.put()
questions.answerName=answerObj
questions.put()
except:
raise webapp2.exc.HTTPBadRequest()
class StackExchange(ndb.Model):
questionId=ndb.StringProperty(indexed=True)
questionName=ndb.StringProperty(indexed=False)
#answerID=ndb.StringProperty(indexed=True)
answerName=ndb.StructuredProperty(AnswerExchange,repeated=True)
class StackHandler(webapp2.RequestHandler):
def get_questions(self):
#p = self.request.get('p') #get QueryString Parameter
#self.response.write(p)
query = StackExchange.query()
questions = query.fetch(6)
self.response.content_type = 'application/json'
self.response.write(json.dumps([d.to_dict() for d in questions]))
def get_question(self, question_id):
query = StackExchange.query(StackExchange.questionId == question_id)
questions = query.fetch(1)
self.response.content_type = 'application/json'
self.response.write(json.dumps([d.to_dict() for d in questions]))
def create_question(self):
try:
question_json = json.loads(self.request.body)
# if id in dept_json:
questionNo = question_json["questionId"]
questionToUpdate = StackExchange.query(StackExchange.questionId == questionNo);
#print deptToUpdate.count()
if questionToUpdate.count() == 0:
question = StackExchange(questionId=question_json["questionId"], questionName=question_json["questionName"])
else:
question = questionToUpdate.get()
question.questionName = question_json["questionName"]
#key = dept.put()
question.put()
except:
raise webapp2.exc.HTTPBadRequest()
self.response.headers['Location'] = webapp2.uri_for('get_question', question_id=questionNo)
self.response.status_int = 201
self.response.content_type = 'application/json'
#self.response.write(json.dumps())
def create_answer(self,question_id):
#try:
question_json = json.loads(self.request.body)
questionNo = question_json["questionId"]
query = StackExchange.query(StackExchange.questionId == questionNo)
questions = query.fetch(1)
ans_json = json.loads(self.request.body)
answerObj = AnswerExchange(ans_json["answer"])
#answerObj.put()
#self.response.write(ans_json["answerName"])
questions.answerName = answerObj
questions.put();
#except:
# raise webapp2.exc.HTTPBadRequest()
def get_answer(self, question_id):
query = StackExchange.query(StackExchange.questionId == question_id)
questions = query.fetch(1)
self.response.content_type = 'application/json'
self.response.write(json.dumps([d.to_dict() for d in questions]))
app = webapp2.WSGIApplication([
webapp2.Route(r'/api/v1/questions/<question_id>', methods=['GET'], handler='api.StackHandler:get_question', name='get_question'),
webapp2.Route(r'/api/v1/questions', methods=['GET'], handler='api.StackHandler:get_questions', name='get_questions'),
webapp2.Route(r'/api/v1/questions', methods=['POST'], handler='api.StackHandler:create_question', name='create_question'),
webapp2.Route(r'/api/v1/questions/<question_id>/answers', methods=['POST'], handler='api.StackHandler:create_answer', name='create_answer'),
webapp2.Route(r'/api/v1/questions/<question_id>/answers', methods=['GET'], handler='api.StackHandler:get_answer', name='get_answer')
], debug=True)
Change,
answerObj = AnswerExchange(ans_json["answer"])
in create_answer method StackHandler class
to
answerObj = AnswerExchange(answer=ans_json["answer"])

Strange error, Exception Value: type object has no attribute 'DoesNoExist'

I have this code. and i dont understand why it shows the error that i seem not to put the DoesNotExist handler when is already there.... and shows me this error:
AttributeError at /hotel/edit/hotel-riodssdfsdf-google-facebook-351/
type object 'hotel' has no attribute 'DoesNoExist'
Request Method: GET Request URL:
http::9000/hotel/edit/hotel-riodssdfsdf-google-facebook-351/ Django
Version: 1.6.2 Exception Type: AttributeError Exception Value:
type object 'hotel' has no attribute 'DoesNoExist'
Exception Location: views.py in update, line 171
LINE 171 is correct....: except hotel.DoesNoExist:
if 'member_id' not in request.session:
return HttpResponseRedirect('/login/')
else:
if request.POST:
try:
hotelObject = hotel.objects.get(slug=slug)
form = UpdateHotelForm(request.POST, instance=hotelObject)
if form.is_valid():
now = datetime.datetime.now()
name = form.cleaned_data['name']
slug_name = slugify(name + ' ' + str(now.microsecond))
hotels = hotel.objects.get(
id=hotelObject.id,
publisher=request.session['member_id'])
hotels.name = name
hotels.slug = slug_name
hotels.save()
args = {}
args.update(csrf(request))
args['form'] = form
args['message'] = False
args['name'] = hotelObject.name
return HttpResponseRedirect('/hotel/edit/' + slug_name)
else:
args = {}
args.update(csrf(request))
args['form'] = form
args['message'] = True
args['name'] = hotelObject.name
return render_to_response('hotel/edit_hotel.html', args)
except hotel.DoesNoExist:
return HttpResponseRedirect('/hotel/')
else:
try:
hotelObject = hotel.objects.get(slug=slug)
form = UpdateHotelForm(request.POST, instance=hotelObject)
form = UpdateHotelForm(instance=hotelObject)
args = {}
args.update(csrf(request))
args['form'] = form
args['name'] = hotelObject.name
return render_to_response('hotel/edit_hotel.html', args)
except hotel.DoesNoExist:
return HttpResponseRedirect('/hotel/')
The correct is hotel.DoesNotExist not hotel.DoesNoExiste a
You misspelled DoesNotExist as DoesNoExist. Change it to:
except hotel.DoesNotExist:

Categories