flask-admin basic example throws builtins.AttributeError exception - flask

Not sure what I am doing wrong. I am following flask-admin's Quick Start guide (link) and just tried running the basic example provided under the Initialization section. When I run that code and browse to localhost:5000/admin/ I get the following error
builtins.AttributeError
AttributeError: 'For' object has no attribute 'test'
There is a detailed exception stack I can paste as well if helpful.
I suspected a dependency is missing and trying reinstalling flask-admin, but it didn't help. Here's my pip freeze output:
$ pip freeze
APScheduler==3.3.1
click==6.7
dominate==2.3.1
Flask==0.12.2
Flask-Admin==1.5.0
Flask-APScheduler==1.7.0
Flask-Bootstrap==3.3.7.1
Flask-SQLAlchemy==2.2
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
python-dateutil==2.6.1
pytz==2017.2
six==1.10.0
SQLAlchemy==1.1.13
SQLAlchemy-Utils==0.32.14
tzlocal==1.4
visitor==0.1.3
Werkzeug==0.12.2
WTForms==2.1
I'm using python 3.6.1
My code is exactly as in the example:
from flask import Flask
from flask.ext.admin import Admin
app = Flask(__name__)
admin = Admin(app)
app.run()
And this is the exception stack:
Traceback (most recent call last):
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\project\.venv\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 69, in inner
return self._run_view(f, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 368, in _run_view
return fn(self, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 452, in index
return self.render(self._template)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 308, in render
return render_template(template, **kwargs)
File "c:\project\.venv\lib\site-packages\flask\templating.py", line 134, in render_template
context, ctx.app)
File "c:\project\.venv\lib\site-packages\flask\templating.py", line 116, in _render
rv = template.render(context)
File "c:\project\.venv\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "c:\project\.venv\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\project\.venv\lib\site-packages\jinja2\_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "c:\project\.venv\lib\site-packages\flask_admin\templates\bootstrap2\admin\index.html", line 1, in top-level template code
{% extends 'admin/master.html' %}
File "c:\project\.venv\lib\site-packages\flask_admin\templates\bootstrap2\admin\master.html", line 1, in top-level template code
{% extends admin_base_template %}
File "c:\project\.venv\lib\site-packages\jinja2\environment.py", line 543, in _generate
optimized=self.optimized)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 82, in generate
generator.visit(node)
File "c:\project\.venv\lib\site-packages\jinja2\visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 772, in visit_Template
self.blockvisit(block.body, block_frame)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 372, in blockvisit
self.visit(node, frame)
File "c:\project\.venv\lib\site-packages\jinja2\visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 1130, in visit_If
self.blockvisit(node.body, if_frame)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 372, in blockvisit
self.visit(node, frame)
File "c:\project\.venv\lib\site-packages\jinja2\visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 1014, in visit_For
if node.test:
AttributeError: 'For' object has no attribute 'test'
Will appreciate any advice.

I suspect I messed up my venv somehow. I tried again with a brand new venv, installed all packages and now everything works fine. Hope this helps someone.

Related

Problems with starting Telegram bot

I'm trying to deploy my telegram-bot on PythonAnywhere. It has worked fine with the free account but there are some troubles with the paid one. I'm getting "OpenSSL.SSL.Error: [('SSL routines', 'ssl3_get_record', 'decryption failed or bad record mac')]" messages in Error logs (accordingly bot works wrong). How can I solve it?
I'm using python3.7 + pyTelegramBotAPI + flask
Code example for error reproducing:
# coding=utf-8
import telebot
import flask
import time
token = 'bot_token'
bot = telebot.TeleBot(token, threaded=False)
WEBHOOK_HOST = '*userName*.pythonanywhere.com'
WEBHOOK_URL_BASE = "https://%s" % (WEBHOOK_HOST)
WEBHOOK_URL_PATH = "/%s/" % (token)
app = flask.Flask(__name__)
# Process webhook calls
#app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
if flask.request.headers.get('content-type') == 'application/json':
json_string = flask.request.get_data().decode('utf-8')
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return ''
else:
flask.abort(403)
#bot.message_handler(commands=['start', 'help'])
def handle_start_help(message):
bot.send_message(message.chat.id, text="Hello, my friend")
bot.remove_webhook()
time.sleep(0.1)
bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH)
Full error trace:
2018-10-30 12:40:33,351: Exception on /*token*/ [POST]
Traceback (most recent call last):
File "/usr/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/kleratoni/bot/bot/Main.py", line 90, in webhook
bot.process_new_updates([update])
File "/home/*accountName*/.local/lib/python3.7/site-packages/telebot/__init__.py", line 326, in process_new_updates
self.process_new_callback_query(new_callback_querys)
File "/home/*accountName*/.local/lib/python3.7/site-packages/telebot/__init__.py", line 354, in process_new_callback_query
self._notify_command_handlers(self.callback_query_handlers, new_callback_querys)
File "/home/*accountName*/.local/lib/python3.7/site-packages/telebot/__init__.py", line 1490, in _notify_command_handlers
self._exec_task(message_handler['function'], message)
File "/home/*accountName*/.local/lib/python3.7/site-packages/telebot/__init__.py", line 464, in _exec_task
task(*args, **kwargs)
File "/home/*accountName*/bot/bot/Main.py", line 535, in callback_inline
MainMenuActions.BetMenu_BackButton(call.message, bot, db)
File "/home/*accountName*/bot/bot/MainMenuActions.py", line 130, in BetMenu_BackButton
bot.send_message(message.chat.id, text=config.StringContent["StartPlayWords"], reply_markup=keyborads.keyboardMainmenu)
File "/home/*accountName*/.local/lib/python3.7/site-packages/telebot/__init__.py", line 598, in send_message
reply_markup, parse_mode, disable_notification))
File "/home/*accountName*/.local/lib/python3.7/site-packages/telebot/apihelper.py", line 140, in send_message
return _make_request(token, method_url, params=payload, method='post')
File "/home/*accountName*/.local/lib/python3.7/site-packages/telebot/apihelper.py", line 54, in _make_request
timeout=(connect_timeout, read_timeout), proxies=proxy)
File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3.7/site-packages/requests/adapters.py", line 445, in send
timeout=timeout
File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
six.raise_from(e, None)
File "<string>", line 2, in raise_from
File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 380, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.7/http/client.py", line 1321, in getresponse
response.begin()
File "/usr/lib/python3.7/http/client.py", line 296, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.7/http/client.py", line 257, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
File "/usr/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 300, in recv_into
return self.recv_into(*args, **kwargs)
File "/usr/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 285, in recv_into
return self.connection.recv_into(*args, **kwargs)
File "/usr/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1814, in recv_into
self._raise_ssl_error(self._ssl, result)
File "/usr/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1639, in _raise_ssl_error
_raise_current_error()
File "/usr/lib/python3.7/site-packages/OpenSSL/_util.py", line 54, in exception_from_error_queue
raise exception_type(errors)
OpenSSL.SSL.Error: [('SSL routines', 'ssl3_get_record', 'decryption failed or bad record mac')]
From an issue on the pyTelegramBotAPI github repo, it looks like it's an incompatibility between the version of requests you're using and the version of OpenSSL you're using. Try using requests 2.10.0 instead.
I had a same error and I fixed like this
token = 'bot_token'
bot = telebot.TeleBot(token, threaded=False)

flask apns - SysCallError: (-1, 'Unexpected EOF')

I'm trying to use Flask-APNS, previously I check that my ck.pem (cert and key on one file) works on a php server.
But everytime I try to execute:
from apns import APNS
#apns = APNS(app, cert_file='ZivingCert.pem', key_file='ZivingKey.pem',passphrase='mypassphrase')
apns = APNS(app, cert_file='ck.pem', passphrase='mypassphrase')
apns.send_message(tokens=['fad71c0b27416f055bfb1617c8db4e55d1b98b412443e68fba65cfe59748b81a'], alert='hi world', extra={})
I get this error:
WARNING:apnsclient.backends.stdio:Failed to establish socket/SSL connection to ('gateway.sandbox.push.apple.com', 2195)
No handlers could be found for logger "apnsclient.backends.stdio"
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask_restful/__init__.py", line 263, in error_router
return original_handler(e)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask_restful/__init__.py", line 260, in error_router
return self.handle_error(e)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask_restful/__init__.py", line 263, in error_router
return original_handler(e)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask_restful/__init__.py", line 260, in error_router
return self.handle_error(e)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask_restful/__init__.py", line 431, in wrapper
resp = resource(*args, **kwargs)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask_httpauth.py", line 60, in decorated
return f(*args, **kwargs)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/flask_restful/__init__.py", line 521, in dispatch_request
resp = meth(*args, **kwargs)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/scheduler/ws/v1/schedulesapns.py", line 21, in get
apns.send_message(tokens=['fad71c0b27416f055bfb1617c8db4e55d1b98b412443e68fba65cfe59748b81a'], alert='hi world', extra={})
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/scheduler/apns/__init__.py", line 134, in send_message
res = srv.send(message)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/apns.py", line 90, in send
status = self._connection.send(message)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/transport.py", line 255, in send
with self:
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/transport.py", line 228, in __enter__
self._open_connection() # can raise exception, bubblit up to the top
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/transport.py", line 519, in _open_connection
timeout=self.session.connect_timeout
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/backends/__init__.py", line 88, in get_cached_connection
return self.get_new_connection(address, certificate, timeout=timeout)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/backends/stdio.py", line 378, in get_new_connection
return self.connection_class(address, certificate, timeout=timeout)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/backends/stdio.py", line 142, in __init__
self._open_connection(timeout)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/backends/stdio.py", line 153, in _open_connection
self._connect_and_handshake()
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/apnsclient/backends/stdio.py", line 188, in _connect_and_handshake
self._connection.do_handshake()
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/OpenSSL/SSL.py", line 1442, in do_handshake
self._raise_ssl_error(self._ssl, result)
File "/Users/Ricardo/Documents/python/openshift/scheduler_env/lib/python2.7/site-packages/OpenSSL/SSL.py", line 1180, in _raise_ssl_error
raise SysCallError(-1, "Unexpected EOF")
SysCallError: (-1, 'Unexpected EOF')
I finally fixed thanks to logging messages.
To enable logging:
import logging
logging.basicConfig()
To fix WARNING:apnsclient.backends.stdio:Failed to establish socket/SSL connection to ('gateway.sandbox.push.apple.com', 2195) caused by security issue with SSL version 3.0 the Apple Push Notification server remove support for SSL 3.0 since Wednesday, October 29 of 2014.
def my_callback(key, reason):
print "my_callbaaaaaaack"
print str(key)
print str(reason)
import OpenSSL
OpenSSL.SSL.SSLv3_METHOD = OpenSSL.SSL.TLSv1_METHOD
from apns import APNS
apns = APNS(app, cert_file='ck.pem', passphrase='mypassphrase', failure_callback=my_callback)

Django Celery with Johnny Cache tasks failing with weird errors

I am running Django 1.4.5, Celery 3.0.15, Django Celery 3.0.11, Johnny Cache 1.4.
The calls to ORM in celery tasks sometimes fail with weird errors like invalid literal for int() with base 10: 'a'" or <MaybeEncodingError: Error sending result: ''<ExceptionInfo: ObjectDoesNotExist()>''. Reason: ''PicklingError("Can\'t pickle <class \'scsite.models.DoesNotExist\'>: attribute lookup scsite.models.DoesNotExist failed",)''.>:
Here is a sample stack trace:
Task scsite.tasks.send_signup_email[aecf0561-65af-4d11-a3a0-63d88b7e1a70] raised exception: ValueError("invalid literal for int() with base 10: 'd'",)
Task scsite.tasks.send_signup_email[aecf0561-65af-4d11-a3a0-63d88b7e1a70] raised exception: ValueError("invalid literal for int() with base 10: 'd'",)
Stacktrace (most recent call last):
File "celery/execute/trace.py", line 192, in trace_task
R = I.handle_error_state(task, eager=eager)
File "scsite/tasks.py", line 537, in send_signup_email
email_html = email_template.render(Context(data))
File "django/template/base.py", line 142, in render
context.render_context.pop()
File "django/template/base.py", line 134, in _render
return self.nodelist.render(context)
File "django/template/base.py", line 823, in render
bit = self.render_node(node, context)
File "django/template/base.py", line 837, in render_node
return node.render(context)
File "django/template/loader_tags.py", line 155, in render
return self.render_template(self.template, context)
File "django/template/loader_tags.py", line 137, in render_template
output = template.render(context)
File "django/template/base.py", line 142, in render
context.render_context.pop()
File "django/template/base.py", line 134, in _render
return self.nodelist.render(context)
File "django/template/base.py", line 823, in render
bit = self.render_node(node, context)
File "django/template/base.py", line 837, in render_node
return node.render(context)
File "django/template/defaulttags.py", line 192, in render
nodelist.append(node.render(context))
File "django/template/defaulttags.py", line 474, in render
self.extra_context.iteritems()])
File "django/template/base.py", line 584, in resolve
obj = settings.TEMPLATE_STRING_IF_INVALID
File "django/template/base.py", line 721, in resolve
value = self._resolve_lookup(context)
File "django/template/base.py", line 781, in _resolve_lookup
raise
File "django/db/models/manager.py", line 119, in count
return self.get_query_set().count()
File "django/db/models/fields/related.py", line 461, in get_query_set
return super(RelatedManager, self).get_query_set().using(db).filter(**self.core_filters)
File "django/db/models/query.py", line 624, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "django/db/models/query.py", line 642, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "django/db/models/sql/query.py", line 1250, in add_q
can_reuse=used_aliases, force_having=force_having)
File "django/db/models/sql/query.py", line 1185, in add_filter
connector)
File "django/db/models/sql/where.py", line 69, in add
value = obj.prepare(lookup_type, value)
File "django/db/models/sql/where.py", line 320, in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "django/db/models/fields/__init__.py", line 310, in get_prep_lookup
return self.get_prep_value(value)
File "django/db/models/fields/__init__.py", line 537, in get_prep_value
return int(value)
Task scsite.tasks.update_various_denorm_fields[edddb260-041d-4195-83d7-f2e731e5d1a5] raised exception: ValueError("invalid literal for int() with base 10: 'a'",)
Stacktrace (most recent call last):
File "celery/task/trace.py", line 242, in trace_task
R = I.handle_error_state(task, eager=eager)
File "celery/task/trace.py", line 415, in __protected_call__
return self.run(*args, **kwargs)
File "scsite/tasks.py", line 470, in update_various_denorm_fields
Person.objects.update_question_counts()
File "scsite/managers.py", line 715, in update_question_counts
person.update_question_count_denorm()
File "scsite/models.py", line 2712, in update_question_count_denorm
self.question_count_denorm = self.questions.count()
File "django/db/models/manager.py", line 119, in count
return self.get_query_set().count()
File "django/db/models/fields/related.py", line 567, in get_query_set
return super(ManyRelatedManager, self).get_query_set().using(db)._next_is_sticky().filter(**self.core_filters)
File "django/db/models/query.py", line 624, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "django/db/models/query.py", line 642, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "django/db/models/sql/query.py", line 1250, in add_q
can_reuse=used_aliases, force_having=force_having)
File "django/db/models/sql/query.py", line 1185, in add_filter
connector)
File "django/db/models/sql/where.py", line 69, in add
value = obj.prepare(lookup_type, value)
File "django/db/models/sql/where.py", line 320, in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "django/db/models/fields/__init__.py", line 310, in get_prep_lookup
return self.get_prep_value(value)
File "django/db/models/fields/__init__.py", line 537, in get_prep_value
return int(value)
I believe the error is not in my code, it looks like cache becomes corrupt for some reason, and something like the following happens:
CustomModel with pk=123 is retrieved.
It is passed on to Celery to process.
For some reason, the pk of the Custom model becomes a character like 'a', 'd' instead of 123. Another call is made with MyModel.objects.get(pk='a') and it obviously fails.
Actually, revisiting the code for this, it seems I am not passing an object to Celery as I mentioned above, just running the following manager method from a simple celery task.
#task
def mytask():
Person.objects.update_question_count()
class PersonManager(models.Manager):
def update_question_counts(self):
persons = self.all() # 1
for person in persons:
person.update_question_count_denorm() #3
My guess is the following: when Line 1 runs, persons is obtained from cache, but while processing line 3, the cache obtained in Line 1 becomes corrupt.

Not using auto_now=True with djangoforms makes GAE crash?

This is my first night playing around with Google App Engine with djangoforms rather than straight Django. I don't understand why this happens with db.DateTimeProperty().
import datetime
from google.appengine.ext import db
class BoringOldEvent(db.Model):
"""Models an individual Event that someone creates"""
creator = db.StringProperty()
date_created = db.DateTimeProperty(auto_now_add=True)
start_date_time = db.DateTimeProperty()
Will crash if start_date_time = db.DateTimeProperty() does not have auto_now_add=True.
I'm sure there is a good reason, but I"m left scratching my head at the moment because surely users expect to enter datetimes at some point....
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 187, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 225, in _LoadHandler
handler = __import__(path[0])
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1858, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1722, in FindAndLoadModule
description)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1665, in LoadModuleRestricted
description)
File "/Users/mw/Documents/yayimin/main.py", line 8, in <module>
import events.views
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1858, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1722, in FindAndLoadModule
description)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1665, in LoadModuleRestricted
description)
File "/Users/mw/Documents/yayimin/events/views.py", line 13, in <module>
class EventForm(djangoforms.ModelForm):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py", line 772, in __new__
form_field = prop.get_form_field()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py", line 353, in get_form_field
return super(DateTimeProperty, self).get_form_field(**defaults)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py", line 200, in get_form_field
return form_class(**defaults)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/forms/fields.py", line 394, in __init__
super(DateTimeField, self).__init__(*args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/forms/fields.py", line 99, in __init__
widget = widget()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/forms/widgets.py", line 414, in __init__
self.format = formats.get_format('DATETIME_INPUT_FORMATS')[0]
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/utils/formats.py", line 67, in get_format
if use_l10n or (use_l10n is None and settings.USE_L10N):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
INFO 2012-08-19 05:07:06,936 dev_appserver.py:2952] "GET /create/ HTTP/1.1" 500 -
Super duper thanks in advance!
It depends whether you're using Python 2.5 or 2.7. If you're using 2.7, you need to set the DJANGO_SETTINGS_MODULE variable in your app.yaml:
env_variables:
DJANGO_SETTINGS_MODULE: 'myapp.settings'
See the Django notes.

Where is the syntax error with **finally:* clause?

I'm trying to run Selenium tests for a Django app on production server.
I am getting a syntax error on the finally: clause.
I don't see where the error is and all the tests ran fine in development.
Here is the code:
def activate_revision(self, user, revision):
self.title = revision.title
self.tagnames = revision.tagnames
self.body = self.rendered(revision.body)
self.active_revision = revision
# Try getting the previous revision
try:
prev_revision = NodeRevision.objects.get(node=self, revision=revision.revision-1)
update_activity = True
# Do not update the activity if only the tags are changed
if prev_revision.title == revision.title and prev_revision.body == revision.body \
and prev_revision.tagnames != revision.tagnames and not settings.UPDATE_LATEST_ACTIVITY_ON_TAG_EDIT:
update_activity = False
except NodeRevision.DoesNotExist:
update_activity = True
finally:
if update_activity:
self.update_last_activity(user)
self.save()
Here is the traceback:
$ python manage.py test forum
Traceback (most recent call last):
File "/usr/lib/python2.4/logging/__init__.py", line 731, in emit
msg = self.format(record)
File "/usr/lib/python2.4/logging/__init__.py", line 617, in format
return fmt.format(record)
File "/usr/lib/python2.4/logging/__init__.py", line 408, in format
s = self._fmt % record.__dict__
KeyError: 'funcName'
/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_lookup method hasn't been updated to take `connection` and `prepared` arguments.
new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_value method hasn't been updated to take `connection` and `prepared` arguments.
new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
Traceback (most recent call last):
File "manage.py", line 13, in ?
execute_manager(settings)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/home/spirituality/lib/python2.7/South-0.7.3-py2.7.egg/south/management/commands/test.py", line 8, in handle
super(Command, self).handle(*args, **kwargs)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/core/management/commands/test.py", line 37, in handle
failures = test_runner.run_tests(test_labels)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/test/simple.py", line 358, in run_tests
suite = self.build_suite(test_labels, extra_tests)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/test/simple.py", line 247, in build_suite
app = get_app(label)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 129, in get_app
self._populate()
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/home/spirituality/lib/python2.7/Django-1.3.1-py2.7.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/__init__.py", line 2, in ?
from question import Question ,QuestionRevision, QuestionSubscription
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/question.py", line 1, in ?
from base import *
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/base.py", line 349, in ?
from node import Node, NodeRevision, NodeManager
File "/home/spirituality/webapps/spirituality/spirit_app/forum/models/node.py", line 383
finally:
^
SyntaxError: invalid syntax
First part of the traceback suggests that it's Python 2.4 on production. As per my comment above, the problem is that try..except..finally is only for Python 2.5 and newer. Upgrade production or rewrite the code to nest try..except inside an outer try..finally.