Django test - 'HTTP_USER_AGENT' invalid keyword argument to test client - python

My Django unit tests have stopped working. Instantiating the Django test client now fails with the following error:
Traceback (most recent call last):
File "/vagrant/my/app/tests.py", line 43, in setUp
self.client = Client(HTTP_USER_AGENT='Mozilla/5.0')
File "/usr/local/lib/python2.6/dist-packages/Django-1.4.1-py2.6.egg/django/db/models/base.py", line 367, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
TypeError: 'HTTP_USER_AGENT' is an invalid keyword argument for this function
They fail when I instantiate the Django test client.
from django.test.client import Client
...
class MyAppTestCase(TestCase):
base_fixtures = ['fixtures.json']
def setUp(self):
self.client = Client(HTTP_USER_AGENT='Mozilla/5.0') # fails here
self.setupSession()
self.authenticateUser()
When I run python manage.py shell and enter the following, it works fine.
vagrant#lucid32:/var/www/mytraps.com/spensa$ python manage.py shell
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.test.client import Client
>>> client = Client(HTTP_USER_AGENT='Mozilla/5.0')
>>>
Any thoughts on why it is chocking on the HTTP_USER_AGENT keyword?

I found the solution.
I had a model class named 'Client'. My models were imported after the django test Client class.
You can't fix stupid.

Related

python - NameError on a variable declared outside class

Python newbie and learning how to use a class. I've defined a class which has a method - "create" that uses a parameter (private_key) as part of a command to create a token.
Here's the command:
jwt.encode(payload, private_key, algorithm="RS256", headers=additional_headers).decode("utf-8")
I use a function outside of the class to populate the variable private_key.
Here's the code (myToken.py):
class MyTokenMgr():
def __init__(self):
pass
def create(self, privkey, email):
<MORE CODE HERE TO CREATE TOKEN>
# Function to load key from file
def load_privkey(privkey_filename):
with open(privkey_filename, 'r') as f:
data = f.read()
return data
#Read the private local key
private_key = load_privkey('testkeys/jwt-key')
print('This is the local private key:', private_key)
Here's my problem. When I run python locally from command line. I want to test instantiation of the object. However, I get NameError and variable is not defined
:
$ python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib.myToken import MyTokenMgr
This is the local private key: -----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEAtr454soMHt7IYU+9mM6OmtzOK/i2ajNwtybYY/fQf3vMOUt8
'''
'''
-----END RSA PRIVATE KEY-----
>>> newtoken = MyTokenMgr()
>>> newtoken.create(private_key,'test#gmail.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'private_key' is not defined
You can see that I printed out the variable so I can view the key and confirm its used by the variable. So why am I still getting the is not defined error?
What concept am i misunderstanding? Thanks for your help.
from lib.myToken import MyTokenMgr
You're only importing the symbol MyTokenMgr. If you want to import other symbols, you need to specify them as well when importing:
from lib.myToken import MyTokenMgr, private_key

NameError: name 'sv' is not defined while importing python module

I am facing a problem in python. Tho the error is quite common, but since i am bit new to python, unable to comprehend the source hence asking you all. There are 2 modules: session.py and objects.py.
session.py
import copy
import pymongo
import spacy
import tweepy
import objects
objects.py:
import re
def refresh (sv = sv, obj = ''):
return 0
now, in python shell, i am getting the error before even executing objects.py:
$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import session
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "session.py", line 6, in <module>
import objects
File "objects.py", line 3, in <module>
def refresh (sv = sv, obj = ''):
NameError: name 'sv' is not defined
>>>
I came from perl background to maybe missing some very common thing, but still i am able to do this:
>>> def ff(t): print t
...
In above, whitout defining t, it is working while in objects.py, how can i define sv without starting execution?

Django can't find model property

In my Django project, I have a models.py that looks like this:
from django.db import models
class Battle(models.Model):
def __str__(self):
return self.battle_name
battle_name = models.CharField(max_length=200)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
password = models.CharField(max_length=50)
When I drop to the Django shell (python manage.py shell), I can't interact either of the DateTimeField properties.
$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
Am I missing something?
Let me add a bit of explanation..
Battle.objects.filter(end_time < datetime.datetime.now())
here filter() is a callable that accepts arguments (args or kwargs). With the above code you are trying to pass a boolean value (object < object) to the filter callable as argument. Now, does a boolean value True or False specify anything about a model field?
What you should be doing is pass a keyword argument, namely
Battle.objects.filter(end_time__lt=datetime.datetime.now())
Now the filter() gets the info it needs, the kwarg parameter end_time__lt (which specifies the model field along with the compare method) and the value that needs to be compared with datetime.datetime.now()
You make syntax error
Try this
Battle.objects.filter(end_time__lt=datetime.datetime.now())

Python script for encrypting / decrypting suddenly doesn't work

I'm brushing up on public/private keypair encryption. To illustrate the concept to myself, I wrote a primitive script. It used to work just a week ago with my python client:
> Python 2.7.9 (default, Apr 2 2015, 15:33:21) [GCC 4.9.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
Today, I tried to run it, and got the following error:
work#work-IdeaPad-U330p:~/projects/Script$ python example_encrypt_decrypt.py
Traceback (most recent call last):
File "example_encrypt_decrypt.py", line 9, in <module>
encrypted_message = public_key_1.encrypt(M, 24)
File "/usr/local/lib/python2.7/dist-packages/Crypto/PublicKey/RSA.py", line 123, in __getattr__
raise AttributeError(attrname)
AttributeError: encrypt
The script I'm running is this:
from Crypto.PublicKey import RSA
import binascii
private_key_1 = RSA.generate(1024)
public_key_1 = private_key_1.publickey()
M = "Hello World."
encrypted_message = public_key_1.encrypt(M, 24)
# print binascii.hexlify(encrypted_message[0])
# The private key corresponding to the public key used
# to encrypt the message can decrypt the message.
decrypted_message = private_key_1.decrypt(encrypted_message)
print decrypted_message
# The message can not be decrypted with another
# private key.
private_key_2 = RSA.generate(1024)
print private_key_2.decrypt(encrypted_message)

Catching imaplib exception (using IMAPClient package) in Python

I am using the external library IMAPClient. When the login fails, i see this error : imaplib.error: [AUTHENTICATIONFAILED] Authentication failed.
When i try except imaplib.error: i get : AttributeError: 'module' object has no attribute 'error'
The documentation of imaplib says that the exception should be IMAP4.error
Then why is IMAPClient raising imaplib.error and how do i catch it ?
The error message you see:
imaplib.error: [AUTHENTICATIONFAILED] Authentication failed.
is describing the error as best it knows how; at the time the exception occurs, the exception class is called "imaplib.error", because whoever is raising it has described it that way (more on this later). I poked around, and I think I've found it for you:
Python 2.7.2 (default, Nov 14 2011, 19:37:59)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imaplib
>>> imaplib.IMAP4.error
<class 'imaplib.error'>
I opened up the imaplib.py file, and found what seems like an odd exception-throwing mechanism. "IMAP4" is a class, and "error" is a class defined inside the IMAP4 class. Python doesn't appear to "nest" the classes - just the class definitions. So once an object of class "error" exists, it's an object of class "error" which was defined in the scope "imaplib". The fact that the "error" class definition was inside the "IMAP4" class lib definition is irrelevant to Python. On the other hand, in order for you to describe an object of class "error" before such an object exists, you need to reference it as imaplib.IMAP4.error in order for Python to find the definition of the class you are talking about.
Very confusing, I know, and I didn't really know all of this before I started investigating the question. Here's a brief illustration:
Python 2.7.2 (default, Nov 14 2011, 19:37:59)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo(object):
... class bar(object):
... pass
... def b(self):
... return bar()
...
>>> bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>> foo.bar
<class '__main__.bar'>
>>> foo().bar()
<__main__.bar object at 0x10048dd10>
Basically, you were trying to do a very reasonable thing, but the way the imaplib library handles exception throwing is a little odd, making your life difficult. Long story short, you should try to catch imaplib.IMAP4.error and move on with your life.
(Disclaimer: I'm the maintainer of IMAPClient)
IMAPClient uses imaplib under the hood which is why you're seeing imaplib errors when using it. To simplify things a little, imaplib's exceptions are aliased on to the IMAPClient class. To catch errors from IMAPClient you can do something like this:
from imapclient import IMAPClient
try:
client = IMAPClient(...)
client.do_something(...)
client.logout()
except IMAPClient.Error, err:
# handle error here
Error is the base exception class (same as imaplib.IMAP4.error). There's also AbortError and ReadOnlyError.
IMAPClient uses these exceptions when it raises errors itself so there's only one set of exceptions to worry about in your code.

Categories