pombreda / formalchemy

Automatically exported from code.google.com/p/formalchemy
MIT License
0 stars 0 forks source link

AbstractField can't query parent's session in virtualenv #109

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I moved my pylons app to use virtualenv and Ubuntu 9.04 and now I get this
error traceback viewing a simple form.  This form worked before moving to
virtualenv.  "No session found" when the AbstractField tries to run a query
using its parent's session:

File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Jobtrax-0.3.3b-py2.5.egg/jobtr
ax/controllers/job.py',
line 1030 in getAccountForm
  '/accountForm.mako')
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Jobtrax-0.3.3b-py2.5.egg/jobtr
ax/controllers/job.py',
line 1126 in _getGenericForm
  return render(makoTemplate)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Pylons-0.9.6.2-py2.5.egg/pylon
s/templating.py',
line 344 in render
  format=format, namespace=kargs, **cache_args)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Pylons-0.9.6.2-py2.5.egg/pylon
s/templating.py',
line 229 in render
  **options)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/ext/
turbogears.py',
line 49 in render
  return template.render(**info)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/temp
late.py',
line 133 in render
  return runtime._render(self, self.callable_, args, data)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/runt
ime.py',
line 347 in _render
  _render_context(template, callable_, context, *args,
**_kwargs_for_callable(callable_, data))
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/runt
ime.py',
line 364 in _render_context
  _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/runt
ime.py',
line 397 in _exec_template
  callable_(context, *args, **kwargs)
File
'/home/bry/jobtrax_ve/jobtrax/trunk/data/templates/accountForm.mako.py',
line 36 in render_body
  __M_writer(unicode(fs.render()))
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/FormAlchemy-1.2-py2.5.egg/form
alchemy/forms.py',
line 210 in render
  return self._render(fieldset=self, **kwargs)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/FormAlchemy-1.2-py2.5.egg/form
alchemy/forms.py',
line 174 in <lambda>
  _render = lambda self, **kwargs:
config.template_engine.render('fieldset', **kwargs)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/FormAlchemy-1.2-py2.5.egg/form
alchemy/templates.py',
line 159 in render
  return template.render_unicode(**kwargs)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/temp
late.py',
line 138 in render_unicode
  return runtime._render(self, self.callable_, args, data, as_unicode=True)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/runt
ime.py',
line 347 in _render
  _render_context(template, callable_, context, *args,
**_kwargs_for_callable(callable_, data))
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/runt
ime.py',
line 364 in _render_context
  _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/Mako-0.2.4-py2.5.egg/mako/runt
ime.py',
line 397 in _exec_template
  callable_(context, *args, **kwargs)
File 'memory:0x95ba32c', line 56 in render_body
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/FormAlchemy-1.2-py2.5.egg/form
alchemy/fields.py',
line 1095 in render
  q = self.query(fk_cls).order_by(order_by)
File
'/home/bry/jobtrax_ve/lib/python2.5/site-packages/FormAlchemy-1.2-py2.5.egg/form
alchemy/fields.py',
line 660 in query
  raise Exception("No session found.  Either bind a session explicitly, or
specify relation options manually so FormAlchemy doesn't try to autoload
them.")
Exception: No session found.  Either bind a session explicitly, or specify
relation options manually so FormAlchemy doesn't try to autoload them.

Original issue reported on code.google.com by bryanv...@gmail.com on 3 Aug 2009 at 10:48

GoogleCodeExporter commented 9 years ago
I setup Ubuntu 9.04 on another empty box so I could run my program without
virtualenv, and I am still getting the same problem.  So virtualenv is not the 
problem. 

The only other changes I have made that I can think of is an update from Ubuntu 
8.04
to 9.04, and an update from MySQL_python-1.2.2 to MySQL_python-1.2.3c1

Original comment by bryanv...@gmail.com on 7 Aug 2009 at 5:51

GoogleCodeExporter commented 9 years ago
I don't have a 9.04 so i can't really help

Can you try to run the tests ? 
It's documented here:
http://code.google.com/p/formalchemy/source/browse/RELEASE_NOTES.txt

Original comment by gael.pas...@gmail.com on 7 Aug 2009 at 6:35

GoogleCodeExporter commented 9 years ago
I couldn't get the buildout environment installed.  bin/buildout failed while
installing the coverage module do to gcc errors.

Original comment by bryanv...@gmail.com on 7 Aug 2009 at 6:50

GoogleCodeExporter commented 9 years ago
I kept removing dependencies from buildout.cfg to try and get bin/buidout to 
work and
I ran into gcc errors for pysqlite also.  It also would not complete because it
couldn't find a distribution for BeautifulSoup.  

Original comment by bryanv...@gmail.com on 7 Aug 2009 at 6:57

GoogleCodeExporter commented 9 years ago
Have you tried without the -S options ?

Else I think you need to install sqlite3-dev to compile pysqlite

Original comment by gael.pas...@gmail.com on 7 Aug 2009 at 11:02

GoogleCodeExporter commented 9 years ago
I think the only thing standing in my way now is that my corporate firewall is
blocking download of BeautifulSoup.  Anyone have a proxy?

Original comment by bryanv...@gmail.com on 11 Aug 2009 at 2:25

GoogleCodeExporter commented 9 years ago
./bin/buildout buildout:index=http://pypi.zopyx.com/

Original comment by gael.pas...@gmail.com on 11 Aug 2009 at 2:42

GoogleCodeExporter commented 9 years ago
All tests run fine.  The error is happening in my generic FormAlchemy form 
handler. 
On GET requests, it shows an empty form if creating a new item, or gets a 
populated
form for existing items.  On POST requests, it attempts a save:

def _getGenericForm(self, request, id, class_, fieldset, makoTemplate):
    '''Generic form processing that allows add/edit single item.

    Not a complete html web page.  Inteded to be embedded in another page.
    If id is None, a new item is created.
    '''
    #TODO: Permissions
    cuser = session['user'] # Get current user
    className = class_().__class__.__name__
    # Set '' or u'' to None, so will be NULL in DB
    for key, val in request.POST.items():
        if val == '' or val == u'':
            request.POST[key] = None

    fs = fieldset
    if not id:
        fs = fs.bind(class_, data=request.POST or None)
        fs.model.createdBy = fs.model.editedBy = cuser.username
    else:
        obj = orm.query(class_).get(id)
        if not obj:
            msg = '%s attempted to get form for non-existant %s %s'
            log.error(msg % (cuser, className, id))
            abort(404, 'Non-existant item.')
        fs = fs.bind(obj, data=request.POST or None)

    if request.method == 'GET':
        # View existing
        log.info('%s viewing %s id:%s' % (cuser, className, id))
    elif request.method == 'POST':
        # Saving existing
        log.info('%s attempting to save %s id %s' % (cuser, className, id))
        if not request.POST:
            log.error('%s attempt to save %s id %s did not provide '\
                    'any POST data.' % (cuser, className, id))
            abort(400, 'Your attempt to save had no data (empty POST)')
        # Save if valid.  validate() call will populate FieldSet with error
        # messages, which will be shown to user at the end of this method.
        if fs.validate():
            fs.sync()
            fs.model.editedBy = cuser.username
            if fs.model not in orm:
                orm.add(fs.model)
            # Attempt save
            # Need to get user info now, because attempting to convert User to
            # string on db fail will raise an error because the User object may
            # access the db
            userOnFail = str(cuser)
            try:
                orm.flush()
                orm.commit()
            except Exception, ex:
                log.error('%s attempt to save %s id:%s '\
                        'failed because of exception %s' % (
                            userOnFail, className, id, ex))
                abort(500, 'Could not save data.')
            # Log info about object that was saved
            vals = [(k, v) for k, v in fs.model.__dict__.items() if v]
            log.info('%s saved %s: %s' % (cuser, className, vals))
            result = '<div id="result">saved</div>'
            result +='<' + className.lower()
            for attr in fs.model.get_field_names():
                val = getattr(fs.model, attr)
                val = quoteattr(str(val)) if val else u''
                result += ' %s=%s' % (attr, val)
            result += ' />'
            return result
        else:
            log.info('%s attempted save of invalid %s: %s' % (cuser,
                className, fs.errors))
    else:
        log.error('%s made invalid request "%s" for %s id %s' %
                (cuser, request.method, className, id))
        raise NotImplementedError("Can't handle request method %s" %
                request.method)

    # Show user object
    c.fs = fs
    return render(makoTemplate)

Original comment by bryanv...@gmail.com on 11 Aug 2009 at 3:36

GoogleCodeExporter commented 9 years ago
None of the code has changed, what part of the environment could interfere with
finding a bound session?

Original comment by bryanv...@gmail.com on 11 Aug 2009 at 4:27

GoogleCodeExporter commented 9 years ago
It looks like this error is occurring whenever I try to view a form for a new 
object.
 The new object does not have a session bound to it because nothing has touched the
database yet.  For example:

fs = FieldSet(Account)

This fieldset does not have a session, but at some point AbstractField.query() 
is
being called which checks if the field's parent fieldset has a session 
attached.  

when I do: fs = FieldSet(Account), should I bind a session after?  If so, why 
wasn't
this causing a problem on a different machine with the same code?

Original comment by bryanv...@gmail.com on 11 Aug 2009 at 5:19

GoogleCodeExporter commented 9 years ago
So I changed my code so that when I am creating a FieldSet for a new object, I 
assign
a session:

fs = FieldSet(Account, session=mysession, data=request.POST or None)

My tests seem to be passing now.  However, how could this code not have thrown 
an
exception on my other server?

Original comment by bryanv...@gmail.com on 11 Aug 2009 at 5:24

GoogleCodeExporter commented 9 years ago
Have you read the docs ?
http://docs.formalchemy.org/pylons_sample.html#using-forms-in-controllers

Btw, issue is closed.

Original comment by gael.pas...@gmail.com on 18 Aug 2009 at 10:42

GoogleCodeExporter commented 9 years ago
Ya, I forgot to bind a session explicitly when getting a fieldset for a new 
object
that hasn't had an sqlalchemy session attached to it.

I still don't understand how this broken code worked, in production, on another 
box

Original comment by bryanv...@gmail.com on 19 Aug 2009 at 2:26