There are a bunch of people on this site have had a similar questions to mine, but I can't seem to find one that has solved it the way I want it to.
I'm trying to get a password out of a database so that I can send an email automatically. To do this, I am calling Credential.objects.get(username='foo').password.
This is where I get the error.
What's really weird about this is I already had access to this database in a python console, and I've created a row in it. I have no clue why it's not showing up!
Other people seem to recommend doing the following:
try:
Credential.objects.get(username='foo').password
except Exception as e:
return None
All that this is doing is making sure the program doesn't return an error.
This doesn't help me because this can't fail.
An email must be sent and this call must get it.
I'm almost certain I'm calling the right function for this, but I've been wrong before. Any help on this would be greatly appreciated.
credential.py (not putting up max_length for security reasons):
import d_models as models
class Credential(models.Model):
username = models.CharField()
password = EncryptedCharField()
Following may clear your concept.
from django.core.exceptions import ObjectDoesNotExist
try:
Credential.objects.get(username='foo').password
except ObjectDoesNotExist:
#If User with username='foo' does not exist in database then it will comes #in exception.
#Even if there are multiple entries in database with username='foo' then also it will give you error for this you need to use another exception.
return "What ever you want to return on exception"
Or else you can try:
python manage.py shell
for user in Credentials.objects.all():
print username
print password
And check what are the users are available in your database(configured in settings.py file).
After two hours of looking at my code, I realized that I am an idiot.
One thing that I left out was that I ran this function in a test case, which spins up separate blank test databases. The function call wouldn't work because it was trying to get at the wrong database!
To fix this I just called: ./manage.py dumpdata --format json --indent 4 -o ./full/path/to/file/credential.json and put fixtures = ['./full/path/to/file/credential.json'] at the top of the test class. Thanks to everyone for the suggestions! Hopefully I didn't waste too much of your time!
Related
i am trying to execute this very short code that took out from my bigger code because i was having problems with it. I was able to reproduce the problem (it gave the exact same error).
BACKGROUND INFO: i am just trying to get the first sentence out of this wikipedia search. but because the word i am searching for (kip, means chicken in Dutch) has a wide variety of meanings or something i get an error. i want to bypass this error using try: except: but it keeps displaying the error message anyway.
here is the code that just doesnt seem to work:
import wikipedia
wikipedia.set_lang('nl')
try:
summry = wikipedia.summary('kip', sentences=1)
print(summry + "\n")
except:
print("error")
i have tried replacing except: with this
except wikipedia.exceptions.DisambiguationError:
but it still doesnt work :( it always displays the error code regradless and prints "error" afterwards
/opt/virtualenvs/python3/lib/python3.8/site-packages/wikipedia/wikipedia.py:389:
GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML
parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on
another system, or in a different virtual environment, it may use a different parser and behave
differently.
The code that caused this warning is on line 389 of the file
/opt/virtualenvs/python3/lib/python3.8/site-packages/wikipedia/wikipedia.py. To get rid of this
warning, pass the additional argument 'features="html5lib"' to the BeautifulSoup constructor.
lis = BeautifulSoup(html).find_all('li')
error
i am using repl.it to program this
if anyone has any idea about why it keeps displaying the error anyway please please let me know :D
First of all, thank you all for commenting :D it helped a lot
At the end the solution that worked for me was inspired from Askold Ilvento's comment
although
with warnings.catch_warnings(): warnings.simplefilter("ignore")
didn't work when i adapted it a little bit it did the job!
this is the code that solved the problem and allowed me to ignore what was actually a warning (not an exception) and stop displaying it
import warnings
warnings.catch_warnings()
warnings.simplefilter("ignore")
i just added this at the start of the script and it solved the problem :D
once again all the credit for this code goes to Askold Ilvento i just had to add a little bit to it to make it work
I'm working on a Django app.
Somewhere in my code, I use a try/except like this:
for tag in category.get("tags"):
try:
newTag, created = MyObject.objects.update_or_create(title=tag.get("title"))
print("HAHAHA", newTag)
except:
pass
It works well, newTag is saved, but print("HAHAHA", newTag) is never rendered. I don't know why.
Please help
Since you're in a Django app, try
import logging
...
logging.debug('HAHA {}'.format(newTag))
and watch your server logs.
There lots of additional info on logging in the Django docs, https://docs.djangoproject.com/en/2.0/topics/logging/
Adding
It's also a good idea to log exceptions to flush issues out of hiding.
...
except Exception as ex:
logging.warn("Caught {!r}".format(ex))
The logging module has exception() to help with that, but I prefer having more choice on what level an exception is.
I am working off of Safari's Pyramid tutorial
WEB APPLICATIONS WITH PYTHON AND THE PYRAMID FRAMEWORK
Inside of my views.py file I having a problem with the following code:
#property
def current(self):
todo_id = self.request.matchdict.get('id')
todo = sample_todos.get(todo_id)
if not todo:
raise HTTPNotFound()
return todo
particularly when the following view function calls this property
#view_config(route_name='view', renderer='templates/view.jinja2')
def view(self):
return dict(todo=self.current)
when I am running the application http://0.0.0.0:6543/5 will not trigger the anticipated HTTPNotFound(), see route below.
config.add_route('view', '/{id}')
the error logs return:
File "/Users/alex/zdev/t-oreilly/mysite/views.py", line 50, in view
return dict(todo=self.current)
File "/Users/alex/zdev/t-oreilly/mysite/views.py", line 25, in current
raise HTTPNotFound()
pyramid.httpexceptions.HTTPNotFound: The resource could not be found.
On the browser waitress returns a default server error.
What is the proper way to remove this error?
I have uploaded this work to github, commit aaf562e
the tutorial link is here, for those eager to help, it can be accessed with their 10 day trial. This problem is from video 17/48.
thank you, if you need additional information please let me know.
This is a different HTTPNotFound exception and it is raised at the route-matching step before your view is even executed. The reason is that you have config.add_route('view', '/{id}'). Note the /{id} NOT /{id}/. Pyramid considers these two different routes and thus the latter does not match. The simplest solution to this is to register all of our canonical routes with a / suffix such as /{id}/ and then pass append_slash=True to your notfound view configuration such as config.add_notfound_view(..., append_slash=True) or #notfound_view_config(append_slash=True). This will trigger a redirect when a user visits the version without the trailing slash.
In two of your Jinja templates you reference the #property view.current. However, since the property throws an HTTPNotFound() exception, your Jinja templates end up hitting that and explode, causing your problem.
Either remove the calls to view.current from your Jinja templates or modify your view.current function so that it doesn't throw.
I'm not sure if this is the solution you are looking for, but it doesn't deviate from the tutorial.
I'm starting to use Behave to implement some tests. I would like to replace some of my existing unittest (which are more feature tests). Some of these uses assertRaises to check that certain calls to the back-end service raise the errors they should. Is it possible to have something similar in Behave (or maybe rather Gherkin)?
The following unittest calls my backend service and as a guest has logged on, is not able to perform the admin task (do_admin_task). It should raise an exception.
def test_mycall(self):
service = myservice('guest', 'pwd')
self.assertRaises(NoPermission, service.do_admin_task, some_param)
In my feature file, how would I create my scenario? Like this?
scenario: test guest can't do an admin task
given I log on to my service as guest / pwd
when I try to perform my admin task
then it should fail saying NoPermission
I believe that this will already raise an exception in the when step, so won't even get to the then step.
One potential way I could imagine around this is to create a specific step that performs both of these steps and does the exception handling. If I however want to mock errors in lower level calls, then I would have to re-write many of these steps, which is exactly what I'm hoping to avoid by switching to Behave in the first place.
How should I approach this?
When thinking on the Gherkin level, the exception is an expected outcome of the when step. So the step definition should have a try block and store the result/exception in the context. The then step can check this result/exception then.
#When(u'I try to perform my admin task')
def step_impl(context):
try:
context.admintaskresult = myservice(context.user, context.pass)
context.admintaskexception = None
except Exception as ex:
context.admintaskresult = None
context.admintaskexception = ex
#Then(u'it should fail saying NoPermission')
def step_impl(context):
assert isinstance(context.admintaskexception, NoPermissionException)
This problem is partly due to my lack of completely understanding scoping in python, so I'll need to review that. Either way, here is a seriously trivial piece of code that keeps crashing on my Django test app.
Here's a snippet:
#login_required
def someview(request):
try:
usergroup = request.user.groups.all()[0].name
except:
HttpResponseRedirect('/accounts/login')
if 'client' in usergroup:
stafflist = ProxyUserModel.objects.filter(groups__name='staff')
No brain surgery here, the problem is I get an error such as the following:
File "/usr/local/django/myapp/views.py", line 18, in someview
if 'client' in usergroup:
UnboundLocalError: local variable 'usergroup' referenced before assignment
My question here is, why is usergroup unbound? If it's unbound, that means the try statement had an exception thrown at which point an HttpResponseRedirect should happen, but it never does. Instead I get an HTTP 500 error back, which is slightly confusing.
Yes I can write smarter code and ensure that the user logging in definitely has a group associated with them. But this isn't a production app, I'm just trying to understand / learn Python/Django. Why exactly is the above happening when a user that's not associated with a group logs in instead of a redirect to a login page?
In this case I'm intentionally logging in as a user that isn't part of a group. That means that the above code should throw an IndexError exception like the following:
>>> somelist = []
>>> print somelist[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
HttpResponseRedirect('/accounts/login')
You're creating it but not returning it. Flow continues to the next line, which references usergroup despite it never having been assigned due to the exception.
The except is also troublesome. In general you should never catch ‘everything’ (except: or except Exception:) as there are lots of odd conditions in there you could be throwing away, making debugging very difficult. Either catch the specific exception subclass that you think is going to happen when the user isn't logged on, or, better, use an if test to see if they're logged on. (It's not really an exceptional condition.)
eg. in Django normally:
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login')
or if your concern is the user isn't in any groups (making the [0] fail):
groups= request.user.groups.all()
if len(groups)==0:
return HttpResponseRedirect('/accounts/login')
usergroup= groups[0].name
Try moving you if 'client' part inside you try block. Either that or define usergroup = None right above the try.
In cases where you have a try…except suite and you want code to run iff no exceptions have occurred, it's a good habit to write the code as follows:
try:
# code that could fail
except Exception1:
# handle exception1
except Exception2:
# handle exception2
else: # the code-that-could-fail didn't
# here runs the code that depends
# on the success of the try clause