Django NoArgsCommand gives NameError: name ' ' is not defined - python

I am trying to make a custom command to run on my celery crontabs, which extracts data from my db, makes a list, and then dumps that information as a list in redis. This list will then be used by other workers.
However, I am getting a NameError, which I haven't been able to solve despite reading relevant stack and Google posts.
My code below:
from django.core.management.base import NoArgsCommand, CommandError
from detail.models import SD
import redis
class Command(NoArgsCommand):
help = 'Gathers the symbols from the database and generates a list for crontabs, saving to redis.'
def handle_noargs(self, **options):
all = SD.objects.all()
data = []
for info in all:
data.append(info.symb)
r = redis.Redis()
try:
r.delete('allsymbols')
except:
pass
for xyz in data: **<---- the NameError refers to this line**
r.rpush('allsymbols', xyz)
TRACEBACK
File "C:\.....command.py", line 5, in <module>
class Command(NoArgsCommand):
File "C:\.....command.py", line 26, in Command
for xyz in data:
NameError: name 'data' is not defined

Script contains mixed tabs and spaces.
You should rather use only spaces, as per pep8, but the choice is yours, as long as you use the same in all your scripts.

Related

How to retrieve the last 5 characters from dictionary value after converting to string

I'm writing a Python script that logs into a server and pulls router data through an api. The pulled data is then used to create a dictionary with router names as the key and a telnet url as the key. Here is an example of the url that's collected.
telnet://192.168.1.113:32769
The telnet port is the last 5 characters of the url and I'm trying to pull that information only. I know with a string I can use (-5) but I'm getting the following error.
Traceback (most recent call last):
File "C:\Users\b\Documents\Atom Test1 Project\test_wip.py", line 41, in <module>
test_value2=test_value.split(-5)
TypeError: must be str or None, not int
[Finished in 1.812s]
I think this means I need to convert it tonto a string. I tried converting and then retrieving the last 5 charcters but it's not working. Here is my code.
from __future__ import unicode_literals, print_function
import eve
import json
import time
from netmiko import ConnectHandler, redispatch
#from resteve import eve
import json
address = '192.168.1.113'
instance = m11.Server(address)
instance.login('admin', 'password', '0')
users = instance.get_all_nodes()
payload = json.loads(users.content)
data = payload['data']
users = instance.get_all_nodes()
payload = json.loads(users.content)
data = payload['data']
for item in payload["data"].values():
result[item["name"]] = item["url"]
test_value=item['url']
print(test_value)
test_value.format(str)
test_value2=test_value.split(-5)
print(test_value2)
I'm new at this and still putting it all together so any help is greatly appreciated. Thanks.
To get last 5 chars use indexing test_value[-5:], because .split() expects a string and here it will try to split on the first argument

Append special character to a value in python

I'm trying to delete all stacks those environments(instances) were terminated. while passing the stack_name to the delete_stack it's throwing an error. I've tried to add the special characters (such as '') to the value of stack_name,but there was no luck. Can someone please help me to fix the issue. Thanks in advance!
#!/usr/bin/env python
import boto
import boto.ec2
import boto.cloudformation
import re
from datetime import datetime, timedelta
utclast = datetime.utcnow() - timedelta(2)
conn = boto.cloudformation.connect_to_region('us-west-1',aws_access_key_id = '<access_key>',aws_secret_access_key = '<secret_key>')
conn_ec2 = boto.ec2.connect_to_region('us-west-1',aws_access_key_id = '<access_key>',aws_secret_access_key = '<secret_key>')
stacks = conn.list_stacks()
for stackSumm in stacks:
pattern = re.compile("Testupload-env([a-zA-Z0-9]+)")
match = pattern.match(stackSumm.stack_name)
if stackSumm.stack_status in "CREATE_COMPLETE" and match and stackSumm.stack_name in match.string:
m = re.split(r'Testupload-', stackSumm.stack_name)
instance = conn_ec2.get_all_instances(filters={"tag:Name": m[1]})
if not instance:
try:
print "Trying to delete stack: %s" % stackSumm.stack_name
conn.delete_stack(stackSumm.stack_name)
except boto.exception.BotoServerError, e:
print e.error_message
Error:
File "delete_stack.py", line 7, in <module>
conn.delete_stack(Testupload-envmeraleb8b01739116b0f36d17a2b5445b949f592bb625-6293)
NameError: name 'Testupload' is not defined
None of you posted code generated the error, but the NameError says that you didn't provide a valid stack name
delete_stack(stack_name_or_id)
Deletes a specified stack. Once the call completes successfully, stack deletion starts. Deleted stacks do not show up in the DescribeStacks API if the deletion has been completed successfully.
Parameters: stack_name_or_id (string) – The name or the unique identifier associated with the stack.
The name/id should be a string, a string in python must be quoted, either by single quotes or double quotes
stack_name = "Testupload-envmeraleb8b01739116b0f36d17a2b5445b949f592bb625-6293"
conn.delete_stack(stack_name)

NameError: name 'TigerXtrm' is not defined

I'm in the process of installing a piece of software from Github: https://github.com/bravecollective/core
It uses MongoDB, Python and WebCore to run. I've managed to get it running and now I've arrived at the part where I need to make myself an admin user. According to the readme, the following needs to be executed in the Paster shell.
from brave.core.account.model import User
from brave.core.character.model import EVECharacter
from brave.core.permission.model import Permission, WildcardPermission
u = User.objects(username=USERNAME_HERE)[0]
u.admin = True
c = u.primary
p1 = Permission.objects(id='core.*').first()
c.personal_permissions.append(p1)
c.save()
u.save()
The username in this case being 'TigerXtrm'. However, when I do this it comes back with the following:
Welcome to the WebCore shell.
from brave.core.account.model import User
from brave.core.character.model import EVECharacter
from brave.core.permission.model import Permission, WildcardPermission
u = User.objects(username=TigerXtrm)[0]
c = u.primary
p1 = Permission.objects(id='core.*').first()
c.personal_permissions.append(p1)
Traceback (most recent call last):
File "console", line 1, in module
NameError: name 'TigerXtrm' is not defined
So NameError: name 'TigerXtrm' is not defined is what creates a problem for me. The user is created and has been entered into the MongoDB database, I've also tried lowercase and e-mail adress, both to no avail. I can't figure out why it's telling me it's not defined. Am I executing it in the wrong place or is there something wrong with the code? Or something else entirely?
That's the Python interpreter complaining because you need to quote TigerXtrm:
u = User.objects(username="TigerXtrm")[0]

Deserialize Protobuf in python from class name

How can I deserialize a protocol buffer message, knowing only the string name of the protoc-generated class?
For some reason, the fully qualified name of the message that I get with DESCRIPTOR.full_name does not match the actual location of the python class, so I am unable to deserialize it with the following function:
def get_class( kls ):
"""Get class given a fully qualified name of a class"""
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
I just get ImportError no module (name).
Any help appreciated.
P.S.: In case it helps, the bigger problem I am trying to solve is to serialize the protobuf message to the database, and then deserialize it back out (I am using postgresql with sqlalchemy in this case). Since regular python pickle doesn't work - I am hoping to store a tuple (message_cls_name, message_binary) where message_cls_name is a fully qualified name of the protobuf message, and message_binary is a result of called SerializeToString on the message. The part I am not clear about is how to get the message out and deserialize it into proper protobuf class.
Here is an example solution..
from ocmg_common.protobuf.rpc_pb2 import Exception as PBException
from importlib import import_module
pb_message = PBException(message='hello world')
pb_message_string = pb_message.SerializeToString()
def deserialize(message, typ):
module_, class_ = typ.rsplit('.', 1)
class_ = getattr(import_module(module_), class_)
rv = class_()
rv.ParseFromString(message)
return rv
print(deserialize(pb_message_string, 'ocmg_common.protobuf.rpc_pb2.Exception'))
will output
(env)➜ httppost git:(master) ✗ python test.py
message: "hello world"
If you dont know the module, but only have the DESCRIPTOR.full_name you have to name them the same way, or create a function that maps a full descriptor name to a module. Otherwise you are stuck and dont know from where to import the module.
I hope it will help you.. ;)
Best of luck..

Generating instances of class in loop gives TypeError: 'list' object is not callable

I've looked through a lot of replies regarding this error, however none was helpfull for my special case and since I'm new to Python, I have difficulties applying the hints to my problem.
I have a class in a file Aheat.py that reads
class Aheat():
name = ""
time = 0
place = 0
def __init__(self,name,time,place):
self.name = name
self.time = time
self.place = place
And a file main.py where I want to read a html file, extract information, and create a list of objects of my class to work with them later on.
The (hopefully) essential part of my main.py reads
import urllib2
import re
from Aheat import Aheat
s = read something from url
ssplit = re.split('<p', s) # now every entry of ssplit contains an event
# and description and all the runners
HeatList = []
for part in ssplit:
newHeat = Aheat("foo",1,1) # of course this is just an example
HeatList.append(newHeat)
But this gives me the following error:
Traceback (most recent call last):
File "/home/username/Workspace/ECLIPSE/running/main.py", line 22, in <module>
newHeat = Aheat("foo",1,1)
TypeError: 'list' object is not callable
which is thrown when performing the second iteration.
If I take out the generation of the object of the loop, i.e.
newHeat = Aheat("foo",1,1)
for part in ssplit:
HeatList.append(newHeat)
My code executes without a problem, but this is not what I want. I'm also not sure, if I can initialize a specific number of instances a priori, since the number of objects is estimated in the loop.
I'm using Eclipse and Python 2.7.
regex is going to bite you.
<p == <pre> || <progress> || <param> || <p> || (any user created directives on a page.)
follow the links in your comments to read up on why we shouldn't parse html with regex.
Thanks, #MarkR ( btw, I was only supplementing your comment and I was agreeing with you )
Why not put the list in your class or better yet extend list functionality with your class.
class AHeat(list):
def append(self,name,time,place):
return super(AHeat,self).append([name,time,place])
# main
heatList= AHeat()
heatList.append("foo",1,2)
heatList.append("bar",3,4)
print(heatList[0])
print(heatList[1])
> ['foo', 1, 2]
> ['bar', 3, 4]
Also

Categories