sqlalchemy - Pyramid console script - DBSession not inserting? -
i have working pyramid web app, based on sqlalchemy scaffold. within application, have function sends emails , inserts/updates tables in database via sqlalchemy. on web, call function via view, i.e., button on web submits view , within view calls function.
i create console script calls same function, on scheduled basis. i'm working through sample documentation setting pyramid console script. in perfect world want able access of models , functions i'm using in web app, able use them console. through trial , error i've managed include basics working, in i'm able query 1 of model objects , print console. i'm able call function want.
however, inside function writes row database , sends out email. when call function console, work (at least printed console) , sends emails. prints 'insert' statements should. isn't either executing inserts or committing them, i'm not sure which. i'm importing dbsession models.py package rest of pyramid app uses, there trick or need know? tried declaring new dbsession , creating custom console script threw sort of "can't find mapper" error.
in example below, sendemail gets called each record; function looks corresponding record, inserts row database model object, sends email. works great part of web app. on console side here, prints out it's doing should doing , sends emails, database record isn't inserted.
here's console script:
# describe script here import datetime email.mime.multipart import mimemultipart email.mime.text import mimetext import logging import optparse import smtplib smtplib import smtpexception import sys import textwrap import pyramid.paster pyramid.paster import bootstrap pyramid.request import request sqlalchemy.exc import dbapierror sqlalchemy import ( or_, and_, not_, asc, desc, func ) functions import sendemail models import dbsession, logsession, groupfinder models import myobject pyramid.session import unencryptedcookiesessionfactoryconfig my_session_factory = unencryptedcookiesessionfactoryconfig('itsaseekreet') pyramid.config import configurator sqlalchemy import engine_from_config pyramid.authentication import authtktauthenticationpolicy pyramid.authorization import aclauthorizationpolicy zope.sqlalchemy import zopetransactionextension def main(): description = """\ print deployment settings pyramid application. example: 'show_settings deployment.ini' """ usage = "usage: %prog config_uri" parser = optparse.optionparser( usage=usage, description=textwrap.dedent(description) ) parser.add_option( '-o', '--omit', dest='omit', metavar='prefix', type='string', action='append', help=("omit settings start prefix (you can use " "option multiple times)") ) options, args = parser.parse_args(sys.argv[1:]) if not len(args) >= 1: print('you must provide @ least 1 argument') return 2 config_uri = args[0] omit = options.omit if omit none: omit = [] request = request.blank('/', base_url='http://localhost:13715/') env = bootstrap(config_uri, request=request) settings = env['registry'].settings pyramid.paster.setup_logging(config_uri) engine = engine_from_config(settings, 'sqlalchemy.') dbsession.configure(bind=engine) logsession.configure(bind=engine) authn_policy = authtktauthenticationpolicy( 'itsaseekreet', callback=groupfinder) authz_policy = aclauthorizationpolicy() config = configurator(settings=settings, root_factory='myapp.models.rootfactory', session_factory=my_session_factory) config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.add_static_view('static', 'static', cache_max_age=3600) log = logging.getlogger(__name__) log.info('starting emailsender...') init_time = datetime.datetime.utcnow() log.info('current datetime (utc): {0}'.format(str(init_time))) items_to_process = dbsession.query(myobject). \ filter(and_(myobject.startdate <= init_time, myobject.enddate >= init_time, myobject.manual_send_only == false)).all() item in items_to_process: log.info('{0}: runtime: {1}'.format(item.description, item.send_time)) item_url = request.route_url('itemresponse', responseid='xxxxxx') rtn = sendemail(item.id, item_url) env['closer']() if __name__ == '__main__': main()
also, thing i'm running not important right now: have logging handlers log.blah goes database (using logsession i've created). works fine web app, not writing database when run it. don't know if it's same issue, or if in config handlers aren't set right console or something. dunno, main issue above i'm looking for. thanks!
edit: poked @ more , found the tutorial talking sqlalchemy setup , looking @ initializedb.py script, since modifies database want , hooks models, too. did import transaction
, wrapping above with
with transaction.manager: items_to_process = dbsession.query(myobject). \ filter(and_(myobject.startdate <= init_time, myobject.enddate >= init_time, myobject.manual_send_only == false)).all() item in items_to_process: log.info('{0}: runtime: {1}'.format(item.description, item.send_time)) item_url = request.route_url('itemresponse', responseid='xxxxxx') rtn = sendemail(item.id, item_url)
this seems want, or @ least actual commit , write database. i'm going have work more since i'm not sure happens if there's db error within called function, if rolls whole thing back, if commits part of it, or what. within function there exception handling , and cleanup think depends on pyramid_tm , zope handle behind scenes stuff.
as far can tell never commit changes.
dbsession.commit()
call before closer
function. should work according how use dbsession
.
Comments
Post a Comment