I keep getting the error "Database.db_search(search) NameError: name 'Database' is not defined".
If anybody could help me I would really appreciate it, I am also new to Stack Overflow so I apologize for any errors I may have made in regards to the overall layout of asking a question.
Thanks.
Database File:
from Staff import *
def db_search(self):
query = "SELECT * FROM customer_information WHERE Last_Name = %s"
cursor.execute(query, (last_name,))
for (Last_Name) in cursor:
print(Last_Name)
return last_name
Staff File:
from Database import *
def gett():
search = search_entry.get()
Database.db_search(search)`
By using
from Database import *
You've just imported all the contents of Database, so to get the thing to work you would now just need to call
db_search(search)
from module import * isn't really a recommended pattern, as you end up rather polluting your namespace (possibility of confusion between methods from different packages).
So if you change your import line to just:
import Database
then your code will work fine.
Related
So to simplify, I'm trying to write my own module (test.py) that looks as follows:
import psycopg2
get_data(xyz):
connection = psycopg2.connect(user="",
password="",
host="",
port="",
database="")
last_qry = """select * from xyz.abc"""
cursor = connection.cursor()
cursor.execute(last_qry)
last_data = cursor.fetchone()
cursor.close()
connection.close()
return last_data
in a different file I am running:
import test
get_data(xyz)
and I get the following error:
name 'psycopg2' is not defined
What am I doing wrong?
There are many bugs in these code snippets that you put here:
Your import should be like this:
from test import get_data
or in this way:
import test
test.get_data()
What is the use of xyz ? the second code snippet must return
NameError because xyz is not define;if you want to use it in last_qry you must have .format() for it.
What is the structure of directory that included the second file ?
and where is the first file?
Tooling:
Raspberry Pi 3B
Raspbian
BME280
Python3
Flask
Sqlite3
Error code:
Traceback (most recent call last):
File "BME280_DataCollector.py", line 65, in <module>
File "BME280_DataCollector.py", line 45, in logData
sqlite3.OperationalError: unable to open database file
Working on Raspbian and want to store my sensor data in sqlite3 database.
Somehow following error code occurs:
"sqlite3.OperationalError: unable to open database file".
Firstly, I thought that I requested the database file too quickly and changed the the measurement time to minutes, but the error is still reproducible.
I looked into /tmp by df /tmp. But this file system is used by 12 % and not overloaded.
Also, I tried to give the full path and also the database all write and read permissions via chmod, but also no differents. In addition, I put the full path to the code.
Furthermore, I tried to make try and exception approaches which also weren't fruitful.
Nevertheless, I wanted to know if this failure occures at a certain number of interactions with the database. I found out that it always stopped at the 1020th interaction.
I also tried to restart the python script with a shell script but it didn't work out due to lack of experience and knowledge.
Code:
from flask import Flask,render_template,url_for,request,redirect, make_response, send_file
import random
import json
from time import sleep
from random import random
from flask import Flask, render_template, make_response
import datetime
import sqlite3
import sys
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
import os
import smbus2
import bme280
## FUNCTIONS ##
# get data
def getBMEdata():
port = 1
adress = 0x77
bus = smbus2.SMBus(port)
calibration_params = bme280.load_calibration_params(bus, adress)
bme_data = bme280.sample(bus, adress, calibration_params)
temp = '%.2f' % bme_data.temperature
hum = '%.2f' % bme_data.humidity
press = '%.2f' % bme_data.pressure
now = datetime.datetime.now() #get time
timeString = now.strftime('%d-%m-%Y %H:%M:%S') #write time to string
return temp, hum, press, timeString
# function to insert data on a table
def logData(temp, hum, press, timeString):
conn = sqlite3.connect(dbname)
curs = conn.cursor()
curs.execute("INSERT INTO BME280_data values((?), (?), (?), (?))", (timeString, temp, hum, press))
conn.commit()
conn.close()
# display data base
def displayData():
conn = sqlite3.connect(dbname)
curs = conn.cursor()
print("\nEntire database contents:\n")
for row in curs.execute("SELECT * FROM BME280_data"):
print(row)
conn.close()
## MAIN
if __name__ == '__main__':
count = 0
dbname = '/home/pi/projects/SmartPlanting/Sensors_Database/sensorsData.db'
sampleFreq = 60 #data collect every minute
while True:
temp, hum, press, timeString = getBMEdata() #get data
logData(temp, hum, press, timeString) #save data
sleep(sampleFreq) #wait
displayData() #show in terminal
#count = count+1
#print(count)
Maybe someone already solved this problem or can give me an alternative to sqlite3 which works with flask.
Suggestion: add a more complete exception handling routine, because your stacktrace could be more verbose.
But judging from your trace the offending line #45 could be this: conn.commit() (or the line above). Python is already helping you pinpoint the error. There is something wrong in function logData.
Could it be that you are feeding incorrect data to your table BME280_data ? To debug your application I would strongly recommend that you print log the data you are trying to insert (use the logging module to output to file and/or console). I don't know the structure of your table but some of your fields could have a definition (data type) that is not compatible with the data you are trying to insert. The fact that you are able to predictably reproduce the problem is quite telling and my hunch is that the data could be the cause.
To sum up: take good habits now and add at least basic exception handling.
A quality application should have exception handling and log errors so they can be reviewed and remediated by a human. This is even more important for unattended applications, because you are not in front of the console and you may not even have a chance to see problems that occur.
Here is one tutorial that may help: https://code.tutsplus.com/tutorials/error-handling-logging-in-python--cms-27932
I run the main module, which should work correctly. But an error gets returned. 'spaceship' is not defined when I define 's=spaceship(parameters)' why is this I don't get it. I'm using zelle graphics for python. thank you
Functions from main module:
spaceshipGame file
from graphics import *
from spaceshipClass import *
def main():
window=createGraphicsWindow()
runGame(window)
def createGraphicsWindow():
win=GraphWin("Spaceship game",800,800)
return win
def createSpaceship(window,p1,p2,p3,speed,colour):
s=spaceship(window,p1,p2,p3,speed,colour)
return s
def runGame(window):
player=createSpaceship(window,Point(500,500),Point(500,470),Point(520,485),0.5,"red")
player.draw(window)
main()
spaceshipClass file
from spaceshipGame import *
from graphics import *
class spaceship:
def __init__(self,window,p1,p2,p3,speed,colour):
self.p1=p1
self.p2=p2
self.p3=p3
self.speed=speed
self.colour=colour
self.window=window
Never mind, I see the problem. Consult this example for more information:
Simple cross import in python
But the problem is the way you are cross importing, so delete from spaceshipGame import * from spaceshipClass or vise-versa (i.e. delete from spaceshipClass import * from spaceshipGame). You can import individually if you need to like in the example I provided.
There are also many other ways around it if you read the example. One of the easiest would be just merging them in the same file if they need to share a lot of methods.
I am trying to build a database driver for Peewee and i'm having trouble getting the save() method to fill in the primary key/id for objects. Here's some sample code:
from datetime import date
from peewee import BooleanField
from peewee import CharField
from peewee import DateField
from peewee import ForeignKeyField
from peewee import IntegerField
from peewee import Model
from SQLRelay import PySQLRDB
from sqlrelay_ext import SQLRelayDatabase
DB = SQLRelayDatabase('test2', host='<host>', user='<un>', password='<pwd>')
class BaseModel(Model):
class Meta:
database = DB
class Person(BaseModel):
name = CharField()
birthday = DateField()
is_relative = BooleanField()
class Pet(BaseModel):
owner = ForeignKeyField(Person, backref='pets')
name = CharField()
animal_type = CharField()
DB.connect()
Person.create_table(safe=False)
Pet.create_table(safe=False)
uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15), is_relative=True)
uncle_bob.save() # bob is now stored in the database
print('Uncle Bob id: {}'.format(uncle_bob.id))
print('Uncle Bob _pk: {}'.format(uncle_bob._pk))
Both uncle_bob.id and uncle_bob._pk are None after .save(). From digging into the peewee.py code, it seems that the _WriteQuery.execute() method is supposed to set the _pk attribute, but that isn't happening. My best guess is that the cursor implementation isn't acting properly. Does anyone have more insight than this that can maybe help me track down this problem?
Thanks!
Edit to answer:
For SQL Server, the following code allows you to return the last inserted id:
def last_insert_id(self, cursor, query_type=None):
try:
cursor.execute('SELECT SCOPE_IDENTITY()')
result = cursor.fetchone()
return result[0]
except (IndexError, KeyError, TypeError):
pass
In your SQLRelayDatabase implementation, you will probably need to correctly implement the last_insert_id() method. For python db-api 2.0 drivers, this typically looks like cursor.lastrowid.
The default implementation is:
def last_insert_id(self, cursor, query_type=None):
return cursor.lastrowid
Where cursor is the cursor object used to execute the insert query.
Databases like Postgresql do not implement this -- instead you execute an INSERT...RETURNING query, so the Postgres implementation is a bit different. The postgres implementation ensures that your insert query includes a RETURNING clause, and then grabs the id returned.
Depending on your DB and the underlying DB-driver, you'll need to pull that last insert id out somehow. Peewee should handle the rest assuming last_insert_id() is implemented.
I'm trying to create a new family parameter by calling a family's document in a project document and using the FamilyManager method to edit the family. There have been about 10 people asking for this on the Dynamo forums, so I figured I'd give it a shot. Here's my Python script below:
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
clr.AddReference("RevitServices")
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
#The inputs to this node will be stored as a list in the IN variables.
familyInput = UnwrapElement(IN[0])
familySymbol = familyInput.Symbol.Family
doc = familySymbol.Document
par_name = IN[1]
par_type = ParameterType.Text
par_grp = BuiltInParameterGroup.PG_DATA
TransactionManager.Instance.EnsureInTransaction(doc)
familyDoc = doc.EditFamily(familySymbol)
OUT = familyDoc.FamilyManager.AddParameter(par_name,par_grp,par_type,False)
TransactionManager.Instance.TransactionTaskDone()
When I run the script, I get this error:
Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed.
Traceback (most recent call last):
File "<string>", line 26, in <module>
Exception: The document is currently modifiable! Close the transaction before calling EditFamily.
I'm assuming that this error is because I am opening a family document that already exists through the script and then never sending the information back to the project document? Or something similar to that. Any tips on how to get around this?
Building up on our discussion from the forum:
import clr
clr.AddReference("RevitServices")
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
par_name = IN[0]
exec("par_type = ParameterType.%s" % IN[1])
exec("par_grp = BuiltInParameterGroup.%s" % IN[2])
inst_or_typ = IN[3]
families = UnwrapElement(IN[4])
# class for overwriting loaded families in the project
class FamOpt1(IFamilyLoadOptions):
def __init__(self): pass
def OnFamilyFound(self,familyInUse, overwriteParameterValues): return True
def OnSharedFamilyFound(self,familyInUse, source, overwriteParameterValues): return True
trans1 = TransactionManager.Instance
trans1.ForceCloseTransaction() #just to make sure everything is closed down
# Dynamo's transaction handling is pretty poor for
# multiple documents, so we'll need to force close
# every single transaction we open
result = []
for f1 in families:
famdoc = doc.EditFamily(f1)
try: # this might fail if the parameter exists or for some other reason
trans1.EnsureInTransaction(famdoc)
famdoc.FamilyManager.AddParameter(par_name, par_grp, par_type, inst_or_typ)
trans1.ForceCloseTransaction()
famdoc.LoadFamily(doc, FamOpt1())
result.append(True)
except: #you might want to import traceback for a more detailed error report
result.append(False)
trans1.ForceCloseTransaction()
famdoc.Close(False)
OUT = result
image of the Dynamo graph
The error message is already telling you exactly what the problem is: "The document is currently modifiable! Close the transaction before calling EditFamily".
I assume that TransactionManager.Instance.EnsureInTransaction opens a transaction on the given document. You cannot call EditFamily with an open transaction.
That is clearly documented in the help file:
http://thebuildingcoder.typepad.com/blog/2012/05/edit-family-requires-no-transaction.html
Close the transaction before calling EditFamily, or, in this case, don't open it at all to start with.
Oh, and then, of course, you wish to modify the family document. That will indeed require a transaction, but on the family document 'familyDoc', NOT on the project document 'doc'.
I don't know whether this will be the final solution, but it might help:
familyDoc = doc.EditFamily(familySymbol)
TransactionManager.Instance.EnsureInTransaction(familyDoc)
OUT = familyDoc.FamilyManager.AddParameter(par_name,par_grp,par_type,False)
TransactionManager.Instance.TransactionTaskDone()