Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
response.status = 403
return 'FORBIDDEN'
@expose()
def notfound(self):
response.status = 404
return 'NOTFOUND'
def custom_commit_veto(environ, status, headers):
if status.startswith('404'):
return True
return False
fake_transaction = FakeTransaction()
import transaction
prev_transaction_manager = transaction.manager
transaction.manager = fake_transaction
package = PackageWithModel()
conf = AppConfig(minimal=True, root_controller=RootController())
conf['package'] = package
conf['model'] = package.model
conf['use_sqlalchemy'] = True
conf['tm.enabled'] = True
conf['tm.commit_veto'] = custom_commit_veto
conf['sqlalchemy.url'] = 'sqlite://'
app = conf.make_wsgi_app()
app = TestApp(app)
assert hasattr(conf, 'use_transaction_manager') is False
app.get('/test')
def upgrade(pyramid_env):
with context.begin_transaction():
op.add_column(
"content", sa.Column(
"subject_id", sa.Integer, sa.ForeignKey("langstring.id")))
op.add_column(
"content", sa.Column(
"body_id", sa.Integer, sa.ForeignKey("langstring.id")))
langstring_idsequence = "%s.%s.langstring_idsequence" % (
config.get("db_schema"), config.get("db_user"))
# Do stuff with the app's models here.
from assembl import models as m
db = m.get_session_maker()()
with transaction.manager:
discussion_locales = db.execute(
"select id, preferred_locales from discussion")
discussion_locales = {
id: (locs or 'und').split(' ')[0]
for (id, locs) in discussion_locales}
locales = dict(list(db.execute("select code, id from locale")))
locale_id_for_discussion = {
id: locales[loc] for (id, loc) in discussion_locales.iteritems()}
for target in ("subject", "body"):
posts = db.execute(
"select id, discussion_id, %s from content" % target)
for post_id, discussion_id, content in posts:
(langstring_id,) = next(iter(db.execute(
"select sequence_next('%s')" % langstring_idsequence)))
db.execute("INSERT into langstring values (%d)" % (
langstring_id,))
def message_generator(settings, project_id, form_id):
generator_start_time = datetime.datetime.now()
ids_sent = []
since = datetime.datetime.now() - datetime.timedelta(hours=24)
while True and not safe_exit(generator_start_time, project_id, form_id):
try:
session_factory = get_session_factory(get_engine(settings))
with transaction.manager:
db_session = get_tm_session(session_factory, transaction.manager)
last_message = (
db_session.query(
TaskMessages.message_id,
Product.celery_taskid,
TaskMessages.message_content,
)
.filter(TaskMessages.celery_taskid == Product.celery_taskid)
.filter(Product.project_id == project_id)
.filter(Product.form_id == form_id)
.filter(TaskMessages.message_date >= since)
.order_by(TaskMessages.message_date.asc())
.all()
)
if last_message is not None:
to_send = []
def __enter__(self):
import transaction
from zope.sqlalchemy.datamanager import join_transaction
from sqlalchemy.orm.scoping import ScopedRegistry
self._original_registry = self._DBSession.registry
self._DBSession.registry = ScopedRegistry(
self._DBSession.session_factory, self._get_scope)
self.scope = self
txn = transaction.begin()
session = self._DBSession()
join_transaction(session)
transaction.manager.free(txn)
return self
# handle this before including the routes
enable_views_admin = set_bool_setting(
config.registry.settings, "enable_views_admin"
)
enable_views_public = set_bool_setting(
config.registry.settings, "enable_views_public"
)
config.include(".routes")
config.include(".models")
config.scan(".views") # shared views, currently just exception handling
# after the models are included, setup the AcmeAccountProvider
dbEngine = models.get_engine(settings)
dbSession = None
with transaction.manager:
session_factory = models.get_session_factory(dbEngine)
dbSession = models.get_tm_session(None, session_factory, transaction.manager)
ctx = ApiContext(
timestamp=datetime.datetime.utcnow(), dbSession=dbSession, request=None,
)
# this will do the heavy lifting
_setup.startup_AcmeAccountProviders(ctx, app_settings)
if dbSession:
dbSession.close()
dbEngine.dispose() # toss the connection in-case of multi-processing
# exit early
def _add_notification(descr, resource_id):
with transaction.manager:
resource = Resource.get(resource_id)
if not resource:
log.error(
u'Can\'t create notification for resource #%s, its not exists'
% resource_id
)
return
notification = Notification(
descr=descr,
notification_resource=resource,
resource=Resource(NotificationsResource, resource.maintainer)
)
for subscriber in resource.subscribers:
subscriber.notifications.append(notification)
log.info(u'Create notification for resource #%s' % resource_id)
def upgrade(pyramid_env):
from assembl.models import Extract, Mailbox
db = Mailbox.db()
with transaction.manager:
for mb in db.query(Mailbox).all():
Mailbox.reprocess_content(mb)
db = Extract.db()
with transaction.manager:
q = db.execute('''
SELECT extract.id, email.subject, email.body, post.id
FROM extract
JOIN email ON (email.id = extract.source_id)
JOIN content ON (email.id = content.id)
JOIN post ON (post.content_id = email.id)
WHERE content.type = 'email'
''')
vals = {ex_id: (sub, body, postid) for (ex_id, sub, body, postid) in q}
for extract in db.query(Extract).options(lazyload('*')).all():
v = vals.get(extract.id)
if v:
tfi = extract._infer_text_fragment_inner(*v)
if tfi:
db.add(tfi)
def downgrade(pyramid_env):
from virtuoso.textindex import TextIndex
from assembl import models as m
db = m.get_session_maker()()
with transaction.manager:
ti = TextIndex(m.Content.body, clusters=[m.Content.discussion_id])
ti.create(db.bind)
parser = ArgumentParser()
parser.add_argument("config",
type=str,
help="config file")
subparsers = parser.add_subparsers()
subparser = subparsers.add_parser("adduser", help="add a new user")
subparser.add_argument("username", help="username")
subparser.add_argument("password", help="password")
subparser.set_defaults(cmd=adduser)
options = parser.parse_args(argv)
settings = setup_from_file(options.config)
sessionmaker = get_sessionmaker(settings)
with transaction.manager:
db = sessionmaker()
options.cmd(db)
def main(argv=sys.argv):
if len(argv) != 3:
usage(argv)
config_uri = argv[1]
section = argv[2]
setup_logging(config_uri)
settings = get_appsettings(config_uri, section)
engine = engine_from_config(settings, 'sqlalchemy.')
initialize_sql(engine, settings)
with transaction.manager:
id, secret = create_client()
print('client_id:', id)
print('client_secret:', secret)