flask.render_template_string

Here are the examples of the python api flask.render_template_string taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

77 Examples 7

3 Source : __init__.py
with MIT License
from 02JanDal

    def html(self):
        primary_domain = self.primary_servername.split(':')[0]
        if request.endpoint == 'flask_consent' or request.consent.is_stale():
            return Markup(render_template_string(
                read_text(__name__, 'injection.html'),
                flask_consent_banner=self.extension._render_template_func(
                    self.banner_template,
                    flask_consent_contact_mail=self.contact_mail,
                    flask_consent_categories=self.extension.categories.values()),
                flask_consent_contact_mail=self.contact_mail,
                flask_consent_primary_domain=primary_domain,
                flask_consent_domains=self.extension.domains + [primary_domain]
            ))
        else:
            return ''


class ConsentData:

3 Source : test_appctx.py
with BSD 3-Clause "New" or "Revised" License
from flaskcwg

def test_custom_app_ctx_globals_class(app):
    class CustomRequestGlobals:
        def __init__(self):
            self.spam = "eggs"

    app.app_ctx_globals_class = CustomRequestGlobals
    with app.app_context():
        assert flask.render_template_string("{{ g.spam }}") == "eggs"


def test_context_refcounts(app, client):

3 Source : test_json.py
with BSD 3-Clause "New" or "Revised" License
from flaskcwg

def test_tojson_filter(app, req_ctx):
    # The tojson filter is tested in Jinja, this confirms that it's
    # using Flask's dumps.
    rv = flask.render_template_string(
        "const data = {{ data|tojson }};",
        data={"name": "  <  /script>", "time": datetime.datetime(2021, 2, 1, 7, 15)},
    )
    assert rv == (
        'const data = {"name": "\\u003c/script\\u003e",'
        ' "time": "Mon, 01 Feb 2021 07:15:00 GMT"};'
    )


def test_json_customization(app, client):

3 Source : test_templating.py
with BSD 3-Clause "New" or "Revised" License
from flaskcwg

def test_original_win(app, client):
    @app.route("/")
    def index():
        return flask.render_template_string("{{ config }}", config=42)

    rv = client.get("/")
    assert rv.data == b"42"


def test_request_less_rendering(app, app_ctx):

3 Source : test_templating.py
with BSD 3-Clause "New" or "Revised" License
from flaskcwg

def test_request_less_rendering(app, app_ctx):
    app.config["WORLD_NAME"] = "Special World"

    @app.context_processor
    def context_processor():
        return dict(foo=42)

    rv = flask.render_template_string("Hello {{ config.WORLD_NAME }} {{ foo }}")
    assert rv == "Hello Special World 42"


def test_standard_context(app, client):

3 Source : test_templating.py
with BSD 3-Clause "New" or "Revised" License
from flaskcwg

def test_escaping_without_template_filename(app, client, req_ctx):
    assert flask.render_template_string("{{ foo }}", foo="  <  test>") == "<test>"
    assert flask.render_template("mail.txt", foo=" < test>") == " < test> Mail"


def test_macros(app, req_ctx):

3 Source : test_templating.py
with BSD 3-Clause "New" or "Revised" License
from flaskcwg

def test_add_template_global(app, app_ctx):
    @app.template_global()
    def get_stuff():
        return 42

    assert "get_stuff" in app.jinja_env.globals.keys()
    assert app.jinja_env.globals["get_stuff"] == get_stuff
    assert app.jinja_env.globals["get_stuff"](), 42

    rv = flask.render_template_string("{{ get_stuff() }}")
    assert rv == "42"


def test_custom_template_loader(client):

3 Source : test_flask.py
with BSD 2-Clause "Simplified" License
from getsentry

def test_sentry_trace_context(sentry_init, app, capture_events):
    sentry_init(integrations=[flask_sentry.FlaskIntegration()])
    events = capture_events()

    @app.route("/")
    def index():
        sentry_span = Hub.current.scope.span
        capture_message(sentry_span.to_traceparent())
        return render_template_string("{{ sentry_trace }}")

    with app.test_client() as client:
        response = client.get("/")
        assert response.status_code == 200
        assert response.data.decode(
            "utf-8"
        ) == '  <  meta name="sentry-trace" content="%s" />' % (events[0]["message"],)


def test_dont_override_sentry_trace_context(sentry_init, app):

3 Source : test_flask.py
with BSD 2-Clause "Simplified" License
from getsentry

def test_dont_override_sentry_trace_context(sentry_init, app):
    sentry_init(integrations=[flask_sentry.FlaskIntegration()])

    @app.route("/")
    def index():
        return render_template_string("{{ sentry_trace }}", sentry_trace="hi")

    with app.test_client() as client:
        response = client.get("/")
        assert response.status_code == 200
        assert response.data == b"hi"

3 Source : app.py
with Apache License 2.0
from GoogleCloudPlatform

def hello_cats():
    if not BUCKET_NAME:
        return flask.render_template_string(
            "Missing environment variable: BUCKET_NAME."
        )

    if not FUNCTION_NAME:
        return flask.render_template_string(
            "Missing environment variable: FUNCTION_NAME."
        )

    cats = get_cats(BUCKET_NAME)
    have_cat = any([c["data"]["is_cat"] for c in cats])
    return flask.render_template("cats.html", cats=cats, have_cat=have_cat)


if __name__ == "__main__":

3 Source : app.py
with MIT License
from infosec-ucalgary

def robotsNeedLoveToo():
    if request.headers.get("User-Agent") == expected_browser:
        return send_from_directory(app.static_folder, "robots.txt")
    else:
        return render_template_string("Unknown User-Agent! Supported Browsers: Internet Explorer 6.01")

if __name__== "__main__":

3 Source : test_appctx.py
with MIT License
from jest-community

def test_custom_app_ctx_globals_class(app):
    class CustomRequestGlobals(object):
        def __init__(self):
            self.spam = 'eggs'

    app.app_ctx_globals_class = CustomRequestGlobals
    with app.app_context():
        assert flask.render_template_string('{{ g.spam }}') == 'eggs'


def test_context_refcounts(app, client):

3 Source : test_templating.py
with MIT License
from jest-community

def test_original_win(app, client):
    @app.route('/')
    def index():
        return flask.render_template_string('{{ config }}', config=42)

    rv = client.get('/')
    assert rv.data == b'42'


def test_request_less_rendering(app, app_ctx):

3 Source : test_templating.py
with MIT License
from jest-community

def test_request_less_rendering(app, app_ctx):
    app.config['WORLD_NAME'] = 'Special World'

    @app.context_processor
    def context_processor():
        return dict(foo=42)

    rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '
                                      '{{ foo }}')
    assert rv == 'Hello Special World 42'


def test_standard_context(app, client):

3 Source : test_templating.py
with MIT License
from jest-community

def test_escaping_without_template_filename(app, client, req_ctx):
    assert flask.render_template_string(
        '{{ foo }}', foo='  <  test>') == '<test>'
    assert flask.render_template('mail.txt', foo=' < test>') == ' < test> Mail'


def test_macros(app, req_ctx):

3 Source : test_templating.py
with MIT License
from jest-community

def test_add_template_global(app, app_ctx):
    @app.template_global()
    def get_stuff():
        return 42

    assert 'get_stuff' in app.jinja_env.globals.keys()
    assert app.jinja_env.globals['get_stuff'] == get_stuff
    assert app.jinja_env.globals['get_stuff'](), 42

    rv = flask.render_template_string('{{ get_stuff() }}')
    assert rv == '42'


def test_custom_template_loader(client):

3 Source : test_cachebust_static_assets.py
with MIT License
from LandRegistry

    def test_url_for_adds_cache_query_string(self):
        filename = "demo/assets/dist/test.txt"
        with open(filename, "w+") as file:
            file.write("Hello")

        with app.test_request_context("/"):
            output = render_template_string("{{ url_for('static', filename='test.txt') }}")

        md5_value = md5_for_file(filename, hexdigest=True)

        self.assertIn("?cache={}".format(md5_value), output)

        os.remove(filename)

    @mock.patch(

3 Source : test_cachebust_static_assets.py
with MIT License
from LandRegistry

    def test_repeated_url_for_calls_hits_cache_not_disk(self, mock_md5_for_file):
        filename = "demo/assets/dist/test.txt"
        with open(filename, "w+") as file:
            file.write("Hello")

        with app.test_request_context("/"):
            hash_one = render_template_string("{{ url_for('static', filename='test.txt') }}")
            hash_two = render_template_string("{{ url_for('static', filename='test.txt') }}")
            hash_three = render_template_string("{{ url_for('static', filename='test.txt') }}")

            self.assertEqual(mock_md5_for_file.call_count, 1)

        self.assertEqual(hash_one, hash_two)
        self.assertEqual(hash_two, hash_three)

        os.remove(filename)

    def test_hashed_url_for_only_runs_for_static_asset_routes(self):

3 Source : test_cachebust_static_assets.py
with MIT License
from LandRegistry

    def test_hashed_url_for_only_runs_for_static_asset_routes(self):
        with app.test_request_context("/"):
            output = render_template_string("{{ url_for('components.index') }}")

        self.assertNotIn("?cache", output)

    @freeze_time("2017-01-18")

3 Source : test_jinja_markdown_filter.py
with MIT License
from LandRegistry

    def check_rendering(self, markdown_to_html):
        for markdown in markdown_to_html:
            with app.test_request_context("/"):
                assert render_template_string(
                    "{{contents|markdown}}", contents=markdown
                ).strip() == markdown_to_html.get(markdown)

    @mock.patch("demo.custom_extensions.jinja_markdown_filter.main.JinjaMarkdownFilter.init_app")

3 Source : bootstrapper_utils.py
with Apache License 2.0
from PaloAltoNetworks

def compile_template(configuration_parameters):
    if 'template_name' not in configuration_parameters:
        raise RequiredParametersError('Not all required keys for bootstrap.xml are present')

    template_name = configuration_parameters['template_name']
    required = get_required_vars_from_template(template_name)
    if not required.issubset(configuration_parameters):
        raise RequiredParametersError('Not all required keys for bootstrap.xml are present')

    template = get_template(template_name)

    if template is None:
        raise TemplateNotFoundError('Could not load %s' % template_name)

    return render_template_string(template, **configuration_parameters)


def normalize_input_params(r: request) -> dict:

3 Source : flask.py
with MIT License
from PlaidWeb

    def _render_notify(self, cdata):
        if self._notify_render_func:
            result = self._notify_render_func(cdata)
            if result:
                return result

        return flask.render_template_string(load_template('notify.html'),
                                            cdata=cdata,
                                            stylesheet=self.stylesheet)

    def render_login_form(self, destination: str, error: typing.Optional[str] = None):

3 Source : test_documents_views.py
with GNU Affero General Public License v3.0
from rero

def test_nl2br(app):
    """Test nl2br conversion."""
    assert render_template_string("{{ 'Multiline text\nMultiline text' | nl2br | safe}}") ==\
        'Multiline text  <  br>Multiline text'


def test_get_code_from_bibliographic_language(app):

3 Source : test_documents_views.py
with GNU Affero General Public License v3.0
from rero

def test_language_value(app):
    """Test language value."""
    values = [{
        'language': 'eng',
        'value': 'Value ENG'
    }, {
        'language': 'fre',
        'value': 'Value FRE'
    }]
    assert render_template_string('{{ values | language_value }}',
                                  values=values) == 'Value ENG'


def test_get_custom_field_label(app):

3 Source : test_documents_views.py
with GNU Affero General Public License v3.0
from rero

def test_markdown_filter(app):
    """Test markdown to HTML conversion."""
    assert render_template_string(
        "{{ 'Markdown text\nwith **strong** and *italic*' | markdown_filter" \
        " | safe}}"
    ) == '  <  p>Markdown text\nwith  < strong>strong < /strong> and  < em>italic < /em>'\
        ' < /p>'

3 Source : utils.py
with GNU General Public License v3.0
from rmountjoy92

def html_from_template_file(file, dashboard_card):
    path = os.path.join(user_templates_folder, file)
    with open(path, "r") as template_file:
        with dashboard_card.dashboard.dm.app.app_context():
            html = render_template_string(
                template_file.read(), dashboard_card=dashboard_card
            )
    return Markup(html)

3 Source : curl.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        if self.response_type.lower() == "json":
            try:
                value = requests.get(self.resource).json()
            except Exception as e:
                value = f"{e}"
        else:
            try:
                value = requests.get(self.resource)
            except Exception as e:
                value = f"{e}"

        return render_template_string(self.value_template, value=value)

3 Source : deluge.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        r = self._api_call("web.update_ui", ["download_rate", "upload_rate"])
        json = r.json()
        data = {}
        for key, field in json["result"]["stats"].items():
            data[key] = field

        value_template = render_template_string(self.value_template, **data)
        return value_template

3 Source : healthchecks.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        if self.api_key == None:
            return "api_key missing"
        if self.host == None:
            return "host missing"

        self.healthchecks.refresh()
        value_template = render_template_string(
            self.value_template, **self.healthchecks.__dict__
        )
        return value_template

3 Source : lidarr.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        if self.api_key == None:
            return "api_key missing"
        if self.host == None:
            return "host missing"

        self.lidarr.refresh()
        value_template = render_template_string(
            self.value_template, **self.lidarr.__dict__
        )
        return value_template

3 Source : pihole.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        self.pihole.refresh()
        value_template = render_template_string(
            self.value_template, **self.pihole.__dict__
        )
        return value_template

3 Source : plex.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        self.plex.refresh()
        value_template = render_template_string(
            self.value_template, **self.plex.__dict__
        )
        return value_template

3 Source : radarr.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        if self.api_key == None:
            return "api_key missing"
        if self.host == None:
            return "host missing"

        self.radarr.refresh()
        value_template = render_template_string(
            self.value_template, **self.radarr.__dict__
        )
        return value_template

3 Source : sonarr.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        if self.api_key == None:
            return "api_key missing"
        if self.host == None:
            return "host missing"

        self.sonarr.refresh()
        value_template = render_template_string(
            self.value_template, **self.sonarr.__dict__
        )
        return value_template

3 Source : tautulli.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):
        if self.api_key == None:
            return "api_key missing"
        if self.host == None:
            return "host missing"

        self.tautulli.refresh()
        value_template = render_template_string(
            self.value_template, **self.tautulli.__dict__
        )
        return value_template

3 Source : transmission.py
with GNU General Public License v3.0
from rmountjoy92

    def process(self):

        torrents = len(self.tc.get_torrents())
        data = {}
        for key, field in self.tc.session_stats().__dict__["_fields"].items():
            data[key] = field.value
        # pp.pprint (data)

        value_template = render_template_string(self.value_template, **data)
        return value_template


# Testing
# test = Platform(host='192.168.1.19', user='', password='').process()

3 Source : app.py
with GNU General Public License v3.0
from Shellmates

def index():
    images = getimages()
    if not images:
        return render_template("index.html", images=None)

    title_error = False
    current = images[0]
    image_url = render_template_string(url_for("send_image", path=current["path"]))
    try:
        image_title = render_template_string(current["title"])
    except Exception as e:
        print(e)
        image_title = ""
        title_error = True

    return render_template("index.html", images=images, image_url=image_url, image_title=image_title, title_error=title_error)

@app.route("/upload", methods=["GET","POST"])

3 Source : ssti.py
with MIT License
from splitline

def index():
	name=request.args.get('name')
	template = '  <  h1>hello {}! < h1>'.format(name)
	print(template)
	return render_template_string(template)

app.run()

3 Source : app.py
with MIT License
from SunshineCTF

def render_template_endpoint():
    data = request.form
    template = request.form["template"]
    if ".py" in template or "app" in template:
        template = "index.html"
    template = requests.get("http://127.0.0.1:5000/" + template).text
    return render_template_string(template)




@app.route("/render", methods=["OPTIONS"])

3 Source : routes.py
with Apache License 2.0
from trailofbits

def index():
    if 'authd' not in session:
        return redirect('/login')

    returnUrl = request.args.get('returnURL') or None
    message = request.args.get('message') or None

    if message is not None:
        return render_template_string(message)

    if returnUrl is not None:
        return redirect(returnUrl)

    return render_template("main.html")


@app.route("/posts/add", methods=["GET", "POST"])

3 Source : routes.py
with Apache License 2.0
from trailofbits

def logout():
    if 'username' in session:
        del(session['username'])
    if 'authd' in session:
        del(session['authd'])

    if 'message' in request.args:
        return render_template_string(request.args.get("message"))

    return redirect('/login')

0 Source : test_consent.py
with MIT License
from 02JanDal

def make_app_and_consent():
    app = Flask(__name__)
    app.config['CONSENT_FULL_TEMPLATE'] = 'full.html'
    app.config['CONSENT_BANNER_TEMPLATE'] = 'banner.html'
    app.config['CONSENT_CONTACT_MAIL'] = '[email protected]'
    app.config['CONSENT_PRIMARY_SERVERNAME'] = 'primary.test'
    consent = Consent(app)
    consent.add_standard_categories()

    @app.route('/')
    def test():
        return jsonify(required=request.consent['required'],
                       preferences=request.consent['preferences'],
                       analytics=request.consent['analytics'])

    @app.route('/banner')
    def banner():
        return render_template_string('''
                  <  html>
                 < head>{{ flask_consent_code() }} < /head>
                 < body> < /body>
                 < /html>
                ''')

    return app, consent


class WebTest(TestCase):

0 Source : tst_app.py
with MIT License
from autonlab

def init_app(app, test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app.config.from_object(__name__+'.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try: app.config.from_object('local_settings')
    except: pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    babel = Babel(app)                              # Initialize Flask-Babel
    mail = Mail(app)                                # Initialize Flask-Mail

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User, UserInvitationClass=UserInvitation)
    user_manager = UserManager(db_adapter, app)

    # Create regular 'member' user
    if not User.query.filter(User.username=='member').first():
        user = User(username='member', email='[email protected]', active=True,
                password=user_manager.hash_password('Password1'), confirmed_at=datetime.datetime.utcnow())
        db.session.add(user)
        db.session.commit()

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username=='user007').first():
        user1 = User(username='user007', email='[email protected]', active=True,
                password=user_manager.hash_password('Password1'))
        user1.roles.append(Role(name='secret'))
        user1.roles.append(Role(name='agent'))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
              <  h2>{%trans%}Home Page{%endtrans%} < /h2>
             < p> < a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%} < /a> < /p>
            {% endblock %}
            """)

    # The '/profile' page requires a logged-in user
    @app.route('/user/profile')
    @login_required                                 # Use of @login_required decorator
    @confirm_email_required
    def user_profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
             < h2>{%trans%}Profile Page{%endtrans%} < /h2>
             < p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }}, < /p>
             < p>  < a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%} < /a> < /p>
             < p>  < a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%} < /a> < /p>
             < p>  < a href="{{ url_for('user.invite') }}">
                {%trans%}Invite User{%endtrans%} < /a> < /p>
             < p>  < a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%} < /a> < /p>
            {% endblock %}
            """)

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route('/special')
    @roles_required('secret', ['sauce', 'agent'])   # Use of @roles_required decorator
    def special_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
             < h2>{%trans%}Special Page{%endtrans%} < /h2>
            {% endblock %}
            """)

    # For testing only
    app.db = db
    app.UserEmailClass = UserEmail

    return app


# Start development web server
if __name__=='__main__':

0 Source : serve.py
with MIT License
from autonlab

def createApp():

    # Instantiate the Flask web application class
    app = Flask(__name__, template_folder=str(config['codeRootPathObj'] / 'static' / 'www' / 'templates'))

    # Auto-reload templates
    app.jinja_env.auto_reload = True

    # Make the root web path available for templates
    @app.context_processor
    def inject_dict_for_all_templates():
        return {
            'rootWebPath': config['rootWebPath']
        }

    # Minify HTML when possible
    @app.after_request
    def response_minify(response):
        if response.content_type == u'text/html; charset=utf-8':
            response.set_data(minify(response.get_data(as_text=True), remove_comments=True))
        return response

    # Apply Flask configuration for Flask-User package
    app.config.from_object(FlaskConfigClass)
    app.config.update({
        'SECRET_KEY': config['secret_key'],
        'SQLALCHEMY_DATABASE_URI': f"sqlite:///{(config['dataPathObj'] / 'database' / 'db.sqlite')}",
        **config['mail'],
        'USER_CHANGE_PASSWORD_URL': config['rootWebPath'] + app.config['USER_CHANGE_PASSWORD_URL'],
        'USER_CHANGE_USERNAME_URL': config['rootWebPath'] + app.config['USER_CHANGE_USERNAME_URL'],
        'USER_CONFIRM_EMAIL_URL': config['rootWebPath'] + app.config['USER_CONFIRM_EMAIL_URL'],
        'USER_EMAIL_ACTION_URL': config['rootWebPath'] + app.config['USER_EMAIL_ACTION_URL'],
        'USER_FORGOT_PASSWORD_URL': config['rootWebPath'] + app.config['USER_FORGOT_PASSWORD_URL'],
        'USER_INVITE_URL': config['rootWebPath'] + app.config['USER_INVITE_URL'],
        'USER_LOGIN_URL': config['rootWebPath'] + app.config['USER_LOGIN_URL'],
        'USER_LOGOUT_URL': config['rootWebPath'] + app.config['USER_LOGOUT_URL'],
        'USER_MANAGE_EMAILS_URL': config['rootWebPath'] + app.config['USER_MANAGE_EMAILS_URL'],
        'USER_PROFILE_URL': config['rootWebPath'] + app.config['USER_PROFILE_URL'],
        'USER_REGISTER_URL': config['rootWebPath'] + app.config['USER_REGISTER_URL'],
        'USER_RESEND_CONFIRM_EMAIL_URL': config['rootWebPath'] + app.config['USER_RESEND_CONFIRM_EMAIL_URL'],
        'USER_RESET_PASSWORD_URL': config['rootWebPath'] + app.config['USER_RESET_PASSWORD_URL']
    })

    # Initialize the db models with the Flask app
    models.init_flask_app(app)

    # Initialize Flask-Mail
    mail = Mail(app)

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(models.db, models.User, UserInvitationClass=models.UserInvitation)  # Select database adapter
    user_manager = UserManager(db_adapter, app)  # Init Flask-User and bind to app

    # You may use this code snippet below to create initial/new admin users
    # (since it is not possible through the interface). Alternatively, you
    # could modify the database.
    #
    with app.app_context():
        if not models.User.query.first():
            from getpass import getpass
            print("You must create an admin user.")
            fn = input("First name: ")
            ln = input("Last name: ")
            em = input("E-mail: ")
            pw = getpass(prompt="Password: ")
            u = models.User(
                first_name=fn,
                last_name=ln,
                email=em,
                active=True,
                password=user_manager.hash_password(pw),
            )
            u.roles.append(models.Role(name='admin'))
            models.db.session.add(u)
            models.db.session.commit()

    # Load projects
    with app.app_context():
        loadProjects()

    # Instantiate a file for realtime, in-memory usage (probably temporary)
    # TODO(gus): Refactor realtime
    #rtf = File(projparent=None)

    @user_registered.connect_via(app)
    def after_registered_hook(sender):
        sender.logger.info("USER REGISTERED")

    @user_sent_invitation.connect_via(app)
    def after_invitation_hook(sender):
        sender.logger.info("USER SENT INVITATION")

    ### NON-SECURE AREAS (NO LOGIN REQUIRED) ###

    # Map our static assets to be served
    app.register_blueprint(Blueprint('css', __name__, static_url_path=config['rootWebPath'] + '/css', static_folder=str(config['codeRootPathObj'] / 'static' / 'www' / 'css')))
    app.register_blueprint(Blueprint('fonts', __name__, static_url_path=config['rootWebPath'] + '/fonts', static_folder=str(config['codeRootPathObj'] / 'static' / 'www' / 'fonts')))
    app.register_blueprint(Blueprint('img', __name__, static_url_path=config['rootWebPath'] + '/img', static_folder=str(config['codeRootPathObj'] / 'static' / 'www' / 'img')))
    app.register_blueprint(Blueprint('js', __name__, static_url_path=config['rootWebPath'] + '/js', static_folder=str(config['codeRootPathObj'] / 'static' / 'www' / 'js')))

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(str(config['codeRootPathObj'] / 'static' / 'www' / 'img' / 'favicons'), 'favicon.ico')

    ### SECURE AREAS (LOGIN REQUIRED) ###
    ### All methods below should have ###
    ### the @login_required decorator ###

    @app.route(config['rootWebPath']+'/bokeh.html')
    @login_required
    def bokeh():
        return send_from_directory('../www', 'bokeh.html')

    @app.route(config['rootWebPath'] + '/close_all_files', methods=['GET'])
    @login_required
    def close_all_files():
        projects = getProjectsPayload(current_user.id)

        for p in projects:
            proj = getProject(p['id'])
            for f in proj.files:
                try:
                    f.close()

                except Exception as e:
                    return app.response_class(
                            response=simplejson.dumps({'success': False}),
                            status=200,
                            mimetype='application/json'
                        )

        ### To be implemented here...
        return app.response_class(
            response=simplejson.dumps({'success': True}),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath'] + '/close_all_project_files', methods=['GET'])
    @login_required
    def close_all_project_files():
        # Parse parameters
        project_id = request.args.get('project_id', type=int)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            return app.response_class(
                response=simplejson.dumps({'success': False}),
                status=200,
                mimetype='application/json'
            )

        ### To be implemented here...
        for f in project.files:
            try:
                f.close()
            except Exception as e:
                print(e)
                return app.response_class(
                        response=simplejson.dumps({'success': False}),
                        status=200,
                        mimetype='application/json'
                    )

        ### This is the success response -- if there is an error you want to catch, just
        ### the same response below but with success=False!
        return app.response_class(
            response=simplejson.dumps({'success': True}),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath'] + '/close_project_file', methods=['GET'])
    @login_required
    def close_project_file():
        # Parse parameters
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            return app.response_class(
                response=simplejson.dumps({'success': False}),
                status=200,
                mimetype='application/json'
            )

        # Get the file
        file = project.getFile(file_id)
        if file is None:
            logging.error(f"File ID {file_id} not found.")
            return app.response_class(
                response=simplejson.dumps({'success': False}),
                status=200,
                mimetype='application/json'
            )

        ### To be implemented here...
        try:
            file.close()
        except Exception as e:
            return app.response_class(
                response=simplejson.dumps({'success':False}),
                status=200,
                mimetype='application/json'
            )

        ### This is the success response -- if there is an error you want to catch, just
        ### the same response below but with success=False!
        return app.response_class(
            response=simplejson.dumps({'success': True}),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath']+'/create_annotation', methods=['GET'])
    @login_required
    def create_annotation():

        # Parse parameters
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)
        left = getFloatParamOrNone('xl')
        right = getFloatParamOrNone('xr')
        top = getFloatParamOrNone('yt')
        bottom = getFloatParamOrNone('yb')
        seriesID = request.args.get('sid')
        label = request.args.get('label')
        pattern_id = request.args.get('pattern_id', type=int)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            return app.response_class(
                response=simplejson.dumps({'success': False}),
                status=200,
                mimetype='application/json'
            )

        # Get the file
        file = project.getFile(file_id)
        if file is None:
            logging.error(f"File ID {file_id} not found.")
            return app.response_class(
                response=simplejson.dumps({'success': False}),
                status=200,
                mimetype='application/json'
            )

        # Write the annotation
        newAnnotationID = file.createAnnotation(current_user.id, left, right, top, bottom, seriesID, label, pattern_id)

        # Output response
        return app.response_class(
            response=simplejson.dumps({'success': True, 'id': newAnnotationID}),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath']+'/delete_annotation')
    @login_required
    def delete_annotation():

        # Parse parameters
        id = request.args.get('id', type=int)
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            return app.response_class(
                response=simplejson.dumps({'success': False}),
                status=200,
                mimetype='application/json'
            )

        # Get the file
        file = project.getFile(file_id)
        if file is None:
            logging.error(f"File ID {file_id} not found.")
            return app.response_class(
                response=simplejson.dumps({'success': False}),
                status=200,
                mimetype='application/json'
            )

        # Write the annotation
        deletionSuccess = file.deleteAnnotation(current_user.id, id)

        # Output response
        return app.response_class(
            response=simplejson.dumps({'success': deletionSuccess}),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath']+'/detect_patterns', methods=['GET'])
    @login_required
    def detect_patterns():

        # TODO(gus): Add checks here

        # Parse the series name and alert parameters
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)
        type = request.args.get('type')
        series = request.args.get('series')
        thresholdlow = request.args.get('thresholdlow', type=float) if request.args.get('thresholdlow') != '' else None
        thresholdhigh = request.args.get('thresholdhigh', type=float) if request.args.get('thresholdhigh') != '' else None
        duration = request.args.get('duration', type=float)
        persistence = request.args.get('persistence', type=float)/100
        maxgap = request.args.get('maxgap', type=float)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID '{project_id}' not found.")
            abort(404, description="Project not found.")
            return

        # Get the file
        file = project.getFile(file_id)
        if file is None:
            logging.error(f"File ID {file_id} not found.")
            return app.response_class(
                response=simplejson.dumps([]),
                status=200,
                mimetype='application/json'
            )

        # Run pattern detection
        alerts = file.detectPatterns(
            type=type,
            series=series,
            thresholdlow=thresholdlow,
            thresholdhigh=thresholdhigh,
            duration=duration,
            persistence=persistence,
            maxgap=maxgap
        )

        # Output response
        return app.response_class(
            response=simplejson.dumps(alerts, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath'] + '/featurize')
    @login_required
    def featurize():

        # Parse parameters
        featurizer = request.args.get('featurizer')
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)
        series = request.args.get('series')
        left = request.args.get('left', type=float)
        right = request.args.get('right', type=float)
        params = json.loads(request.args.get('params'));

        print("\n".join([
            f"\nFeaturizer {featurizer} requested, with parameters:",
            f"Project ID: {project_id}",
            f"File ID: {file_id}",
            f"Series: {series}",
            f"Left: {left}",
            f"Right: {right}",
            f"Params: {params}\n",
        ]))

        if featurizer in featurizers:
            featurizerFunction = featurizers[featurizer].getFeaturizeFunction(params)
        else:
            raise Exception(f"Unknown featurizer requested: {featurizer}")

        try:

            # Get the project
            project = getProject(project_id)
            if project is None:
                logging.error(f"Project ID {project_id} not found.")
                abort(404, description="Project not found.")
                return

            # Get the file
            file = project.getFile(file_id)
            if file is None:
                logging.error(f"File ID {file_id} not found.")
                return app.response_class(
                    response=simplejson.dumps({'success': False}),
                    status=200,
                    mimetype='application/json'
                )

            utc = pytz.UTC

            s = file.getSeries(series)
            if s is None:
                raise Exception('series not found')
            df = s.getDataAsDF().set_index('time')
            window_size = params['window_size']

            # # Option 1 (sometimes this works) – make sure to correlate with option above
            left = datetime.fromtimestamp(left).astimezone(utc)
            right = datetime.fromtimestamp(right).astimezone(utc)

            # Option 2 (and sometimes this works) – make sure to correlate with option above
            # left = np.datetime64(datetime.fromtimestamp(left).astimezone(utc))
            # right = np.datetime64(datetime.fromtimestamp(right).astimezone(utc))

            # # This was from an earlier attempt, probably discard...
            # left = pd.to_datetime(datetime.fromtimestamp(left).astimezone(utc))
            # right = pd.to_datetime(datetime.fromtimestamp(right).astimezone(utc))

            df = df[(df.index >= left) & (df.index   <  = right)]

            # TODO: Might make label side configurable

            featurization = df.resample(window_size, label='right').agg(featurizerFunction).replace(np.inf, np.nan).replace(-np.inf, np.nan).dropna().reset_index()
            print(featurization)

            # Option 1 (sometimes this works) – make sure to correlate with option above
            featurization['time'] = ((featurization['time'].dt.tz_convert(utc) - pd.Timestamp("1970-01-01").replace(tzinfo=utc)) // pd.Timedelta("1ms")) / 1000

            # Option 2 (and sometimes this works) – make sure to correlate with option above
            # featurization['time'] = ((featurization['time'].dt.tz_localize('UTC') - pd.Timestamp("1970-01-01").replace(tzinfo=utc)) // pd.Timedelta("1ms")) / 1000

            nones = [None] * featurization.shape[0]
            data = [list(i) for i in zip(featurization['time'], nones, nones, featurization['value'])]
            response = {
                'id': f"{window_size}_{featurizer}_{series}",
                'success': True,
                'labels': ['Date/Offset', 'Min', 'Max', 'Sample Entropy for '+series],
                'data': data,
                'output_type': 'real',
                'temporary': True,
            }

            # Output response
            return app.response_class(
                response=simplejson.dumps(response, ignore_nan=True),
                status=200,
                mimetype='application/json',
            )

        except Exception as e:

            logging.error("There was an exception while featurizing.", exc_info=True)

            response = {
                'success': False,
                'error_message': f"There was an error while featurizing: {e}",
            }

            return app.response_class(
                response=simplejson.dumps(response, ignore_nan=True),
                status=200,
                mimetype='application/json',
            )

    @app.route(config['rootWebPath']+'/get_project_annotations')
    @login_required
    def get_project_annotations():

        # Parse parameters
        project_id = request.args.get('project_id', type=int)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            abort(404, description="Project not found.")
            return

        # Assemble project annotations
        projectAnnotations = project.getAnnotationsOutput(current_user.id)

        # Output response
        return app.response_class(
            response=simplejson.dumps(projectAnnotations, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath']+'/')
    @app.route(config['rootWebPath']+'/index.html')
    @login_required
    def index():
        return render_template('index.html', projects=getProjectsPayload(current_user.id), assignments=getAssignmentsPayload(current_user.id))

    @app.route(config['rootWebPath']+'/initial_file_payload')
    @login_required
    def initial_file_payload():
        # Parse parameters
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            abort(404, description="Project not found.")
            return

        # Get the file
        file = project.getFile(file_id)
        if file is None:
            logging.error(f"File ID {file_id} not found.")
            abort(404, description="File not found.")
            return

        # Assemble the initial file payload (full zoomed-out & downsampled, if
        # necessary, datasets for all data series.
        initialFilePayload = file.getInitialPayload(current_user.id)

        # Output response
        return app.response_class(
            response=simplejson.dumps(initialFilePayload, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/initial_evaluator_payload')
    # @login_required
    def initial_evaluator_payload():
        project_id = request.args.get('project_id', type=int)

        project = getProject(project_id)
        res = dict()
        res = project.applyLabelModel()
        return app.response_class(
            response=simplejson.dumps(res, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/reprioritize_file')
    # @login_required
    def prioritize_file():
        project_id = request.args.get('project_id', type=int)
        file_idx = request.args.get('file_idx', type=int)

        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            abort(404, description="Project not found.")
            return
        try:
            project.file_ids
        except:
            fileIds = [f.id for f in project.files]
            project.file_ids = fileIds

        fileIds = project.file_ids
        if file_idx  <  0 or file_idx > len(fileIds):
            return 
        fileIds = [fileIds[file_idx]] + fileIds[:file_idx] + fileIds[file_idx+1:]
        project.file_ids = fileIds

        filesPayload = project.queryWeakSupervision({
            'randomFiles': False,
            # 'amount': 5
        }, fileIds = fileIds)

        _ = project.populateInitialSupervisorValuesToDict(fileIds, filesPayload)
        filesPayload['thresholds'] = project.getThresholdsPayload()
        filesPayload['existent_segments'], _ = project.getSegments()
        return app.response_class(
            response=simplejson.dumps(filesPayload, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/initial_supervisor_payload')
    # @login_required
    def initial_supervisor_payload():
        project_id = request.args.get('project_id', type=int)

        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            abort(404, description="Project not found.")
            return

        fileIds = [f.id for f in project.files]
        filesPayload = project.queryWeakSupervision({
            'randomFiles': False,
            # 'amount': 5
        }, fileIds = fileIds)
        # {
        #     'randomFiles': bool,
        #     'categorical': List[Category],
        #     'labelingFunction': str,
        #     'amount': int,
        #     # 'sortByConfidence': bool,
        #     # 'patientSearchString': str,
        # }
        # supervisorPayload = project.queryWeakSupervision({
        #     'randomFiles': True,
        #     'categorical': None,
        #     'labelingFunction': None,
        #     'amount': 10
        # })
        _ = project.populateInitialSupervisorValuesToDict(fileIds, filesPayload)
        filesPayload['thresholds'] = project.getThresholdsPayload()
        filesPayload['existent_segments'], _ = project.getSegments()
        return app.response_class(
            response=simplejson.dumps(filesPayload, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/get_labels')
    # @login_required
    def get_labels():
        project_id = request.args.get('project_id', type=int)

        labels = getProject(project_id).getLabels()
        return app.response_class(
            response=simplejson.dumps({'possible_labels': list(labels.keys())}, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/get_labelers')
    # @login_required
    def get_labelers():
        project_id = request.args.get('project_id', type=int)

        labelers = getProject(project_id).getLabelers()
        return app.response_class(
            response=simplejson.dumps({'possible_labelers': labelers}, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/get_segments')
    # @login_required
    def get_segments():
        project_id = request.args.get('project_id', type=int)
        type = request.args.get('segment_type', type=str)

        segments, windowInfo = getProject(project_id).getSegments(type)
        return app.response_class(
            response=simplejson.dumps({'segments': segments, 'window_info': windowInfo}, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/get_labeler_statistics')
    # @login_required
    def get_labeler_stats():
        project_id = request.args.get('project_id', type=int)
        segment_type = request.args.get('segment_type', type=str)

        project = getProject(project_id)
        stats = project.getLFStats(segment_type)

        return app.response_class(
            response=simplejson.dumps(stats, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/update_threshold', methods=['PUT'])
    # @login_required
    def put_threshold():
        project_id = request.args.get('project_id', type=int)
        p = getProject(project_id)
        req = request.get_json()
        success = p.updateThreshold(req)
        print(success)
        return app.response_class(
            response=simplejson.dumps({'success': success}, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/delete_vote_segments', methods=['POST'])
    # @login_required
    def delete_vote_segments():
        project_id = request.args.get('project_id', type=int)
        project = getProject(project_id)

        payload = request.get_json()
        voteSegments = payload['vote_segments']
        numDeleted, success = project.deleteSegments(voteSegments)

        returnPayload = {
            'success': success,
            'number_deleted': numDeleted
        }

        return app.response_class(
            response=simplejson.dumps(returnPayload, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/create_vote_segments', methods=['POST'])
    # @login_required
    def create_vote_segments():
        project_id = request.args.get('project_id', type=int)
        project = getProject(project_id)

        payload = request.get_json()
        voteSegments = payload.get('vote_segments')
        windowInfo = payload.get('window_info')
        createdSegments, success, numAdded = project.createSegments(voteSegments, windowInfo)

        returnPayload = {
            'newly_created_segments': createdSegments,
            'success': success,
            'num_added': numAdded
            }

        return app.response_class(
            response=simplejson.dumps(returnPayload, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/preview_threshold_change', methods=['POST'])
    # @login_required
    def preview_threshold():
        project_id = request.args.get('project_id', type=int)
        project = getProject(project_id)

        req = request.get_json()
        file_ids = req['files']
        thresholds = req['thresholds']
        labeler = req['labeler']
        timeSegment = req['time_segment']

        voteOutputs, endIndicesOutputs = project.previewThresholds(file_ids, thresholds, labeler, timeSegment)
        returnLoad = {'votes': voteOutputs,
            'end_indices': endIndicesOutputs}

        return app.response_class(
            response=simplejson.dumps(returnLoad, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/get_votes', methods=["GET", "POST"])
    # @login_required
    def get_votes():
        project_id = request.args.get('project_id', type=int)
        recalculate = request.args.get('recalculate', type=bool)
        fileIds = request.args.getlist('file_ids[]')
        windowInfo = request.get_json()['window_info']
        '''
            window_info: {
                window_size_ms: 30*60*1000,
                window_roll_ms: 30*60*1000
            }
        '''

        project = getProject(project_id)
        if (len(fileIds) == 0):
            fileIds = [f.id for f in project.files]
        print(fileIds, windowInfo)
        fileIds = [int(fileId) for fileId in fileIds]
        if (len(models.Vote.query.filter_by(project_id=project_id).all()) > 0):
            print('getting votes instead')
            votes, preds = project.getVotes(fileIds, windowInfo)
            d = dict()
            d['lm_predictions'] = preds
        else:
            votes = project.computeVotes(fileIds, windowInfo)
            d = dict()
        d['labeling_function_votes'] = votes
        return app.response_class(
            response=simplejson.dumps(d, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/query_supervisor_series', methods=['POST'])
    # @login_required
    def query_supervisor_series():
        project_id = request.args.get('project_id', type=int)
        request_data = request.get_json()
        query_payload = request_data['query_payload']

        project = getProject(project_id)
        query_response = project.queryWeakSupervision(query_payload)
        _ = project.populateInitialSupervisorValuesToDict([f[0] for f in query_response['files']], query_response)
        return app.response_class(
            response=simplejson.dumps(query_response),
            status=200,
            mimetype='application/json'
        )

    # @app.route(config['rootWebPath']+'/upload_custom_segments', methods=['POST'])
    # @login_required
    def custom_segments_upload():
        project_id = request.args.get('project_id', type=int)
        p = getProject(project_id)
        file = request.files['file_payload']

        segments, count = p.parseAndCreateSegmentsFromFile(file.filename, file)
        return app.response_class(
            response=simplejson.dumps({'segments': segments, 'num_added': count}),
            status=200,
            mimetype='application/json'
        )
        #receives function that takes in patient series' and returns necessary inputs for LF votes

    @app.route(config['rootWebPath']+'/project')
    @login_required
    def project():

        # Parse parameters
        id = request.args.get('id', type=int)

        p = getProject(id)
        if p is None:
            logging.error(f"Project ID {id} not found.")
            abort(404, description="Project not found.")
            return

        # Project payload data for the HTML template
        projectPayload = p.getInitialPayload(current_user.id)

        # Assemble the data into a payload. We JSON-encode this twice. The first
        # one converts the dict into JSON. The second one essentially makes the
        # JSON string safe to drop straight into JavaScript code, as we are doing.
        projectPayloadJSON = simplejson.dumps(simplejson.dumps(projectPayload))








        #### TEMP FOR FEATURIZERS

        # Assemble the data into a payload. We JSON-encode this twice. The first
        # one converts the dict into JSON. The second one essentially makes the
        # JSON string safe to drop straight into JavaScript code, as we are doing.
        featurizersJSONPayload = simplejson.dumps(simplejson.dumps({
            f.id: {
                'id': f.id,
                'name': f.name,
                'fields': f.getFields(),
            } for f in featurizers.values()
        }))

        # m = MeanFeaturizer()
        #
        # # Assemble the data into a payload. We JSON-encode this twice. The first
        # # one converts the dict into JSON. The second one essentially makes the
        # # JSON string safe to drop straight into JavaScript code, as we are doing.
        # featurizersJSONPayload = simplejson.dumps(simplejson.dumps(m.getFields()))







        return render_template('project.html', project_name=projectPayload['project_name'], payload=projectPayloadJSON, featurizersJSONPayload=featurizersJSONPayload)

    # @app.route(config['rootWebPath']+'/supervisor')
    # @login_required
    def supervisor():
        # Parse parameters
        id = request.args.get('id', type=int)
        p = getProject(id)
        if p is None:
            logging.error(f"Project ID {id} not found.")
            abort(404, description="Project not found.")
            return

        # Project payload data for the HTML template
        projectPayload = p.getInitialPayload(current_user.id)

        # Assemble the data into a payload. We JSON-encode this twice. The first
        # one converts the dict into JSON. The second one essentially makes the
        # JSON string safe to drop straight into JavaScript code, as we are doing.
        projectPayloadJSON = simplejson.dumps(simplejson.dumps(projectPayload))

        return render_template('supervisor.html', project_name=projectPayload['project_name'], payload=projectPayloadJSON)

    @app.route(config['rootWebPath']+'/series_ranged_data', methods=['GET'])
    @login_required
    def series_ranged_data():

        # Parse parameters
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)
        series = request.args.getlist('s[]')
        start = request.args.get('start', type=float)
        stop = request.args.get('stop', type=float)

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            abort(404, description="Project not found.")
            return

        # Get the file
        file = project.getFile(file_id)
        if file is None:
            logging.error(f"File ID {file_id} not found.")
            abort(404, description="File not found.")
            return

        # Assemble the series ranged data
        seriesRangedData = file.getSeriesRangedOutput(series, start, stop)

        # Output response
        return app.response_class(
            response=simplejson.dumps(seriesRangedData, ignore_nan=True),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath']+'/update_annotation', methods=['GET'])
    @login_required
    def update_annotation():

        # Parse parameters
        project_id = request.args.get('project_id', type=int)
        file_id = request.args.get('file_id', type=int)
        id = request.args.get('id')
        left = getFloatParamOrNone('xl')
        right = getFloatParamOrNone('xr')
        top = getFloatParamOrNone('yt')
        bottom = getFloatParamOrNone('yb')
        seriesID = request.args.get('sid')
        label = request.args.get('label')

        # Get the project
        project = getProject(project_id)
        if project is None:
            logging.error(f"Project ID {project_id} not found.")
            return app.response_class(
                response=simplejson.dumps({ 'success': False }),
                status=200,
                mimetype='application/json'
            )

        # Get the file
        file = project.getFile(file_id)
        if file is None:
            logging.error(f"File ID {file_id} not found.")
            return app.response_class(
                response=simplejson.dumps({ 'success': False }),
                status=200,
                mimetype='application/json'
            )

        # Update the annotation
        updateSuccess = file.updateAnnotation(current_user.id, id, left, right, top, bottom, seriesID, label)

        # Output the response
        return app.response_class(
            response=simplejson.dumps({'success': updateSuccess}),
            status=200,
            mimetype='application/json'
        )

    @app.route(config['rootWebPath'] + '/user_manage')
    @login_required
    def user_manage():
        pprint(vars(current_user))
        return render_template_string("""
                {% extends "base.html" %}
                {% block content %}
                     < h2>Profile Page < /h2>
                     < p>Hello {{ current_user.email }}, < /p>
                     < p> < a href="{{ url_for('home_page') }}">Home Page < /a> < /p>
                     < p> < a href="{{ url_for('user.change_password') }}">Change password < /a> < /p>
                     < p> < a href="{{ url_for('user.invite') }}">Invite User < /a> < /p>
                     < p> < a href="{{ url_for('user.logout') }}">Sign out < /a> < /p>
                {% endblock %}
                """)

    ### HELPERS ###

    # Returns the named request parameter as a float or None if the parameter is
    # empty or not present. The default return of None may be overridden.
    def getFloatParamOrNone(name, default=None):
        param = request.args.get(name)
        if param is not None and len(param) > 0:
            return request.args.get(name, type=float)
        else:
            return default

    return app

def main():

0 Source : autodoc.py
with MIT License
from blakebjorn

    def html(self, groups='all', template=None, **context):
        """Return an html string of the routes specified by the doc() method

        A template can be specified. A list of routes is available under the
        'autodoc' value (refer to the documentation for the generate() for a
        description of available values). If no template is specified, a
        default template is used.

        By specifying the group or groups arguments, only routes belonging to
        those groups will be returned.
        """
        if template:
            return render_template(template,
                                   autodoc=self.generate(groups=groups),
                                   **context)
        else:
            filename = os.path.join(
                os.path.dirname(__file__),
                'templates',
                'docs.html'
            )
            with open(filename) as file:
                content = file.read()
                with current_app.app_context():
                    return render_template_string(
                        content,
                        autodoc=self.generate(groups=groups),
                        **context)

0 Source : users.py
with GNU General Public License v3.0
from cellgeni

def create_app():
    """ Flask application factory """

    # Create Flask app load app.config
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Initialize Flask-BabelEx
    babel = Babel(app)

    # Initialize Flask-SQLAlchemy
    db = SQLAlchemy(app)

    # Define the User data-model.
    # NB: Make sure to add flask_user UserMixin !!!
    class User(db.Model, UserMixin):
        __tablename__ = 'users'
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1')

        # User authentication information. The collation='NOCASE' is required
        # to search case insensitively when USER_IFIND_MODE is 'nocase_collation'.
        email = db.Column(db.String(255, collation='NOCASE'), nullable=False, unique=True)
        email_confirmed_at = db.Column(db.DateTime())
        password = db.Column(db.String(255), nullable=False, server_default='')

        # User information
        first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
        last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')

        # Define the relationship to Role via UserRoles
        roles = db.relationship('Role', secondary='user_roles')

    # Define the Role data-model
    class Role(db.Model):
        __tablename__ = 'roles'
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define the UserRoles association table
    class UserRoles(db.Model):
        __tablename__ = 'user_roles'
        id = db.Column(db.Integer(), primary_key=True)
        user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))
        role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))

    # Setup Flask-User and specify the User data-model
    user_manager = UserManager(app, db, User)

    # Create all database tables
    db.create_all()

    # Create '[email protected]' user with no roles
    if not User.query.filter(User.email == '[email protected]').first():
        user = User(
            email='[email protected]',
            email_confirmed_at=datetime.datetime.utcnow(),
            password=user_manager.hash_password('Password1'),
        )
        db.session.add(user)
        db.session.commit()

    # Create '[email protected]' user with 'Admin' and 'Agent' roles
    if not User.query.filter(User.email == '[email protected]').first():
        user = User(
            email='[email protected]',
            email_confirmed_at=datetime.datetime.utcnow(),
            password=user_manager.hash_password('Password1'),
        )
        user.roles.append(Role(name='Admin'))
        user.roles.append(Role(name='Agent'))
        db.session.add(user)
        db.session.commit()

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
                {% extends "flask_user_layout.html" %}
                {% block content %}
                      <  h2>{%trans%}Home page{%endtrans%} < /h2>
                     < p> < a href={{ url_for('user.register') }}>{%trans%}Register{%endtrans%} < /a> < /p>
                     < p> < a href={{ url_for('user.login') }}>{%trans%}Sign in{%endtrans%} < /a> < /p>
                     < p> < a href={{ url_for('home_page') }}>{%trans%}Home Page{%endtrans%} < /a> (accessible to anyone) < /p>
                     < p> < a href={{ url_for('member_page') }}>{%trans%}Member Page{%endtrans%} < /a> (login_required: [email protected] / Password1) < /p>
                     < p> < a href={{ url_for('admin_page') }}>{%trans%}Admin Page{%endtrans%} < /a> (role_required: [email protected] / Password1') < /p>
                     < p> < a href={{ url_for('user.logout') }}>{%trans%}Sign out{%endtrans%} < /a> < /p>
                {% endblock %}
                """)

    # The Members page is only accessible to authenticated users
    @app.route('/members')
    @login_required  # Use of @login_required decorator
    def member_page():
        return render_template_string("""
                {% extends "flask_user_layout.html" %}
                {% block content %}
                     < h2>{%trans%}Members page{%endtrans%} < /h2>
                     < p> < a href={{ url_for('user.register') }}>{%trans%}Register{%endtrans%} < /a> < /p>
                     < p> < a href={{ url_for('user.login') }}>{%trans%}Sign in{%endtrans%} < /a> < /p>
                     < p> < a href={{ url_for('home_page') }}>{%trans%}Home Page{%endtrans%} < /a> (accessible to anyone) < /p>
                     < p> < a href={{ url_for('member_page') }}>{%trans%}Member Page{%endtrans%} < /a> (login_required: [email protected] / Password1) < /p>
                     < p> < a href={{ url_for('admin_page') }}>{%trans%}Admin Page{%endtrans%} < /a> (role_required: [email protected] / Password1') < /p>
                     < p> < a href={{ url_for('user.logout') }}>{%trans%}Sign out{%endtrans%} < /a> < /p>
                {% endblock %}
                """)

    # The Admin page requires an 'Admin' role.
    @app.route('/admin')
    @roles_required('Admin')  # Use of @roles_required decorator
    def admin_page():
        return render_template_string("""
                {% extends "flask_user_layout.html" %}
                {% block content %}
                     < h2>{%trans%}Admin Page{%endtrans%} < /h2>
                     < p> < a href={{ url_for('user.register') }}>{%trans%}Register{%endtrans%} < /a> < /p>
                     < p> < a href={{ url_for('user.login') }}>{%trans%}Sign in{%endtrans%} < /a> < /p>
                     < p> < a href={{ url_for('home_page') }}>{%trans%}Home Page{%endtrans%} < /a> (accessible to anyone) < /p>
                     < p> < a href={{ url_for('member_page') }}>{%trans%}Member Page{%endtrans%} < /a> (login_required: [email protected] / Password1) < /p>
                     < p> < a href={{ url_for('admin_page') }}>{%trans%}Admin Page{%endtrans%} < /a> (role_required: [email protected] / Password1') < /p>
                     < p> < a href={{ url_for('user.logout') }}>{%trans%}Sign out{%endtrans%} < /a> < /p>
                {% endblock %}
                """)

    return app


# Start development web server
if __name__ == '__main__':

0 Source : notifications.py
with Creative Commons Zero v1.0 Universal
from cisagov

    def _set_context(self, message_type, context):
        """
        Set context.

        Required fields when creating context-
        [send_to] - User,Admins,All,Application
        [subject] - Subject of email
        [text_content] - Text content of email
        [html_content] - Html content of email
        """
        return {
            "email_received": {
                "send_to": "ForwardEmail",
                "subject": f"[Domain Manager] FW: {context.get('subject', '')}",
                "text_content": render_template_string(
                    "emails/email_received.html", **context
                ),
                "html_content": render_template(
                    "emails/email_received.html", **context
                ),
            },
            "test": {
                "send_to": "User",
                "subject": "[Domain Manager] Test Event",
                "text_content": render_template_string("emails/test.html", **context),
                "html_content": render_template("emails/test.html", **context),
            },
            "website_launched": {
                "send_to": "User",
                "subject": "[Domain Manager] Your Website has been Launched",
                "text_content": render_template_string(
                    "emails/website_launched.html", **context
                ),
                "html_content": render_template(
                    "emails/website_launched.html", **context
                ),
            },
            "user_registered": {
                "send_to": "UserRegistered",
                "subject": "[Domain Manager] A New User Has Registered",
                "text_content": render_template_string(
                    "emails/new_user_registered.html", **context
                ),
                "html_content": render_template(
                    "emails/new_user_registered.html", **context
                ),
            },
            "user_confirmed": {
                "send_to": "Specified",
                "subject": "[Domain Manager] Your Account Has Been Confirmed",
                "text_content": render_template_string(
                    "emails/user_confirmed.html", **context
                ),
                "html_content": render_template(
                    "emails/user_confirmed.html", **context
                ),
            },
            "categorization_request": {
                "send_to": "CategorizationEmail",
                "subject": "[Domain Manager] Categorization Request",
                "text_content": render_template_string(
                    "emails/categorization_request.html", **context
                ),
                "html_content": render_template(
                    "emails/categorization_request.html", **context
                ),
            },
            "categorization_updates": {
                "send_to": "CategorizationEmail",
                "subject": "[Domain Manager] Categorization Updates",
                "text_content": render_template_string(
                    "emails/categorization_updates.html", **context
                ),
                "html_content": render_template(
                    "emails/categorization_updates.html", **context
                ),
            },
        }.get(message_type)

    def get_to_addresses(self, content):

0 Source : N2G_V3D.py
with MIT License
from dmulyalin

    def run(self, ip="0.0.0.0", port=9000, dry_run=False):
        """
        Method to run FLASK web server using built-in browser app.
        
        :param ip: (str) IP address to bound WEB server to
        :param port: (int) port number to run WEB server on
        :dry_run: (bool) if True, do not start, return status info instead, 
          default is False
        """
        from flask import Flask, render_template_string, Markup
        from N2G.utils.V3D_web_server import graph_browser

        app = Flask(__name__)

        # based on https://stackoverflow.com/a/19269087/12300761 answer:
        app.jinja_env.filters["json"] = lambda v: Markup(json.dumps(v))

        @app.route("/")
        def home():
            return render_template_string(graph_browser, json_data=self.dump_json())

        print("Starting server on http://{}:{}".format(ip, port))
        if dry_run:
            return {
                "message": "would start flask development server using graph_browser app",
                "ip": ip,
                "port": port,
            }
        else:
            app.run(host=ip, port=port, debug=True)

0 Source : snippet.py
with Apache License 2.0
from dockerizeme

def index():
    images = []
    for root, dirs, files in os.walk('.'):
        for filename in [os.path.join(root, name) for name in files]:
            if not filename.endswith('.jpg'):
                continue
            im = Image.open(filename)
            w, h = im.size
            aspect = 1.0*w/h
            if aspect > 1.0*WIDTH/HEIGHT:
                width = min(w, WIDTH)
                height = width/aspect
            else:
                height = min(h, HEIGHT)
                width = height*aspect
            images.append({
                'width': int(width),
                'height': int(height),
                'src': filename
            })

    return render_template_string(TEMPLATE, **{
        'images': images
    })

if __name__ == '__main__':

0 Source : views.py
with MIT License
from evinaypatil

    def login(self, flag=True):

        sm = self.appbuilder.sm
        oidc = sm.oid

        @self.appbuilder.sm.oid.require_login
        def handle_login():
            user = sm.auth_user_oid(oidc.user_getfield('email'))

            # Get user roles.
            user_roles = oidc.user_getfield(ROLES_OIDC_FIELD)
            
            # Iterate through each role, and check if its available.
            assign_roles = []
            if ENABLE_ROLE_OIDC_ACCESS.lower() in ['true']:
                if user_roles:
                    if isinstance(user_roles, str):
                        user_roles = [user_roles]
                    for role in user_roles:
                        fetch_role = sm.find_role(role)
                        if fetch_role:
                            assign_roles.append(fetch_role)
            else:
                if sm.auth_user_registration_role:
                    user_reg_role = sm.find_role(sm.auth_user_registration_role)
                    if user_reg_role:
                        assign_roles.append(sm.find_role(sm.auth_user_registration_role))

            # Thrown 401 if no roles are assigned to the user
            if len(assign_roles) == 0:
                log.debug(f"No role available for the user {oidc.user_getfield('email')} for access...")
                return render_template_string("Unauthorized Access! Please contact administrator...")

            # Get user info.
            info = oidc.user_getinfo([
                USERNAME_OIDC_FIELD,
                FIRST_NAME_OIDC_FIELD,
                LAST_NAME_OIDC_FIELD,
                'email',
            ])

            # Add user, if not in system, else update user
            if user is None:
                user = sm.add_user(
                    username=info.get(USERNAME_OIDC_FIELD),
                    first_name=info.get(FIRST_NAME_OIDC_FIELD),
                    last_name=info.get(LAST_NAME_OIDC_FIELD),
                    email=info.get('email'),
                    role=assign_roles[0]
                )

                user.roles.clear()
                user.roles.extend(assign_roles)
                sm.update_user(user)
                log.debug(f"New User added {info.get('email')} with roles {assign_roles}")
            else:
                # Update user information
                update_user = sm.find_user(email=info.get('email'))

                update_user.username = info.get(USERNAME_OIDC_FIELD)
                update_user.first_name = info.get(FIRST_NAME_OIDC_FIELD)
                update_user.last_name = info.get(LAST_NAME_OIDC_FIELD)
                update_user.email = info.get('email')
                update_user.active = True

                update_user.roles.clear()
                update_user.roles.extend(assign_roles)

                sm.update_user(update_user)
                log.debug(f"Logged in User {info.get('email')} with roles {assign_roles}")

            login_user(user, remember=False)
            return redirect(self.appbuilder.get_url_for_index)

        return handle_login()

    @expose('/logout/', methods=['GET', 'POST'])

See More Examples