def create_app(object_name):
    install_logger()

    app = Flask(__name__)
    app.config.from_object(object_name)

    # Per request logging
    request_started.connect(log_request, app)
    template_rendered.connect(log_template, app)

    # CSRF protection
    csrf.init_app(app)

    routes.prefix = app.config.get('URL_PREFIX')
    routes.host = app.config.get('CLIENT_FACING_URL').strip('/')
    app.routes = routes

    from .main import create_module as main_create_module
    from .yourdetails import create_module as yourdetails_create_module
    from .verification import create_module as verification_create_module

    main_create_module(app)
    yourdetails_create_module(app)
    verification_create_module(app)

    return app
Exemplo n.º 2
0
def init_app(app):
    if "pybrake" in app.extensions:
        raise ValueError("pybrake is already injected")
    if "PYBRAKE" not in app.config:
        raise ValueError("app.config['PYBRAKE'] is not defined")

    notifier = Notifier(**app.config["PYBRAKE"])
    apm_disabled = notifier._apm_disabled

    notifier.add_filter(request_filter)

    app.extensions["pybrake"] = notifier
    got_request_exception.connect(_handle_exception, sender=app)

    if not apm_disabled:
        before_render_template.connect(_before_render_template, sender=app)
        template_rendered.connect(_template_rendered, sender=app)

        app.before_request(_before_request(notifier))
        app.after_request(_after_request(notifier))

        if _sqla_available:
            _sqla_instrument(app)

    return app
Exemplo n.º 3
0
def create_app(config="config.json"):
	app = Flask(__name__)
	app.config.from_json(config)

	db.init_app(app)
	bcrypt.init_app(app)
	login_manager.init_app(app)

	login_manager.login_view = 'users.login'
	login_manager.login_message = ''

	from blog.users.routes import users
	from blog.admin.routes import admin
	from blog.main.routes import main
	from blog.posts.routes import posts
	from blog.messages.routes import messages
	app.register_blueprint(users)
	app.register_blueprint(admin)
	app.register_blueprint(main)
	app.register_blueprint(posts)
	app.register_blueprint(messages)

	template_rendered.connect(working, app)

	return app
Exemplo n.º 4
0
    def setup(self, obj, app):
        obj.client = app.test_client()
        obj.xhr_client = xhr_test_client(obj, app.test_client())
        obj._ctx = app.test_request_context()
        obj._ctx.push()

        obj.templates = []
        template_rendered.connect(obj._add_template)
Exemplo n.º 5
0
 def setUp(self):
     template_rendered.connect(self._registrar_template)
     self.template_str = open(
         os.path.join(os.path.dirname(__file__),
                      'templates/' + self._template)).read()
     self.client = app.test_client()
     self.response = self.client.get(self._url)
     self.conteudo = self.response.data.decode('UTF-8')
Exemplo n.º 6
0
 def record(sender, template, context, **extra):
     template = create_product_form()
     recorded.append((template, context))
     template_rendered.connect(record, app)
     try:
         yield recorded
     finally:
         template_rendered.disconnect(record, app)
Exemplo n.º 7
0
def captured_templates(app):
    recorded = []
    def record(sender, template, context, **extra):
        recorded.append((template, context))
    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
def captured_templates(app):
    recorded = []
    def record(sender, template, context, **extra):
        recorded.append((template, context))
    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 9
0
    def run(self, result=None):
        self.rendered_templates = []

        def record(sender, template, context, **extra):
            self.rendered_templates.append((template, context))

        template_rendered.connect(record, self.app)
        super().run(result)
        template_rendered.disconnect(record, self.app)
Exemplo n.º 10
0
def get_context_variables(app):
    recorded = []
    
    def record(sender, template, context, **extra):
        recorded.append(context)
    template_rendered.connect(record, app)
    try:
        yield iter(recorded)
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 11
0
def captured_templates(app):
    ''' Records which templates are used '''
    recorded = []

    def record(app, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record)
    yield recorded
    template_rendered.disconnect(record)
Exemplo n.º 12
0
def template_spy(test_app):
    calls = []

    def spy(sender, template, context, **extra):
        calls.append((template, context))

    template_rendered.connect(spy, test_app)

    yield calls

    template_rendered.disconnect(spy, test_app)
Exemplo n.º 13
0
def templates(app):
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append(template)

    template_rendered.connect(record, app)

    yield recorded

    template_rendered.disconnect(record, app)
Exemplo n.º 14
0
def templates(app):
    templates = []

    def gravador_de_templates(remetente, template, context, **extra):
        templates.append(template)

    template_rendered.connect(gravador_de_templates, app)

    yield templates

    template_rendered.disconnect(gravador_de_templates, app)
Exemplo n.º 15
0
def used_templates(flask_app):
    recorded = []

    def record(_, template, context):
        recorded.append((template, context))

    template_rendered.connect(record, flask_app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, flask_app)
Exemplo n.º 16
0
def captured_templates(app):
    """ Context manger to capture all rendered templates into a list."""
    def record(sender, template, context, **extra):
        nonlocal recorded
        recorded.append((template, context))

    recorded = []
    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 17
0
def captured_templates(app):
    """Use signals to capture the templates rendered for a route."""
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 18
0
def captured_templates(app):
    """use to keep track of templates rendered for testing"""
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 19
0
def captured_templates(app):
    """ Function return the data from jinja templates """
    recorded = []

    def record(sender, template, context, **kwags):
        recorded.append((template, context))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 20
0
    def setup_method(self, method):
        self.app = self.create_app()

        self.client = self.app.test_client()

        self._ctx = self.app.test_request_context()
        self._ctx.push()

        db.create_all()

        self.templates = []
        template_rendered.connect(self._add_template)
Exemplo n.º 21
0
def captured_templates():
    """receive templates name and context during flask render"""
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 22
0
def templates(app):
    records = []
    RenderedTemplate = namedtuple('RenderedTemplate', 'template context')

    def record(sender, template, context, **extra):
        records.append(RenderedTemplate(template, context))
    template_rendered.connect(record, app)

    try:
        yield records
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 23
0
def captured_templates(app):
    """Context manager to help determine which templates were rendered"""
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 24
0
def captured_templates(app):
    """Context manager to provide a list of templates rendered by a request."""
    templates = []

    def capture_template(sender, template, context, **kwargs):
        templates.append((template, context))

    template_rendered.connect(capture_template, app)
    try:
        yield templates
    finally:
        template_rendered.disconnect(capture_template, app)
Exemplo n.º 25
0
def record_templates(app):
    recorded = []

    def record(sender, template, context, **extra):
        print('received template rendered sign~')
        print("sender:%s \n template:%s \n" % (sender, template))
        recorded.append((template, sender))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 26
0
def rendered_context(app):
    """ Store templates and contexts rendered during a request.

    May be refactored out if needed elsewhere.
    """
    merged_context = {}
    def record(sender, template, context, **extra): # pylint: disable=unused-argument
        merged_context.update(context)
    template_rendered.connect(record, app)
    try:
        yield merged_context
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 27
0
def connect_signals(app):
    appcontext_popped.connect(handle_appcontext_popped)
    appcontext_pushed.connect(handle_appcontext_pushed)
    appcontext_tearing_down.connect(handle_appcontext_tearing_down)

    before_render_template.connect(handle_before_render_template, app)
    got_request_exception.connect(handle_got_request_exception, app)

    request_finished.connect(handle_request_finished, app)
    request_started.connect(handle_request_started, sender=app, weak=True)
    request_tearing_down.connect(handle_request_tearing_down, app, False)

    template_rendered.connect(handle_template_rendered, sender=app)
Exemplo n.º 28
0
def captured_templates(app):
    """Determines which templates were rendered and what variables were passed to the template"""
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record, app)

    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 29
0
def captured_templates(app):
    """Capture all templates being rendered along with the context used."""
    recorded = []

    def record(sender, template, context, **extra):
        # pylint:disable=unused-argument
        recorded.append((template, context))

    template_rendered.connect(record, app)

    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 30
0
def captured_templates(app):
    """Capture all templates being rendered along with the context used."""
    recorded = []

    def record(sender, template, context, **extra):
        # pylint:disable=unused-argument
        recorded.append((template, context))

    template_rendered.connect(record, app)

    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 31
0
def capture_templates(app):
    """
    Capture template in order to call them in test functions
    """
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 32
0
    def captured_context(self, app):
        recorded = []

        def record(sender, template, context, **extra):
            recorded.append(context)

        # This signal is sent when a template was successfully rendered.
        # The signal is invoked with the instance of the template as
        # template and the context as dictionary (named context).
        template_rendered.connect(record, app)
        try:
            yield recorded
        finally:
            template_rendered.disconnect(record, app)
Exemplo n.º 33
0
    def setUp(self):

        """
        Create database, set testing mode, create testing client, get
        template tracking set up.
        """

        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
        app.config["TESTING"] = True
        self.app = app.test_client()
        db.create_all()

        self.templates = []
        template_rendered.connect(self.addTemplate)
Exemplo n.º 34
0
def template(app):
    """Return information about templates rendered"""

    with app.test_client() as client:

        template_info = TemplateInfo()

        def on_template_rendered(sender, template, **kwargs):
            template_info.path = template.name
            template_info.args = kwargs['context']

        template_rendered.connect(on_template_rendered)

        yield template_info
Exemplo n.º 35
0
    def setUp(self):
        BaseTestCase.setUp(self)
        
        self.flask_app = self._create_app()
        self.client = self.flask_app.test_client()
        self._ctx = self.flask_app.test_request_context()
        self._ctx.push()

        self.json_mod = json
        self.templates = []
        self.current_user = None
        template_rendered.connect(self._add_template)
        user_logged_in.connect(self._signal_login)
        user_logged_out.connect(self._signal_logout)
Exemplo n.º 36
0
    def setUp(self, **kwargs):
        super(BaseTestCase, self).setUp()
        SQLALCHEMY_OPTIONS.update({'url': 'mysql://root@localhost:3306/test_nobot?charset=utf8', 'echo': False})
#       SQLALCHEMY_OPTIONS.update({'url': 'mysql://root@localhost:3306/nobot?charset=utf8', 'echo': False})
        self.app = get_wsgi_app(FlaskConfig)
        celery_app.DBSession = sessionmaker(self.app.sa_engine)
        self.app_context = self.app.test_request_context()
        self.app_context.push()
        self.app.config['TESTING'] = True
        self.app.preprocess_request()
        self.client = self.app.test_client()
        self.login_user_id = 100 
        self.db = self.app.DBSession()
        template_rendered.connect(self._render_callback)
        self.template_context = {}
Exemplo n.º 37
0
def templates(request, app):
    Record = collections.namedtuple("Record", "template context")

    records = []

    def record(sender, template, context, **extra):
        records.append(Record(template, context))

    template_rendered.connect(record, app)

    def teardown():
        template_rendered.disconnect(record, app)

    request.addfinalizer(teardown)

    return records
Exemplo n.º 38
0
    def _pre_setup(self):
        self.app = self._ctx = None

        self.app = self.create_app()

        self._orig_response_class = self.app.response_class
        self.app.response_class = _make_test_response(self.app.response_class)

        self.client = self.app.test_client()

        self._ctx = self.app.test_request_context()
        self._ctx.push()

        self.templates = []
        if _is_signals:
            template_rendered.connect(self._add_template)
Exemplo n.º 39
0
def subscribe_logging_helpers(app):
    """
    Configure functions that log in response to Flask signals emitted by app.

    Flask signal            function invoked
    ------------            -------------------
    request_started         log_request
    template_rendered       log_template_rendered
    request_finished        log_response
    got_request_exception   log_exception

    """
    request_started.connect(log_request, app)
    template_rendered.connect(log_template_rendered, app)
    request_finished.connect(log_response, app)
    got_request_exception.connect(log_exception, app)
Exemplo n.º 40
0
def captured_templates(app):
    """
    Used for figuring which templates and what context was used to
    render a request

    Thanks: http://flask.pocoo.org/docs/0.10/signals/
    """
    # Pylint comaplins about sender and extra, these are used by signals
    # pylint: disable=unused-argument
    recorded = []

    def record(sender, template, context, **extra):
        recorded.append((template, context))

    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
Exemplo n.º 41
0
    def _pre_setup(self):
        self.app = self.create_app()

        self._orig_response_class = self.app.response_class
        self.app.response_class = _make_test_response(self.app.response_class)

        self.client = self.app.test_client()

        self._ctx = self.app.test_request_context()
        self._ctx.push()

        if not self.render_templates:
            # Monkey patch the original template render with a empty render
            self._original_template_render = templating._render
            templating._render = _empty_render

        self.templates = []
        if _is_signals:
            template_rendered.connect(self._add_template)
Exemplo n.º 42
0
 def capture(self):
     self.templates = []
     template_rendered.connect(self._add_template)
     yield
     template_rendered.disconnect(self._add_template)
Exemplo n.º 43
0
 def __init__(self, *args, **kwargs):
     super(self.__class__, self).__init__(*args, **kwargs)
     self.templates = []
     template_rendered.connect(self._store_template_info)
  def _pre_setup(self):
    if hasattr(self, 'pre_setup_hook'):
      self.pre_setup_hook()
    # First, create an instance of the Testbed class.
    self.tb = testbed.Testbed()
    # Then activate the testbed, which prepares the
    # service stubs for use
    self.tb.activate()
    # Next, declare which service stubs you want to use.
    self.tb.init_mail_stub()
    self.tb.init_xmpp_stub()
    self.tb.init_files_stub()
    # if PIL is not installed this will raise..
    try:
      import PIL
      self.testbed.init_images_stub()
    except ImportError:
      pass
    except testbed.StubNotSupportedError:
      pass
    self.tb.init_channel_stub()
    self.tb.init_memcache_stub()
    self.tb.init_urlfetch_stub()
    self.tb.init_blobstore_stub()
    self.tb.init_taskqueue_stub()
    # hack to load in yaml file definition for queue names
    # see: http://stackoverflow.com/questions/5324515/task-queue-works-from-view-but-unknownqueueerror-when-run-from-unit-tests
    if hasattr(self, 'taskqueue_yaml_path'):
      self.taskqueue_stub._root_path = self.taskqueue_yaml_path

    self.tb.init_capability_stub()
    self.tb.init_logservice_stub()
    self.tb.init_app_identity_stub()

    # for high replication datastore tests
    if self.pseudorandomhrconsistencypolicy is not None:
      self.policy = ds_stub_util.PseudoRandomHRConsistencyPolicy(
        probability=self.pseudorandomhrconsistencypolicy)
    # initialize the datastore stub with this policy.
    # self.tb.init_datastore_v3_stub(consistency_policy=self.policy)
    self.tb.init_datastore_v3_stub()

    # from google.appengine.ext.ndb import model, tasklets
    # model.make_connection()
    # model.Model._reset_kind_map()
    # ctx = tasklets.make_default_context()
    # tasklets.set_context(ctx)
    # ctx.set_datastore_policy(True)
    # ctx.set_cache_policy(False)
    # ctx.set_memcache_policy(True)

    # flask setup
    self.gae_client = GaeTestClient()
    self.app = self._ctx = None
    self.app = self.create_app()
    self._orig_response_class = self.app.response_class
    self.app.response_class = self._test_response_cls(self.app.response_class)
    self.client = self.app.test_client()
    self._ctx = self.app.test_request_context()
    self._ctx.push()
    self.templates = []
    if _is_signals:
      template_rendered.connect(self._add_template)

    global taskqueue_test_client
    taskqueue_test_client = self.app.test_client()

    if hasattr(self, 'post_setup_hook'):
      self.post_setup_hook()
Exemplo n.º 45
0
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'

        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))

#signals
def log_template_renders(sender, template, context, **extra):
    sender.logger.debug('Rendering template "%s" with context %s',
            template.name or 'string template',
            context)

from flask import template_rendered
template_rendered.connect(log_template_renders, app)

if __name__ == '__main__':
    app.run()

    # app.run(use_debugger=use_debugger, debug = app.debug,
            # user_reloader =use_debugger, host='0.0.0.0')
Exemplo n.º 46
0
    def __call__(self, result=None):
        self.templates = []
        template_rendered.connect(self._add_template)

        super(ViewTestCase, self).__call__(result)