Example #1
0
    def send_invites_success(self, appstruct):
        settings = self.request.registry.settings
        mailer = Mailer(
            host=settings['mail.host'],
            port=settings['mail.port'],
            username=settings['bimt.referrals_mail_username'],
            password=settings['bimt.referrals_mail_password'],
            tls=True,
            default_sender=settings['bimt.referrals_mail_sender'],
        )
        emails = appstruct['emails'].splitlines()
        for email in emails:
            mailer.send(
                Message(
                    subject=u'Your friend, {}, gave you exclusive access to {}'
                    .format(  # noqa
                        self.request.user.fullname,
                        settings['bimt.app_title']),
                    recipients=[
                        email,
                    ],
                    html=render('pyramid_bimt:templates/referral_email.pt',
                                {'request': self.request}),
                ), )
            self.request.registry.notify(
                ReferralEmailSent(self.request, self.request.user,
                                  'Referral email sent to: {}'.format(email)))

        self.request.session.flash(u'Referral email sent to: {}'.format(
            ', '.join(appstruct['emails'].splitlines())))
        return HTTPFound(location=self.request.route_path('referrals'))
Example #2
0
class ThreadMailer(threading.Thread):
    """
    인덱스 추가/삭제를 위한 쓰레드
    """
    def __init__(self):
        threading.Thread.__init__(self)
        self.queue = Queue.Queue()
        self.mailer = Mailer(host="localhost")
    
    def send(self, msg):
        self.queue.put(msg)
        
    def run(self):

        while True:
            # 큐에서 작업을 하나 가져온다
            msg = self.queue.get()
            self.mailer.send(msg)
            log.info(msg.subject)
            transaction.commit()
            log.info("MAIL COMMITTED!")
            
            # 작업 완료를 알리기 위해 큐에 시그널을 보낸다.
            self.queue.task_done()
    
    def end(self):
        self.queue.join()
Example #3
0
def email(subject=None, recipients=None, body=None):
    mailer = Mailer(host='192.168.101.5')
    message = Message(subject=subject,
                      sender='*****@*****.**',
                      recipients=recipients,
                      html=body)

    mailer.send_immediately(message)
Example #4
0
def home_view(request):
    mailer = Mailer()
    message = Message(subject="測試信件",
                      sender="*****@*****.**",
                      recipients=['*****@*****.**'],
                      body="這是測試信")
    mailer.send(message)
    return {}
Example #5
0
    def test_send(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        mailer = Mailer()

        msg = Message(subject="testing", sender="*****@*****.**", recipients=["*****@*****.**"], body="test")

        mailer.send(msg)
Example #6
0
    def test_send_immediately_and_fail_silently(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        mailer = Mailer()

        msg = Message(subject="testing", sender="*****@*****.**", recipients=["*****@*****.**"], body="test")

        mailer.send_immediately(msg, True)
Example #7
0
    def test_send_immediately_and_fail_silently(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        mailer = Mailer(host="localhost", port="28322")

        msg = Message(subject="testing", sender="*****@*****.**", recipients=["*****@*****.**"], body="test")

        result = mailer.send_immediately(msg, True)
        self.assertEqual(result, None)
    def test_bcc_without_recipients(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.mailer import Mailer

        msg = Message(subject="testing", sender="*****@*****.**", body="testing", bcc=["*****@*****.**"])
        mailer = Mailer()
        msgid = mailer.send(msg)
        response = msg.to_message()

        self.assertFalse("Bcc: [email protected]" in text_type(response))
        self.assertTrue(msgid)
Example #9
0
    def test_send_immediately_and_fail_silently(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        mailer = Mailer()

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body="test")

        mailer.send_immediately(msg, True)
Example #10
0
    def test_send(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        mailer = Mailer()

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body="test")

        mailer.send(msg)
Example #11
0
    def test_cc_without_recipients(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.mailer import Mailer

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      body="testing",
                      cc=["*****@*****.**"])
        mailer = Mailer()
        msgid = mailer.send(msg)
        response = msg.to_message()

        self.assertTrue("Cc: [email protected]" in text_type(response))
        self.assertTrue(msgid)
    def test_send_without_body(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.exceptions import InvalidMessage

        msg = Message(subject="testing", sender="*****@*****.**", recipients=["*****@*****.**"])

        mailer = Mailer()

        self.assertRaises(InvalidMessage, mailer.send, msg)

        msg.html = "<b>test</b>"

        mailer.send(msg)
Example #13
0
def includeme(config):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('perturbtrafic_api.models')``.

    """
    settings = config.get_settings()
    settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'

    # use pyramid_tm to hook the transaction lifecycle to the request
    config.include('pyramid_tm')

    # use pyramid_retry to retry a request when transient exceptions occur
    config.include('pyramid_retry')

    session_factory = get_session_factory(get_engine(settings))
    config.registry['dbsession_factory'] = session_factory

    # Include pyramid mail
    config.registry['mailer'] = Mailer.from_settings(settings)

    # make request.dbsession available for use in Pyramid
    config.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(session_factory, r.tm),
        'dbsession',
        reify=True)
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, "sqlalchemy.")
    mailer = Mailer.from_settings(settings)
    DBSession.configure(bind=engine)

    rootFolder = settings["reports.folder"]

    request = Request.blank("/", base_url=settings["reports.app.url"])
    env = bootstrap(config_uri, request=request)
    request = env["request"]

    try:
        remove_groups(request)
        remove_reports(request)
        handleRootFolder(request, rootFolder)
        # email_users(request, mailer)
        email_admin_users(request, mailer)
        transaction.commit()
    except Exception as e:
        transaction.abort()
        stack = traceback.format_exc()
        body = "Got an exception while processing reports: %s\n\n%s" % (e, stack)
        message = Message(
            subject="Famoso Reports - failed to process",
            sender="*****@*****.**",
            recipients=["*****@*****.**"],
            body=body,
        )
        mailer.send_immediately(message)
Example #15
0
def main(global_config, **settings):
    """
    This function returns a Pyramid WSGI application.
    """
    # the database session:
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

#    session_factory = session_factory_from_settings(settings)
    config = Configurator(
        settings=settings,
        root_factory=get_root,
        authentication_policy=GyAuthenticationPolicy(),
        authorization_policy=GyAuthorizationPolicy(),
        session_factory = session_factory_from_settings(settings),
        request_factory = GyRequest,
    )

    config.add_static_view('static', 'static', cache_max_age=3600)
    
#    config.include('pyramid_mailer')

    mailer = Mailer.from_settings(settings)
    config.registry['mailer'] = mailer

    config.include('gy.core')
    config.include('gy.blog')
    config.add_notfound_view(gy_not_found, append_slash=True)


    config.scan()
    return config.make_wsgi_app()
Example #16
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application. """


    config = Configurator(settings=settings)

    #set up beaker session
    session_factory = session_factory_from_settings(settings)
    config.set_session_factory(session_factory)


    # add security tweens
 #   config.add_tween('aws_demo.tweens.clickjacking.clickjacking_factory')
 #   config.add_tween('aws_demo.tweens.secure_headers.secure_headers_factory')

    config.registry['mailer'] = Mailer.from_settings(settings=settings)

    # modify the built in json renderer to serialize dates properly
    json_date_renderer = JSON()
    json_date_renderer.add_adapter(datetime.datetime, new_datetime_adapter)
    
    # set .html renderer to allow mako templating
    config.add_renderer('.html', 'pyramid.mako_templating.renderer_factory')
    config.add_renderer('.htm', 'pyramid.mako_templating.renderer_factory')
    config.add_renderer('json', json_date_renderer)
    
    config.add_static_view('static', 'static', cache_max_age=3600)

    # login / registration
    config.add_route('index_view', '/')


    config.scan()
    return config.make_wsgi_app()
Example #17
0
    def test_use_ssl_mailer(self):

        try:
            from smtplib import SMTP_SSL
            ssl_enabled = True
        except ImportError:  # pragma: no cover
            from smtplib import SMTP
            ssl_enabled = False
        from pyramid_mailer.mailer import Mailer

        mailer = Mailer(ssl=True)
        if ssl_enabled:
            self.assert_(mailer.direct_delivery.mailer.smtp == SMTP_SSL)
            from ssl import SSLError
            try:
                self.assert_(mailer.direct_delivery.mailer.smtp_factory())
            except (IOError, SSLError):
                pass

        else:  # pragma: no cover
            self.assert_(mailer.direct_delivery.mailer.smtp == SMTP)
            import socket
            try:
                self.assert_(mailer.direct_delivery.mailer.smtp_factory())
            except socket.error, e:
                # smtp mailer might fail to resolve hostname
                self.assert_(e.args[0] == 61)
Example #18
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, "sqlalchemy.")
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    authn_policy = AuthTktAuthenticationPolicy("sosecret", callback=groupfinder, hashalg="sha512")
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings, root_factory="webapp.models.RootFactory")
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.registry["mailer"] = Mailer.from_settings(settings)
    config.add_static_view("static", "static", cache_max_age=3600)
    config.add_route("index", "/")
    config.add_route("login", "/login")
    config.add_route("logout", "/logout")
    config.add_route("registration", "/registration")
    # config.add_route('end_reg', '/activate/{a_code}')
    config.add_route("verify", "/verify/{code}")
    # config.add_route('confirm', '/confirm')
    config.add_route("content", "/content/{id}")
    config.add_route("about", "/about")
    config.add_route("pay", "/pay")
    config.add_route("preview", "/preview")
    config.add_route("bundle_preview", "/bundle_preview")
    config.add_route("b_content", "/bonus/{id}")
    config.add_route("bundle", "/bundle/{id}")
    config.add_route("account", "/account/{parameters}")
    config.scan()

    return config.make_wsgi_app()
Example #19
0
def app_factory(global_config, **settings):
    from datetime import datetime
    from io import open as io_open
    from os import listdir
    from os.path import join as joinpath
    from random import Random
    from urllib2 import build_opener
    import uuid

    from sqlalchemy import create_engine
    import ldap

    cwd = Path('.', open=io_open, joinpath=joinpath, listdir=listdir)

    log.debug('in app_factory')
    [config] = RunTime.make([HeronAdminConfig],
                            cwd=cwd,
                            settings=settings,
                            create_engine=create_engine,
                            ldap=ldap,
                            uuid=uuid,
                            urlopener=build_opener(),
                            timesrc=datetime,
                            rng=Random(),
                            mailer=Mailer.from_settings(settings))

    # https://pylonsproject.org/projects/pyramid_exclog/dev/
    # self.include('pyramid_exclog')
    config.add_view(server_error_view,
                    renderer='oops.html',
                    context=Exception,
                    permission=pyramid.security.NO_PERMISSION_REQUIRED)

    return config.make_wsgi_app()
Example #20
0
def mailer_factory_from_settings(settings, prefix='mail.'):
    """
    Factory function to create a Mailer instance from settings.
    Equivalent to :meth:`pyramid_mailer.mailer.Mailer.from_settings`.

    :versionadded: 0.2.2
    """
    return Mailer.from_settings(settings, prefix)
Example #21
0
def mailer_factory_from_settings(settings, prefix='mail.'):
    """
    Factory function to create a Mailer instance from settings.
    Equivalent to :meth:`pyramid_mailer.mailer.Mailer.from_settings`.

    :versionadded: 0.2.2
    """
    return Mailer.from_settings(settings, prefix)
Example #22
0
    def test_send_without_body(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.exceptions import InvalidMessage

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"])

        mailer = Mailer()

        self.assertRaises(InvalidMessage, mailer.send, msg)

        msg.html = "<b>test</b>"

        mailer.send(msg)
Example #23
0
    def test_send(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Attachment
        from pyramid_mailer.message import Message

        mailer = Mailer()

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body="test")
        msg.attach(Attachment('test.txt',
                              data=b"this is a test", 
                              content_type="text/plain"))

        mailer.send(msg)
Example #24
0
def mailer_factory_from_settings(settings, prefix='mail.'):
    """
    Factory function to create a Mailer instance from settings.
    Equivalent to **Mailer.from_settings**

    :versionadded: 0.2.2
    """
    return Mailer.from_settings(settings, prefix)
Example #25
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    authentication_policy = AuthTktAuthenticationPolicy('seekrit', callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()

    engine = engine_from_config(settings, prefix='sqlalchemy.')
    db_maker = sessionmaker(bind=engine)
    settings['rel_db.sessionmaker'] = db_maker

    config = Configurator(settings=settings,
                          root_factory='scielobooks.resources.RootFactory',
                          authentication_policy=authentication_policy,
                          authorization_policy=authorization_policy,
                          request_factory=MyRequest,
                          renderer_globals_factory=renderer_globals_factory)

    config.include(pyramid_zcml)
    config.load_zcml('configure.zcml')
    config.include('pyramid_mailer')
    config.include('pyramid_celery')

    config.registry['mailer'] = Mailer.from_settings(settings)
    config.registry['app_version'] = APP_VERSION

    db_uri = settings['db_uri']
    conn = couchdbkit.Server(db_uri)
    config.registry.settings['db_conn'] = conn
    config.add_subscriber(add_couch_db, NewRequest)

    config.scan('scielobooks.models')
    initialize_sql(engine)

    if settings['serve_static_files'] == 'true':
        config.add_static_view(name='static', path='static')
    config.add_static_view('deform_static', 'deform:static')
    config.add_static_view('/'.join((settings['db_uri'], settings['db_name'])), 'scielobooks:database')
    config.add_static_view(settings['fileserver_url'], 'scielobooks:fileserver')

    config.add_view(custom_forbidden_view, context=Forbidden)

    config.add_translation_dirs('scielobooks:locale/')
    config.set_locale_negotiator(custom_locale_negotiator)

    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    config.set_session_factory(my_session_factory)

    application = config.make_wsgi_app()

    try:
        if settings.get('newrelic.enable', 'False').lower() == 'true':
            newrelic.agent.initialize(os.path.join(APP_PATH, '..', 'newrelic.ini'), settings['newrelic.environment'])
            return newrelic.agent.wsgi_application()(application)
        else:
            return application
    except IOError:
        config.registry.settings['newrelic.enable'] = False
        return application
Example #26
0
    def __init__(self, *args, **settings):
        if len(args) == 1:
            # regular app
            app = None
        else:
            app = args[0]
        self.initialize_settings(app, settings)

        # db configuration
        db_factory_name = settings.get('db_factory_name', 'sql')
        if db_factory_name not in db_factories:
            raise Exception("Invalid db_factory_name: %s" % db_factory_name)
        settings['db_session_id'], self.db = db_factories[db_factory_name](
            settings, self)  # noqa

        self.setup_autouserfinder(settings)

        # start pyramid application configuration
        config = Configurator(settings=settings, request_factory=Request)
        try:
            import pyramid_chameleon  # noqa
            config.include('pyramid_chameleon')
        except ImportError:
            pass

        self.setup_plugins(config, settings)

        from factored.views import auth_chooser, notfound
        config.add_route('auth', self.base_auth_url)
        config.add_view(auth_chooser,
                        route_name='auth',
                        renderer='templates/layout.pt')

        # setup template customization registration
        if TEMPLATE_CUSTOMIZATIONS not in config.registry:
            config.registry[TEMPLATE_CUSTOMIZATIONS] = {}

        # static paths for resources
        self.static_path = os.path.join(self.base_auth_url, 'authstatic')
        config.add_static_view(name=self.static_path, path='factored:static')
        config.add_notfound_view(notfound, append_slash=True)

        # add some things to registry
        config.registry['mailer'] = Mailer.from_settings(settings)
        config.registry['settings'] = self.__dict__
        config.registry['formtext'] = nested_settings(
            get_settings(settings, 'formtext.'))
        config.registry['app'] = self

        config.scan()
        self.config = config
        self.registry = self.config.registry
        try:
            self.app.config.registry['factored'] = self
        except:
            pass
        self.pyramid = config.make_wsgi_app()
Example #27
0
def profile(request):
    """
    View profile page.
    """
    user = User.get(request.session['login'])

    if request.method =='POST':

        flashError = "Sorry dude : wrong password"

        if not request.POST['initPassword'].strip():
            request.session.flash('No password provided')
            return {'user':user}


        elif not bcrypt.hashpw(request.POST['initPassword'].encode('utf-8'), user.password) == user.password:
            request.session.flash(flashError)
            return {'user':user}

        if request.POST['submitDelete']:
            mailer = Mailer()
            message = Message(subject="Account deleted",
                             sender=settings['mail_from'],
                             recipients=[user.mail],
                             body="Your account have been deleted")
            mailer.send_immediately(message, fail_silently=False)
            user.delete()
            request.session.delete()
            return HTTPFound(location=request.route_path('home'))

        if request.POST['newPassword'].strip():
            if request.POST['newPassword'] == request.POST['confirmPassword']:
                password = bcrypt.hashpw(request.POST['newPassword'].encode('utf-8'), bcrypt.gensalt())
                user.password = password
            else:
                request.session.flash(u"Password not confirm")
                return {'user' : user}

        user.name = request.POST['name']
        user.description = request.POST['description']
        user.mail = request.POST['email']
        user.save()
        request.session.flash(u"Modification saved !")
    return {'user':user}
Example #28
0
def contato(request):
    """Contato"""
    # Import smtplib for the actual sending function
    import smtplib
	
    esquema = FormContato().bind(request=request)
    esquema.title = "Entre em contato com o Cuidando"
    form = deform.Form(esquema, buttons=('Enviar',))
    if 'Enviar' in request.POST:
        # Validação do formulário
        try:
            form.validate(request.POST.items())
        except deform.ValidationFailure as e:
            return {'form': e.render()}

        #sender = request.POST.get("email")
        #receivers = ['*****@*****.**']	
        #message = request.POST.get("assunto")	
				        						
        try:
            #s = smtplib.SMTP( [host [, port [, local_hostname]]] )
            #s = smtplib.SMTP('pop.mail.yahoo.com.br',587)
            #smtpObj.sendmail(sender, receivers, message)	
            #s.quit()			
            #mailer = get_mailer(request)		
            mailer = Mailer()			
            message = Message(
                subject=request.POST.get("assunto"),
                sender= request.POST.get("email"), #"*****@*****.**",
                recipients=['*****@*****.**'],
                body=request.POST.get("mensagem")
            )		
            mailer.send(message)	
            transaction.commit() 	
            print "Successfully sent email"
		#except SMTPException:
        except:
            print "Error: unable to send email"		
      
		
        return HTTPFound(location=request.route_url('inicial'))
    else:
        # Apresentação do formulário
        return {'form': form.render()}
Example #29
0
    def __init__(self, *args, **settings):
        if len(args) == 1:
            # regular app
            app = None
        else:
            app = args[0]
        self.initialize_settings(app, settings)

        # db configuration
        db_factory_name = settings.get('db_factory_name', 'sql')
        if db_factory_name not in db_factories:
            raise Exception("Invalid db_factory_name: %s" % db_factory_name)
        settings['db_session_id'], self.db = db_factories[db_factory_name](settings, self)  # noqa

        self.setup_autouserfinder(settings)

        # start pyramid application configuration
        config = Configurator(settings=settings, request_factory=Request)
        try:
            import pyramid_chameleon  # noqa
            config.include('pyramid_chameleon')
        except ImportError:
            pass

        self.setup_plugins(config, settings)

        from factored.views import auth_chooser, notfound
        config.add_route('auth', self.base_auth_url)
        config.add_view(auth_chooser, route_name='auth',
                        renderer='templates/layout.pt')

        # setup template customization registration
        if TEMPLATE_CUSTOMIZATIONS not in config.registry:
            config.registry[TEMPLATE_CUSTOMIZATIONS] = {}

        # static paths for resources
        self.static_path = os.path.join(self.base_auth_url, 'authstatic')
        config.add_static_view(name=self.static_path,
                               path='factored:static')
        config.add_notfound_view(notfound, append_slash=True)

        # add some things to registry
        config.registry['mailer'] = Mailer.from_settings(settings)
        config.registry['settings'] = self.__dict__
        config.registry['formtext'] = nested_settings(
            get_settings(settings, 'formtext.'))
        config.registry['app'] = self

        config.scan()
        self.config = config
        self.registry = self.config.registry
        try:
            self.app.config.registry['factored'] = self
        except:
            pass
        self.pyramid = config.make_wsgi_app()
Example #30
0
def send_confirmation_email(email, link):
    email = email
    link = link

    mailer = Mailer(host=host,
                    port=port,
                    username=username,
                    password=password,
                    ssl=True)

    subject = "Welcome.  Please verify your email."
    body = f'Please verify your email by clicking this link: {link} '
    #Create html.jinja2 template for email body

    message = Message(subject=subject,
                      sender=username,
                      recipients=[email],
                      body=body)

    mailer.send_immediately(message)
Example #31
0
    def test_send_to_queue(self):

        import os
        import tempfile

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        test_queue = os.path.join(tempfile.gettempdir(), "test_queue")
        for dir in ("cur", "new", "tmp"):
            try:
                os.makedirs(os.path.join(test_queue, dir))
            except OSError:
                pass

        mailer = Mailer(queue_path=test_queue)

        msg = Message(subject="testing", sender="*****@*****.**", recipients=["*****@*****.**"], body="test")

        mailer.send_to_queue(msg)
Example #32
0
    def test_send_without_recipients(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.exceptions import InvalidMessage

        mailer = Mailer()

        msg = Message(subject="testing", recipients=[], body="testing")

        self.assertRaises(InvalidMessage, mailer.send, msg)
Example #33
0
    def test_send_immediately_multipart(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        mailer = Mailer()

        utf_8_encoded = b('mo \xe2\x82\xac')
        utf_8 = utf_8_encoded.decode('utf_8')

        text_string = utf_8
        html_string = '<p>'+utf_8+'</p>'

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body=text_string,
                      html=html_string)

        mailer.send_immediately(msg, True)
Example #34
0
    def test_send_to_queue_unconfigured(self):

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body="test")
        mailer = Mailer()

        self.assertRaises(RuntimeError, mailer.send_to_queue, msg)
Example #35
0
def send_mail(request):

    mailer = Mailer( host='smtp.gmail.com',
                     port=587, #???
                     username='******',
                     password='******',
                     tls=True)

    if request.params.get('email') is not None:
        email = request.params['email']
    else:
        email = "the email does not exist"

    send_topic = 'Welcome to join us for the seminar'
    send_er = '*****@*****.**'
    send_to = [email]
    send_this = "Thank you for signing up at our website..."

    message = Message( subject = send_topic,
                       sender = send_er,
                       recipients = send_to,
                       body = send_this )

    here = os.path.dirname(__file__)
    att1 = os.path.join(here, 'static','velur1.pdf')
    attachment = Attachment(att1, "image/jpg",
                        open(att1, "rb"))

    message.attach(attachment)

    here = os.path.dirname(__file__)
    att2 = os.path.join(here, 'static','velur2.pdf')
    attachment = Attachment(att2, "image/jpg",
                        open(att2, "rb"))

    message.attach(attachment)

   # mailer.send_immediately(message, fail_silently=False)
    mailer.send(message)
    return Response(email)
Example #36
0
def init_mailer(config, mailer=None):

    settings = config.registry.settings
    settings['mail.default_sender'] = settings.get(
        'mail.default_sender',
        formataddr(('Site administrator', 'admin@localhost')))

    if not mailer:
        mailer = Mailer.from_settings(settings)

    config.registry.registerUtility(mailer, IMailer)

    log.info("Initialize mailer")
Example #37
0
def main():
    if len(sys.argv) < 2:
        usage(sys.argv)
    config_uri = sys.argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    Session.configure(bind=engine)

    mailer = Mailer.from_settings(settings)
    ldap_conn = helper.connect()
    for line in sys.stdin:
        merge_to_umail(ldap_conn, mailer, *line.strip().split())
    transaction.commit()
Example #38
0
def main():
    if len(sys.argv) < 2:
        usage(sys.argv)
    config_uri = sys.argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    Session.configure(bind=engine)

    mailer = Mailer.from_settings(settings)
    ldap_conn = helper.connect()
    for line in sys.stdin:
        merge_to_umail(ldap_conn, mailer, *line.strip().split())
    transaction.commit()
Example #39
0
    def test_send_to_queue(self):

        import os
        import tempfile

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        test_queue = os.path.join(tempfile.gettempdir(), 'test_queue')
        for dir in ('cur', 'new', 'tmp'):
            try:
                os.makedirs(os.path.join(test_queue, dir))
            except OSError:
                pass

        mailer = Mailer(queue_path=test_queue)

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body="test")

        mailer.send_to_queue(msg)
Example #40
0
    def test_bad_header_sender(self):

        from pyramid_mailer.message import Message
        from pyramid_mailer.mailer import Mailer

        from pyramid_mailer.exceptions import BadHeaders

        mailer = Mailer()

        msg = Message(subject="testing",
                      sender="[email protected]\n\r",
                      recipients=["*****@*****.**"],
                      body="testing")
        self.assertRaises(BadHeaders, mailer.send, msg)
Example #41
0
def send_mail(request):

    mailer = Mailer(
        host='smtp.gmail.com',
        port=587,  #???
        username='******',
        password='******',
        tls=True)

    if request.params.get('email') is not None:
        email = request.params['email']
    else:
        email = "the email does not exist"

    send_topic = 'Welcome to join us for the seminar'
    send_er = '*****@*****.**'
    send_to = [email]
    send_this = "Thank you for signing up at our website..."

    message = Message(subject=send_topic,
                      sender=send_er,
                      recipients=send_to,
                      body=send_this)

    attachment = Attachment("velur1.pdf", "image/jpg",
                            open("velur1.pdf", "rb"))

    message.attach(attachment)

    attachment = Attachment("velur2.pdf", "image/jpg",
                            open("velur2.pdf", "rb"))

    message.attach(attachment)

    # mailer.send_immediately(message, fail_silently=False)
    mailer.send(message)
    return Response(email)
Example #42
0
    def __init__(self, *args, **settings):
        if len(args) == 1:
            # regular app
            app = None
        else:
            app = args[0]
        self.initialize_settings(app, settings)

        # db configuration
        engine = engine_from_config(settings, 'sqlalchemy.')
        configure_db = settings.pop('configure_db', 'true').lower() == 'true'

        if configure_db:
            DBSession.configure(bind=engine)
            self.db_session_id = 'f'
        else:
            self.db_session_id = settings.pop('db_session_id')

        self.setup_autouserfinder(settings)

        # start pyramid application configuration
        config = Configurator(settings=settings, request_factory=Request)

        self.setup_plugins(config, settings)

        from factored.views import auth_chooser, notfound
        config.add_route('auth', self.base_auth_url)
        config.add_view(auth_chooser, route_name='auth',
                        renderer='templates/layout.pt')

        # setup template customization registration
        if TEMPLATE_CUSTOMIZATIONS not in config.registry:
            config.registry[TEMPLATE_CUSTOMIZATIONS] = {}

        # static paths for resources
        self.static_path = os.path.join(self.base_auth_url, 'authstatic')
        config.add_static_view(name=self.static_path,
                               path='factored:static')
        config.add_notfound_view(notfound, append_slash=True)

        # add some things to registry
        config.registry['mailer'] = Mailer.from_settings(settings)
        config.registry['settings'] = self.__dict__
        config.registry['formtext'] = nested_settings(
            get_settings(settings, 'formtext.'))
        config.registry['app'] = self

        config.scan()
        self.pyramid = config.make_wsgi_app()
Example #43
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    l = LoginDAO()
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)    
    Base.metadata.bind = engine
    authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=l.groupfinder, hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings, root_factory="terminus.models.Login")
    config.registry['mailer'] = Mailer.from_settings(settings)
    config.set_session_factory(my_session_factory)
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    #Admin routes
    config.add_route('adm', '/adm')
    config.add_route('clientes', '/adm/clientes')
    config.add_route('gerentes', '/adm/gerentes')
    config.add_route('novoprojeto', '/adm/novoprojeto')
    config.add_route('novogerente', '/adm/novogerente')
    config.add_route('addgerente', '/adm/addgerente')
    config.add_route('editargerente', '/adm/{id}/editargerente')
    config.add_route('deletargerente', '/adm/{id}/deletargerente')
    config.add_route('deletarcliente', '/adm/{id}/deletarcliente')
    config.add_route('atualizargerente', '/adm/atualizargerente')
    config.add_route('novocliente', '/adm/novocliente')
    config.add_route('addcliente', '/adm/addcliente')
    config.add_route('projeto', '/adm/projeto/{pid}/')
    config.add_route('addprojeto', '/adm/addprojeto')
    config.add_route('tarefa', '/adm/projeto/{id}/addtarefa')
    config.add_route('finalizar-tarefa', '/adm/projeto/{id}/finalizar/{status}/{pid}')
    config.add_route("responder-alteracao","adm/{id}/responderalteracao/{pid}")
    config.add_route("configuracoes","/adm/configuracoes")
    config.add_route("cadastro-email","/adm/cadastro-email/")
    config.add_route("atualizar-email","/adm/atualizar-email/")

    #Client routes
    config.add_route('login-gerentes', '/adm/login')
    config.add_route("cliente-index","/{id}/index")
    config.add_route("cliente-dados","/{id}/dados")
    config.add_route("cliente-atualizar","/{id}/atualizarcliente")
    config.add_route("projeto-cliente","/{id}/projeto/{pid}")
    config.add_route("projeto-aprovacao","/{id}/projetoaprovacao/{pid}")
    config.add_route("solicitar-alteracao","/{id}/solicitaralteracao/{pid}")
    config.scan()
    return config.make_wsgi_app()
Example #44
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings.update(parse_settings(settings))
    
    authentication_policy = AuthTktAuthenticationPolicy('seekrit', callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings,
                          root_factory='scielobooks.resources.RootFactory',
                          authentication_policy=authentication_policy,
                          authorization_policy=authorization_policy,
                          request_factory=MyRequest,
                          renderer_globals_factory=renderer_globals_factory)

    engine = engine_from_config(config.registry.settings, prefix='sqlalchemy.')
    db_maker = sessionmaker(bind=engine)

    config.registry.settings['rel_db.sessionmaker'] = db_maker
    config.include(pyramid_zcml)
    config.load_zcml('configure.zcml')
    config.include('pyramid_mailer')
    config.include('pyramid_celery')

    config.registry['mailer'] = Mailer.from_settings(config.registry.settings)
    config.registry['app_version'] = APP_VERSION

    db_uri = config.registry.settings['db_uri']
    conn = couchdbkit.Server(db_uri)
    config.registry.settings['db_conn'] = conn
    config.add_subscriber(add_couch_db, NewRequest)

    config.scan('scielobooks.models')
    initialize_sql(engine)

    if config.registry.settings['serve_static_files'] is True:
        config.add_static_view(name='static', path='static')
    config.add_static_view('deform_static', 'deform:static')
    config.add_static_view('/'.join((config.registry.settings['db_uri'], config.registry.settings['db_name'])), 'scielobooks:database')
    config.add_static_view(config.registry.settings['fileserver_url'], 'scielobooks:fileserver')

    config.add_view(custom_forbidden_view, context=Forbidden)

    config.add_translation_dirs('scielobooks:locale/')
    config.set_locale_negotiator(custom_locale_negotiator)

    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    config.set_session_factory(my_session_factory)

    return config.make_wsgi_app()
Example #45
0
def send_mail(request):

    mailer = Mailer( host='smtp.gmail.com',
                     port=587, #???
                     username='******',
                     password='******',
                     tls=True)

    if request.params.get('email') is not None:
        email = request.params['email']
    else:
        email = "the email does not exist"

    send_topic = 'Welcome to join us for the seminar'
    send_er = '*****@*****.**'
    send_to = [email]
    send_this = "Thank you for signing up at our website..."

    message = Message( subject = send_topic,
                       sender = send_er,
                       recipients = send_to,
                       body = send_this )

    attachment = Attachment("velur1.pdf", "image/jpg",
                        open("velur1.pdf", "rb"))

    message.attach(attachment)

    attachment = Attachment("velur2.pdf", "image/jpg",
                        open("velur2.pdf", "rb"))

    message.attach(attachment)

   # mailer.send_immediately(message, fail_silently=False)
    mailer.send(message)
    return Response(email)
Example #46
0
    def test_send_immediately(self):

        import socket

        from pyramid_mailer.mailer import Mailer
        from pyramid_mailer.message import Message

        mailer = Mailer(host='localhost', port='28322')

        msg = Message(subject="testing",
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"],
                      body="test")

        self.assertRaises(socket.error, mailer.send_immediately, msg)
Example #47
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    
    # Authentication & authorisation
    authentication_policy = AuthTktAuthenticationPolicy('seekrit', callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()
    
    # Sessions
    session_factory = pyramid_beaker.session_factory_from_settings(settings)
    
    config = Configurator(
            root_factory=Root,
            settings=settings,
            authentication_policy=authentication_policy,
            authorization_policy=authorization_policy,
            session_factory=session_factory,
            )

    # Add helpers to render
    config.add_subscriber(add_renderer_globals, BeforeRender)

    # MongoDB related
    db_uri = settings['db_uri']
    conn = pymongo.Connection(db_uri)    
    config.registry.settings['db_conn'] = conn
    config.add_subscriber(add_mongo_db, NewRequest)
    
    # Delete if running in development mode
    if settings['db.reset'] == 'true':
        conn.drop_database(settings['db_name'])
    
    initialize_mongo(conn[settings['db_name']])
    dbupdates.update(conn[settings['db_name']])
    
    # Mailer
    config.include('pyramid_mailer')
    config.registry['mailer'] = Mailer.from_settings(settings)
    
    # CSRF check
    config.add_subscriber(csrf_validation, NewRequest)
    
    config.add_static_view('static', 'formative:static')
    config.scan()
    return config.make_wsgi_app()
Example #48
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    authentication_policy = AuthTktAuthenticationPolicy('seekrit', callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()
    
    engine = engine_from_config(settings, prefix='sqlalchemy.')
    db_maker = sessionmaker(bind=engine)
    settings['rel_db.sessionmaker'] = db_maker

    config = Configurator(settings=settings,
                          root_factory='scielobooks.resources.RootFactory',
                          authentication_policy=authentication_policy,
                          authorization_policy=authorization_policy,
                          request_factory=MyRequest)

    config.include(pyramid_zcml)
    config.load_zcml('configure.zcml')
    config.include('pyramid_mailer')

    config.registry['mailer'] = Mailer.from_settings(settings)

    db_uri = settings['db_uri']
    conn = couchdbkit.Server(db_uri)
    config.registry.settings['db_conn'] = conn
    config.add_subscriber(add_couch_db, NewRequest)
    
    config.scan('scielobooks.models')
    initialize_sql(engine)

    if settings['serve_static_files'] == 'true':
        config.add_static_view(name='static', path='static')
    config.add_static_view('deform_static', 'deform:static')
    config.add_static_view(settings['books_static_url'], 'scielobooks:books')
    config.add_static_view('/'.join((settings['db_uri'], settings['db_name'])), 'scielobooks:database')
    
    config.add_view(custom_forbidden_view, context=Forbidden)

    config.add_translation_dirs('scielobooks:locale/')
    config.set_locale_negotiator(custom_locale_negotiator)

    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    config.set_session_factory(my_session_factory)

    return config.make_wsgi_app()
 def __init__(self, access_token, search_fields, keywords, mail_settings=None,
              mail_targets=None):
     self.access_token = access_token
     self.search_fields = search_fields
     self.keywords = keywords
     self.regex_get_keywords = re.compile("[\w']+")
     self.processed_posts = collections.Counter()
     self.keyword_frequency = collections.Counter()
     self.run_count = 0
     self.failure_count = 0
     if mail_settings is not None:
         self.mailer = Mailer.from_settings(mail_settings)
         self.mail_settings = mail_settings
         self.mail_targets = mail_targets
     else:
         self.mailer = None
         self.mail_settings = None
         self.mail_targets = None
Example #50
0
def main(global_config, **settings):
    """ This function returns a WSGI application.
    """
    #engine = engine_from_config(settings, 'sqlalchemy.')
    #DBSession.configure(bind=engine)
    
    config = Configurator(settings=settings, root_factory=RootFactory)
#    config = Configurator(settings=settings)
    #config.add_subscriber(add_renderer_globals, BeforeRender)
    # HTML Rederer
    config.add_renderer('.html', 'pyramid.mako_templating.renderer_factory')
    # Configure Beaker sessions
    #session_factory = UnencryptedCookieSessionFactoryConfig(settings)
    session_factory = pyramid_beaker.session_factory_from_settings(settings)
    print session_factory
    config.set_session_factory(session_factory)
    # Authendication/Autherization
    authn_policy = AuthTktAuthenticationPolicy(
                       settings.get('mool.auth_secret'),
                       #secure = True,
                       http_only = True,
                       callback=group_finder)
    config.set_authentication_policy(authn_policy)

    authz_policy = ACLAuthorizationPolicy()
    config.set_authorization_policy(authz_policy)
    # Request Object With user object
    config.set_request_factory(RequestWithUserAttribute)
    # Pyramid_mailer Configuration 
    config.registry['mailer'] = Mailer.from_settings(settings)

    config.add_view('pyramid.view.append_slash_notfound_view',
                    context='pyramid.httpexceptions.HTTPNotFound')
    config.add_static_view('static', 'mool:static', cache_max_age=360000)
    config.add_route('index', '')
    config.add_route('register.view', '/register/')
    config.add_route('durga_update.view', '/durga_update/')
    config.add_route('durga_find.view', '/durga_find/')
    config.scan('durga.views')

    #Base.metadata.create_all(engine)
    #initialize_connection()
    return config.make_wsgi_app()
Example #51
0
def main(argv=sys.argv):
    """main function
    """
    if len(argv) != 2:
        usage(argv)

    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)

    # global here
    global stalker_server_external_url
    global mailer
    global resource_mail_html_template
    global responsible_mail_html_template
    global resource_mail_html_template_content
    global responsible_mail_html_template_content

    # here = os.path.dirname(os.path.realpath(sys.argv[0]))
    stalker_server_external_url = settings.get('stalker.external_url')
    mailer = Mailer.from_settings(settings)

    with open(resource_mail_html_template_path) as f:
        resource_mail_html_template_content = f.read()

    with open(responsible_mail_html_template_path) as f:
        responsible_mail_html_template_content = f.read()

    resource_mail_html_template = Template(resource_mail_html_template_content)
    responsible_mail_html_template = Template(
        responsible_mail_html_template_content)

    db.setup(settings)

    for user in User.query.all():
        send_resource_remainder(user)
        send_responsible_remainder(user)

    transaction.commit()
Example #52
0
    def test_from_settings(self):

        try:
            from smtplib import SMTP_SSL
            ssl_enabled = True
        except ImportError:  # pragma: no cover
            from smtplib import SMTP
            ssl_enabled = False
        from pyramid_mailer.mailer import Mailer

        settings = {
            'mymail.host': 'my.server.com',
            'mymail.port': 123,
            'mymail.username': '******',
            'mymail.password': '******',
            'mymail.tls': True,
            'mymail.ssl': True,
            'mymail.keyfile': 'ssl.key',
            'mymail.certfile': 'ssl.crt',
            'mymail.queue_path': '/tmp',
            'mymail.debug': 1
        }

        mailer = Mailer.from_settings(settings, prefix='mymail.')

        self.assert_(mailer.direct_delivery.mailer.hostname == 'my.server.com')
        self.assert_(mailer.direct_delivery.mailer.port == 123)
        self.assert_(mailer.direct_delivery.mailer.username == 'tester')
        self.assert_(mailer.direct_delivery.mailer.password == 'test')
        self.assert_(mailer.direct_delivery.mailer.force_tls == True)
        if ssl_enabled:
            self.assert_(mailer.direct_delivery.mailer.smtp == SMTP_SSL)
        else:  # pragma: no cover
            self.assert_(mailer.direct_delivery.mailer.smtp == SMTP)

        self.assert_(mailer.direct_delivery.mailer.keyfile == 'ssl.key')
        self.assert_(mailer.direct_delivery.mailer.certfile == 'ssl.crt')
        self.assert_(mailer.queue_delivery.queuePath == '/tmp')
        self.assert_(mailer.direct_delivery.mailer.debug_smtp == 1)
Example #53
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    authn_policy = AuthTktAuthenticationPolicy('sosecret',
                                               callback=groupfinder,
                                               hashalg='sha512',
                                               timeout=60 * 60 * 24 *
                                               7)  ## Change it
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings,
                          root_factory='main_page.models.RootFactory')
    config.include('pyramid_mailer')
    config.include('pyramid_mako')
    config.registry['mailer'] = Mailer.from_settings(settings)
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    #config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view('assets', 'assets', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('install', '/install')
    config.add_route('radio', '/radio')

    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('register', '/register')
    config.add_route('forgot_password', '/forgot-password')
    config.add_route('activate_account', '/activate-account')

    config.add_route('zastepstwa', '/zastepstwa')
    config.add_renderer('jsonp', JSONP(param_name='callback'))

    config.add_route('api', '/api')
    config.add_route('jsonp_mobile_login', '/api/jsonp/mobile_login')

    config.add_route('jsonp_system_info', '/api/jsonp/system_info')

    config.add_route('admin_home', '/admin')
    config.add_route('admin', '/admin/{page}')
    config.add_route('admin_pp', '/admin/{pp}/{page}')

    config.add_route('admin_log_years_groups',
                     '/admin/log/years/groups/{year}')
    config.add_route('admin_log_years_groups_students',
                     '/admin/log/years/groups/{year}/{group}')
    config.add_route('admin_log_timetables', '/admin/log/timetables')
    config.add_route('admin_log_timetables_edit', '/admin/log/timetables/{id}')

    config.add_route('admin_substitutions', '/admin/substitutions')
    config.add_route('admin_substitutions_add', '/admin/substitutions/add')
    config.add_route('admin_substitutions_view',
                     '/admin/substitutions_view/{id}')
    config.add_route('admin_substitutions_edit',
                     '/admin/substitutions_edit/{id}')
    config.add_route('admin_substitutions_del',
                     '/admin/substitutions_del/{id}')

    config.add_route('account_folders', '/account/folders')
    config.add_route('account_entries', '/account/entries')
    config.add_route('account_presentations', '/account/presentations')
    config.add_route('account_tasks_sets', '/account/tasks-sets')
    config.add_route('account_questions_sets', '/account/questions-sets')
    config.add_route('account_other', '/account/other')
    config.add_route('account', '/account')
    config.add_route('phone_app', '/account/phone')

    config.add_route('support_ask', '/support/ticket-new')
    config.add_route('support_ask_ticket', '/support/ticket-{id}')
    config.add_route('support_faq', '/support/faq')

    config.add_route('gallery_list', '/gallery')
    config.add_route('gallery', '/gallery/{id}')

    config.add_route('syllabus', '/syllabus')
    config.add_route('syllabus_year', '/syllabus/{year}')
    config.add_route('syllabus_profile', '/syllabus/{year}/{profile}')
    config.add_route('syllabus_extension',
                     '/syllabus/{year}/{profile}/{extension}')
    config.add_route('competitions', '/competitions/{path_name}')

    config.add_route('file_upload', '/file-upload')

    config.add_route('connection', '/connection')

    config.add_route('loading', '/loading')
    config.add_route('entries', '/entries')
    config.add_route('entry_save', '/entry/save')
    config.add_route('page', '/p/{id}')
    config.add_route('user', '/u/{id}')
    config.add_route('entry', '/entry/{id}')
    config.add_route('folder', '/folder/{id}')
    config.add_route('presentations', '/presentations')
    config.add_route('presentation', '/presentation/{id}')
    config.add_route('set', '/set/{id}')

    config.add_route('lucky', '/sis/lucky')
    config.add_route('sis_home', '/sis')
    config.add_route('sis_about', '/sis/about')
    config.add_route('schedule', '/sis/schedule')
    config.add_route('map', '/map')
    config.add_route('socketio', 'socket.io/*remaining')

    #    config.add_route('anki_sync_meta', '/syncmeta')
    #    config.add_route('anki_sync_upload', '/syncupload')
    #    config.add_route('sync_media_list', '/syncmediaList')
    #    config.add_route('sync_remove', '/syncremove')
    #    config.add_route('sync_files', '/syncfiles')
    #    config.add_route('sync_host_key', '/synchostKey')
    #    config.add_route('sync_download', '/syncdownload')

    config.add_route('joomla', '/joomla')
    config.add_route('confirm', '/confirm')

    config.add_route('easy_link', '/{link}')

    wa_env = get_webassets_env(config)
    for x in os.walk("main_page/static/src/"):
        for y in x:
            for z in y:
                if z[-7:] == ".min.js":
                    name = x[0][21:] + "/" + z
                    b = Bundle("src/" + name,
                               output=name,
                               filters=['closure_js'])
                    wa_env.register(name + "h", b)
                    print b.urls()
                if z[-3:] == ".js":
                    name = x[0][21:] + "/" + z
                    b = Bundle("src/" + name,
                               output=name[:-3] + ".min.js",
                               filters=['closure_js'])
                    wa_env.register(name, b)
                    print b.urls()
    for x in os.walk("main_page/static/src/"):
        for y in x:
            for z in y:
                if z[-4:] == ".css":
                    name = x[0][21:] + "/" + z
                    b = Bundle("src/" + name, output=name[:-4] + ".min.css")
                    wa_env.register(name, b)
                    print b.urls()
    #, filters=['cssmin']
    #scroll_up_css=Bundle("libs/scrollup/themes/pill.css")
    #scroll_up_js=Bundle("libs/scrollup/jquery.scrollUp.min.js","js/scroll_up.js")

    #diagrams=Bundle("libs/raphael/raphael-min.js","libs/jquery.browser/jquery.browser.js","js/diagrams.js")
    #noisy_js=Bundle("js/noisy.js")
    #content_js=Bundle("js/content.js") ## bonzo (?)
    #content_css=Bundle("css/content.css","css/entries.css")
    #spoiler_js=Bundle("libs/spoiler/spoiler.js","js/spoiler.js")

    #easteregg_js=Bundle('libs/easter/easter.js')  #easter_egg
    #gravity = Bundle('libs/easter/gravity/jGravity.js')  #does not work properly

    #c_css = Bundle(scroll_up_css, owl_css, content_css, social_css, raptor_css, output='gen/content.min.css',  debug=False)

    #r_js = Bundle(cookie_js, bootstrap_js, owl_js, time_js, fit_vids_js, flickr_js, base_js, holder_js, progression_js, 'js/form_login.js', output='gen/main.min.js', debug=False)
    #r_css =  Bundle(bootstrap_css, cookie_css, owl_css, base_css,progression_css, output='gen/main.min.css', debug=False)

    config.include('pyramid_rewrite')
    config.add_rewrite_rule(r'/(?P<path>.*)/', r'/%(path)s')
    config.scan()
    return config.make_wsgi_app()
Example #54
0
def main(global_config, **settings):

    authn_policy = AuthTktAuthenticationPolicy('sosecret',
                                               callback=groupfinder)
    authz_policy = ACLAuthorizationPolicy()
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    config = Configurator(settings=settings,
                          root_factory='yapp.models.root_factory.RootFactory',
                          session_factory=my_session_factory)
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    mailer = Mailer()
    config.registry['mailer'] = Mailer.from_settings(settings)
    config.add_static_view('static', os.path.join(here, 'static'))
    config.add_route('login', '/')
    #    config.add_route('index', '/index')
    config.add_route('readproyectos', '/readProyectos')
    config.add_route('createproyectos', '/createProyectos')
    config.add_route('updateproyectos', '/updateProyectos/{id}')
    config.add_route('deleteproyectos', '/deleteProyectos/{id}')
    config.add_route('obtenercrearfases', '/fases')
    config.add_route('actualizareliminarfases', '/fases/{id}')
    config.add_route('obtenercrearatributofase', '/atributofase')
    config.add_route('actualizareliminaratributofase', '/atributofase/{id}')
    config.add_route('obtenercreartipofase', '/tipofase')
    config.add_route('eliminartipofase', '/tipofase/{id}')
    config.add_route('obtenercrearrecursos', '/recursos')
    config.add_route('actualizareliminarrecursos', '/recursos/{id}')
    config.add_route('obtenercrearunidadtrabajo', '/unidadtrabajo')
    config.add_route('actualizareliminarunidadtrabajo', '/unidadtrabajo/{id}')
    config.add_route('obtenertrabajorecurso', '/unidadtrabajorecurso')
    config.add_route('asignarrecursos', '/asignarRecursos')
    config.add_route('tipos_recursos', '/tipo_recurso')
    config.add_route('logout', '/logout')
    config.add_route('crearProyecto', '/crearProyecto')

    config.add_route('roles', '/roles/{id_rol}')
    config.add_route('estados_roles', '/roles_estados')
    config.add_route('obtenerTipos', '/obtenerTipos')
    config.add_route('crearTipo', '/crearTipo')
    config.add_route('eliminarTipo', '/eliminarTipo/{id}')
    config.add_route('guardarTipo', '/guardarTipo/{id}')
    config.add_route('importarTipo', '/importarTipos')
    config.add_route('crearListarAtributos', '/atributoItem')
    config.add_route('editarEliminarAtributos', '/atributoItem/{id}')
    config.add_route('crearListarItems', '/item')
    config.add_route('editarEliminarItems', '/item/{id}')
    config.add_route('crearAtributo', '/crearAtributo')
    config.add_route('eliminarAtributo', '/eliminarAtributo')
    config.add_route('guardarAtributo', '/guardarAtributo')
    config.add_route('entidades_padre', '/entidades_padre/{id_entidad}')
    config.add_route('suscripciones', '/suscripciones/{id_suscripcion}')
    config.add_route('crearListarEsquemas', '/esquemas')
    config.add_route('editarEliminarEsquemas', '/esquemas/{id}')
    config.add_route('crearListarAtributosEsquemas', '/atributosEsquemas')
    config.add_route('editarEliminarAtributosEsquemas',
                     '/atributosEsquemas/{id}')
    config.add_route('rolPrivilegios', '/rolPrivilegios/{id}')
    config.add_route('crearListarItemEsquemas', '/itemsEsquemas')
    config.add_route('editarEliminarItemEsquemas', '/itemsEsquemas/{id}')
    config.add_route('rolesfinales', '/rolesfinales/')
    config.add_route('notificaciones', '/notificaciones/')
    config.add_route('calculo_impacto', '/calculo_impacto')
    config.add_route('asignarUnidadItem', '/unidadItem')
    config.add_route('editarUnidadItem', '/unidadItem/{id}')

    config.add_route('asignarAtributoItem', '/itemAtributo')
    config.add_route('editarAtributoItem', '/itemAtributo/{id}')

    config.add_route('upload', '/upload')
    config.add_route('download', '/download')
    config.add_route('archivos', '/archivos')
    config.add_route('eliminarArchivo', '/archivos/{id}')

    #rutas volpe
    config.add_route('crearRol', '/crearRol')
    config.add_route('rol_privilegios', '/rol_privilegios/{id_privilegio}')
    config.add_route('privilegios', '/privilegios')

    #rutas Volpe 5 iteracion
    config.add_route('lineas_base', '/lineas_base')
    config.add_route('lineas_base_rest', '/lineas_base/{id}')
    #rutas Volpe 6 iteracion
    config.add_route('gantt', '/gantt')
    config.add_route('permisos', '/permisos')
    config.add_route('rol_permisos', '/rol_permisos')
    config.add_route('rol_permisos_rest', '/rol_permisos/{id}')

    config.add_route('login2', '/asd')
    config.scan()
    #    config.scan("views")

    return config.make_wsgi_app()
Example #55
0
def get_mailer():
    # Consider that we may have persistent settings
    if _inject_mailer:
        return _inject_mailer[0]
    return Mailer.from_settings(get_settings()) # pragma: no cover
Example #56
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    auth_tkt_policy = AuthTktAuthenticationPolicy(
        settings['authtkt.secret'],
        hashalg='sha512',
        callback=groupfinder,
        max_age=2592000,
        secure=asbool(settings.get('authtkt.secure', 'false')))
    auth_token_policy = AuthTokenAuthenticationPolicy(
        callback=groupfinder
    )
    authorization_policy = ACLAuthorizationPolicy()
    authentication_policy = AuthenticationStackPolicy()
    authentication_policy.add_policy('auth_tkt', auth_tkt_policy)
    authentication_policy.add_policy('auth_token', auth_token_policy)
    # set crypto key
    encryption.ENCRYPTION_SECRET = settings.get('encryption_secret')
    # import this later so encyption key can be monkeypatched
    from appenlight.models import DBSession, register_datastores
    # update config with cometd info
    settings['cometd_servers'] = {'server': settings['cometd.server'],
                                  'secret': settings['cometd.secret']}

    # Create the Pyramid Configurator.
    settings['_mail_url'] = settings['mailing.app_url']
    config = CythonCompatConfigurator(
        settings=settings,
        authentication_policy=authentication_policy,
        authorization_policy=authorization_policy,
        root_factory='appenlight.security.RootFactory',
        default_permission='view')
    # custom registry variables

    # resource type information
    config.registry.resource_types = ['resource', 'application']
    # plugin information
    config.registry.appenlight_plugins = {}

    config.set_default_csrf_options(require_csrf=True, header='X-XSRF-TOKEN')
    config.add_view_deriver('appenlight.predicates.csrf_view',
                            name='csrf_view')

    # later, when config is available
    dogpile_config = {'url': settings['redis.url'],
                      "redis_expiration_time": 86400,
                      "redis_distributed_lock": True}
    cache_regions.regions = cache_regions.CacheRegions(dogpile_config)
    config.registry.cache_regions = cache_regions.regions
    engine = engine_from_config(settings, 'sqlalchemy.',
                                json_serializer=json.dumps)
    DBSession.configure(bind=engine)

    # json rederer that serializes datetime
    config.add_renderer('json', json_renderer)
    config.set_request_property('appenlight.lib.request.es_conn', 'es_conn')
    config.set_request_property('appenlight.lib.request.get_user', 'user',
                                reify=True)
    config.set_request_property('appenlight.lib.request.get_csrf_token',
                                'csrf_token', reify=True)
    config.set_request_property('appenlight.lib.request.safe_json_body',
                                'safe_json_body', reify=True)
    config.set_request_property('appenlight.lib.request.unsafe_json_body',
                                'unsafe_json_body', reify=True)
    config.add_request_method('appenlight.lib.request.add_flash_to_headers',
                              'add_flash_to_headers')
    config.add_request_method('appenlight.lib.request.get_authomatic',
                              'authomatic', reify=True)

    config.include('pyramid_redis_sessions')
    config.include('pyramid_tm')
    config.include('pyramid_jinja2')
    config.include('appenlight_client.ext.pyramid_tween')
    config.include('ziggurat_foundations.ext.pyramid.sign_in')
    es_server_list = aslist(settings['elasticsearch.nodes'])
    redis_url = settings['redis.url']
    log.warning('Elasticsearch server list: {}'.format(es_server_list))
    log.warning('Redis server: {}'.format(redis_url))
    config.registry.es_conn = pyelasticsearch.ElasticSearch(es_server_list)
    config.registry.redis_conn = redis.StrictRedis.from_url(redis_url)

    config.registry.redis_lockmgr = Redlock([settings['redis.redlock.url'], ],
                                            retry_count=0, retry_delay=0)
    # mailer
    config.registry.mailer = Mailer.from_settings(settings)

    # Configure sessions
    session_factory = session_factory_from_settings(settings)
    config.set_session_factory(session_factory)

    # Configure renderers and event subscribers
    config.add_jinja2_extension('jinja2.ext.loopcontrols')
    config.add_jinja2_search_path('appenlight:templates')
    # event subscribers
    config.add_subscriber("appenlight.subscribers.application_created",
                          "pyramid.events.ApplicationCreated")
    config.add_subscriber("appenlight.subscribers.add_renderer_globals",
                          "pyramid.events.BeforeRender")
    config.add_subscriber('appenlight.subscribers.new_request',
                          'pyramid.events.NewRequest')
    config.add_view_predicate('context_type_class',
                              'appenlight.predicates.contextTypeClass')

    register_datastores(es_conn=config.registry.es_conn,
                        redis_conn=config.registry.redis_conn,
                        redis_lockmgr=config.registry.redis_lockmgr)

    # base stuff and scan

    # need to ensure webassets exists otherwise config.override_asset()
    # throws exception
    if not os.path.exists(settings['webassets.dir']):
        os.mkdir(settings['webassets.dir'])
    config.add_static_view(path='appenlight:webassets',
                           name='static', cache_max_age=3600)
    config.override_asset(to_override='appenlight:webassets/',
                          override_with=settings['webassets.dir'])

    config.include('appenlight.views')
    config.include('appenlight.views.admin')
    config.scan(ignore=['appenlight.migrations', 'appenlight.scripts',
                        'appenlight.tests'])

    config.add_directive('register_appenlight_plugin',
                         register_appenlight_plugin)

    for entry_point in iter_entry_points(group='appenlight.plugins'):
        plugin = entry_point.load()
        plugin.includeme(config)

    # include other appenlight plugins explictly if needed
    includes = aslist(settings.get('appenlight.includes', []))
    for inc in includes:
        config.include(inc)

    # run this after everything registers in configurator

    def pre_commit():
        jinja_env = config.get_jinja2_environment()
        jinja_env.filters['tojson'] = json.dumps
        jinja_env.filters['toJSONUnsafe'] = jinja2_filters.toJSONUnsafe

    config.action(None, pre_commit, order=PHASE3_CONFIG + 999)

    def wrap_config_celery():
        configure_celery(config.registry)

    config.action(None, wrap_config_celery, order=PHASE3_CONFIG + 999)

    app = config.make_wsgi_app()
    return app