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.
Related
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)
I tried to get array parameters values in another class , where and why i wrong here ?
My second python file => myModule.py :
parameters = ([])
class MyFirstClass():
def __init__(self, params):
global parameters
parameters = params
class MySecondClass():
def __init__(self):
global parameters
print parameters
class MyClassWhereIHaveAProblem(http.HTTPFactory):
proto = .....
global parameters
print parameters **// array is empty here**
class start_server():
def __init__(self, params):
self.x_params = params[0] //ip
self.y_params = int(params[1]) //port
global parameters
parameters = params[2]
def start():
reactor.listenTCP(self.y, MyClassWhereIHaveAProblem(), interface=self.x)
My first python file => Handle.py :
from myModule import MyFisrtClass
from myModule import MySecondClass
from myModule import MyClassWhereIHaveAProblem
from myModule import start_server
class Handle():
def __init__(self):
params = (["vector1", "vector2"])
self.params = (["127.0.0.1","3128", params])
def go_to_another(self):
s = start_server(self.params)
s.start()
if __name__ == '__main__':
H = Handle()
H.go_to_another()
I tried to get array parameters values in another class , where and why i wrong here ?
It looks like you are simply:
forgetting the second set of double underscores for the special method names
making typos in the class names, you had "First" spelled "Fisrt"
you never did anything to use the MySecondClass class, so I initialized one in your main routine with: y = MySecondClass()
Handle.py:
#!/usr/bin/env python
from myModule import MyFirstClass
from myModule import MySecondClass
class Handle():
def __init__(self):
self.params = (["ele1","ele2","ele3"])
def go_to_another(self):
X = MyFirstClass(self.params)
if __name__ == '__main__':
H = Handle()
H.go_to_another()
y = MySecondClass()
myModule.py:
#!/usr/bin/env python
parameters = ([])
class MyFirstClass():
def __init__(self, params):
global parameters
parameters = params
class MySecondClass():
def __init__(self):
global parameters
print 'this should not be empty: %s' % parameters # array is no longer empty here
Output:
this should not be empty: ['ele1', 'ele2', 'ele3']
You have X = MyFisrtClass(self.params) instead of X = MyFirstClass(self.params)! Also __init should be __init__.
You are printing the variable when the class is first defined, but defining the variable when the class is initialized.
In Python, anything here:
class MyClass:
# here
Is evaluated as soon as the interpreter reaches that line-- not when the class is initialized.
Try running this code to get a better idea of what I mean:
my_global_var = 'set initially!'
class MyClass():
# Will print 'set initially', as this
# print statement is run before an instance of the
# class ever gets initialized,
print 'in class defn: %s' % my_global_var
def __init__( self ):
global my_global_var
my_global_var = 'set by the class instance!'
x = MyClass()
# Will print 'set by the class instance', as now
# you are printing it after the class has been initialized
# at least once
print 'after class is initialized: %s' % my_global_var
For your code:
# I have a problem here
class MyClassWhereIHaveAProblem(http.HTTPFactory):
#proto = .....
#global = parameters
print 'not set here, this is static: %s' % parameters #**// array is empty here**
def __init__(self):
print 'now it is set: %s' % parameters
But make sure you actually initialize one of those MyClassWhereIHaveAProblem.
From what I think is the documentation:
listenTCP(port, factory, backlog=50, interface='')
port a port number on which to listen
factory a twisted.internet.protocol.ServerFactory instance
backlog size of the listen queue
interface The local IPv4 or IPv6 address to which to bind; defaults to '', ie all IPv4 addresses. To bind to all IPv4 and IPv6 addresses, you must call this method twice.
So I think you want to simply do:
listenTCP(self.y_params, YourProblemClass(), interface=self.x_params)
Where:
- y_params is what you called the port, and
- x_params is what you called the address.
ok, I'll go to sleep :) I had also itinialise my object (logical), now everything is ok, Thanks for your time Alex.B, solution here:
class MyClassWhereIHaveAProblem(http.HTTPFactory):
proto = .....
def __init__(self):
http.HTTPFactory.__init__(self)
global parameters
print parameters
for some reason when I try to add an object to a dictionary in a class, where the dictionary belongs to another class and objects are added/removed by class functions it always seems to fail adding.
Heres the datahandler :
class datastore():
def __init__(self, dict=None):
self.objectStore = {}
self.stringStore = {}
if dict is not None:
self.objectStore = dict
def __addobj__(self,obj,name):
print("adddedval")
self.objectStore[name] = obj
def __getobject__(self,name):
_data = self.objectStore.get(name)
return _data
def __ripobj__(self,name,append):
if isinstance(append, object):
self.objectStore[name] = append
def __returnstore__(self):
return self.objectStore
def __lst__(self):
return self.objectStore.items()
and heres the trigger code to try to add the item :
if self.cmd=="addtkinstance-dev":
print("Adding a tk.Tk() instance to dataStore")
#$$ below broken $$#
_get = datastore.__dict__["__returnstore__"](self.dat)
_get["test-obj"] = tk.Tk()
datastore.__init__(self.dat, dict=_get)
#--------------------------------------------#
tool(tk.Tk(), "test-obj", datastore())
and also heres the init for the class that trys to add the object
class cmdproc(tk.Tk, datastore):
def __init__(self,lst,variable_mem,restable):
self.pinst = stutils(lst,restable,variable_mem)
self.vinst = varutils(variable_mem,lst,restable)
self.tki = tkhandler()
self.dat = datastore(dict=None)
datastore.__init__(self, dict=datastore.__returnstore__(self.dat))
tk.Tk.__init__(self)
self.lst = lst
self.vdat = variable_mem
self.restable = restable
please help this is seriously baffling me
(note that tkhandler dosn't have to do with anything)
I will appreciate any effort to clarify the following: is there a way in Python to dynamically create one object per class, where several classes are declared? My silly guess can be described as following:
...
suppose we have some data from db
props = dict_cur.fetchall()
classes_names = []
data = []
for i in props:
classes_names.append(i['client_name'].title())
classes = []
data = []
for i in props:
data.append(dict(i))
for i, d in zip(classes_names, data):
classes.append(type(i, (object,), dict(**d)))
print classes
#printing list of classes
objects = []
for obj in classes:
objects.append(obj())
for obj in objects:
print obj.client_name, obj.client_id
This is very naive approach and it never lets inherit from created classes in a regular way, just like this:
class ClientProcess(Someclient): #Someclient is the name of the created class before
def __init__(self):
print "Someclient stuff"
The goal is pretty simple: create the objects of several classes, preferably with the properties that are stored in the tables, but at the same time have class declaration for every client which will have specific method implemented that will very from class to class. The initial script that works well and uses Python version of Factory method is not sufficient because it only can process one class(client) a time (based on command-line argument which is client id).
If I understand you correctly, you can use the following ways to subclass dynamically created classes:
In : classes = []
In : cls_name = 'BaseCls1'
In : classes.append(type(cls_name, (object, ), {'x': 1}))
In : classes[0].x
Out: 1
In : classes[0].__bases__
Out: (object,)
# two ways to create subclass out of BaseCls1
In : class SubCls1(classes[0]):
: x = 2
:
In : SubCls1.x
Out: 2
In : SubCls1.__bases__
Out: (__main__.BaseCls1,)
In : SubCls2 = type('SubCls2', (classes[0],), {'x': 2})
In : SubCls2.x
Out: 2
In : SubCls2.__bases__
Out: (__main__.BaseCls1,)
class GetConfig(object):
def __init__(self, client_id):
self.client_id = client_id
#construct the query here to get the clients data ...where client_id = self.client_id
d = {'logfile': 'some_long_path', 'contact_name': 'some_name'}
class FirstClient(object):
def __init__(self):
client_id = '111111111'
props = GetConfig(client_id)
#print props.d
def check_source(self):
print "Checking FirstClient source"
return "Something"
#print props.d
def check_downl(self):
print "Checking FirstClient downloaded"
class SecondClient(object):
def __init__(self):
client_id = "222222"
props = GetConfig(client_id)
def check_source(self):
print "Checking SecondClient source"
def check_downl(self):
print "Checking SecondClient downloaded"
myfactory = {
"firstclient" : FirstClient,
"secondclient" : SecondClient,
}
for i in myfactory.values():
i().check_source()
i().check_downl()
collections.namedtuple. done.
Edit: to elaborate,
from collections import namedtuple
rows = dict_cur.fetchall()
# creates the class Row which is a tuple, but each position argument
# corresponds to the column name in that position
# Row can be instantiated as a tuple and then its elements can be accessed
# by name class attributes
Row = namedtuple("Row", zip(*dict_cur.description)[0])
objects = [Row(row) for row in rows]
for o in objects:
print o.client_name, ' is ' , o
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