Exemplo n.º 1
0
def create_app(defer_init_app=False, freezer_kwargs=None):
    app = Flask(__name__)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    if not freezer_kwargs:
        freezer_kwargs = {}
    if defer_init_app:
        freezer = Freezer(**freezer_kwargs)
    else:
        freezer = Freezer(app, **freezer_kwargs)

    @app.route("/")
    def index():
        return "Main index " + url_for("product", product_id="5", revision="b12ef20")

    @app.route("/page/<name>/")
    def page(name):
        url_for("product", product_id="3")  # Pretend we’re adding a link
        url_for("product", product_id="4")  # Another link
        return u"Hello\xa0World! " + name

    @app.route("/where_am_i/")
    def where_am_i():
        return url_for("where_am_i") + " " + url_for("where_am_i", _external=True)

    @app.route("/robots.txt")
    def robots_txt():
        content = "User-agent: *\nDisallow: /"
        return app.response_class(content, mimetype="text/plain")

    for asset in ("favicon.ico",):
        url = "/" + asset
        name = asset.replace(".", "_")
        app.add_url_rule(url, name, partial(app.send_static_file, filename=asset))

    @app.route("/product_<int:product_id>/")
    def product(product_id):
        return "Product num %i" % product_id

    @freezer.register_generator
    def product():
        # endpoint, values
        yield "product", {"product_id": 0}
        # Just a `values` dict. The endpoint defaults to the name of the
        # generator function, just like with Flask views
        yield {"product_id": 1}
        # single string: url
        yield "/product_2/"

        yield "page", {"name": u"I løvë Unicode"}

    @app.errorhandler(404)
    def not_found(e):
        return "Page not found", 404

    freezer.error_handler_spec[None] = {404: "/404.html"}

    if defer_init_app:
        freezer.init_app(app)

    return app, freezer
Exemplo n.º 2
0
def main():
    server.app.config['FREEZER_DESTINATION'] = config.OPTIONS['destination']
    server.app.config['FREEZER_BASE_URL'] = config.OPTIONS['baseurl']
    freezer = Freezer(server.app)
    freezer.freeze()

    return freezer
Exemplo n.º 3
0
    def handle(self, app, serve, no_index):
        app.jinja_loader  # ugly workaround
        app.blohg.init_repo(REVISION_DEFAULT)

        app.url_map = self.remap_rules(app.url_map, no_index)

        # That's a risky one, it woud be better to give a parameter to the
        # freezer
        app.root_path = app.config.get('REPO_PATH')

        freezer = Freezer(app)

        def static_generator(static_dir):
            for f in app.blohg.changectx.files:
                if f.startswith(static_dir):
                    yield dict(filename=f[len(static_dir):] \
                               .strip(posixpath.sep))

        @freezer.register_generator
        def static():
            """Walk the static dir and freeze everything"""
            return static_generator('static')

        @freezer.register_generator
        def attachments():
            """Walk the attachment dir and freeze everything"""
            return static_generator(app.config['ATTACHMENT_DIR'])

        freezer.freeze()
        if serve:
            freezer.serve()
Exemplo n.º 4
0
def freeze(destination):
    '''Freeze the wiki to the destination directory.'''
    # If the freezer is provided a relative URL then it behaves by trying to
    # write to package area. This won't work if the package is installed so
    # convert the relative path to an absolute one.
    if not os.path.isabs(destination):
        destination = os.path.join(os.getcwd(), destination)

    # Set MarkWiki in a freezing mode so that certain elements of the views
    # won't get rendered.
    app.config['FREEZING'] = True

    app.config['FREEZER_IGNORE_MIMETYPE_WARNINGS'] = True
    app.config['FREEZER_DESTINATION'] = destination

    # The freeze operation is destructive because it follows the delete
    # links. Copy the wiki into a temporary area and work with that instead.
    _create_wiki_copy()

    freezer = Freezer(app)

    # Add the URL generator to suppress a warning. It won't really do anything.
    @freezer.register_generator
    def delete():
        yield {'page_path': 'Home'}

    try:
        freezer.freeze()
    except OSError:
        return ('Failed to freeze the MarkWiki. Do you have permission to '
                'write to the destination directory?')

    return _prune_frozen(destination)
Exemplo n.º 5
0
def freeze_topic_model_browser():
    global token
    topic_model_browser_app.config.update(
        FREEZER_BASE_URL='http://mediamining.univ-lyon2.fr/people/guille/cats/tom/' + token,
        FREEZER_DESTINATION='tom/' + token,
        FREEZER_IGNORE_404_NOT_FOUND=True,
        FREEZER_REMOVE_EXTRA_FILES=False,
        FREEZER_DESTINATION_IGNORE=['.tsv', '.json']
    )
    topic_model_browser_app.debug = False
    topic_model_browser_app.testing = True
    topic_model_browser_app.config['ASSETS_DEBUG'] = False
    print('Freeze topic model browser')
    topic_model_freezer = Freezer(topic_model_browser_app)
    print('Finalizing the topic model browser...')

    @topic_model_freezer.register_generator
    def topic_details():
        for _topic_id in range(topic_model.nb_topics):
            yield {'tid': _topic_id}

    @topic_model_freezer.register_generator
    def document_details():
        for _doc_id in range(topic_model.corpus.size):
            yield {'did': _doc_id}

    @topic_model_freezer.register_generator
    def word_details():
        for _word_id in range(len(topic_model.corpus.vocabulary)):
            yield {'wid': _word_id}

    topic_model_freezer.freeze()
    print('Done.')
Exemplo n.º 6
0
def create_app(defer_init_app=False, freezer_kwargs=None):
    app = Flask(__name__)
    app.register_blueprint(admin_blueprint, url_prefix='/admin')
    if not freezer_kwargs:
        freezer_kwargs = {}
    if defer_init_app:
        freezer = Freezer(**freezer_kwargs)
    else:
        freezer = Freezer(app, **freezer_kwargs)

    @app.route('/')
    def index():
        return ('Main index ' +
                url_for('product', product_id='5', revision='b12ef20'))

    @app.route('/page/<name>/')
    def page(name):
        url_for('product', product_id='3')  # Pretend we’re adding a link
        url_for('product', product_id='4')  # Another link
        return u'Hello\xa0World! ' + name

    @app.route('/where_am_i/')
    def where_am_i():
        return (url_for('where_am_i') + ' ' +
                url_for('where_am_i', _external=True))

    @app.route('/robots.txt')
    def robots_txt():
        content = 'User-agent: *\nDisallow: /'
        return app.response_class(content, mimetype='text/plain')

    for asset in ("favicon.ico",):
        url = "/" + asset
        name = asset.replace(".", "_")
        _partial = partial(app.send_static_file, filename=asset)
        app.add_url_rule(url, name, _partial)

    @app.route('/product_<int:product_id>/')
    def product_route(product_id):
        return 'Product num %i' % product_id

    @app.route('/add/', methods=['POST'])
    def add_something(product_id):
        return 'This view should be ignored as it does not accept GET.'

    @freezer.register_generator
    def product_generator():
        # endpoint, values
        yield 'product', {'product_id': 0}
        yield 'page', {'name': 'foo'}
        # Just a `values` dict. The endpoint defaults to the name of the
        # generator function, just like with Flask views
        yield {'product_id': 1}
        # single string: url
        yield '/product_2/'

    if defer_init_app:
        freezer.init_app(app)

    return app, freezer
Exemplo n.º 7
0
    def take_action(self, args):
        self.app.ara.config['FREEZER_DESTINATION'] = os.path.abspath(args.path)

        if args.playbook is not None:
            self.app.ara.config['ARA_PLAYBOOK_OVERRIDE'] = args.playbook

        self.log.warning('Generating static files at %s...', args.path)
        filterwarnings('ignore', '.*', NotFoundWarning)
        if self.app.ara.config['ARA_IGNORE_EMPTY_GENERATION']:
            filterwarnings('ignore', '.*', MissingURLGeneratorWarning)
        freezer = Freezer(self.app.ara)

        # Patternfly fonts are called from inside the CSS and are therefore
        # not automatically found by flask-frozen. We need to generate URLs
        # for the fonts.
        patternfly = self.app.ara.config['XSTATIC']['patternfly']

        @freezer.register_generator
        def serve_static_packaged():
            for font in walk_directory(os.path.join(patternfly, 'fonts')):
                yield dict(
                    module='patternfly',
                    filename='fonts/%s' % font
                )
        freezer.freeze()

        print('Done.')
Exemplo n.º 8
0
def freeze():
    """Prepare and run the freezer"""
    app = app_factory({'FREEZER_DESTINATION': join('..', 'output')})
    app.context_processor(freezer_template_context)
    freezer = Freezer(app, with_static_files=False)
    freezer.register_generator(partial(bootstrap_fonts, app))
    freezer.freeze()
    copy_extra(freezer)
Exemplo n.º 9
0
def freeze():
    """
    Freeze the site into static files.
    This function has severe problem. Do not use!
    """
    from flask_frozen import Freezer
    freezer = Freezer(app)
    freezer.freeze()
Exemplo n.º 10
0
def freeze():
    """首页静态化"""
    from xueer.hello import hello
    from flask_frozen import Freezer

    freezer = Freezer(hello)

    if __name__ == '__main__':
        freezer.freeze()
Exemplo n.º 11
0
def freeze(*args):
	import shutil
	from flask import url_for

	freezer = Freezer(app)
	freezer.freeze()
	# Copy the boilerplate files (favicon, robots.txt) to the freezer
	for filename in app.config.get('BOILER_FILES'):
		shutil.copy(app.config.get('BOILER_FULL_URL') + filename, app.config.get('FREEZER_DESTINATION'))
Exemplo n.º 12
0
Arquivo: cli.py Projeto: madflow/toni
def process_preview(args):
    args.base = 'http://localhost:' + str(args.port)
    args.dir = create_temp_dir()
    app.config['FREEZER_DESTINATION'] = args.dir
    process_build(args)
    print ' * Tempdir %s' % args.dir
    freezer = Freezer(app)
    freezer.serve(port=args.port)
    print' * Deleting %s' % args.dir
    delete_dir(args.dir)
Exemplo n.º 13
0
def freeze_app():
    from flask_frozen import Freezer
    debugged = app.debug
    app.debug = True
    url_rules = ('about', 'schedule', 'logistics', 'partner', 'register', 'thanks', 'downloads', 'live')
    for rule in url_rules:
        app.add_url_rule('/<lang>/{}/'.format(rule), rule, partial(page, page=rule))
    freezer = Freezer(app)
    freezer.freeze()
    app.debug = debugged
Exemplo n.º 14
0
Arquivo: cli.py Projeto: madflow/toni
def process_build(args):
    """Process the build"""
    if args.dir:
        if os.path.isdir(args.dir):
            target = args.dir
        else:
            target = os.path.join(APP_BASE_PATH, args.dir)
        app.config['FREEZER_DESTINATION'] = target
    if args.base:
        app.config['FREEZER_BASE_URL'] = args.base
    freezer = Freezer(app)
    freezer.freeze()
Exemplo n.º 15
0
 def test_transitivity(self):
     with self.built_app() as (temp, app, freezer, urls):
         with temp_directory() as temp2:
             # Run the freezer on it's own output
             app2 = freezer.make_static_app()
             app2.config["FREEZER_DESTINATION"] = temp2
             app2.debug = True
             freezer2 = Freezer(app2)
             freezer2.register_generator(self.filenames.iterkeys)
             freezer2.freeze()
             destination = app.config["FREEZER_DESTINATION"]
             self.assertEquals(read_all(destination), read_all(temp2))
Exemplo n.º 16
0
Arquivo: run.py Projeto: alanhdu/blog
def build():
    """Build blog"""
    app.config["BLOG"]["posts"] = sorted(load(["posts"]),
                                         key=lambda post: post.revdate,
                                         reverse=True)
    app.config["FREEZER_BASE_URL"] = app.config["BLOG"]["base_url"]
    app.config["FREEZER_DESTINATION"] = "../build"

    app.static_url_path = app.config["BLOG"]["base_path"] + "static/"

    freezer = Freezer(app)
    freezer.freeze()
Exemplo n.º 17
0
Arquivo: flekky.py Projeto: xi/flekky
def create_freezer(*args, **kwargs):
    """Freezer factory.

    Any arguments will be forwarded to the underlying app factory.
    """
    def urls():
        yield '.page_route', {'path': '/'}
        for page in pages:
            yield '.page_route', {'path': page.path}

    freezer = Freezer(create_app(*args, **kwargs))
    freezer.register_generator(urls)
    return freezer
Exemplo n.º 18
0
def build_individual_repositories(repository_list):
    app.config['FREEZER_DESTINATION'] = os.path.abspath("static")
    app.config['FREEZER_BASE_URL'] = "https://dabo.guru/"
    app.config['FREEZER_REMOVE_EXTRA_FILES'] = False
    freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=False, log_url_for=True)
    for repository in repository_list:
        def url_generator():
            return documentation.get_possible_pages_for_frozen_flask(repository)

        freezer.register_generator(url_generator)
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=MissingURLGeneratorWarning)
        freezer.freeze()
Exemplo n.º 19
0
def freeze():
    freezer = Freezer(app)

    @freezer.register_generator
    def page_list():
        for lang_code in ['en', 'fr']:
            yield 'pages.index', {'lang_code': lang_code}
            yield 'pages.guide', {'lang_code': lang_code}
            yield 'schedule.index', {'lang_code': lang_code}
            yield '/{}/schedule/schedule.json'.format(lang_code)
            yield '/{}/schedule/schedule.ics'.format(lang_code)

    freezer.freeze()
Exemplo n.º 20
0
def create_app(defer_init_app=False, freezer_kwargs=None):
    app = Flask(__name__)
    app.register_blueprint(admin_blueprint, url_prefix='/admin')
    if not freezer_kwargs:
        freezer_kwargs = {}
    if defer_init_app:
        freezer = Freezer(**freezer_kwargs)
    else:
        freezer = Freezer(app, **freezer_kwargs)

    @app.route('/')
    def index():
        return ('Main index ' +
                url_for('product', product_id='5', revision='b12ef20'))

    @app.route('/page/<name>/')
    def page(name):
        url_for('product', product_id='3')  # Pretend we’re adding a link
        url_for('product', product_id='4')  # Another link
        return u'Hello\xa0World! ' + name

    @app.route('/where_am_i/')
    def where_am_i():
        return (url_for('where_am_i') + ' ' +
                url_for('where_am_i', _external=True))

    @app.route('/robots.txt')
    def robots_txt():
        content = 'User-agent: *\nDisallow: /'
        return app.response_class(content, mimetype='text/plain')

    @app.route('/product_<int:product_id>/')
    def product(product_id):
        return 'Product num %i' % product_id

    @freezer.register_generator
    def product():
        # endpoint, values
        yield 'product', {'product_id': 0}
        # Just a `values` dict. The endpoint defaults to the name of the
        # generator function, just like with Flask views
        yield {'product_id': 1}
        # single string: url
        yield '/product_2/'

        yield 'page', {'name': u'I løvë Unicode'}

    if defer_init_app:
        freezer.init_app(app)

    return app, freezer
Exemplo n.º 21
0
    def run(self):
        app = self.app
        app.init()
        freezer = Freezer(app)

        logging.getLogger().setLevel(logging.INFO)
        logging.info('Generating static pages...')

        @freezer.register_generator
        def generate_pages():
            for p in app.pages:
                if p.path == 'index':
                    yield '/'
                # logging.info('Generating %s' % p.url)
                yield p.url

        @freezer.register_generator
        def generate_datafiles():
            yield '/api/pages/all.json'
            yield '/api/posts.json'
            for p in app.pages:
                yield '/api/pages/%s.json' % p.path

        @freezer.register_generator
        def generate_attachments():
            for p in app.pages:
                res_path = path.join(path.dirname(p._filename), p.name)
                if path.exists(res_path):
                    for root, dirs, files in walk(res_path):
                        for f in files:
                            if not f.endswith('.md'):
                                f_p = path.join(path.dirname(p._filename), p.name, f)
                                if path.exists(f_p):
                                    yield p.url + '/' + f

        @freezer.register_generator
        def generate_archives():
            for archive in app.site.archives:
                yield '/archives/%s' % archive.title

        freezer.freeze()
        logging.info('Generation completed.Doing cleanup....')

        for root, dirs, files in walk(path.join(getcwd(), 'builds')):
            for d in dirs:
                if path.basename(d) in ['.webassets-cache', '_styles', '_scripts']:
                    rmtree(path.join(root, d))

            for f in files:
                if path.splitext(f)[1] in ['.less', '.scss', '.coffee']:
                    remove(path.join(root, f))
Exemplo n.º 22
0
def create_app(defer_init_app=False, freezer_kwargs=None):
    app = Flask(__name__)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    if not freezer_kwargs:
        freezer_kwargs = {}
    if defer_init_app:
        freezer = Freezer(**freezer_kwargs)
    else:
        freezer = Freezer(app, **freezer_kwargs)

    @app.route("/")
    def index():
        return "Main index"

    @app.route("/page/<name>/")
    def page(name):
        url_for("product", product_id="3")  # Pretend we’re adding a link
        url_for("product", product_id="4")  # Another link
        return u"Hello\xa0World! " + name

    @app.route("/where_am_i/")
    def where_am_i():
        return url_for("where_am_i") + " " + url_for("where_am_i", _external=True)

    @app.route("/robots.txt")
    def robots_txt():
        content = "User-agent: *\nDisallow: /"
        return app.response_class(content, mimetype="text/plain")

    @app.route("/product_<int:product_id>/")
    def product(product_id):
        return "Product num %i" % product_id

    @freezer.register_generator
    def product():
        # endpoint, values
        yield "product", {"product_id": 0}
        # Just a `values` dict. The endpoint defaults to the name of the
        # generator function, just like with Flask views
        yield {"product_id": 1}
        # single string: url
        yield "/product_2/"

        yield "page", {"name": u"I løvë Unicode"}

    if defer_init_app:
        freezer.init_app(app)

    return app, freezer
Exemplo n.º 23
0
def generate():
	app.config['FREEZER_DESTINATION'] = settings.web_app_location
	app.config['FREEZER_BASE_URL'] = settings.external_url

	freezer = Freezer(app)

	copy = copytext.Copy(settings.copy_sheet_location)
	@freezer.register_generator
	def candidate_page():
		for sheetName in copy.sheetNames():
			if sheetName == 'metadata' or sheetName == 'Attribution': continue
			for row in copy[sheetName]:
				yield {"candidate_id": row['Candidate Name'].unescape().replace(" ", "_").replace("/", "_")}
				
	freezer.freeze()
Exemplo n.º 24
0
    def __init__(self, path, client_secrets_path=None, quiet=False):
        self.app = Flask(__name__)

        self.quiet = quiet

        self.app.jinja_env.finalize = silent_none  # Don't print "None"
        self.app.debug = True  # Always debug

        self.path = path
        self.project, self.base = self.load_project(path)

        self.data = {}
        self.hooks = self.process_hooks(hooks)
        self.expires = 0

        # add routes
        self.app.add_url_rule('/', view_func=self.preview)
        self.app.add_url_rule('/<path:path>', view_func=self.preview)
        self.app.add_url_rule('/data.json', view_func=self.data_json)

        self.app.register_blueprint(filters)

        self.app.before_request(self.add_site_to_context)
        self.app.after_request(self.never_cache_preview)

        # centralized freezer setup
        self.app.config.setdefault('FREEZER_RELATIVE_URLS', True)
        self.app.config.setdefault('FREEZER_REMOVE_EXTRA_FILES', False)
        self.app.config.setdefault('FREEZER_DESTINATION', 
            os.path.join(os.path.realpath(self.path), '_site'))

        self.freezer = Freezer(self.app) 
        self.freezer.register_generator(self.find_files)
Exemplo n.º 25
0
def freeze_event_browser():
    global topic_associations, author_list, token
    os.makedirs('mabed/'+token+'/static/data')
    print('Freeze event browser')
    event_browser_app.config.update(
        FREEZER_BASE_URL='http://mediamining.univ-lyon2.fr/people/guille/cats/mabed/'+token,
        FREEZER_DESTINATION='mabed/'+token,
        FREEZER_IGNORE_404_NOT_FOUND=True,
        FREEZER_REMOVE_EXTRA_FILES=False,
    )
    event_browser_freezer = Freezer(event_browser_app)
    event_browser_app.debug = False
    event_browser_app.testing = True
    event_browser_app.config['ASSETS_DEBUG'] = False
    event_browser_freezer.freeze()
    print('Done.')
Exemplo n.º 26
0
def _generate(app, destination):
    app.config.update(
        FREEZER_RELATIVE_URLS=True
      , FREEZER_DESTINATION=destination
    )

    freezer_config = app.config['generator_config'].get('freezer_config', None)
    if freezer_config:
        app.config.update(freezer_config)

    freezer = Freezer( app
                       # We'll have to request all pages manually. This
                       # way we can create some endpoints pro forma
                       # without yielding 404 errors.
                     , with_no_argument_rules=False)
    freezer.register_generator(app.config['menu'].allLinks)
    freezer.freeze()
Exemplo n.º 27
0
def build(config_overrides):
    app = create_app(config_overrides)
    app.config['FREEZER_REMOVE_EXTRA_FILES'] = True
    freezer = Freezer(app)

    @freezer.register_generator
    def page_url_generator():
        cms = get_or_create_cms()
        contents = cms.structure()
        folder_names = contents['folders'].keys()
        for folder in folder_names:
            yield 'page_router.folder_index', {'folder_name': folder}
            page_names = contents['folders'][folder]['pages'].keys()
            for page in page_names:
                yield 'page_router.render_page', {'folder_name': folder,
                                                  'page_name': page}

    freezer.freeze()
Exemplo n.º 28
0
def build_html():
    from flask_frozen import Freezer
    from app import views
    views.app.config['FREEZER_DESTINATION'] = '../build'
    views.app.testing = True
    freezer = Freezer(views.app, with_static_files=False)
    freezer.register_generator(views.school_url_generator)
    freezer.register_generator(views.blog_url_generator)
    freezer.freeze()
Exemplo n.º 29
0
def build_pages():
    ignored = [bundle.output for bundle in assets] + ["rust"]
    app.config['FREEZER_DESTINATION'] = os.path.abspath("static")
    app.config['FREEZER_BASE_URL'] = "https://dabo.guru/"
    app.config['FREEZER_DESTINATION_IGNORE'] = ignored
    app.config['FREEZER_IGNORE_ENDPOINTS'] = ['oauth_respond', 'mc_api_name', 'mc_api_uuid', 'serve_markdown',
                                              'uuid_api']
    freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=False, log_url_for=True)
    freezer.register_generator(no_argument_rules_urls_with_ignore)
    freezer.register_generator(markdown_url_generator)
    freezer.register_generator(lambda: completely_static_files)
    print("Updating documentation")
    documentation.update_all_repositories(config)
    print("Freezing")
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=MissingURLGeneratorWarning)
        freezer.freeze()
Exemplo n.º 30
0
def build_html():
    from flask_frozen import Freezer
    from app import views

    views.app.config["FREEZER_DESTINATION"] = "../build"
    views.app.config["FREEZER_REMOVE_EXTRA_FILES"] = False
    views.app.testing = True
    freezer = Freezer(views.app, with_static_files=False)
    freezer.register_generator(views.school_url_generator)
    freezer.register_generator(views.blog_url_generator)
    freezer.freeze()
Exemplo n.º 31
0
# -*- coding: utf-8 -*-
from flask_frozen import Freezer
from myapp import app
from scripts import tabledef
from scripts import forms
from scripts import helpers
from flask import Flask, redirect, url_for, render_template, request, session
import json
import sys
import os

freezer = Freezer(app)

app = Flask(__name__)
app.secret_key = os.urandom(12)  # Generic key for dev purposes only

# Heroku
#from flask_heroku import Heroku
#heroku = Heroku(app)


# ======== Routing =========================================================== #
# -------- Login ------------------------------------------------------------- #
@app.route('/', methods=['GET', 'POST'])
def login():
    if not session.get('logged_in'):
        form = forms.LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = request.form['password']
            if form.validate():
Exemplo n.º 32
0
from src.encoder import DateAwareEncoder
from src.externals import process_nav_includes
from src.grammar import get_grammar
from src.markdown.makrdown import jinja_aware_markdown
from src.pages.MyFlatPages import MyFlatPages
from src.pdf import generate_pdf
from src.processors.processors import process_code_blocks
from src.search import build_search_indices
from src.sitemap import generate_sitemap

app = Flask(__name__, static_folder='_assets')
app.config.from_pyfile('mysettings.py')
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
pages = MyFlatPages(app)
freezer = Freezer(app)
ignore_stdlib = "--ignore-stdlib" in sys.argv
build_mode = False
build_errors = []
url_adapter = app.create_url_adapter(None)

root_folder = path.join(os.path.dirname(__file__))
data_folder = path.join(os.path.dirname(__file__), "data")

_nav_cache = None
_nav_lock = threading.RLock()


def get_site_data():
    data = {}
    for data_file in os.listdir(data_folder):
Exemplo n.º 33
0
import redis
from flask_sqlalchemy import SQLAlchemy
from flask_frozen import Freezer
from flask_migrate import Migrate
from flasgger import Swagger
from raven.contrib.flask import Sentry

from flask_server.config import SENTRY_URL, Config
from flask_server.utils import CacheDict

db = SQLAlchemy()
migrate = Migrate(db=db)
freezer = Freezer(with_no_argument_rules=False, log_url_for=False)
swagger = Swagger(template_file='swagger.yml')
sentry = Sentry(dsn=SENTRY_URL)
if Config.REDIS:
    cache = redis.StrictRedis(host=Config.REDIS_HOST,
                              port=Config.REDIS_PORT,
                              db=Config.REDIS_DB)
else:
    cache = CacheDict()
Exemplo n.º 34
0
if os.environ.get('FREEZER_RELATIVE_URLS'):
    print("Using FREEZER_RELATIVE_URLS: {}".format(
        os.environ.get('FREEZER_RELATIVE_URLS')))
    app.config['FREEZER_RELATIVE_URLS'] = eval(
        os.environ.get('FREEZER_RELATIVE_URLS'))

# add also a differnet base_URL
if os.environ.get('FREEZER_BASE_URL'):
    print("Using FREEZER_BASE_URL: {}".format(
        os.environ.get('FREEZER_BASE_URL')))
    app.config['FREEZER_BASE_URL'] = os.environ.get('FREEZER_BASE_URL')

# http://pythonhosted.org/Frozen-Flask/#api-reference
freezer = Freezer(
    app,
    # with_no_argument_rules=False
    # ignore all other url's
    log_url_for=False)


@freezer.register_generator
def all_urls():
    df = kipoi.get_source("kipoi").list_models()
    model = df.model
    urls = set()
    for m in model:
        while m:
            urls.add(m)
            m = os.path.dirname(m)
    groups = {x for x in urls if get_view(x, df)[0] == "group_list"}
    # exclude the final models
Exemplo n.º 35
0
from flask import Flask
from flask_frozen import Freezer
from config import config
from .main import main as main_blueprint

freezer = Freezer()

app = Flask(__name__)
app.config.from_object(config['dev'])
config['dev'].init_app(app)
freezer.init_app(app)
app.register_blueprint(main_blueprint)
Exemplo n.º 36
0
def create_freezer(app):
    return Freezer(app)
Exemplo n.º 37
0
from src.externals import process_nav_includes
from src.grammar import get_grammar
from src.markdown.makrdown import jinja_aware_markdown
from src.pages.MyFlatPages import MyFlatPages
from src.pdf import generate_pdf
from src.processors.processors import process_code_blocks
from src.processors.processors import set_replace_simple_code
from src.search import build_search_indices, get_pages
from src.sitemap import generate_sitemap

app = Flask(__name__, static_folder='_assets')
app.config.from_pyfile('mysettings.py')
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
pages = MyFlatPages(app)
freezer = Freezer(app)
ignore_stdlib = False
build_mode = False
build_contenteditable = False
build_check_links = True
build_errors = []
url_adapter = app.create_url_adapter(None)

root_folder = path.join(os.path.dirname(__file__))
data_folder = path.join(os.path.dirname(__file__), "data")

_nav_cache = None
_nav_lock = threading.RLock()

_cached_asset_version = {}
Exemplo n.º 38
0
 def __init__(self):
     """
         >>> f = FreezeThings()
         """
     self.freezer = Freezer(app)
Exemplo n.º 39
0
def create_app(defer_init_app=False, freezer_kwargs=None):
    app = Flask(__name__)
    app.register_blueprint(admin_blueprint, url_prefix='/admin')
    if not freezer_kwargs:
        freezer_kwargs = {}
    if defer_init_app:
        freezer = Freezer(**freezer_kwargs)
    else:
        freezer = Freezer(app, **freezer_kwargs)

    @app.route('/')
    def index():
        return ('Main index ' +
                url_for('product', product_id='5', revision='b12ef20'))

    @app.route('/redirect/')
    def redirected_page():
        return redirect('/')

    @app.route('/page/<name>/')
    def page(name):
        url_for('product', product_id='3')  # Pretend we’re adding a link
        url_for('product', product_id='4')  # Another link
        return u'Hello\xa0World! ' + name

    @app.route('/where_am_i/')
    def where_am_i():
        return (url_for('where_am_i') + ' ' +
                url_for('where_am_i', _external=True))

    @app.route('/robots.txt')
    def robots_txt():
        content = 'User-agent: *\nDisallow: /'
        return app.response_class(content, mimetype='text/plain')

    for asset in ("favicon.ico",):
        url = "/" + asset
        name = asset.replace(".", "_")
        app.add_url_rule(url, name, partial(app.send_static_file, filename=asset))

    @app.route('/product_<int:product_id>/')
    def product(product_id):
        return 'Product num %i' % product_id

    @app.route('/add/', methods=['POST'])
    def add_something(product_id):
        return 'This view should be ignored as it does not accept GET.'

    @freezer.register_generator
    def product():
        # endpoint, values
        yield 'product', {'product_id': 0}
        yield 'page', {'name': 'foo'}
        # Just a `values` dict. The endpoint defaults to the name of the
        # generator function, just like with Flask views
        yield {'product_id': 1}
        # single string: url
        yield '/product_2/'

    if defer_init_app:
        freezer.init_app(app)

    return app, freezer
def build():
    freezer = Freezer(app)
    freezer.freeze()
Exemplo n.º 41
0
import argparse

from collections import OrderedDict

from flask import Flask, render_template
from flask_mysqldb import MySQL
from flask_frozen import Freezer

import minimCrawler

app = Flask(__name__)
mysql = MySQL(app)

freezer = Freezer(app, True)

app.config.update(
    dict(DEBUG=True,
         FREEZER_DESTINATION='build',
         FREEZER_REMOVE_EXTRA_FILES=False))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

orderedSites = OrderedDict(
    sorted(minimCrawler.sites.items(),
           key=lambda t: t[0]))  # fix sites order alphabetically


@app.route('/')
def home():
    db = mysql.connection
    for site in orderedSites:
        orderedSites[site]['data'] = []
Exemplo n.º 42
0
from flask_frozen import Freezer
from main import app
freeze = Freezer(app)

if __name__ == '__main__':
    freeze.freeze()
Exemplo n.º 43
0
        event_descriptions.append((mag,
                                   str(mabed.corpus.to_date(time_interval[0])),
                                   str(mabed.corpus.to_date(time_interval[1])),
                                   main_term,
                                   ', '.join(related_terms)))
        for i in range(0, mabed.corpus.time_slice_count):
            value = 0
            if time_interval[0] <= i <= time_interval[1]:
                value = raw_anomaly[i]
                if value < 0:
                    value = 0
            formatted_anomaly.append('['+str(formatted_dates[i])+','+str(value)+']')
        impact_data.append('{"key":"' + main_term + '", "values":[' + ','.join(formatted_anomaly) + ']}')

    if args.o is not None:
        if os.path.exists(args.o):
            shutil.rmtree(args.o)
        os.makedirs(args.o)
        print('Freezing event browser into %s...' % args.o)
        event_browser_freezer = Freezer(event_browser)
        event_browser.config.update(
            FREEZER_DESTINATION=args.o,
            FREEZER_RELATIVE_URLS=True,
        )
        event_browser.debug = False
        event_browser.config['ASSETS_DEBUG'] = False
        event_browser_freezer.freeze()
        print('Done.')
    else:
        event_browser.run(debug=False, host='localhost', port=2016)
Exemplo n.º 44
0
from flask_frozen import Freezer

import web

freezer = Freezer(web.create_app())

if __name__ == "__main__":
    freezer.freeze()
    # freezer.run(debug=True)
Exemplo n.º 45
0
def freeze(args):
    "https://pythonhosted.org/Frozen-Flask/"
    from flask_frozen import Freezer
    _setup_app(args)
    freezer = Freezer(app)
    freezer.freeze(debug=args.debug)
Exemplo n.º 46
0
""" Flask freezer """
#from shutil import copyfile
from flask_frozen import Freezer
from flaskblog import app

Freezer = Freezer(app)

if __name__ == "__main__":
    Freezer.freeze()

    # copy the _redirects file to the /build path
    #copyfile("_redirects", "src/build/_redirects")
Exemplo n.º 47
0
from flask_frozen import Freezer
from app import app as flask_app
import app
import yaml
from utils import gdrive_parsing
import urllib
from utils import resources

freezer = Freezer(flask_app)


def quote_plus_url(url):
    "Take a url with pre-urlencoded segments and give it another round of urlencoding"
    return "/".join(urllib.parse.quote_plus(seg) for seg in url.split("/"))


def generate_urls(tree, path):

    out = []

    # We have to call quote_plus_url twice because frozen flask will attempt to de-urlencode the paths

    for resource in tree.contents:
        if isinstance(resource, resources.HTMLResource) or isinstance(
                resource, resources.FileResource):
            out.append(
                app.quote_plus_url(
                    app.quote_plus_url(path + "/" + resource.id + "/")))
        elif isinstance(resource, resources.ResourceFolder):
            out.append(
                app.quote_plus_url(
Exemplo n.º 48
0
from flask_frozen import Freezer
from test_app import app

app.config.update(FREEZER_IGNORE_404_NOT_FOUND=True)

freezer = Freezer(app, with_static_files=False)

if __name__ == '__main__':
    freezer.freeze()
from flask import Flask, render_template
from flask_flatpages import FlatPages
from config import config
from flask_frozen import Freezer
from flask.ext.assets import Environment
from . import asset_bundle

flatpages = FlatPages()
freezer = Freezer()
assets = Environment()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    flatpages.init_app(app)
    freezer.init_app(app)
    assets.init_app(app)
    assets.register('js_all', asset_bundle.js_all)
    assets.register('css_all', asset_bundle.css)
    assets.register('portfolio_css', asset_bundle.portfolio_css)
    assets.register('resume_css', asset_bundle.resume_css)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
    return app
Exemplo n.º 50
0
import os
try:
    import config
except ImportError, e:
    print("Please run install.py first.")
    raise e

DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FREEZER_REMOVE_EXTRA_FILES = False

athena = Flask(__name__)
athena.config.from_object(__name__)
pages = FlatPages(athena)
freezer = Freezer(athena)
athena.jinja_env.comment_start_string = "{##}"
FlatPagesPandoc("markdown+raw_tex+yaml_metadata_block",
                athena,
                pre_render=True)


def make_external(url):
    return urljoin(request.url_root, url)


@athena.route("/feed.atom")
def recent_feed():
    feed = AtomFeed(config.config["title"],
                    feed_url=request.url_root,
                    url=request.url_root,
Exemplo n.º 51
0
# -*- coding: utf-8 -*-
import sys
import threading
import time

import main
from flask_frozen import Freezer

freezer = Freezer(main.app)


class ProgressBarLoading(threading.Thread):
    def run(self):
        global stop
        global kill
        msg = ("\tL a  c o p i a  c o m p a r t e  c u l t u r a!")

        print("[!] Generando la biblioteca")
        sys.stdout.flush()
        i = 0
        while stop is not True:
            msg_ = msg[:i] + msg[i].upper() + msg[i + 1:]

            sys.stdout.write('%s' % msg_)
            sys.stdout.write("\b" * len(msg))
            sys.stdout.flush()
            time.sleep(0.07)
            i += 1
            # Para mantenernos siempre dentro del largo del string
            i = i % len(msg)
            msg_ = ""
"""
Generates static HTML by walking over all URLs.
"""

from flask_frozen import Freezer
from app import application
import os

# set WD to this folder
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

application.config["FREEZER_DESTINATION_IGNORE"] = [
    "source/", ".vscode/", ".git", ".gitignore", "README.md"]

application.config["FREEZER_DESTINATION"] = "./../.."

freezer = Freezer(application)

if __name__ == '__main__':
    freezer.freeze()
Exemplo n.º 53
0
        return send_from_directory('static', 'embeddings_' + emb + '_2.json')
    except FileNotFoundError:
        return ""


@app.route('/schedule.json')
def schedule_json():
    return jsonify(site_data["schedule"])


@app.route('/static/<path:path>')
def send_static(path):
    return send_from_directory('static', path)

# Code to turn it all static
freezer = Freezer(app, with_no_argument_rules=False, log_url_for=False)


@freezer.register_generator
def your_generator_here():
    yield "livestream", {}
    yield "home", {}
    yield "papers", {}
    yield "schedule", {}
    yield "socials", {}
    yield "sponsors", {}
    yield "workshops", {}
    yield "paperVis", {}
    yield "papers", {}
    yield "paper_json", {}
    yield "index", {}
Exemplo n.º 54
0
def freeze():
    """Create a static version of the LimbaHub HTML pages."""

    freezer = Freezer(app)
    freezer.freeze()
Exemplo n.º 55
0
 def test_without_app(self):
     freezer = Freezer()
     self.assertRaises(Exception, freezer.freeze)
Exemplo n.º 56
0
from flask_frozen import Freezer
from pools import app

blue_snek = Freezer(app)

if __name__ == '__main__':
    blue_snek.freeze()
Exemplo n.º 57
0
# -*- coding: utf-8 -*-

from flask import Flask
from flask_frozen import Freezer

app = Flask(__name__)
app.config.from_pyfile('settings.py')
freezer = Freezer(app)
Exemplo n.º 58
0
competitions = [
    c for c in competitions
    if c["deadtime"] > datetime.date.today().strftime("%Y-%m-%d")
]
competitions.sort(key=lambda x: x["deadtime"])

# Find CVPR competitions
# CVPR_comps = [comp for comp in competitions if 'CVPR' in  [ 'CVPR' for l in comp['hostby'] if 'CVPR' in [ 'CVPR' for key in l.keys() if 'CVPR' in key ] ]  ]

app = Flask(__name__)

app.config["FREEZER_DESTINATION"] = "docs"
# https://stackoverflow.com/questions/11577147/how-to-fix-page-404-on-github-page
app.config["FREEZER_DESTINATION_IGNORE"] = [".git*", "CNAME", "favicon.ico"]

freezer = Freezer(app)

id_type_checkboxs = [
    {
        "id": "PF-checkbox",
        "name": "Platform"
    }
    # ,{'id': 'IT-checkbox', 'name': 'Industry'}
    ,
    {
        "id": "AC-checkbox",
        "name": "Academia"
    },
]

id_type2_checkboxs = [
Exemplo n.º 59
0
Arquivo: wsgi.py Projeto: elcr/muhblog
 def freeze() -> None:
     freezer = Freezer(app)
     app.logger.info('Freezing to "%s"', app.config['OUTPUT_DIRECTORY'])
     freezer.freeze()
Exemplo n.º 60
0
from flask_frozen import Freezer
from simplertimes import create_app

if __name__ == '__main__':

    import warnings
    from flask_frozen import MissingURLGeneratorWarning, MimetypeMismatchWarning
    # This supress warnings of this kind:
    # MissingURLGeneratorWarning: Nothing frozen for endpoints admin. Did you forget a URL generator?
    warnings.simplefilter('ignore', MissingURLGeneratorWarning)

    # This supress warnings of this kind:
    # MimetypeMismatchWarning: Filename extension of 'admin' (type application/octet-stream) does not match Content-Type: text/html; charset=utf-8
    warnings.simplefilter('ignore', MimetypeMismatchWarning)

    freezer = Freezer(create_app())
    freezer.freeze()