Exceptions in django stop the flow? - python

in my view I am executing this piece of code:
try:
activeterm = LeaseTerm.objects.get(lease=lease, is_active = True)
except LeaseTenant.DoesNotExist:
activeterm = None
And I expected there will be no value in LeaseTerm I will get exception but I am getting an error:
LeaseTerm matching query does not exist.
But I expected that I have handled the exception and flow should continue.
What is my miss understanding?

Please retry with:
try:
activeterm = LeaseTerm.objects.get(lease=lease, is_active = True)
except LeaseTerm.DoesNotExist: # LeaseTerm
activeterm = None

Related

Keep getting this error not sure why "Can't convert 'set' object to str implicitly"

#admin.register(Book)
class BookAdmin(ImportExportActionModelAdmin):
resource_class = BookResource
def get_import_form(self):
return CustomImportForm
def get_resource_kwargs(self, request, *args, **kwargs):
rk = super().get_resource_kwargs(request, *args, **kwargs)
rk['input_author'] = None
if request.POST:
author = request.POST.get('input_author', None)
if author:
request.session['input_author'] = author
else:
try:
author = request.session['input_author']
except KeyError as e:
raise Exception("Context failure on row import" + {e})
rk['input_author'] = author
return rk
Have this code in django admin page, but getting an error during the export. Can anyone let me know where is the issue?
Your issue is on this line:
raise Exception("Context failure on row import" + {e})
The ‘{e}’ means that you create a set containing the error, and try to join it to the exception message string. You should be able to get rid of that error by replacing ‘{e}’ with just ‘e’.

AttributeError: instance has no attribute error in Linux only

I am getting the AttributeError: PortalTesting instance has no attribute 'reporting_screenshot' error in Linux only. When I run this code on Windows, its working as expected.
#!/usr/bin/env python
class PortalTesting:
def __init__(self):
self.start_time = time.time()
self.status = OrderedDict()
self.screenshots_folder = ''
self.new_folder_name = ''
self.tday = datetime.today().strftime('%Y%m%d-%H%M')
self.dt = date.today() - timedelta(2)
self.start_date = self.dt.strftime('%m-%d-%Y')
# self.reporting_screenshot = ''
# self.transcript = ''
def login(self):
try:
URL = ''
driver.get(URL)
# ------------------- Transcript ------------------- #
def transcript(self):
try:
tr_e1 = driver.find_element_by_id('Transcript_ID')
hover1 = ActionChains(driver).move_to_element(tr_e1)
hover1.click().perform()
....
....
self.transcript_screenshot = self.path + self.tday + "_Transcripts.png"
driver.get_screenshot_as_file(self.transcript_screenshot)
self.status['Transcript'] = ["Pass", self.transcript_screenshot]
# THIS IS WHERE I GET ERROR
except:
self.status['Transcript'] = ["Fail", self.transcript_screenshot]
# ------------------- Reporting ------------------- #
def reporting(self):
try:
# Reports tab
rpt_e1 = driver.find_element_by_id('report_menu_id')
hover1 = ActionChains(driver).move_to_element(rpt_e1)
hover1.click().perform()
.....
.....
WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.ID, 'PortalChartContainer'))).click()
self.reporting_screenshot = self.tday + "_Reports.png"
driver.get_screenshot_as_file(self.path + self.reporting_screenshot)
print("Reporting check complete.")
self.status['Reporting'] = ["Pass", self.reporting_screenshot]
# THIS IS WHERE I GET ERROR
except:
self.status['Reporting'] = ["Fail", self.reporting_screenshot]
pt = PortalTesting()
pt.login()
pt.reporting()
pt.transcript()
pt.admin()
pt.print_status()
What I am doing here is, login to URL. Run reports/ transcript. If success, add Pass and screenshot to self.status dictionary. If fails, add Fail and screenshot to self.status dictionary.
Above code works fine on Windows but, gives error when I copy paste same code on Linux.
If I add self.transcript = '' and self.reporting_screenshot = '' in __init__, I get TypeError: 'str' object is not callable
Traceback Error:
Traceback (most recent call last):
File "DC1PortalTesting.py", line 477, in <module>
pt.reporting()
File "DC1PortalTesting.py", line 375, in reporting
self.status['Reporting'] = ["Fail", self.reporting_screenshot]
AttributeError: PortalTesting instance has no attribute 'reporting_screenshot'
I would really appreciate your help.
#merlyn is right: the first error arise because of you try/except statement in the definition of reporting(). If any error pops up before self.reporting_screenshot = self.tday + "_Reports.png", then the attribute does not exist, and the except clause will raise this error.
Two suggestions here:
self.reporting_screenshot should be create at first in the definition of reporting(), because all its components already exist at this point.
def reporting(self):
self.reporting_screenshot = self.tday + "_Reports.png"
try:
# Reports tab
rpt_e1 = driver.find_element_by_id('report_menu_id')
hover1 = ActionChains(driver).move_to_element(rpt_e1)
hover1.click().perform()
.....
.....
WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.ID, 'PortalChartContainer'))).click()
# Removed line here
driver.get_screenshot_as_file(self.path + self.reporting_screenshot)
print("Reporting check complete.")
self.status['Reporting'] = ["Pass", self.reporting_screenshot]
...
Catch the error in your except statement, for debugging purpose.
...
# THIS IS WHERE I GET ERROR
except Exception as e: # catches any exception
# print(e) # uncomment for debugging, or make it smarter with a switch
self.status['Reporting'] = ["Fail", self.reporting_screenshot]
Regarding the other error: #merlyn also provided an explanation in his comment.
Regarding why your code fails on Linux: I assume it is working on Windows so you never tested the except clause there, right?

raise in raise error

I have an error raise eb : list index out of range.
I don't understand why when i do a raise in an other try - catch
I'm doing a try - catch in a try - catch and both raises errors.
Here is my code and the error line is at raise eb :
try:
print("debut edit")
print(p)
modif_box = get_modif_box_profile(p)
post_box = get_Post_Box(p)
print("modi_box")
print(modif_box)
print("mbu id")
print(modif_box.id)
diff = {}
posts = {}
new_post = []
diff["posts"] = posts
posts["modified_post"] = new_post
for post in modif_box.edit_post_user.all():
# print(post.id_mod)
try:
messagenew = post_box.post.all().filter(id=post.id_mod)[0]
# print(post_new)
print("posts")
print(post)
# todo a factoriser
if messagenew.id > int(last_id) and messagenew.sender.id != p.id:
name = get_name_contact(p, messagenew)
return_post = {}
return_post["uid"] = messagenew.sender.id
return_post["pid"] = messagenew.id
return_post["author"] = name
return_post["title"] = messagenew.title
return_post["date"] = unix_time_millis(messagenew.date)
return_post["smile"] = count_smile(messagenew)
return_post["comment"] = count_comment(messagenew)
return_post["data"] = messagenew.data
return_post["type"] = messagenew.type_post.type_name
new_post.append(return_post)
else:
print("depop edit")
modif_box.edit_post_user.remove(post)
modif_box.save()
except Exception as eb:
PrintException()
# raise eb (if i decomment here i have an error in my program)
print(diff)
return diff
except Exception as e:
PrintException()
raise e
Regards and thanks
If you comment the raise statement there, it doesn't mean that you don't have an Error; it simply means that you handled the Exception -- which in your case is from what I can tell an IndexError -- by catching it with the except Exception and then calling PrintException().
When you raise an exception what you actually do is:
The raise statement allows the programmer to force a specified exception to occur.
So, by un-commenting, you allow the IndexError named eb to re-appear after catching it in the inner try-except block and get caught by the outer try - except clause in which you again re-raise it.
Generally, you don't want to catch exceptions in such a generic way because it might hide some unpredicted behaviour of the program that you would like to know about.
Limit the exceptions you catch in the except clause by simply specifying them, in your case, an except clause of the form:
except IndexError as eb:
PrintException()
would probably suffice.

Verify if a topic exists based on topic name

I'm trying to verify if a topic exists based on topic name.
Do you know if this is possible?
For example I want to verify if topic with name "test" already exist.
Below is what I'm trying but doesn't work because topicsList contains topicArns and not topicNames...
topics = sns.get_all_topics()
topicsList = topics['ListTopicsResponse']['ListTopicsResult'['Topics']
if "test" in topicsList:
print("true")
This code will work if you have more than 100 topics
def get_topic(token=None):
topics = self.sns.get_all_topics(token)
next_token = topics['ListTopicsResponse']['ListTopicsResult']['NextToken']
topic_list = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
for topic in topic_list:
if "your_topic_name" in topic['TopicArn'].split(':')[5]:
return topic['TopicArn']
else:
if next_token:
get_topic(next_token)
else:
return None
What if you try to catch An error occurred (NotFound) when calling the GetTopicAttributes operation: Topic does not exist exception?
from botocore.exceptions import ClientError
topic_arn = "arn:aws:sns:us-east-1:999999999:neverFound"
try:
response = client.get_topic_attributes(
TopicArn=topic_arn
)
print "Exists"
except ClientError as e:
# Validate if is this:
# An error occurred (NotFound) when calling the GetTopicAttributes operation: Topic does not exist
print "Does not exists"
This is kind of a hack but it should work:
topics = sns.get_all_topics()
topic_list = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
topic_names = [t['TopicArn'].split(':')[5] for t in topic_list]
if 'test' in topic_names:
print(True)

AttributeError: 'NoneType' object has no attribute 'userName'

reqUser = friends.UserFriends.gql("where udid =:1", str(udid) ).get()
reqUserName = reqUser.userName
This is my code i want to know how to handle this error, this error comes at line 2
you can use pythons try/except pair.
reqUser = friends.UserFriends.gql("where udid =:1", str(udid) ).get()
try:
reqUserName = reqUser.userName
except AttributeError:
reqUserName = "No username found!"
this catches only AttributeError exceptions, so anything else will still be raised.

Categories