Why are two objects being created in my sqlalchemy init? [duplicate] - flask

This question already has answers here:
Why does running the Flask dev server run itself twice?
(7 answers)
Closed 5 years ago.
This is my Model:
class Category(db.Model):
__tablename__='category'
id = db.Column(db.Integer,primary_key=True)
items = db.relationship('Item',backref='category',lazy='dynamic')
name = db.Column(db.String(80))
order = db.Column(db.Integer)
private = db.Column(db.Boolean)
color = db.Column(db.String(80),unique=False)
def __init__(self,name,order=None,private=None):
r = lambda: random.randint(0, 255)
color = (r(), r(), r())
color = ('#%02X%02X%02X' % color)
count = db.session.query(Category).count()
print count
self.name = name
self.color = color
self.order = count+1
self.private = 1
def __repr__(self):
return '<Category %r>' % self.name
and I create the tables here:
def initialize_tables():
db.create_all()
c = Category(name="uncategorized")
db.session.add(c)
db.session.commit()
if __name__ == '__main__':
initialize_tables()
app.run(debug=True)
This creates two categories in my database named 'uncategorized'. Why is this happening?

That's because you're using app.run with debug=True:
If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened.
The way the reloader works is by starting itself again in a subprocess, so if __name__ == '__main__' (and hence initialize_tables) runs twice.

Related

Can anyone help me with the below code as it is working fine without flask in local system but not with FLASK? [duplicate]

This question already has answers here:
Method Not Allowed flask error 405
(7 answers)
Closed 3 years ago.
Code is running fine with local system but I'm getting the following error whenever I try to submit data to my Flask form:
Error: Method Not Allowed The method is not allowed for the requested URL.
Relevant parts of my code are as follows:
pytesseract.pytesseract.tesseract_cmd = 'C:\\Users\\Abhi\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\site-packages\\pytesseract\\Tesseract-OCR\\tesseract.exe'
#Poppler executable file is mandatory to load
PDFTOPPMPATH = r"C:\Users\Abhi\Downloads\poppler-0.68.0_x86\poppler-0.68.0\bin\pdftoppm.exe"
PDFFILE = "C:\\Users\\Abhi\\rep.pdf"
subprocess.Popen('"%s" -png "%s" out' % (PDFTOPPMPATH, PDFFILE))
app = Flask(__name__)
#app.route('/', methods=['POST'])
def predict():
im = Image.open("out-2.png")
rgb_im = im.convert('RGB')
rgb_im.save('m.jpg')
im = Image.open("m.jpg")
text1 = pytesseract.image_to_string(im, lang = 'eng')
with open("report.txt","w") as f:
f.write(text1)
para = ["Emissivity","Refl. temp.","Distance","Relative humidity","Atmospheric temperature","Transmission"]
f=open('report.txt')
lines=f.readlines()
#lines.remove("\n")
for i in range(0,len(lines)):
if "jpg" in lines[i]:
end1 = i-1
if "MEASUREMENTS (°C)" in lines[i]:
start1 = i+1
if "Report" in lines[i]:
end2 = i-1
if "Transmission" in lines[i]:
trans = i+1
#print(str(start1) + " " + str(end1)+" " +str(trans) + " " + str(end2))
for i in range(start1-1,trans):
return str(lines[i])
if __name__ == '__main__':
#p = int(os.getenv('PORT', 5000))
#app.run(debug = True, port=p, host='0.0.0.0')
#app.run()
app.run(debug=True, use_reloader=False)
What is happening here is that route does not accept any url methods.its look like you are trying to return a string.U have to convert that in to a json.use Mashmellow to serialize ur output.or use bellow method(using json lib to covert list to a json format)
import json
def index():
lines=[1,2,3,4,5]
return json.dumps(lines[0])
use above template and customize it to your needs.hope this help

Tkinter assign buttons to entries in dynamically created widgets

How can I access an Entry content with pressing the corresponding Button in dynamically created widgets?
Below is the best I come up with so far. Thank you for any help.
from Tkinter import *
class App(object):
def __init__(self, master):
self.master = master
self.mf = Frame(self.master)
self.l = ["white", "red", "blue", "brown"]
self.font = ("Arial", 30)
self.c, self.r = 1, 0
self.cc, self.rr = 0, 0
self.bel = []
for c in self.l:
action = self.print_entry
self.e = Entry(self.mf, bg=c, width=10, font=self.font)
self.e.grid(row=self.r, column=self.c)
self.b = Button(self.mf, bg=c, text=c, font=self.font)
self.b.grid(row=self.rr, column=self.cc)
self.b.config(command=action)
self.bel.append((self.b, self.e))
self.rr += 1
self.r += 1
self.mf.pack()
def print_entry(self): # this function prints the content of the entry
pass
def main():
root = Tk()
display = App(root)
root.mainloop()
if __name__=="__main__":
main()
You can pass a reference to the entry widget into the command, using lambda or functools.partial. For example:
self.b.config(command= lambda entry=self.e: action(entry))
...
def print_entry(self, entry):
print("the entry is '%s'" % entry.get())
By the way, using self.b and self.e is pointless, since those variables will only ever hold references to the last button and last entry. You should either use a local variable, and/or append the values to a list.

Python: Script doesn't run without print

I have written a small executable script. This program only works when I use a print-statement (at the end of the on_start()-method of the QDialog()class). Please, take a look in the on_start()-method of the QDialog-class.
As you can see I create an a task_thread- and work_object-instance. But, when I execute this script without print-statement nothing happens - no Traceback or other error messages.
Where is the bug? I guess the problem is that I create the instances at the local level - I am not sure. How can I fix it?
import sys
from time import sleep
from PyQt4.QtCore import QThread, pyqtSignal, Qt, QStringList, QObject, QTimer
from PyQt4.QtGui import QVBoxLayout, QPushButton, QDialog, QProgressBar, QApplication, \
QMessageBox, QTreeWidget, QTreeWidgetItem, QLabel
def create_items(total):
for elem in range(total):
yield elem
class WorkObject(QObject):
notify_progress = pyqtSignal(object)
fire_label = pyqtSignal(object)
finished = pyqtSignal()
def __init__(self, parent=None):
QObject.__init__(self, parent)
def add_items(self):
total = 190000
x = (total/100*1)
a = x
counter = 0
for element in create_items(10000):
counter += 1
self.notify_progress.emit((element))
self.fire_label.emit((counter))
if counter == x:
x += a
sleep(1)
if not self.keep_running:
self.keep_running = True
break
def run(self):
self.keep_running = True
self.add_items()
def stop(self):
self.keep_running = False
class MyCustomDialog(QDialog):
finish = pyqtSignal()
def __init__(self, parent=None):
QDialog.__init__(self, parent)
layout = QVBoxLayout(self)
self.tree = QTreeWidget(self)
self.label = QLabel(self)
self.pushButton_start = QPushButton("Start", self)
self.pushButton_stopp = QPushButton("Stopp", self)
self.pushButton_close = QPushButton("Close", self)
layout.addWidget(self.label)
layout.addWidget(self.tree)
layout.addWidget(self.pushButton_start)
layout.addWidget(self.pushButton_stopp)
layout.addWidget(self.pushButton_close)
self.pushButton_start.clicked.connect(self.on_start)
self.pushButton_stopp.clicked.connect(self.on_finish)
self.pushButton_close.clicked.connect(self.close)
def fill_tree_widget(self, i):
parent = QTreeWidgetItem(self.tree)
self.tree.addTopLevelItem(parent)
parent.setText(0, unicode(i))
parent.setCheckState(0, Qt.Unchecked)
parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
def on_label(self, i):
self.label.setText("Result: {}".format(i))
def on_start(self):
self.tree.clear()
self.label.clear()
task_thread = QThread(self)
work_object = WorkObject()
work_object.fire_label.connect(self.on_label)
work_object.notify_progress.connect(self.fill_tree_widget)
work_object.finished.connect(task_thread.quit)
self.finish.connect(work_object.stop)
work_object.moveToThread(task_thread)
task_thread.started.connect(work_object.run)
task_thread.finished.connect(task_thread.deleteLater)
timer = QTimer()
# I set the single shot timer on False,
# because I don't want the timer to fires only once,
# it should fires every interval milliseconds
timer.setSingleShot(False)
timer.timeout.connect(work_object.stop)
timer.start(0)
task_thread.start()
print
def on_finish(self):
self.finish.emit()
def main():
app = QApplication(sys.argv)
window = MyCustomDialog()
window.resize(600, 400)
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
You are right, work_object is created as a local instance.
Here is a simple solution:
work_object = WorkObject()
self.work_object = work_object # Add this line

Setting and Retrieving Data with TkInter

I just ran into some strange behavior that has me stumped. I'm writing a simple little GUI for some in-house data processing. I want to allow a user to switch between a few different data-processing modes and input some parameters which define how the data is processed for each mode. The problem is that when the user inputs new parameters, the app ignores requests to switch modes.
The code below replicates the issue. I apologize for the size, this was the shortest code that replicates the problem.
import Tkinter as Tk
class foo(Tk.Frame):
def __init__(self):
self.master = master =Tk.Tk()
Tk.Frame.__init__(self,self.master) #Bootstrap
#Here mode and parameters as key, value pairs
self.data = {'a':'Yay',
'b':'Boo'
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,
text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,
text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#This is how I'm retrieving the user selected parameters
#property
def innerdata(self):
return self.data[self.sv.get()]
#And how I'm setting the user defined parameters
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
app = foo()
app.mainloop()
Expected behavior:
1) Press button 'a' then 'print' prints:
Yay
2) Press button 'b' then 'print' prints:
Boo
3) Type 'Zep Rocks' into the entry field and press apply
4) Pressing 'print' now yields
Zep Rocks
5) Pressing 'a' then 'print' should yield
Yay
But instead yields
Zep Rocks
Which might be true, but not desired right now. What is going on here?
Edit: I have some new information. Tk.Frame in python 2.7 is not a new-style class. It isn't friendly with descriptors, so rather than interpreting the '=' as a request to use the foo.innerdata's __set__ method, it just assigns the result of self.e.get() to innerdata.
ARGLEBARGLE!!!
Still an open question: how do I get this to do what I want in a clean manner?
So the core problem is that Tk.Frame doesn't subclass from object, so it is not a new-style python class. Which means it doesn't get down with descriptors like I was trying to use. One solution that I found is to subclass my app from object instead.
Code that solves my problem is below:
import Tkinter as Tk
class foo(object):
def __init__(self,master):
self.master = master #Bootstrap
self.mainloop = master.mainloop
self.data = {'a':{'value':7,'metavalue':False},
'b':{'value':'Beeswax','metavalue':True}
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#property
def innerdata(self):
return self.data[self.sv.get()]
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
master = Tk.Tk()
app = foo(master)
app.mainloop()

Denormalising field in django

I'm finding it difficult to denormalise a field in a django model. I have:
class AnswerSet(models.Model):
title = models.CharField(max_length=255)
num_answers = models.PositiveIntegerField(editable=False, default=0)
answers = models.ManyToManyField(Answer, through='AnswerSetAnswer')
...
class AnswerSetAnswer(models.Model):
answer = models.ForeignKey(Answer)
answer_set = models.ForeignKey(AnswerSet)
...
I want num_answers to contain a count of the number of answers in the set.
If 5 answers are initially associated with the AnswerSet "Food" and I edit one so it becomes associated with the AnswerSet "Colours", how can I recalculate the number of answers in the AnswerSet with "Food"? All the signals only seem to send the new data so I can't just override the save method.
I've tried using the m2m_changed signal, but it never gets called when I edit relationships through the admin form.
Here's my code anyway:
def update_answer_set_num_answers(sender, **kwargs):
"""
Updates the num_answers field to reflect the number of answers
associated with this AnswerSet
"""
instance = kwargs.get('instance', False)
print "no instance" # never gets here
if not instance:
return
action = kwargs.get('action')
print "action: ", action
if (action != 'pre_remove' and action != 'pre_add' and action != 'clear'):
return
reverse = kwargs.get('reverse')
if reverse:
answer_set = instance.answer_set
else:
answer_set = instance.answer_set
num_answers = AnswerSetAnswer.objects.filter(answer_set=answer_set.id).count()
if (action == 'pre_remove'):
num_answers -= int(kwargs.get('pk_set'))
elif (action == 'pre_add'):
num_answers += int(kwargs.get('pk_set'))
elif (action == 'clear'):
num_answers = 0
answer_set.num_answers = num_answers
print 'n a: ', answer_set.num_answers
answer_set.save()
m2m_changed.connect(update_answer_set_num_answers, \
AnswerSet.answers.through, weak=False)
Do you really need to denormalise this? You can calculate it with a simple aggregate:
from django.db.models import Count
answersets = AnswerSet.objects.all().annotate(num_answers=Count('answers')