Good day, I am stuck on an issue I would like to see if anyone knows how to fix this, I have a python script that is to control a field in access. I need to be able to view data in the field as well as write new info to the db. I know I need to use an UpdateCursor. But when I run this I get several errors, errors that I don't know how to fix. I am new to python. I am simply trying to write new data in the combobox into the mdb. here is one class for one field in my table.
class ISDComboBoxClass3(object):
"""Implementation for WOformV2_addin.combobox (ComboBox)"""
def __init__(self):
#self.items = ["12/1/2000", "5/3/2010"]
self.editable = True
self.enabled = True
self.dropdownWidth = 'WWWWWW'
self.width = 'WWWWWW'
def onSelChange(self, selection):
pass
def onEditChange(self, text):
fc = 'C:\GISdata\WO\WorkOrderData.shp'
field1 = "ISD"
cursor = arcpy.UpdateCursor(fc)
for row in cursor:
row.setValue(field1)
cursor.updateRow(row)
def onFocus(self, focused):
fc = 'C:\GISdata\WO\WorkOrderData.shp'
field1 = "ISD"
cursor = arcpy.UpdateCursor(fc)
for row in cursor:
row.setValue("ISD")
cursor.updateRow(row)
def refresh(self):
pass
Looking at the ArcGIS documentation, it looks like row.setValue requires 2 arguments.
example: row.setValue(FieldIndex, value)
http://resources.arcgis.com/en/help/main/10.1/index.html#//018v00000064000000
Related
I'm new to OOP python and trying to understand how to handle instances, I have a method:
class Object:
things = []
def __init__(self, table):
self.table = table
self.things.append(table)
( ... )
def thingy(self):
return self.db.execute(f"select date, p1, p2 from {self.table}")
def all_things(self):
self.things.extend(
map(lambda t: Object(thing=t + '_thing').thingy(), Constants.THINGS))
return self.things
Now how would I call this object, because my thing is driven by a list from Constants.THINGS, I.E: THINGS = ["table1", "table2" ... ], but in order to create the object to call the method all_things() - I must have a thing set - even tho the method sets the thing on call ...
This feels a little backward, so would appreciate what it is I am misunderstanding as I think I need to change the constructor/object
a = Object(end_date="2020-01-05",
start_date="2020-01-01",
thing=WHAT_TO_PUT_HERE).all_things()
If I add anything to this thing I get a double output
Any help is appreciated
UPDATE:
The desired output would be that thing() will fire, based on a list input provided by Constants.THINGS, if we input: THINGS = ["table1", "table2"] we would expect thingy() to execute twice with:
select date, p1, p2 from table1,
select date, p1, p2 from table2
And this would be added to the things class variable, and then when all_things() finishes we should have the content of the two select statements in a list
However,
Object.things
will actually have [WHAT_TO_PUT_HERE, table_1, table2]
So according to your update, this is what I think you're attempting to do.
class Object:
def __init__(self):
# do some initialization
pass
def thingy(self, table):
return self.db.execute(f"select date, p1, p2 from {table}")
# call the method "thingy" on all Constants.THINGS
def all_things(self):
map(self.thingy, Constants.THINGS)
Then from outside the class you would call it like this.
my_instance = Object()
my_instance.all_things()
I'm assuming the class will also have some setup and teardown of your db connection. As well as some other things but this is simply a minimalistic attempt at giving an example of how it should work.
Okay, so rather than having a class variable which #Axe319 informed me doesn't get reset with every instance as self.table would. I altered the constructor to just have:
class Object:
def __init__(self, table):
self.table = table
self.things = list()
Then when I call the particular method outside the class:
all_things() I can just pass None into the table as the method builds that for me. i.e:
a = Object(thing=None).all_things()
This might be an anti-pattern - again I'm new to OOP, but it's creating something that looks correct.
P.S yes I agree, things, thingy, and the thing was a bad choice for variables for this question...
Thanks
I started working with flask-python recently.
I am trying to send an array read from the database to a class that defines a form.
Here is my class :
# livraison Form Class
class livraisonForm(Form):
list_assurances=['-', u'Aucune assurance trouvée']
type_assur = SelectField(u'Type d\'assurance', choices=list_assurances)
# INIT function :
def __init__(self, list_assurances, *args, **kwargs):
super(Form)
self.list_assurances = list_assurances
Here is how I am trying to pass the array to the init function
def add_livraison():
form = livraisonForm(request.form, get_assurances())
the get_assurances() function returns an array as mentionned below :
def get_assurances():
# Create db cursor
cur = mysql.get_db().cursor()
# Get user by username
result = cur.execute("SELECT ID_ASSURANCE, DESCRIPTION FROM type_assurance ")
if result > 0:
# Get assurances list
data = cur.fetchone()
# Close connection
cur.close()
return [(i[0]+'', i[1]+'') for i in data]
# Close connection
cur.close()
return ['-', u'Aucun assur trouvée']
unfortunately, I am having this problem concerning the form class :
TypeError: 'UnboundField' object is not callable
I tried to delete the list_assurances variable from the form and called the function directly but I got a problem saying that the database has no attribute cursor.
I would like to know what is the right way to send an array to a class -form class- in flask.
Thank you so much
form = livraisonForm(request.form, get_assurances())
Here you're actually assigning the request.form to the self.assurances, not get_assurances() as you should.
Try it like that:
form = livraisonForm(get_assurances())
I have the following class:
class SomeClass:
def __init__(self, name, date):
self.name = name
self.date = date
Now I have a function in another module, which connects to a SQLite database and executes a query:
def getEntry(user):
data = []
connection = lite.connect(database)
with connection:
cur = connection.cursor()
cur.execute("SELECT name, date FROM table WHERE column = ?", [user])
events = cur.fetchall()
# instantiate an instance of `SomeClass`
return data
So how would I create an instance of SomeClass and pass name and date entries to my newly created instance?
Since fetchall() returns a list of the rows, you should be able to do this (this should cover occasions where multiple results are returned as well):
for result in events:
my_instance = SomeClass(result[0], result[1])
# Do whatever you want to do with the instances, which looks like
# it may be appending to data
data.append(my_instance) # Or data.append(SomeClass(result[0], result[1]))
Can't test it right now, so apologies if it is way off :)
I'm rewriting this post to clarify some things and provide a full class definition for the Virtual List I'm having trouble with. The class is defined like so:
from wx import ListCtrl, LC_REPORT, LC_VIRTUAL, LC_HRULES, LC_VRULES, \
EVT_LIST_COL_CLICK, EVT_LIST_CACHE_HINT, EVT_LIST_COL_RIGHT_CLICK, \
ImageList, IMAGE_LIST_SMALL, Menu, MenuItem, NewId, ITEM_CHECK, Frame, \
EVT_MENU
class VirtualList(ListCtrl):
def __init__(self, parent, datasource = None,
style = LC_REPORT | LC_VIRTUAL | LC_HRULES | LC_VRULES):
ListCtrl.__init__(self, parent, style = style)
self.columns = []
self.il = ImageList(16, 16)
self.Bind(EVT_LIST_CACHE_HINT, self.CheckCache)
self.Bind(EVT_LIST_COL_CLICK, self.OnSort)
if datasource is not None:
self.datasource = datasource
self.Bind(EVT_LIST_COL_RIGHT_CLICK, self.ShowAvailableColumns)
self.datasource.list = self
self.Populate()
def SetDatasource(self, datasource):
self.datasource = datasource
def CheckCache(self, event):
self.datasource.UpdateCache(event.GetCacheFrom(), event.GetCacheTo())
def OnGetItemText(self, item, col):
return self.datasource.GetItem(item, self.columns[col])
def OnGetItemImage(self, item):
return self.datasource.GetImg(item)
def OnSort(self, event):
self.datasource.SortByColumn(self.columns[event.Column])
self.Refresh()
def UpdateCount(self):
self.SetItemCount(self.datasource.GetCount())
def Populate(self):
self.UpdateCount()
self.datasource.MakeImgList(self.il)
self.SetImageList(self.il, IMAGE_LIST_SMALL)
self.ShowColumns()
def ShowColumns(self):
for col, (text, visible) in enumerate(self.datasource.GetColumnHeaders()):
if visible:
self.columns.append(text)
self.InsertColumn(col, text, width = -2)
def Filter(self, filter):
self.datasource.Filter(filter)
self.UpdateCount()
self.Refresh()
def ShowAvailableColumns(self, evt):
colMenu = Menu()
self.id2item = {}
for idx, (text, visible) in enumerate(self.datasource.columns):
id = NewId()
self.id2item[id] = (idx, visible, text)
item = MenuItem(colMenu, id, text, kind = ITEM_CHECK)
colMenu.AppendItem(item)
EVT_MENU(colMenu, id, self.ColumnToggle)
item.Check(visible)
Frame(self, -1).PopupMenu(colMenu)
colMenu.Destroy()
def ColumnToggle(self, evt):
toggled = self.id2item[evt.GetId()]
if toggled[1]:
idx = self.columns.index(toggled[2])
self.datasource.columns[toggled[0]] = (self.datasource.columns[toggled[0]][0], False)
self.DeleteColumn(idx)
self.columns.pop(idx)
else:
self.datasource.columns[toggled[0]] = (self.datasource.columns[toggled[0]][0], True)
idx = self.datasource.GetColumnHeaders().index((toggled[2], True))
self.columns.insert(idx, toggled[2])
self.InsertColumn(idx, toggled[2], width = -2)
self.datasource.SaveColumns()
I've added functions that allow for Column Toggling which facilitate my description of the issue I'm encountering. On the 3rd instance of this class in my application the Column at Index 1 will not display String values. Integer values are displayed properly. If I add print statements to my OnGetItemText method the values show up in my console properly. This behavior is not present in the first two instances of this class, and my class does not contain any type checking code with respect to value display.
It was suggested by someone on the wxPython users' group that I create a standalone sample that demonstrates this issue if I can. I'm working on that, but have not yet had time to create a sample that does not rely on database access. Any suggestions or advice would be most appreciated. I'm tearing my hair out on this one.
Are you building on the wxPython demo code for virtual list controls? There are a couple of bookkeeping things you need to do, like set the ItemCount property.
One comment about your OnGetItemText method: Since there's no other return statement, it will return None if data is None, so your test has no effect.
How about return data or "" instead?
There's a problem with the native object in Windows. If GetImg returns None instead of -1 the list has a problem with column 1 for some reason. That from Robin over on the Google Group post for this issue.
I'm trying to figure out the best way to create a class that can modify and create new users all in one. This is what I'm thinking:
class User(object):
def __init__(self,user_id):
if user_id == -1
self.new_user = True
else:
self.new_user = False
#fetch all records from db about user_id
self._populateUser()
def commit(self):
if self.new_user:
#Do INSERTs
else:
#Do UPDATEs
def delete(self):
if self.new_user == False:
return False
#Delete user code here
def _populate(self):
#Query self.user_id from database and
#set all instance variables, e.g.
#self.name = row['name']
def getFullName(self):
return self.name
#Create a new user
>>u = User()
>>u.name = 'Jason Martinez'
>>u.password = 'linebreak'
>>u.commit()
>>print u.getFullName()
>>Jason Martinez
#Update existing user
>>u = User(43)
>>u.name = 'New Name Here'
>>u.commit()
>>print u.getFullName()
>>New Name Here
Is this a logical and clean way to do this? Is there a better way?
Thanks.
You can do this with metaclasses. Consider this :
class MetaCity:
def __call__(cls,name):
“”“
If it’s in the database, retrieve it and return it
If it’s not there, create it and return it
““”
theCity = database.get(name) # your custom code to get the object from the db goes here
if not theCity:
# create a new one
theCity = type.__call__(cls,name)
return theCity
class City():
__metaclass__ = MetaCity
name = Field(Unicode(64))
Now you can do things like :
paris = City(name=u"Paris") # this will create the Paris City in the database and return it.
paris_again = City(name=u"Paris") # this will retrieve Paris from the database and return it.
from : http://yassinechaouche.thecoderblogs.com/2009/11/21/using-beaker-as-a-second-level-query-cache-for-sqlalchemy-in-pylons/
Off the top of my head, I would suggest the following:
1: Use a default argument None instead of -1 for user_id in the constructor:
def __init__(self, user_id=None):
if user_id is None:
...
2: Skip the getFullName method - that's just your Java talking. Instead use a normal attribute access - you can convert it into a property later if you need to.
What you are trying to achieve is called Active Record pattern. I suggest learning existing systems providing this sort of things such as Elixir.
Small change to your initializer:
def __init__(self, user_id=None):
if user_id is None: