I have face some problem handling the database after certain logic applies.
I have a WTForm that passed the date from a leave application form. Update the LeaveApplication class. And after performing the calculation of the difference between date_to and date_from. I update the LeaveBalance class with the remaining leaves available.
However, i try to simulate this in flask shell session but gotten the error above.
Here's my simulation in the shell session.
> leave = LeaveApplication(user_id='1', leavetype_id='1',
... date_created=datetime.utcnow(),
... date_from=datetime.today() + timedelta(days=3),
... date_to=datetime.today() + timedelta(days=5),
... description='testing')
> db.session.add(leave)
> db.session.commit()
> leave_period = leave.date_to - leave.date_from
> current_leavebalance = LeaveBalance.query.filter_by(user_id='1', leavetype_id=leave.leavetype_id).first()
> updated_leavebalance = current_leavebalance.credits - leave_period.days
> update = LeaveBalance.query.get(leave.id)
> LeaveBalance.credits = updated_leavebalance
> db.session.add(update)
Everything is fine until i perform db.session.add(update) and i received the following traceback
Traceback (most recent call last):
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 2016, in add
state = attributes.instance_state(instance)
AttributeError: 'NoneType' object has no attribute '_sa_instance_state'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/orm/scoping.py", line 163, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 2018, in add
util.raise_(
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.NoneType' is not mapped
I am very new to programming and I am not sure what went wrong despite reading all the existing threads. Would someone explain the problem?
Related
So I tried to make Jarvis (Inspired by iron man) and everything was going well, until lines 32-39.
Here is the output:Here is an image of my code
PS C:\Users\HP> & C:/Users/HP/AppData/Local/Programs/Python/Python311/python.exe c:/Users/HP/Desktop/Python/Jarvis_AI.py
<function take_command at 0x000001C3A659C7C0>
Traceback (most recent call last):
File "c:\Users\HP\Desktop\Python\Jarvis_AI.py", line 42, in <module>
run_jarvis()
File "c:\Users\HP\Desktop\Python\Jarvis_AI.py", line 35, in run_jarvis
if "play" in command:
^^^^^^^^^^^^^^^^^
TypeError: argument of type 'function' is not iterable
'''
In line 35, you're saving the function take_command to the variable command. I imagine you're wanting to save whatever gets returned from take_command.
So on line 35, change
command = take_command
to
command = take_command()
So just adding the brackets to take_command.
I'm using a NAO robot with naoqi version 2.1 and Choregraphe on Windows. I want to parse json from an attached file to the behavior. I attached the file like in that link.
Code:
def onLoad(self):
self.filepath = os.path.join(os.path.dirname(ALFrameManager.getBehaviorPath(self.behaviorId)), "fileName.json")
def onInput_onStart(self):
with open(self.filepath, "r") as f:
self.data = self.json.load(f.get_Response())
self.dataFromFile = self.data['value']
self.log("Data from file: " + str(self.dataFromFile))
But when I run this code on the robot (connected with a router) I'll get an error:
[ERROR] behavior.box :_safeCallOfUserMethod:281 _Behavior__lastUploadedChoregrapheBehaviorbehavior_1136151280__root__AbfrageKontostand_3__AuslesenJSONDatei_1: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/naoqi.py", line 271, in _safeCallOfUserMethod
func()
File "<string>", line 20, in onInput_onStart
File "/usr/lib/python2.7/site-packages/inaoqi.py", line 265, in <lambda>
__getattr__ = lambda self, name: _swig_getattr(self, behavior, name)
File "/usr/lib/python2.7/site-packages/inaoqi.py", line 55, in _swig_getattr
raise AttributeError(name)
AttributeError: json
I already tried to understand the code from the correspondending lines but I couldn't fixed the error. But I know that the type of my object f is 'file'. How can I open the json file as a json file?
Your problem comes from this:
self.json.load(f.get_Response())
... there is no such thing as "self.json" on a Choregraphe box, import json and then do json.load. And what is get_Response ? That method doesn't exist on anything in Python that I know of.
You might want to first try making a standalone python script (that doesn't use the robot) that can read your json file before you try it with choregraphe. It will be easier.
I have a list from an mysql query that I'm trying to return in my bottle website. Is this possible? Here's what I have:
def create_new_location():
kitchen_locations = select_location()
return template('''
% for kitchen_location in {{kitchen_locations}}:
{{kitchen_location}} Kitchen
<br/>
% end''',kitchen_locations=kitchen_locations)
This is the error that I get.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "index.py", line 32, in create_new_location
</form>''',kitchen_locations=kitchen_locations)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3609, in template
return TEMPLATES[tplid].render(kwargs)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3399, in render
self.execute(stdout, env)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3386, in execute
eval(self.co, env)
File "<string>", line 6, in <module>
TypeError: unhashable type: 'set'
Got It (took me a while...)
% for kitchen_location in {{kitchen_locations}}:
Should be
% for kitchen_location in kitchen_locations:
When using the % at the beginning you don't need the {{}}.
This error:
TypeError: unhashable type: 'set'
is trying to use a set literal {{kitchen_locations}} ==>
kitchen_locations in a set in another set. since set is not hash-able you got the error
I've faced following issue and I'm not entirely sure it's a django or MySQL issue.
It happens when I want to retry django's save method in case of database error such as deadlock. Lets not focus on how ugly it is because it was just temporary hack which revealed potentially another problem.
To reproduce it I've prepared a script that runs 3 concurrent processes and simulate database failure by raising AssertionError.
models.py
from django.db import models, transaction
from time import sleep
from django.db.utils import OperationalError
class ModelA(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
def save_record(attempt):
print attempt
try:
with transaction.atomic():
super(ModelA, self).save(*args, **kwargs)
if attempt > 1:
assert False
except (AssertionError, OperationalError):
# dirty hack to retry
sleep(1)
if attempt > 0:
save_record(attempt-1)
else:
raise
save_record(5)
test script
import time
from multiprocessing import Process
from django.core.management.base import BaseCommand
from django.db import transaction
from atomic import models
#transaction.atomic
def create_record():
a = models.ModelA()
a.name = "test {}".format(time.time())
a.save()
class Command(BaseCommand):
def handle(self, *args, **options):
procs = []
for i in range(3):
p = Process(target=create_record)
procs.append(p)
for p in procs:
p.start()
for p in procs:
p.join()
If I run only 1 process everything works but with 3 concurrent processes 1 works (saves data) and another 2 fails with following traceback
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/transaction.py", line 371, in inner
return func(*args, **kwargs)
File "/media/django/atomictest/atomic/management/commands/test_atomic.py", line 14, in create_record
a.save()
File "/media/django/atomictest/atomic/models.py", line 29, in save
save_record(5)
File "/media/django/atomictest/atomic/models.py", line 25, in save_record
save_record(attempt-1)
File "/media/django/atomictest/atomic/models.py", line 25, in save_record
save_record(attempt-1)
File "/media/django/atomictest/atomic/models.py", line 25, in save_record
save_record(attempt-1)
File "/media/django/atomictest/atomic/models.py", line 18, in save_record
super(ModelA, self).save(*args, **kwargs)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/models/base.py", line 545, in save
force_update=force_update, update_fields=update_fields)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/models/base.py", line 573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/models/base.py", line 635, in _save_table
forced_update)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/models/base.py", line 679, in _do_update
return filtered._update(values) > 0
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/models/query.py", line 510, in _update
return query.get_compiler(self.db).execute_sql(None)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 980, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/backends/util.py", line 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/backends/util.py", line 47, in execute
self.db.validate_no_broken_transaction()
File "/home/blue/.virtualenvs/atomictest/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 372, in validate_no_broken_transaction
"An error occurred in the current transaction. You can't "
TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
I use django 1.6.5 and MySQL 5.5.37. Tested also with sqlite and postgres and there's no such issue with those backends.
I've also noticed that this happends only with nested atomic blocks. If i remove #transaction.atomic decorator from create_record() function it works again.
You should avoid catching exceptions inside atomic:
When exiting an atomic block, Django looks at whether it’s exited
normally or with an exception to determine whether to commit or roll
back. If you catch and handle exceptions inside an atomic block, you
may hide from Django the fact that a problem has happened. This can
result in unexpected behavior.
This is mostly a concern for DatabaseError and its subclasses such as
IntegrityError. After such an error, the transaction is broken and
Django will perform a rollback at the end of the atomic block. If you
attempt to run database queries before the rollback happens, Django
will raise a TransactionManagementError. You may also encounter this
behavior when an ORM-related signal handler raises an exception.
The correct way to catch database errors is around an atomic block as
shown above. If necessary, add an extra atomic block for this purpose.
This pattern has another advantage: it delimits explicitly which
operations will be rolled back if an exception occurs.
If you catch exceptions raised by raw SQL queries, Django’s behavior
is unspecified and database-dependent.
In this case you're catching DataBaseErrors inside the create_record's atomic block.
You should move your save retry attempt logic to the create_record method.
def create_record(retry=5):
instance = models.ModelA(name="test {}".format(time.time()))
try:
with transaction.atomic():
instance.save()
except DataBaseError:
if retry:
time.sleep(1)
create_record(retry-1)
else:
raise
And avoid overriding models.Model.save.
I have a view that sends back json data from events as described in Arsawh's fullcalendar jquery plugin. Using this worked fine. But after installing Django 1.6.2 I get the follwoing error
Internal Server Error: /customer/todaysfeed/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/avlahop/development/django/rhombus2/rhombus/utils/decorators.py", line 18, in wrapper
return view(request, *args, **kw)
File "/home/avlahop/development/django/rhombus2/rhombus/customer/views.py", line 103, in todaysfeed
json_list = json.dumps(json_list, cls=DjangoJSONEncoder)
File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 369, in dumps
**kw).encode(obj)
TypeError: __init__() got an unexpected keyword argument 'namedtuple_as_object
What could be wrong? This is the code again
if request.is_ajax():
doctor = Doctor.objects.get(user=request.user)
try:
start = datetime.fromtimestamp(int(request.GET.get('start',''))).replace(tzinfo=utc)
end = datetime.fromtimestamp(int(request.GET.get('end',''))).replace(tzinfo=utc)
except ValueError:
start = datetime.now().replace(tzinfo=utc)
end = datetime.now().replace(tzinfo=utc)
entries = Entry.objects.filter(start__gte=start, end__lte=end, creator=doctor)
json_list = []
for entry in entries:
id=entry.id
title=str(entry.patient)
start=entry.start
end=entry.end
color= doctor.color if doctor.color else "blue"
allDay=False
item = dict(id=id, title=title, start=start, end=end, allDay=allDay, color=color)
json_list.append(item)
json_list = json.dumps(json_list, cls=DjangoJSONEncoder)
return HttpResponse(json_list, content_type='application/json')
EDIT: Found it!! Clamsy of me, i was importing an older version of json. Now everything works great just used import json. Thank you!
This answer should help.
In short, you've got a system simplejson vs Django-packaged json clash as mentioned in the release notes