Example #1
0
def server(ctx, host=None, port=5000, debug=True, live=False, gitlogs=False):
    """Run the app server."""
    if gitlogs:
        git_logs(ctx)
    from website.app import init_app

    os.environ["DJANGO_SETTINGS_MODULE"] = "api.base.settings"
    app = init_app(set_backends=True, routes=True)
    settings.API_SERVER_PORT = port

    if live:
        from livereload import Server

        server = Server(app.wsgi_app)
        server.watch(os.path.join(HERE, "website", "static", "public"))
        server.serve(port=port)
    else:
        if settings.SECURE_MODE:
            context = (settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)
        else:
            context = None
        app.run(
            host=host,
            port=port,
            debug=debug,
            threaded=debug,
            extra_files=[settings.ASSET_HASH_PATH],
            ssl_context=context,
        )
Example #2
0
    def do(self, *args):
        """Run Django with ImportD."""
        for bp in self.blueprint_list:
            self._apply_blueprint(bp)

        if not args:
            args = sys.argv[1:]

        if len(args) == 0:
            return self._handle_management_command(
                self._get_runserver_cmd(), "8000")

        if 'livereload' in sys.argv:
            if not hasattr(self, "lr"):
                print("Livereload setting, lr not configured.")
                return
            from livereload import Server
            server = Server(self)
            for pat, cmd in self.lr.items():
                parts = pat.split(",")
                for part in parts:
                    server.watch(part, cmd)
            server.serve(port=8000)
            return

        return self._act_as_manage(*args)
Example #3
0
def main():
    parser = get_parser()
    args = parser.parse_args()

    srcdir = os.path.realpath(args.sourcedir)
    outdir = os.path.realpath(args.outdir)

    build_args = []
    for arg, meta in SPHINX_BUILD_OPTIONS:
        val = getattr(args, arg)
        if not val:
            continue
        opt = '-{}'.format(arg)
        if meta is None:
            build_args.extend([opt] * val)
        else:
            for v in val:
                build_args.extend([opt, v])

    build_args.extend([srcdir, outdir])
    build_args.extend(args.filenames)

    ignored = []
    if args.w:  # Logfile
        ignored.append(os.path.realpath(args.w[0]))
    if args.d:  # Doctrees
        ignored.append(os.path.realpath(args.d[0]))

    if not os.path.exists(outdir):
        os.makedirs(outdir)

    server = Server(watcher=LivereloadWatchdogWatcher())
    server.watch(srcdir, SphinxBuilder(outdir, build_args, ignored))
    server.watch(outdir)
    server.serve(port=args.port, root=outdir)
Example #4
0
    def _execute(self, options, args):
        """Start the watcher."""
        try:
            from livereload import Server
        except ImportError:
            req_missing(['livereload>=2.0.0'], 'use the "auto" command')
            return

        # Run an initial build so we are uptodate
        subprocess.call(("nikola", "build"))

        port = options and options.get('port')

        server = Server()
        server.watch('conf.py')
        server.watch('themes/')
        server.watch('templates/')
        server.watch(self.site.config['GALLERY_PATH'])
        for item in self.site.config['post_pages']:
            server.watch(os.path.dirname(item[0]))
        for item in self.site.config['FILES_FOLDERS']:
            server.watch(os.path.dirname(item))

        out_folder = self.site.config['OUTPUT_FOLDER']
        if options and options.get('browser'):
            webbrowser.open('http://localhost:{0}'.format(port))

        server.serve(port, None, out_folder)
Example #5
0
 def handle_noargs(self, **options):
     server = Server()
     pathlist = []
     # Find statics/templates directories of all installed apps
     for app in settings.INSTALLED_APPS:
         try:
             mod = import_module(app)
         except ImportError as e:
             raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
         staticfiles_dir = os.path.join(os.path.dirname(mod.__file__),
                                        'statics')
         templates_dir = os.path.join(os.path.dirname(mod.__file__),
                                      'templates')
         if os.path.isdir(staticfiles_dir):
             pathlist.append("{}".format(staticfiles_dir))
         if os.path.isdir(templates_dir):
             pathlist.append("{}".format(templates_dir))
     # STATICFILES_DIRS, TEMPLATE_DIRS
     for path in settings.STATICFILES_DIRS:
         pathlist.append("{}".format(path))
     for path in settings.TEMPLATE_DIRS:
         pathlist.append("{}".format(path))
     print('Start livereloading with followings...')
     for path in pathlist:
         print('- {}'.format(path))
         server.watch(path)
     # Listen 35729 which is a common port for LiveReload browser ext.
     server.serve(port=35729)
Example #6
0
File: auto.py Project: rghv/nikola
    def _execute(self, options, args):
        """Start the watcher."""
        try:
            from livereload import Server
        except ImportError:
            req_missing(["livereload==2.1.0"], 'use the "auto" command')
            return

        # Run an initial build so we are up-to-date
        subprocess.call(("nikola", "build"))

        port = options and options.get("port")

        server = Server()
        server.watch("conf.py", "nikola build")
        server.watch("themes/", "nikola build")
        server.watch("templates/", "nikola build")
        server.watch(self.site.config["GALLERY_PATH"], "nikola build")
        for item in self.site.config["post_pages"]:
            server.watch(os.path.dirname(item[0]), "nikola build")
        for item in self.site.config["FILES_FOLDERS"]:
            server.watch(item, "nikola build")

        out_folder = self.site.config["OUTPUT_FOLDER"]
        if options and options.get("browser"):
            webbrowser.open("http://localhost:{0}".format(port))

        server.serve(port, None, out_folder)
Example #7
0
    def _execute(self, options, args):
        """Start the watcher."""
        try:
            from livereload import Server
        except ImportError:
            req_missing(['livereload'], 'use the "auto" command')
            return

        # Run an initial build so we are up-to-date
        subprocess.call(("nikola", "build"))

        port = options and options.get('port')

        server = Server()
        server.watch('conf.py', 'nikola build')
        server.watch('themes/', 'nikola build')
        server.watch('templates/', 'nikola build')
        server.watch(self.site.config['GALLERY_PATH'], 'nikola build')
        for item in self.site.config['post_pages']:
            server.watch(os.path.dirname(item[0]), 'nikola build')
        for item in self.site.config['FILES_FOLDERS']:
            server.watch(item, 'nikola build')

        out_folder = self.site.config['OUTPUT_FOLDER']
        if options and options.get('browser'):
            browser = True
        else:
            browser = False

            server.serve(port, None, out_folder, True, browser)
Example #8
0
 def start_livereload(self):
     from livereload import Server
     server = Server()
     for path in settings.STATICFILES_DIRS:
         server.watch(path)
     for path in settings.TEMPLATE_DIRS:
         server.watch(path)
     server.serve(port=settings.LIVERELOAD_PORT)
Example #9
0
def main(filenames, port, host, settings, debug, profile, profile_dir,
         profile_restriction):
    """Start fava for FILENAMES on http://host:port."""

    if profile_dir:
        profile = True
    if profile:
        debug = True

    env_filename = os.environ.get('BEANCOUNT_FILE', None)
    if env_filename:
        filenames = filenames + (env_filename,)

    if not filenames:
        raise click.UsageError('No file specified')

    app.config['BEANCOUNT_FILES'] = filenames
    app.config['USER_SETTINGS'] = settings

    load_settings()
    load_file()

    if debug:
        if profile:
            from werkzeug.contrib.profiler import ProfilerMiddleware
            app.config['PROFILE'] = True
            app.wsgi_app = ProfilerMiddleware(
                app.wsgi_app,
                restrictions=(profile_restriction,),
                profile_dir=profile_dir if profile_dir else None)

        app.run(host, port, debug)
    else:
        server = Server(app.wsgi_app)
        if settings:
            server.watch(settings, load_settings)

        def reload_source_files(api):
            filename = api.options['filename']
            api.load_file()
            include_path = os.path.dirname(filename)
            for filename in api.options['include'] + \
                    api.options['documents']:
                server.watch(os.path.join(include_path, filename),
                             lambda: reload_source_files(api))

        for api in app.config['APIS'].values():
            reload_source_files(api)

        try:
            server.serve(port=port, host=host, debug=debug)
        except OSError as error:
            if error.errno == errno.EADDRINUSE:
                print("Error: Can not start webserver because the port/address"
                      "is already in use.")
                print("Please choose another port with the '-p' option.")
            else:
                raise
Example #10
0
def livereload():
    from livereload import Server
    server = Server(app)

    # watch all js files else we'll only reload when app.js changes
    paths = pathlib.Path('bauble/static/').glob('**/*.js')
    for f in filter(lambda p: 'vendor' not in p, map(str, paths)):
        server.watch(f)
    server.serve(port=app.config.get('PORT', 5000))
Example #11
0
def watch(name):
    build(name)

    def _build():
        build(name)

    server = Server()
    server.watch(name, _build)
    server.serve(root='_build')
Example #12
0
def serve_docs():
    from livereload import Server, shell

    build_command = "sphinx-build -b html docs dist/docs"
    run(build_command)

    server = Server()
    server.watch("*.rst", shell(build_command))
    server.watch("docs/", shell(build_command))
    server.serve(root="dist/docs")
Example #13
0
def keep_alive(app, build_func):
    """Run the server and keep it reload and rebuild when contents changed
    :return:
    """
    live_server = Server(app.wsgi_app)

    # [live_server.watch(path.join(app.path, p), build_func) for p in
    # ['pages', 'static', 'templates', '_assets.yml', '_config.yml']]

    live_server.watch(app.path)
    live_server.serve()
Example #14
0
def main():

    build_project_path = '_build'
    if not os.path.exists(build_project_path):
        os.system('make html')

    server = Server()
    server.watch('./*.rst', shell('make html'))
    server.watch('./*/*.rst', shell('make html'))
    webbrowser.open_new_tab('http://127.0.0.1:5500')
    server.serve(root='_build/html')
Example #15
0
def server(host=None, port=5000, debug=True, live=False):
    """Run the app server."""
    from website.app import init_app
    app = init_app(set_backends=True, routes=True, mfr=True)

    if live:
        from livereload import Server
        server = Server(app.wsgi_app)
        server.watch(os.path.join(HERE, 'website', 'static', 'public'))
        server.serve(port=port)
    else:
        app.run(host=host, port=port, debug=debug, extra_files=[settings.ASSET_HASH_PATH])
Example #16
0
def livereload():
    url = 'http://dev:35729/livereload.js'
    print (
        'To livereload your web pages add the following script tag to '
        'your HTML:'
    )
    print ''
    print '    <script type="text/javascript" src="{}"></script>'.format(url)
    print ''
    server = Server()
    server.watch(env.static_dir)
    server.watch(env.templates_dir)
    server.serve(port=35729, host='0.0.0.0')
Example #17
0
def run_livereload(config):
    "Run app in foreground. don't use for production"
    app = make_app(config=config)

    server = Server(app)

    # The command to build a site's resources will probably be different.  The
    # `.livereload` file triggers a livereload if it is modified.
    server.watch('.livereload')

    server.serve(
            host=app.config.get("HOST", '127.0.0.1'),
            port=app.config.get("PORT", 5000)
            )
Example #18
0
def develop(ctx: click.core.Context, site_path: str, host: str,
            port: int) -> None:
    """Runs a local development server"""
    def rebuild_site() -> mackerel.site.Site:
        site = mackerel.site.Site(path=Path(site_path))
        build = mackerel.build.Build(site=site)
        build.execute()
        return site

    site = rebuild_site()
    server = Server()
    server.watch(str(site.content_path), rebuild_site)
    server.watch(str(site.template_path), rebuild_site)
    server.serve(host=host.strip(), port=port, root=str(site.output_path))
Example #19
0
File: cli.py Project: cgrinds/fava
def main(filename, port, host, settings, debug, profile, profile_dir,
         profile_restriction):
    """Start fava for FILENAME on http://host:port."""

    if profile_dir:
        profile = True
    if profile:
        debug = True

    app.config['BEANCOUNT_FILE'] = filename
    app.config['USER_SETTINGS'] = settings

    load_settings()

    if debug:
        load_file()
        if profile:
            from werkzeug.contrib.profiler import ProfilerMiddleware
            app.config['PROFILE'] = True
            app.wsgi_app = ProfilerMiddleware(
                app.wsgi_app,
                restrictions=(profile_restriction,),
                profile_dir=profile_dir if profile_dir else None)

        app.run(host, port, debug)
    else:
        server = Server(app.wsgi_app)
        if settings:
            server.watch(settings, load_settings)

        def reload_source_files():
            load_file()
            include_path = os.path.dirname(app.config['BEANCOUNT_FILE'])
            for filename in api.options['include'] + api.options['documents']:
                server.watch(os.path.join(include_path, filename),
                             reload_source_files)
        reload_source_files()

        try:
            server.serve(port=port, host=host, debug=debug)
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                print("Error: Can not start webserver because the port/address"
                      "is already in use.")
                print("Please choose another port with the '-p' option.")
            else:
                raise
        except:
            print("Unexpected error:", e)
            raise
Example #20
0
    def run(self):
        mimetypes.init()

        self.reload()

        try:
            from livereload import Server
        except ImportError:
            print("Please install the python3 livereload module to use this function.", file=sys.stderr)
            return
        server = Server(self.application)
        server.watch(self.content_root, self.reload)
        server.watch(self.theme_root, self.reload)
        server.serve(port=8000, host="localhost")
Example #21
0
def livereload():
    db.create_all()
    server = Server(app)
    server.watch("gather/*.py")
    server.watch("gather/templates/*.html")
    server.watch("gather/assets/stylesheets/*.sass")
    server.watch("gather/assets/javascripts/*.coffee")
    server.serve(port=8000)
Example #22
0
def server(host=None, port=5000, debug=True, live=False, gitlogs=False):
    """Run the app server."""
    if gitlogs:
        git_logs()
    from website.app import init_app
    os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings'
    app = init_app(set_backends=True, routes=True)
    settings.API_SERVER_PORT = port

    if live:
        from livereload import Server
        server = Server(app.wsgi_app)
        server.watch(os.path.join(HERE, 'website', 'static', 'public'))
        server.serve(port=port)
    else:
        app.run(host=host, port=port, debug=debug, threaded=debug, extra_files=[settings.ASSET_HASH_PATH])
Example #23
0
def serve():
    """Serve site at http://localhost:8000/"""
    rebuild()
    server = Server()
    server.watch('content/*/*.md', build_html)
    server.watch('theme/templates/*.html', build_html)
    server.watch('theme/scss/*.scss', build_css)
    server.watch('theme/scss/base/*.scss', build_css)
    server.serve(root='output', port=8000, host='localhost', open_url_delay=0.1)
Example #24
0
File: serve.py Project: lrvick/rant
class Server(object):
    """Generate web-ready static files from templates/data/config"""

    def __init__(self, source_dir='.', dest_dir='./deploy'):
        self._source_dir = source_dir
        self._dest_dir = dest_dir
        self._server = LRServer()
        self._port = 8080

    def serve(self):
        builder = Builder(self._source_dir, self._dest_dir)
        self._server.watch('*/*.md', builder.build, delay=2)
        self._server.serve(
            root=self._dest_dir,
            port=self._port
        )
        logging.info('Starting server on port: %s' % self._port)
Example #25
0
def start(host, port):
    app = Flask(
        __name__,
        static_folder='/static'
    )

    app.config['DEBUG'] = True

    @app.route('/')
    def index():
        template_name = request.args.get('template')
        vars_file = request.args.get('vars')
        make_pdf = request.args.get('pdf')

        if template_name is None:
            return usage

        if vars_file is not None:
            with open(os.path.join('template-vars', vars_file), 'r') as f:
                template_vars = json.load(f)
        else:
            template_vars = {}

        for folder in jinja_config['template_folders']:
            copy_tree(folder, '/static', update=1)
        env = create_environment(jinja_config)
        template = env.get_template(template_name)
        rendered = template.render(**template_vars).encode('utf-8')
        if make_pdf:
            print('MAKING PDF!')
            with open('/static/pdf_tmp.html', 'wb') as pdf:
                pdf.write(rendered)
            Popen(render_pdf_cmd, shell=True).wait()
        return rendered

    server = Server(app.wsgi_app)
    watched_files = formic.FileSet(include='**/*',
                                   exclude=['templates/**/*.css',
                                            'templates/pdf_tmp.html',
                                            '**/*.pdf'])
    for file_name in watched_files:
        server.watch(file_name, shell(
            'node-sass-chokidar scss -o templates'
        ))
    server.serve(host=host, port=port, liveport=35729)
Example #26
0
def run(argv):
    parser = argparse.ArgumentParser(description=__doc__,
                formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('-p', '--port',
                        action='store',
                        type=int,
                        default=5000,
                        help="Port to listen on.")

    parser.add_argument('-H', '--host',
                        action='store',
                        type=str,
                        default='localhost',
                        help="Host for the webserver.")

    parser.add_argument('-d', '--debug',
                        action='store_true',
                        help="Turn on debugging. This uses the built-in Flask \
                              webserver, and live-reloading of beancount-files is disabled.")

    parser.add_argument('filename',
                        type=str,
                        help="Beancount input file.")

    args = parser.parse_args(argv)

    app.beancount_file = args.filename
    app.filter_year = None
    app.filter_tag = None

    app.api = BeancountReportAPI(app.beancount_file)

    if args.debug:
        app.run(args.host, args.port, args.debug)
    else:
        server = Server(app.wsgi_app)

        # auto-reload the main beancount-file and all it's includes
        server.watch(app.beancount_file, app.api.load_file)
        include_path = os.path.dirname(app.beancount_file)
        for filename in app.api.options()['include']:
            server.watch(os.path.join(include_path, filename), app.api.load_file)

        server.serve(port=args.port, host=args.host, debug=args.debug)
Example #27
0
    def run(self):
        mimetypes.init()

        self.reload()

        try:
            from livereload import Server
        except ImportError:
            print("Please install the python3 livereload module to use this function.", file=sys.stderr)
            return
        server = Server(self.application)

        # see https://github.com/lepture/python-livereload/issues/171
        def do_reload():
            self.reload()
        server.watch(self.content_root, do_reload)
        server.watch(self.theme_root, do_reload)
        server.serve(port=8000, host="localhost")
def cmd(tool_opts, open_browser, tool, source):
    with tempdir() as dirpath:
        server = Server()
        source_abspath = os.path.abspath(source)
        command_instance = get_command(tool, source_abspath, dirpath,
                                       tool_opts)
        command_str = str(command_instance)
        sh = shell(command_str, cwd=dirpath)
        sh()
        server.watch(source, sh)

        image_filepath = command_instance.destination
        image_filename = os.path.basename(image_filepath)

        page = render(image_filename)
        deploy(dirpath, page)

        server.serve(root=dirpath, open_url_delay=open_browser)
Example #29
0
def testserver(livereload, port):
    from flask_app.app import create_app

    os.environ['CONFIG_DIRECTORY'] = from_project_root("conf.d")

    extra_files=[
        from_project_root("flask_app", "app.yml")
    ]

    app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy'})
    if livereload:
        from livereload import Server
        s = Server(app)
        for filename in extra_files:
            s.watch(filename)
        s.watch('flask_app')
        s.serve(port=port, liveport=35729)
    else:
        app.run(port=port, extra_files=extra_files)
Example #30
0
def make_livereload_server(wsgi_app):
    server = Server(wsgi_app)

    # XXX: build step could be useful, e.g.
    # making it `python app.py build`, but
    # in this use case not really necessary
    build_cmd = "true"

    print "Files being monitored:"

    cwd = getcwd()

    for pattern in WATCH_PATTERNS:
        print "Pattern: ", pattern
        for filepath in FileSet(include=pattern):
            print "=>", path.relpath(filepath, cwd)
            server.watch(filepath, build_cmd)
        print

    return server

def remove_redundant_files(actual_files, directory, extension='html'):
    files_in_directory = glob.glob(f'{directory}/*.{extension}')
    for file in files_in_directory:
        if file not in actual_files:
            os.remove(file)


if __name__ == '__main__':
    os.makedirs(HTML_PAGES_DIRNAME, exist_ok=True)

    env = Environment(loader=FileSystemLoader(TEMPLATE_DIRNAME),
                      autoescape=select_autoescape(['html']))

    args = get_parsed_arguments()
    result_filepath = args.json_path or os.path.join(args.dest_dir,
                                                     'downloaded_books.json')

    render_pages_from_template = partial(render_pages_from_template,
                                         result_filepath, TEMPLATE_FILENAME)

    render_pages_from_template()

    template_filepath = os.path.join(TEMPLATE_DIRNAME, TEMPLATE_FILENAME)

    server = Server()
    server.watch(template_filepath, render_pages_from_template)
    server.watch(result_filepath, render_pages_from_template)
    server.serve(root='.')
Example #32
0
def dev():
    live_server = Server(app.wsgi_app)
    live_server.watch('**/*.*')
Example #33
0
from livereload import Server, shell
from pathlib import Path
import sys

doc_dir = Path(__file__).parent
root_dir = doc_dir.parent
server = Server()


def get_paths(*exts):
    for tp in exts:
        # top level
        yield root_dir / f"**.{tp}"
        # nested
        yield root_dir / f"**/*.{tp}"


if "no" not in sys.argv:
    exts = ("rst", "py", "jinja2", "md")
    cmd = shell("make html", cwd=str(doc_dir))
    for path in get_paths(*exts):
        print(f"watching {path}")
        server.watch(str(path), cmd)

server.serve(root=str(doc_dir / "_build" / "html"))
Example #34
0
            os.remove(filename)


def render_pages():
    book_on_page = 10

    with open("books.json", "r") as books_file:
        books_json = books_file.read()
    books = json.loads(books_json)
    books_by_pages = list(chunked(books, book_on_page))

    count_of_pages = len(books_by_pages)
    paths_of_pages = []

    for page_number, books_on_current_page in enumerate(books_by_pages, 1):
        page_path = render_page(page_number, count_of_pages, books_on_current_page)
        paths_of_pages.append(page_path)

    template = env.get_template('main_page_template.html')
    rendered_page = template.render(page_count = count_of_pages)
    with open('index.html', 'w', encoding="utf8") as file:
        file.write(rendered_page)
    delete_old_pages(paths_of_pages)


if __name__ =='__main__':
    render_pages()
    server = Server()
    server.watch('page_template.html', render_pages)
    server.serve(root='.')
Example #35
0
#!/usr/bin/env python

# This starts a web server on http://localhost:5500/ where doc files are automatically recompiled.
#
# If you need to create the docs from scratch, run:
# cd docs
# make html
#

from livereload import Server, shell
server = Server()
server.watch('docs/*.rst', shell('make html  --always-make', cwd='docs'))
server.watch('docs/_static/*.css', shell('make html  --always-make',
                                         cwd='docs'))
print('PORT IS 5500')
server.serve(root='docs/_build/html')
Example #36
0
livereload_: https://pypi.python.org/pypi/livereload
"""
import os

from livereload import Server, shell

rebuild_cmd = shell("make html", cwd=".")
rebuild_root = "_build/html"

watch_dirs = [
    ".",
    "release_notes",
]

watch_globs = ["*.rst", "*.ipynb"]

watch_source_dir = "../xaitk_saliency"

server = Server()
server.watch("conf.py", rebuild_cmd)
# Cover above configured watch dirs and globs matrix.
for d in watch_dirs:
    for g in watch_globs:
        server.watch(os.path.join(d, g), rebuild_cmd)
# Watch source python files.
for dirpath, dirnames, filenames in os.walk(watch_source_dir):
    server.watch(os.path.join(dirpath, "*.py"), rebuild_cmd)
# Optionally change to host="0.0.0.0" to make available outside localhost.
server.serve(root=rebuild_root)
Example #37
0
#!/usr/bin/env python
from livereload import Server, shell

server = Server()
server.watch("source/", shell("make html"))
server.watch("../piccolo_api", shell("make html"))
server.serve(root="build/html")
Example #38
0
#!/usr/bin/env python

from livereload import Server, shell

server = Server()
server.watch('*.rst', shell('make html'))
server.serve(root='_build/html', open_url=True)
Example #39
0
        return render_template('upload.html')
    f = request.files['file']
#    basepath = path.abspath(path.dirname(__file__))
#    uploadpath = path.join(basepath, 'static\upload', secure_filename(f.filename))
    uploadpath = path.join('E:\python\upload', f.filename)
    f.save(uploadpath )
    return render_template('upload.html')


@app.route('/about')
def about():
    return 'Hello about!'


@app.route('/context')
def context():
    return 'Hello context!'


#自定义测试函数
@app.template_test('current_url')
def is_current_url(link):
    return link['href'] == url_for('context')
#    return link['href'] == request.url


if __name__ == '__main__':
    lvrld = Server(app.wsgi_app)
    lvrld.watch('**/*.html')
    lvrld.serve(open_url=True)
Example #40
0
#!/usr/bin/env python

import sys

from livereload import Server, shell

if len(sys.argv) > 1:
    md = sys.argv[1]
    html = f"../docs/slides/{md.replace('.md', '.html')}"
else:
    exit(0)

PANDOC_CMD = f'''pandoc
  --from markdown+smart+footnotes+fenced_code_blocks+fenced_code_attributes
  --to revealjs --output={html}
  --variable revealjs-url=/y19-vis/lib/reveal.js
  --css=/y19-vis/lib/reveal.css
  --slide-level=2 --standalone --mathjax
  {md}'''

print(PANDOC_CMD)

server = Server()
server.watch(md, shell(PANDOC_CMD, html))
server.serve()
Example #41
0
#!/usr/bin/env python

from livereload import Server, shell
server = Server()
server.watch('./', shell('make html'))
server.serve(root='docs/_build/html')
Example #42
0
def dev():
    from livereload import Server
    live_server = Server(app.wsgi_app)
    live_server.watch('**/*.*')
    live_server.serve(open_url=True)
Example #43
0
nb_name = 'mathpsych-2018-slides'

exporter_standalone = nbconvert.SlidesExporter()
exporter_standalone.reveal_url_prefix = "https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.6.0"
exporter_standalone.reveal_transition = "none"

exporter_local = nbconvert.SlidesExporter()
exporter_local.reveal_url_prefix = "reveal.js/"
exporter_local.reveal_transition = "none"

writer = nbconvert.writers.FilesWriter()


def export_slides():
    print("regenerating {}".format(nb_name))
    slides, resources = exporter_local.from_filename(
        "{}.ipynb".format(nb_name))
    writer.write(slides, resources, notebook_name="{}.local".format(nb_name))
    slides_standalone, resources_standalone = exporter_standalone.from_filename(
        "{}.ipynb".format(nb_name))
    writer.write(slides_standalone,
                 resources_standalone,
                 notebook_name=nb_name)


export_slides()

server = Server()
server.watch('{}.ipynb'.format(nb_name), export_slides, delay=2)
server.serve()
Example #44
0
from bottle import template
from livereload import Server, shell

from hydrate.demo import state

# TODO Instead of forking and running Python, extract
#   stuff from transcrypt.__main__.main
transpile = '../env/bin/transcrypt -b -m -n demo.py'

bottle.debug(True)


@route('/')
def index():
    return template('hydrate/index', state=state)


@route('/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='hydrate')


if __name__ == '__main__':
    app = default_app()
    server = Server(app)
    server.watch('hydrate/demo.py', shell(transpile, cwd='hydrate'))
    server.watch('hydrate/__target__/*', delay=2)
    server.watch('hydrate/demo.css')
    server.watch('hydrate/index.tpl', ignore=False)
    server.serve(root='hydrate')
Example #45
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from livereload import Server, shell

server = Server()
server.watch('./posts/*.md', shell('nikola build'))
server.serve(port=8889, root='./output')
Example #46
0
        return pages_href[count - 1]
    else:
        return None


def get_next_page_link(count, pages_href):
    if count != len(pages_href) - 1:
        return pages_href[count + 1]
    else:
        return None


def remove_files():
    pages_folder = os.path.join(os.getcwd(), 'pages/*')
    files = glob.glob(pages_folder)
    for file in files:
        os.remove(file)


if __name__ == '__main__':
    os.makedirs('pages', exist_ok=True)
    with open('books_metadata.json', 'r') as file:
        books_metadata_json = json.load(file)

    BOOKS_METADATA = quote_url(books_metadata_json)
    
    render_website_pages()
    server = Server()
    server.watch('template.html', render_website_pages)
    server.serve(root='.')
Example #47
0

@app.route('/')
def index():
    return render_template('index.html',
                           title="<h1>Welcome</h1>",
                           body="## header2")


@app.template_filter('md')
def markdown_to_html(txt):
    from markdown import markdown
    return markdown(txt)


def read_md(filename):
    with open(filename) as md_file:
        content = reduce(lambda x, y: x + y, md_file.readlines())
    return content


@app.context_processor
def inject_methods():
    return dict(read_md=read_md)


if __name__ == '__main__':
    live_sever = Server(app.wsgi_app)
    live_sever.watch('**/*.*')
    live_sever.serve(open_url=True)
    #app.run(debug=True)  #debug 参数
Example #48
0

def cmd() -> None:
    subprocess.run(build_cmd, cwd=docsdir)


def docs(p: str) -> str:
    return path.join(docsdir, p)


# subprocess.run(['make', 'clean'], cwd=docsdir)
cmd()  # build once
server = Server()

# Wtach documets
server.watch(docs('/*.md'), cmd, delay=1)
server.watch(docs('/*.rst'), cmd, delay=1)
server.watch(docs('../*.rst'), cmd, delay=1)
server.watch(docs('*/*.rst'), cmd, delay=1)
server.watch(docs('*/*.md'), cmd, delay=1)
server.watch(docs('*/*/*.rst'), cmd, delay=1)
server.watch(docs('*/*/*.md'), cmd, delay=1)

# Watch template/style
server.watch(docs('_templates/'), cmd, delay=1)
server.watch(docs('_static/'), cmd, delay=1)

# Watch package
server.watch(docs('../wdom/*.py'), cmd, delay=1)
server.watch(docs('../wdom/*/*.py'), cmd, delay=1)
server.watch(docs('../wdom/*/*/*.py'), cmd, delay=1)
Example #49
0
def dev():
    from livereload import Server
    live_server = Server(app.wsgi_app)
    #监控文件变化参数是目录e.g:监控static文件夹  static/*.*
    live_server.watch("**/*.*")  #监控整个项目
    live_server.serve(open_url=True)
Example #50
0
    for book in books:
        current_book_path = book['book_path']
        book['book_path'] = quote(current_book_path)

    env = Environment(loader=FileSystemLoader('.'),
                      autoescape=select_autoescape(['html', 'xml']))
    template = env.get_template('template.html')

    chunked_books = chunked(books, books_per_page)
    for num, chunk_books in enumerate(chunked_books, start=1):

        rendered_page = template.render(total_pages=total_pages,
                                        current_page=num,
                                        books=chunked(chunk_books, 2))

        with open(f'pages/{num}.html', 'w', encoding="utf8") as file:
            file.write(rendered_page)
            exists_pages = exists_pages | {num}

    clean_pages_files(exists_pages)


if __name__ == '__main__':
    template_file = 'template.html'

    on_reload()
    server = Server()
    server.watch(template_file, on_reload)
    server.serve(root='.')
Example #51
0
@app.route('/context')
def context():
    return 'Hello context!'


#自定义测试函数
@app.template_test('current_url')
def is_current_url(link):
    return link['href'] == url_for('context')


#    return link['href'] == request.url


def readfile(file):
    with open(file) as f:
        text = reduce(lambda x, y: x + y, f.readlines())
    return text.decode('utf-8')


@app.context_processor
def cntxtp():
    return dict(readfile=readfile)


if __name__ == '__main__':
    lvrld = Server(app.wsgi_app)
    lvrld.watch('**/base.html')
    lvrld.serve(open_url=True)
    app.run(debug=True)
Example #52
0
#!/usr/bin/env python
"""
A script to launch a livereload server to watch and rebuild documentation
on some sources changes.

You need to have installed package with extra requirements ``dev`` to use it.

Once launched, server will be available on port 8002, like: ::

    http://localhost:8002/

Borrowed from: ::

    https://livereload.readthedocs.io/en/latest/#script-example-sphinx

"""
from livereload import Server, shell

server = Server()

# Watch root documents (not recursive)
server.watch('docs/*.rst', shell('make html', cwd='docs'))

# Serve the builded documentation
server.serve(
    root='docs/_build/html',
    port=8002,
    host="0.0.0.0",
)
Example #53
0
def dev():
    """reload when modification happened"""
    from livereload import Server
    live_server = Server(app.wsgi_app)
    live_server.watch('**/*.*')
    live_server.serve()
Example #54
0
"""
Use livereload to serve, build, and reload the website when files change.
"""
from livereload import Server, shell


server = Server()
files = ["**/**.md", "_site.yml", "images/", "css/", "js/", "_layouts/", "_python/"]
for filename in files:
    server.watch(filename, "urubu build")
server.serve(root="_build", port="8008", host="localhost", open_url_delay=1)
Example #55
0
def readme():
    """Live reload readme"""
    from livereload import Server, shell
    server = Server()
    server.watch("README.rst", lambda: run_task("readme_build"))
    server.serve(open_url_delay=1, root="build/readme")
Example #56
0
def livereload(c):
    """Automatically reload browser tab upon file modification."""
    from livereload import Server

    build(c)
    server = Server()
    # Watch the base settings file
    server.watch(CONFIG["settings_base"], lambda: build(c))
    # Watch content source files
    content_file_extensions = [".md", ".rst"]
    for extension in content_file_extensions:
        content_blob = "{0}/**/*{1}".format(SETTINGS["PATH"], extension)
        server.watch(content_blob, lambda: build(c))
    # Watch the theme's templates and static assets
    theme_path = SETTINGS["THEME"]
    server.watch("{}/templates/*.html".format(theme_path), lambda: build(c))
    server.watch("{}/templates/ea/*.html".format(theme_path), lambda: build(c))
    server.watch("{}/templates/ea/includes/*.html".format(theme_path),
                 lambda: build(c))
    static_file_extensions = [".css", ".js"]
    for extension in static_file_extensions:
        static_file = "{0}/static/**/*{1}".format(theme_path, extension)
        server.watch(static_file, lambda: build(c))
    # Serve output path on configured port
    server.serve(port=CONFIG["port"], root=CONFIG["deploy_path"])
Example #57
0
def watch_and_serve(args):
    server = Server()
    server.watch('template.html', lambda: build_page(args))
    server.watch(__file__, lambda: reload_script() and build_page(args))
    webbrowser.open('http://localhost:5500/page.html')
    server.serve(root=PARENT_DIR, port=5500)
Example #58
0
from livereload import Server
from app import app

if __name__ == '__main__':
    server = Server(app.wsgi_app)
    server.watch('../temp/index.css')
    server.watch('templates/*.html')
    server.serve()
Example #59
0
def main(filenames, port, host, settings, debug, profile, profile_dir,
         profile_restriction):
    """Start fava for FILENAMES on http://host:port."""

    if profile_dir:
        profile = True
    if profile:
        debug = True

    env_filename = os.environ.get('BEANCOUNT_FILE', None)
    if env_filename:
        filenames = filenames + (env_filename, )

    if not filenames:
        raise click.UsageError('No file specified')

    app.config['BEANCOUNT_FILES'] = filenames
    app.config['USER_SETTINGS'] = settings

    load_settings()
    load_file()

    if debug:
        if profile:
            from werkzeug.contrib.profiler import ProfilerMiddleware
            app.config['PROFILE'] = True
            app.wsgi_app = ProfilerMiddleware(
                app.wsgi_app,
                restrictions=(profile_restriction, ),
                profile_dir=profile_dir if profile_dir else None)

        app.run(host, port, debug)
    else:
        server = Server(app.wsgi_app)
        if settings:
            server.watch(settings, load_settings)

        def reload_source_files(api):
            filename = api.options['filename']
            api.load_file(filename)
            include_path = os.path.dirname(filename)
            for filename in api.options['include'] + \
                    api.options['documents']:
                server.watch(os.path.join(include_path, filename),
                             lambda: reload_source_files(api))

        for api in app.config['APIS'].values():
            reload_source_files(api)

        try:
            server.serve(port=port, host=host, debug=debug)
        except OSError as e:
            if e.errno == errno.EADDRINUSE:
                print("Error: Can not start webserver because the port/address"
                      "is already in use.")
                print("Please choose another port with the '-p' option.")
            else:
                raise
        except:
            print("Unexpected error:", e)
            raise
Example #60
0
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

    from django.core.management import execute_from_command_line
    from dj_static import Cling, MediaCling
    from local_settings import ENV

    if len(sys.argv) >= 2 and sys.argv[1] == 'livereload':

        import formic

        from django.core.wsgi import get_wsgi_application
        from livereload import Server

        application = get_wsgi_application()
        server = Server(Cling(application))

        # Add your watch
        for filepath in formic.FileSet(include=["**/*.html", "**/*.js"]):
            server.watch(filepath)

        server.serve(port=8000)
    else:
        execute_from_command_line(sys.argv)