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
Related
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?
I'm accessing an environment variable in a script with os.environ.get and it's throwing a KeyError. It doesn't throw the error from the Python prompt. This is running on OS X 10.11.6, and is Python 2.7.10.
What is going on?
$ python score.py
Traceback (most recent call last):
File "score.py", line 4, in <module>
setup_logging()
File "/score/log.py", line 29, in setup_logging
config = get_config()
File "/score/log.py", line 11, in get_config
environment = os.environ.get('NODE_ENV')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'NODE_ENV'
$ python -c "import os; os.environ.get('NODE_ENV')"
$
As requested, here's the source code for score.py
from __future__ import print_function
from log import get_logger, setup_logging
setup_logging()
log = get_logger('score')
And here's log.py
import json
import os
import sys
from iron_worker import IronWorker
from logbook import Logger, Processor, NestedSetup, StderrHandler, SyslogHandler
IRON_IO_TASK_ID = IronWorker.task_id()
def get_config():
environment = os.environ.get('NODE_ENV')
if environment == 'production':
filename = '../config/config-production.json'
elif environment == 'integration':
filename = '../config/config-integration.json'
else:
filename = '../config/config-dev.json'
with open(filename) as f:
return json.load(f)
def setup_logging():
# This defines a remote Syslog handler
# This will include the TASK ID, if defined
app_name = 'scoreworker'
if IRON_IO_TASK_ID:
app_name += '-' + IRON_IO_TASK_ID
config = get_config()
default_log_handler = NestedSetup([
StderrHandler(),
SyslogHandler(
app_name,
address = (config['host'], config['port']),
level = 'ERROR',
bubble = True
)
])
default_log_handler.push_application()
def get_logger(name):
return Logger(name)
Try running:
find . -name \*.pyc -delete
To delete your .pyc files.
Researching your problem I came across this question, where a user was experiencing the same thing: .get() seemingly raising a KeyError. In that case, it was caused, according to this accepted answer, by a .pyc file which contained code where a dict value was being accessed by key (i.e., mydict['potentially_nonexistent_key']), while the traceback was showing the code from the updated .py file where .get() was used. I have never heard of this happening, where the traceback references current code from a .py file, but shows an error raised by an outdated .pyc file, but it seems to have happened at least once in the history of Python...
It is a long shot, but worth a try I thought.
I encountered a similar error when I set the environment variable without exporting it. So if you do this:
me#host:/# NODE_ENV=foo
You will get this:
me#host:/# python3
Python 3.8.2 (default, Apr 27 2020, 15:53:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> node_env = os.environ['NODE_ENV']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.8/os.py", line 675, in __getitem__
raise KeyError(key) from None
KeyError: 'NODE_ENV'
>>>
But if you do this:
me#host:/# NODE_ENV=foo
me#host:/# export NODE_ENV
It works:
me#host:/# python3
Python 3.8.2 (default, Apr 27 2020, 15:53:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> node_env = os.environ['NODE_ENV']
>>> print(node_env)
foo
>>>
Command for windows to delete the .pyc files:
del /S *.pyc
I had the same problem. I solved that by making some corrections on the .env file:
Before:
Key = Value
After my correction:
Key=Value
without blank spaces and worked!
I was getting this error while trying to source from a .env file.
I didn't explicitly export the env vars so I had to change this.
ENVIRONMENT=DEV
to this
export ENVIRONMENT=DEV
Use export a=10 instead of a=10 while setting env variable. Add the same in ~./bashrc to reload the env var wherever you login.
Doing this resolved the issue
I'd recommend you start debugging os.py, for instance, on windows it's being used this implementation:
def get(self, key, failobj=None):
print self.data.__class__
print key
return self.data.get(key.upper(), failobj)
And if I test it with this:
import os
try:
os.environ.get('NODE_ENV')
except Exception as e:
print("-->{0}".format(e.__class__))
os.environ['NODE_ENV'] = "foobar"
try:
os.environ.get('NODE_ENV')
except Exception as e:
print("{0}".format(e.__class__))
The output will be:
<type 'dict'>
PYTHONUSERBASE
<type 'dict'>
APPDATA
<type 'dict'>
NODE_ENV
<type 'dict'>
NODE_ENV
So it makes sense the exception is not spawned reading dict.get docs.
In any case, if you don't want to mess up or debugging the python modules, try cleaning up the *.pyc files, try to set up properly NODE_ENV. And if all that don't work, restart your terminal to clear up.
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)
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.
I have this python code for opening a .cfg file, writing to it and saving it:
import ConfigParser
def get_lock_file():
cf = ConfigParser.ConfigParser()
cf.read("svn.lock")
return cf
def save_lock_file(configurationParser):
cf = configurationParser
config_file = open('svn.lock', 'w')
cf.write(config_file)
config_file.close()
Does this seem normal or am I missing something about how to open-write-save files? Is there a more standard way to read and write config files?
I ask because I have two methods that seem to do the same thing, they get the config file handle ('cf') call cf.set('blah', 'foo' bar) then use the save_lock_file(cf) call above. For one method it works and for the other method the write never takes place, unsure why at this point.
def used_like_this():
cf = get_lock_file()
cf.set('some_prop_section', 'some_prop', 'some_value')
save_lock_file(cf)
Just to note that configuration file handling is simpler with ConfigObj.
To read and then write a config file:
from configobj import ConfigObj
config = ConfigObj(filename)
value = config['entry']
config['entry'] = newvalue
config.write()
Looks good to me.
If both places call get_lock_file, then cf.set(...), and then save_lock_file, and no exceptions are raised, this should work.
If you have different threads or processes accessing the same file you could have a race condition:
thread/process A reads the file
thread/process B reads the file
thread/process A updates the file
thread/process B updates the file
Now the file only contains B's updates, not A's.
Also, for safe file writing, don't forget the with statement (Python 2.5 and up), it'll save you a try/finally (which you should be using if you're not using with). From ConfigParser's docs:
with open('example.cfg', 'wb') as configfile:
config.write(configfile)
Works for me.
C:\temp>type svn.lock
[some_prop_section]
Hello=World
C:\temp>python
ActivePython 2.6.2.2 (ActiveState Software Inc.) based on
Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigParser
>>> def get_lock_file():
... cf = ConfigParser.ConfigParser()
... cf.read("svn.lock")
... return cf
...
>>> def save_lock_file(configurationParser):
... cf = configurationParser
... config_file = open('svn.lock', 'w')
... cf.write(config_file)
... config_file.close()
...
>>> def used_like_this():
... cf = get_lock_file()
... cf.set('some_prop_section', 'some_prop', 'some_value')
... save_lock_file(cf)
...
>>> used_like_this()
>>> ^Z
C:\temp>type svn.lock
[some_prop_section]
hello = World
some_prop = some_value
C:\temp>