Issue with python object/class "instance has no attribute" from external PythonServerPage - python

So I created this class called BigIPLTM in a python script file named pycontrol.py. I also have a python server page which imports the script and creates an object. I am running into an issue when trying to call methods of this object. Error is BigIPLTM has no instance of get_pool_name. Here is my code: Also any feedback on my class would be great, since it is the first class I have written in python.
pycontrol.py:
import pycontrol.pycontrol as pycontrol
class BigIPLTM:
def __init__(self, host, user="xxxx", passwd="xxxx",
content = ['LocalLB.VirtualServer', 'LocalLB.Pool',
'LocalLB.VirtualAddress', 'LocalLB.PoolMember',
'LocalLB.Monitor', 'System.SystemInfo']):
self.host = host
self.b = pycontrol.BIGIP(hostname = host, username = user,
password = passwd, fromurl = True, wsdls = content)
def get_destination(self, vipName):
destination = self.b.LocalLB.VirtualServer.get_destination(vipName)
return destination
def get_pool_name(self, vipName):
#needs to be a list
vip = list()
vip.append(vipName)
poolName = self.b.LocalLB.VirtualServer.get_default_pool_name(vip)
return poolName
def get_vip_state(self, vipName):
'''Returns a data structure containing a vip config, status and statistics'''
vip = list()
vip.append(vipName)
state = self.b.LocalLB.VirtualServer.get_enabled_state(vip)
return state
def get_members(self, poolName):
'''Returns array of members in a pool'''
pool = list()
pool.append(poolName)
members = self.b.LocalLB.Pool.get_member(pool)
#returns 3 dimensional array(default,member_number, address/port)
return members
test.psp
def get_vip_properties(vip, env):
import pycontrol
tempDict ={}
vipList = list()
vipList.append(vip)
#get pool name
b = pycontrol.BigIPLTM(env)
tempDict['pool'] = b.get_pool_name(vipList)
#get destination address and port
tempDict['destination'] = b.get_destination(vipList)
tempDict['port'] = b.get_destination(vipList)
tempDict['vipState'] = b.get_vip_state(vipList)
#get members is a 3dimensional array (default, membernumber, address/port)
tempArray = b.get_members(b.get_pool_name(vipList))
members = list()
for row in tempArray:
for entry in row:
members.append(entry[0])
tempDict['members'] = members
tempDict['member_port'] = b.get_members(b.get_pool_name(vipList))[0][0][1]
return tempDict

Related

Return an object from a class

Is it possible to return an object just by calling a class? Take for exemple, I am trying to connect to a client server and just by calling the class, I get the connection.
And if I want to start a new project on that server, I would only need to init the project and the connection is called automatically.
class LabellingProject():
def __init__(self,
web_app=False,
port=8888,
data_dir="/xxxx/xxx/",
local_files_root="/xxxx/datasets",
disable_signup_without_link=True,
username= "xxxx#xxxx"):
self.web_app = web_app
self.port = port
self.data_dir = data_dir
self.local_files_root = local_files_root
self.disable_signup_without_link = disable_signup_without_link
self.username = username
def connection(cls):
"""
"""
config = Config(web_app=cls.web_app,
port = cls.port,
data_dir = cls.data_dir,
local_files_root=cls.local_files_root,
disable_signup_without_link=cls.disable_signup_without_link,
username=cls.username)
server = LabelStudioServer()
server.start(config)
client = Client(url="http://localhost:"+str(config.port),
api_key=config.token)
return client
def create_new(self,client):
"""
"""
project = client.start_project()
return project
I want to call the function like this.
labelling = LabellingProject() => it will return the connection
project = labelling.create_new() => it will return the project and the client it should take it from the __init__.
createFromA needs to be a staticmethod as it does not operate on instances of the class Constructor
class A:
def __init__(self):
pass
def create_project(self,argA):
newA = self.Constructor.createFromA(argA)
return newA
class Constructor:
def __init__(self):
pass
#staticmethod
def createFromA(argA):
A = 2*argA
return A
cons = A()
cons.create_project(2)

different websocket connections but received messages get mixed up

import alice_blue
from alice_blue import *
class socket:
#global variables
live_data=[]
socket_opened = False
#credentials
username=
password=
api_secret=
app_id=
twoFA=
#access token and alice objects
access_token = AliceBlue.login_and_get_access_token(username=username, password=password, twoFA=twoFA, api_secret=api_secret, app_id=app_id)
alice = AliceBlue(username=username, password=password, access_token=access_token, master_contracts_to_download=['NSE', 'BSE'])
#alice.start_websocket handlers
def _event_handler_quote_update(self,message):
self.live_data.append(message)
def _open_callback(self):
self.socket_opened = True
#init.py
def __init__(self):
self.alice.start_websocket(subscribe_callback=self._event_handler_quote_update,
socket_open_callback=self._open_callback,
run_in_background=True)
while (self.socket_opened==False):
pass
#subscription methods
def subscribe_nse_market(self,instruments):
for x in instruments :
self.alice.subscribe(self.alice.get_instrument_by_symbol('NSE', x), LiveFeedType.MARKET_DATA)
def subscribe_nse_snapquote(self,instruments):
for x in instruments :
self.alice.subscribe(self.alice.get_instrument_by_symbol('NSE', x), LiveFeedType.SNAPQUOTE)
a=alice_obj.socket()
b=alice_obj.socket()
ins=[ ]
a.subscribe_nse_market(ins)
b.subscribe_nse_snapquote(ins)
#but both of the below gives same content with messges mixed up
a.live_data
b.live_data
#how can i make different socket connections to store messages separately in their respective objects.
I tried making live_data & event handler methods protected/private members. But still the same.
I guess the messages are directly streamed through a single channel in the device.
#thanksAlready
Here's a simplification of your problem.
class Foo:
arr = []
def add(self, value):
self.arr.append(value)
a = Foo()
b = Foo()
a.add(1)
print(b.arr) # prints [1]
print(a.arr) # prints [1]
class Bar:
def __init__(self):
self.arr = []
def add(self, value):
self.arr.append(value)
a = Bar()
b = Bar()
a.add(1)
print(b.arr) # prints []
print(a.arr) # prints [1]
In class Foo, arr is a class attribute which means it is shared among instances.
In class Bar, arr is an instance attribute.

Python List Bug in a for loop

I'm not sure how to describe the issue but I'll try it.
Background info
I have in my Django web application a function where the user can import other users. The user can via drag and drop import a .csv file which gets converted to a JSON 2D Array (with Papaparse JS)
In the view, I loop through the elements in the 2D array and create an "Importuser" which contains some properties like "firstname", "lastname", email and so on.
class Importuser:
firstname = None
lastname = None
email = None
import_errors = []
def __init__(self, fn, ln, e):
self.firstname = fn
self.lastname = ln
self.email = e
class Importerror:
message = None
type = None
def __init__(self, m, t):
self.message = m
self.type = t
In the for-loop, I also validate the email-address, so that there are no doubled users.
data = jsonpickle.decode(method.POST["users"])
users = []
for tempuser in data:
u = validate(Importuser(tempuser[0], tempuser[1], tempuser[2])
users.append(u)
In the validate function I check if there any user with the same email
def validate(user : Importuser):
user_from_db = User.objects.filter(email=user.email)
if user_from_db:
user.import_errors.append(Importerror("The user exists already!", "doubleuser"))
return user
Issue
After the for-loop finished all user have the same error but not when I print each user while doing the for-loop. The Importerror-Object in each user refers to the same memory location but in my test import should only have one user an error.
test.csv:
Dave,Somename,dave#example.com
Joe,Somename2,joe#example.com
Yannik,Somename3,yannik#example.com <<That's me (exsiting user)
What I'm doing wrong? can someone help me to understand why this happens?
You've defined import_errors as a class-level static, so it's shared between all instances of Importuser.
See: Static class variables in Python
For your particular problem, rewrite your classes as
class Importuser:
def __init__(self, firstname, lastname, email):
self.firstname = firstname
self.lastname = lastname
self.email = email
self.import_errors = []
class Importerror:
def __init__(self, message, type):
self.message = message
self.type = type
import_errors is a class-attribute of ImportUser. It should be a instance-attribute:
class Importuser:
def __init__(self, fn, ln, e):
self.firstname = fn
self.lastname = ln
self.email = e
self.import_errors = []

Python error "unbound method must be called with instance as first argument"

It's high time I start using Classes. I have always found another way. Yesterday I found exactly the code I need, but it's in a nice little Class and I can't figure out how to access it. I've read all the tutorials and even similar solutions here. I just can't wrap my head around it. The only part I wrote, is "main()" which is the part that doesn't work. I have re-written main a few dozen ways, and none of them work the way I expect them to work.
Thank you for your time, and patience.
All credit goes to Nathan Adams - aka dinnerbone
import socket
import struct
class MinecraftQuery:
MAGIC_PREFIX = '\xFE\xFD'
PACKET_TYPE_CHALLENGE = 9
PACKET_TYPE_QUERY = 0
HUMAN_READABLE_NAMES = dict(
game_id = "Game Name",
gametype = "Game Type",
motd = "Message of the Day",
hostname = "Server Address",
hostport = "Server Port",
map = "Main World Name",
maxplayers = "Maximum Players",
numplayers = "Players Online",
players = "List of Players",
plugins = "List of Plugins",
raw_plugins = "Raw Plugin Info",
software = "Server Software",
version = "Game Version",
)
def __init__(self, host, port, timeout=10, id=0, retries=2):
self.addr = (host, port)
self.id = id
self.id_packed = struct.pack('>l', id)
self.challenge_packed = struct.pack('>l', 0)
self.retries = 0
self.max_retries = retries
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.settimeout(timeout)
def send_raw(self, data):
self.socket.sendto(self.MAGIC_PREFIX + data, self.addr)
def send_packet(self, type, data=''):
self.send_raw(struct.pack('>B', type) + self.id_packed + self.challenge_packed + data)
def read_packet(self):
buff = self.socket.recvfrom(1460)[0]
type = struct.unpack('>B', buff[0])[0]
id = struct.unpack('>l', buff[1:5])[0]
return type, id, buff[5:]
def handshake(self, bypass_retries=False):
self.send_packet(self.PACKET_TYPE_CHALLENGE)
try:
type, id, buff = self.read_packet()
except:
if not bypass_retries:
self.retries += 1
if self.retries < self.max_retries:
self.handshake(bypass_retries=bypass_retries)
return
else:
raise
self.challenge = int(buff[:-1])
self.challenge_packed = struct.pack('>l', self.challenge)
def get_status(self):
if not hasattr(self, 'challenge'):
self.handshake()
self.send_packet(self.PACKET_TYPE_QUERY)
try:
type, id, buff = self.read_packet()
except:
self.handshake()
return self.get_status()
data = {}
data['motd'], data['gametype'], data['map'], data['numplayers'], data['maxplayers'], buff = buff.split('\x00', 5)
data['hostport'] = struct.unpack('<h', buff[:2])[0]
buff = buff[2:]
data['hostname'] = buff[:-1]
for key in ('numplayers', 'maxplayers'):
try:
data[key] = int(data[key])
except:
pass
return data
def get_rules(self):
if not hasattr(self, 'challenge'):
self.handshake()
self.send_packet(self.PACKET_TYPE_QUERY, self.id_packed)
try:
type, id, buff = self.read_packet()
except:
self.retries += 1
if self.retries < self.max_retries:
self.handshake(bypass_retries=True)
return self.get_rules()
else:
raise
data = {}
buff = buff[11:] # splitnum + 2 ints
items, players = buff.split('\x00\x00\x01player_\x00\x00') # Shamefully stole from https://github.com/barneygale/MCQuery
if items[:8] == 'hostname':
items = 'motd' + items[8:]
items = items.split('\x00')
data = dict(zip(items[::2], items[1::2]))
players = players[:-2]
if players:
data['players'] = players.split('\x00')
else:
data['players'] = []
for key in ('numplayers', 'maxplayers', 'hostport'):
try:
data[key] = int(data[key])
except:
pass
data['raw_plugins'] = data['plugins']
data['software'], data['plugins'] = self.parse_plugins(data['raw_plugins'])
return data
def parse_plugins(self, raw):
parts = raw.split(':', 1)
server = parts[0].strip()
plugins = []
if len(parts) == 2:
plugins = parts[1].split(';')
plugins = map(lambda s: s.strip(), plugins)
return server, plugins
def main():
check = MinecraftQuery.get_status('10.0.10.8',25565)
print check
main()
I think it should be as follows. Try and see if it works.
def main():
check = MinecraftQuery('10.0.10.8', 25565)
# It calls the __init__() method and constructs an object/instance of the class named 'MinecraftQuery'
# using the given arguments and associate it with the given identifier 'check'
check.get_status()
# Now, this invokes the get_status() method of the instance named 'check'.
print check
An unbound method is one that is not called with an instance of a class. Your error means that you are calling the method on the class rather than on an instance. So, you should first create an instance of the class and then call the method.

Read MongoEngine DynamicDocuments

my issue is that I am saving dict objects with MongoEngine:
class MongoRecord(DynamicDocument):
record_id = SequenceField(primary_key = True)
class SimpleMongo(object):
def __init__(self, *args, **kwargs):
"""
Very simple dict-like Mongo interface
"""
if PY_VERSION == 2:
self.iterattr = 'iteritems'
else:
self.iterattr = 'items'
self.debug = DEBUG
self.dict_type = type(dict())
self.dbname = kwargs.get('dbname', 'untitled')
self.collection_name = kwargs.get('collection', 'default')
self.ip = kwargs.get('ip', '127.0.0.1')
self.port = kwargs.get('port', 27017)
self.dbconn = connect(self.dbname, host=self.ip, port=self.port)
drop = kwargs.get('drop', False)
if drop:
self.dbconn.drop_database(self.dbname)
def put(self, data):
"""
Put dict
"""
assert type(data) == self.dict_type
record = MongoRecord()
record.switch_collection(self.collection_name)
generator = getattr(data, self.iterattr)
__res__ = [setattr(record, k, v) for k,v in generator()] # iteritems() for Python 2.x
record.save()
but when trying to access them:
def get(self):
record = MongoRecord()
record.switch_collection(self.collection_name)
return record.objects
getting
mongoengine.queryset.manager.QuerySetManager object, not an iterator.
So, what is the proper way to get my data back from Mongo being saved as DynamicDocument?
The problem isn't that MongoRecordis a DynamicDocument or that it contains a dict. You would get the same result with a regular Document. Your problem is with querying, you should change record.objects to MongoRecord.objects to get a cursor.
Regarding your usage of switch_collection()...
If MongoRecord documents will be saved to a collection with the same name, at most times, you can define this like below, and you don't have to use switch_collection() when a collection with that name is being queried.
class MongoRecord(DynamicDocument):
record_id = SequenceField(primary_key = True)
meta = {'collection': 'records'}
In case you do want to retrieve MongoRecord documents from a collection which isn't called 'records', and you want to define a function for this (which can give an UnboundLocalError), you can do it like this (source):
from mongoengine.queryset import QuerySet
def get(self):
new_group = MongoRecord.switch_collection(MongoRecord(), self.collection_name)
new_objects = QuerySet(MongoRecord, new_group._get_collection())
all = new_objects.all()
# If you would like to filter on an MongoRecord attribute:
filtered = new_objects.filter(record_id=1)
return all

Categories