How to pass an array to a python class in FLASK - python

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())

Related

How to delete a document in MongoDB

I am trying to create a delete method in order to delete a document that has the key:"name" and the value:"Rhonda". Whenever I execute my current code, I get an AttributeError saying:"'AnimalShelter' object has no attribute 'delete'". How do I get the method to return the deleted document's JSON contents? Here is my code:
testing_script.ipynb
from animal_shelter import AnimalShelter
# now need to create the object from the class
shelter = AnimalShelter("aacuser","Superman")
data = {"age_upon_outcome":"2 years","animal_type":"Dog","breed":"Dachshund","color":"Black and tan","name":"Rhonda","outcome_subtype":"Partner","outcome_type":"Adopt","sex_upon_outcome":"Female"}
new_values = {"$set": {"age_upon_outcome":"3 years"}}
# if shelter.create(data):
# print("Animal added")
# else:
# print("Failed to add animal")
# Calls the read function
# shelter.read(data)
# Calls the update function
# shelter.update(data, new_values)
# Calls the delete function
shelter.delete(data)
output
AttributeError Traceback (most recent call last)
<ipython-input-5-60b1d887dfb8> in <module>
17
18 # Calls the delete function
---> 19 shelter.delete(data)
20
AttributeError: 'AnimalShelter' object has no attribute 'delete'
animal_shelter.py
from pymongo import MongoClient
from bson.objectid import ObjectId
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
def __init__(self,username,password):
# Initializing the MongoClient. This helps to
# access the MongoDB databases and collections.
# init to connect to mongodb without authentication
self.client = MongoClient('mongodb://localhost:55996')
# init connect to mongodb with authentication
# self.client = MongoClient('mongodb://%s:%s#localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password))
self.database = self.client['AAC']
# Complete this create method to implement the C in CRUD.
def create(self, data):
if data is not None:
self.database.animals.insert(data) # data should be dictionary
return True # Tells whether the create function ran successfully
else:
raise Exception("Nothing to save ...")
# Create method to implement the R in CRUD.
def read(self, data):
return self.database.animals.find_one(data) #returns only one
# Update method to implement the U in CRUD.
def update(self, data, new_values):
if self.database.animals.count(data):
self.database.animals.update(data, new_values)
return self.database.animals.find({"age_upon_outcome":"3 years"})
else:
raise Exception("Nothing to update ...")
# Delete method to implement the D in CRUD
def delete(self, data)
result = self.database.animals.find_one_and_delete(data)
# print the _id key only if the result is not None
if("_id" in result):
print("find_one_and_delete ID:",result["_id"])
else:
print("Nothing to delete")
Problem is that functions that you are defining are outside the class. You have to put indentation on functions in class AnimalShelter
Also as pointed out in comment you are missing : in delete
Updated animal_sheltor.py
from pymongo import MongoClient
from bson.objectid import ObjectId
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
def __init__(self,username,password):
# Initializing the MongoClient. This helps to
# access the MongoDB databases and collections.
# init to connect to mongodb without authentication
self.client = MongoClient('mongodb://localhost:55996')
# init connect to mongodb with authentication
# self.client = MongoClient('mongodb://%s:%s#localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password))
self.database = self.client['AAC']
# Complete this create method to implement the C in CRUD.
def create(self, data):
if data is not None:
self.database.animals.insert(data) # data should be dictionary
return True # Tells whether the create function ran successfully
else:
raise Exception("Nothing to save ...")
# Create method to implement the R in CRUD.
def read(self, data):
return self.database.animals.find_one(data) #returns only one
# Update method to implement the U in CRUD.
def update(self, data, new_values):
if self.database.animals.count(data):
self.database.animals.update(data, new_values)
return self.database.animals.find({"age_upon_outcome":"3 years"})
else:
raise Exception("Nothing to update ...")
# Delete method to implement the D in CRUD
def delete(self, data):
result = self.database.animals.find_one_and_delete(data)
# print the _id key only if the result is not None
if("_id" in result):
print("find_one_and_delete ID:",result["_id"])
else:
print("Nothing to delete")

Querying MongoDB by a subclass field

SOLVED:
This works:
print("\nTrying to access by embedded_doc__embedded_int=1:")
for data in Doc.objects(embedded_doc__embedded_int=1):
print(data)
You have to access subclass fields by using the main class variable name (not the class name), followed by __, followed by the subclass variable name, as above.
UPDATE:
My original question is below. I wrote an example to show in condensed and complete form what I'm trying to do.
In this example, I have a Doc class. Each Doc has an Embedded class called "embedded_doc". And within the Embedded class is an integer called "embedded_int".
My goal is to store Docs in MongoDB via MongoEngine, and query the database for Docs that have embedded_doc.embedded_int == 1. So far I haven't been able to figure out how.
class Embedded(EmbeddedDocument):
embedded_int = IntField()
def __eq__(self, other):
return other == self.embedded_int
def __str__(self):
return(str(self.embedded_int))
class Doc(Document):
doc_str = StringField()
embedded_doc = EmbeddedDocumentField(Embedded)
def __str__(self):
return f"{self.doc_str} {str(self.embedded_doc)}"
data1 = Doc(doc_str = "first", embedded_doc = Embedded(embedded_int = 1))
data2 = Doc(doc_str = "second", embedded_doc = Embedded(embedded_int = 2))
#Gives correct output:
#Showing Doc objects in database:
#first 1
#second 2
print("Showing Doc objects in database:")
for data in Doc.objects():
print(data)
#Gives correct output:
#Trying to access by doc_str='first':
#first 1
print("\nTrying to access by doc_str='first':")
for data in Doc.objects(doc_str='first'):
print(data)
#ValueError: The source SON object needs to be of type 'dict' but a '<class 'int'>' was found
#During handling of the above exception, another exception occurred:
#mongoengine.errors.InvalidQueryError: Querying the embedded document 'Embedded' failed, due to an invalid query value
#print("\nTrying to access by embedded_doc=1:")
#for data in Doc.objects(embedded_doc=1):
# print(data)
#SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
#print("\nTrying to access by embedded_doc.embedded_int=1:")
#for data in Doc.objects(embedded_doc.embedded_int=1):
# print(data)
#NameError: name 'embedded_doc' is not defined
#print("\nTrying to access by embedded_doc.embedded_int==1:")
#for data in Doc.objects(embedded_doc.embedded_int==1):
# print(data)
#SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
#print("\nTrying to access by Embedded.embedded_int=1:")
#for data in Doc.objects(Embedded.embedded_int=1):
# print(data)
#Runs, but gives incorrect output:
#Trying to access by Embedded.embedded_int==1:
#first 1
#second 2
print("\nTrying to access by Embedded.embedded_int==1:")
for data in Doc.objects(Embedded.embedded_int==1):
print(data)
ORIGINAL QUESTION:
I'm using Python + MongoDB + MongoEngine to get started with a NoSQL database.
I have a class, Article, which contains a field ArticleMetadata. In turn, ArticleMetadata contains a field called pub_year. I want to query my database for Articles that contain ArticleMetadata with pub_year == 2002. I'm trying this:
for article in Article.objects(ArticleMetadata.pub_year == 2002):
print(article)
input()
But it's printing every article in the database, not just the ones with pub_year == 2002. What do I need to change?
Try ArticleMetadata__pub_year = 2002 instead of ArticleMetadata.pub_year == 2002

Python write to Access db with comboboxes

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

Create an instance of a class from SQL query

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 :)

Create a Python User() class that both creates new users and modifies existing users

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:

Categories

Resources