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)
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)
def serve(context, config, host, port, debug, livereload): """Start the web server.""" pymongo_config = dict( MONGO_HOST=context.obj['host'], MONGO_PORT=context.obj['port'], MONGO_DBNAME=context.obj['mongodb'], MONGO_USERNAME=context.obj['username'], MONGO_PASSWORD=context.obj['password'], ) valid_connection = check_connection( host=pymongo_config['MONGO_HOST'], port=pymongo_config['MONGO_PORT'], username=pymongo_config['MONGO_USERNAME'], password=pymongo_config['MONGO_PASSWORD'], authdb=context.obj['authdb'], ) log.info("Test if mongod is running") if not valid_connection: log.warning("Connection could not be established") log.info("Is mongod running?") context.abort() config = os.path.abspath(config) if config else None app = create_app(config=pymongo_config, config_file=config) if livereload: server = Server(app.wsgi_app) server.serve(host=host, port=port, debug=debug) else: app.run(host=host, port=port, debug=debug)
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, )
def serve(): from livereload import Server watcher = FileWatcher() watcher.watch('web') watcher.watch('templates') server = Server(app, watcher) server.serve(port=8000)
def serve(): from livereload import Server from livereload.watcher import Watcher watcher = Watcher() watcher.watch('site') watcher.watch('templates') server = Server(app, watcher) server.serve(port=8000)
def serve(): from livereload import Server from livereload.watcher import Watcher watcher = Watcher() watcher.watch('site', ignore=lambda p: p.endswith('.babel')) watcher.watch('templates') server = Server(app, watcher) server.serve(port=8000)
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
def watch(name): build(name) def _build(): build(name) server = Server() server.watch(name, _build) server.serve(root='_build')
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))
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")
def serve(config): """ Start the devserver, and rebuild the docs whenever any changes take effect. """ # Create a temporary build directory, and set some options to serve it tempdir = tempfile.mkdtemp() config['site_dir'] = tempdir def builder(): build(config, live_server=True) # Perform the initial build builder() server = Server() # Watch the documentation files, the config file and the theme files. server.watch(config['docs_dir'], builder) server.watch(config['config'].name) for d in config['theme_dir']: server.watch(d, builder) host, port = config['dev_addr'].split(':', 1) server.serve(root=tempdir, host=host, port=int(port), restart_delay=0)
def watch(): server = Server() server.watch('templates/**/*', scan_files) server.watch('raml/*', scan_files) server.watch('examples/*.json', scan_files) server.serve()
def run(): server = Server(app.wsgi_app) server.watch('app/*.py') server.watch('app/templates/*.html') server.watch('app/static/css/*.css') server.watch('app/static/js/*.js') server.serve(host='0.0.0.0')
def live(): """Run livereload server""" from livereload import Server server = Server(app) map(server.watch, glob2.glob("application/pages/**/*.*")) # pages map(server.watch, glob2.glob("application/macros/**/*.html")) # macros map(server.watch, glob2.glob("application/static/**/*.*")) # public assets server.serve(port=PORT)
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()
def main(): server = Server() server.watch('assets/scripts', shell('make assets')) server.watch('assets/images', shell('make assets')) server.watch('assets/styles', shell('make styles')) server.watch('src', shell('make html')) server.serve(root='build/', port=8080)
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])
def run(): app.host = '0.0.0.0' app.port = PORT app.debug = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Jackson/work/web/myblog/database/test.db' db.init_app(app) db.create_all() from livereload import Server server = Server(app) server.serve(port=PORT)
def run_livereload(self): app = create_app(root_path=self.folder, config_file=self.config_file) configure_views(app, self.file_renderer) server = Server(app) for glob_pattern in self.manager.globs_to_watch(): server.watch('assets/%s' % glob_pattern, self.manager.build_environment) server.watch('templates/*', self.manager.build_environment) server.watch('templates/**/*', self.manager.build_environment) server.serve(host="0.0.0.0")
def serve(): server = Server() load_data() server.watch('*.scss', css()) server.watch('*.js', js()) server.watch('*.html', render()) server.serve(root='dist/', port=PORT, debug=False)
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
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) )
def develop_watch(options): server = Server() reloader = shell('pkill -HUP gunicorn') def js_bundle_changed(): copy_js_bundle(options) server.watch('/mnt/src/front_demo/dist/main.js', js_bundle_changed) server.watch('/mnt/src/clang_ast_webservice/*.py', reloader) server.watch('/mnt/src/clang_ast_webservice/assets/*', reloader) server.serve() sys.exit(1)
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])
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)
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)
def _livereload(host, port, config, builder, site_dir): from livereload import Server server = Server() # Watch the documentation files, the config file and the theme files. server.watch(config['docs_dir'], builder) server.watch(config['config_file_path'], builder) for d in config['theme_dir']: server.watch(d, builder) server.serve(root=site_dir, host=host, port=int(port), restart_delay=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)
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)
parser = argparse.ArgumentParser() parser.add_argument('--only-data-id', type=int) args = parser.parse_args() cmd = ["python3", "build.py", "--use-cache"] if args.only_data_id: cmd.append("--only-data-id %s" % args.only_data_id) def rebuild_all(): print(subprocess.call(cmd)) cmd_md = cmd.copy() cmd_md += ["--only-markdown-pages"] def rebuild_md(): print(subprocess.call(cmd_md)) cmd_lists = cmd.copy() cmd_lists += ["--only-list-pages"] def rebuild_lists(): print(subprocess.call(cmd_lists)) server = Server() server.watch('templates/data.mustache', rebuild_all) server.watch('templates/list.mustache', rebuild_lists) server.watch('templates/_*.mustache', rebuild_lists) server.watch('templates/markdown_page.mustache', rebuild_md) server.watch('markdown_pages/*.md', rebuild_md) server.watch('*.py', rebuild_all) server.serve(root=BUILD_PATH)
def build_docs(self, path=None, fmt='html', outdir=None, auto_open=True, serve=True, http=None, archive=False, upload=False): try: which.which('jsdoc') except which.WhichError: return die('jsdoc not found - please install from npm.') self._activate_virtualenv() self.virtualenv_manager.install_pip_requirements(os.path.join( here, 'requirements.txt'), quiet=True) import moztreedocs import webbrowser from livereload import Server outdir = outdir or os.path.join(self.topobjdir, 'docs') format_outdir = os.path.join(outdir, fmt) path = path or os.path.join(self.topsrcdir, 'tools') path = os.path.normpath(os.path.abspath(path)) docdir = self._find_doc_dir(path) if not docdir: return die('failed to generate documentation:\n' '%s: could not find docs at this location' % path) props = self._project_properties(docdir) savedir = os.path.join(format_outdir, props['project']) run_sphinx = partial(self._run_sphinx, docdir, savedir, fmt) result = run_sphinx() if result != 0: return die('failed to generate documentation:\n' '%s: sphinx return code %d' % (path, result)) else: print('\nGenerated documentation:\n%s' % savedir) if archive: archive_path = os.path.join(outdir, '%s.tar.gz' % props['project']) moztreedocs.create_tarball(archive_path, savedir) print('Archived to %s' % archive_path) if upload: self._s3_upload(savedir, props['project'], props['version']) if not serve: index_path = os.path.join(savedir, 'index.html') if auto_open and os.path.isfile(index_path): webbrowser.open(index_path) return # Create livereload server. Any files modified in the specified docdir # will cause a re-build and refresh of the browser (if open). try: host, port = http.split(':', 1) port = int(port) except ValueError: return die('invalid address: %s' % http) server = Server() server.watch(docdir, run_sphinx) server.serve(host=host, port=port, root=savedir, open_url_delay=0.1 if auto_open else None)
from livereload import Server, shell server = Server() server.watch('assets/*', shell('npm run build')) server.watch('docs/*', shell('make docs')) server.watch('sphinx_typlog_theme/*', shell('make docs')) server.watch('sphinx_typlog_theme/static/*', shell('make docs')) server.serve(root='docs/_build/html', port=5234)
from typing import Callable from os import path from livereload import Server, shell def prefix_matcher(str: str) -> Callable[[str], bool]: return lambda target: target.startswith(str) if __name__ == '__main__': server = Server() cmd = shell('pipenv run doc') dir = path.dirname(path.abspath(__file__)) server.watch(dir, cmd, ignore=prefix_matcher(path.join(dir, '_build'))) server.watch('structural_calculator', cmd) server.serve(root=path.join(dir, '_build', 'html'))
def build_docs( command_context, path=None, fmt="html", outdir=None, auto_open=True, serve=True, http=None, archive=False, upload=False, jobs=None, write_url=None, verbose=None, ): # TODO: Bug 1704891 - move the ESLint setup tools to a shared place. sys.path.append( mozpath.join(command_context.topsrcdir, "tools", "lint", "eslint")) import setup_helper setup_helper.set_project_root(command_context.topsrcdir) if not setup_helper.check_node_executables_valid(): return 1 setup_helper.eslint_maybe_setup() # Set the path so that Sphinx can find jsdoc, unfortunately there isn't # a way to pass this to Sphinx itself at the moment. os.environ["PATH"] = ( mozpath.join(command_context.topsrcdir, "node_modules", ".bin") + os.pathsep + _node_path() + os.pathsep + os.environ["PATH"]) command_context.activate_virtualenv() command_context.virtualenv_manager.install_pip_requirements( os.path.join(here, "requirements.txt")) import webbrowser from livereload import Server from moztreedocs.package import create_tarball unique_id = "%s/%s" % (project(), str(uuid.uuid1())) outdir = outdir or os.path.join(command_context.topobjdir, "docs") savedir = os.path.join(outdir, fmt) path = path or command_context.topsrcdir path = os.path.normpath(os.path.abspath(path)) docdir = _find_doc_dir(path) if not docdir: print(_dump_sphinx_backtrace()) return die("failed to generate documentation:\n" "%s: could not find docs at this location" % path) result = _run_sphinx(docdir, savedir, fmt=fmt, jobs=jobs, verbose=verbose) if result != 0: print(_dump_sphinx_backtrace()) return die("failed to generate documentation:\n" "%s: sphinx return code %d" % (path, result)) else: print("\nGenerated documentation:\n%s" % savedir) # Upload the artifact containing the link to S3 # This would be used by code-review to post the link to Phabricator if write_url is not None: unique_link = BASE_LINK + unique_id + "/index.html" with open(write_url, "w") as fp: fp.write(unique_link) fp.flush() print("Generated " + write_url) if archive: archive_path = os.path.join(outdir, "%s.tar.gz" % project()) create_tarball(archive_path, savedir) print("Archived to %s" % archive_path) if upload: _s3_upload(savedir, project(), unique_id, version()) if not serve: index_path = os.path.join(savedir, "index.html") if auto_open and os.path.isfile(index_path): webbrowser.open(index_path) return # Create livereload server. Any files modified in the specified docdir # will cause a re-build and refresh of the browser (if open). try: host, port = http.split(":", 1) port = int(port) except ValueError: return die("invalid address: %s" % http) server = Server() sphinx_trees = manager().trees or {savedir: docdir} for _, src in sphinx_trees.items(): run_sphinx = partial(_run_sphinx, src, savedir, fmt=fmt, jobs=jobs, verbose=verbose) server.watch(src, run_sphinx) server.serve( host=host, port=port, root=savedir, open_url_delay=0.1 if auto_open else None, )
from app import app from dynaconf import settings from livereload import Server server = Server(app.wsgi_app) server.serve(debug=settings.DEBUG, port=settings.PORT)
""" import os from livereload import Server, shell rebuild_cmd = shell('make html', cwd='.') watch_dirs = [ '.', 'architecture', 'examples', 'examples/nnss_incremental_update', 'quickstarts', 'release_notes', 'webservices', ] watch_globs = ['*.rst', '*.ipynb'] 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('../python/smqtk'): 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='_build/html')
from datax_website import app from livereload import Server if __name__ == '__main__': server = Server(app.wsgi_app) server.serve()
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)) 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 host and port server.serve(host=CONFIG['host'], port=CONFIG['port'], root=CONFIG['deploy_path'])
action="store_true") parser.add_argument("--test", help="Run the test suite", action="store_true") args = parser.parse_args() # initialize new database if needed if args.initdb: from app_server.database.db_utils import init_engine from config import DevelopmentConfig init_engine(DevelopmentConfig.SQLALCHEMY_DATABASE_URI, clear_db=True) # dev mode: watch file and autoreload if args.dev: from config import DevelopmentConfig app = create_app(config=DevelopmentConfig) # watch files and autoreload using livereload from livereload import Server server = Server(app.wsgi_app) static_dir = Path.cwd() / 'app_frontend' / 'dist' server.watch((static_dir / 'index.html').as_posix()) server.watch((static_dir / 'js' / 'bundle.js').as_posix()) server.watch((static_dir / 'styles' / 'main.css').as_posix()) server.serve(port=args.port, host=args.host) elif args.test: import pytest """Runs the unit tests without test coverage.""" pytest.main(["-s", "tests"])
def dev(): app.config.debug = True live_server = Server(app.wsgi_app) # 监控文件变化参数是目录e.g:监控static文件夹 static/*.* live_server.watch("**/*.*") # 监控整个项目 live_server.serve(open_url=True)
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "igor_personal_site.settings") from django.core.management import execute_from_command_line if 'livereload' in sys.argv: from django.core.wsgi import get_wsgi_application from livereload import Server application = get_wsgi_application() server = Server(application) # Add your watch # server.watch('path/to/file', 'your command') server.serve('8000') else: execute_from_command_line(sys.argv)
from livereload import Server, shell from livereload.watcher import Watcher server = Server(watcher=Watcher(provide_filename=True)) def printfilename(filename): print(filename) server.watch('*.less', printfilename) server.serve(open_url_delay=1)
#!/usr/bin/env python from livereload import Server, shell server = Server() server.watch('*.js') server.serve(port=8000)
with open(os.path.join(folder, f'index{page_number}.html'), 'w', encoding="utf8") as file: file.write(rendered_page) def on_reload(): env = Env() env.read_env() folder = env('FOLDER', default='pages') books_per_page = env.int('BOOKS_PER_PAGE', default=10) books_per_col = int(books_per_page / 2) env = Environment(loader=FileSystemLoader('.'), autoescape=select_autoescape(['html', 'xml'])) template = env.get_template('template.html') pages_count, chunked_books = get_books('books.json', books_per_page) os.makedirs(folder, exist_ok=True) for page_number, books_on_page in enumerate(chunked_books, 1): first_col_books, second_col_books = more_itertools.chunked( books_on_page, math.ceil(len(books_on_page) / 2)) render_page(template, pages_count, page_number, first_col_books, second_col_books, folder) if __name__ == '__main__': on_reload() server = Server() server.watch('template.html', on_reload) server.serve(root='.', default_filename='pages/index.html')
jinja2_env=env, topics_list=topics_list, article=article, content=html_content, ) save_page(SITE_FOLDER, article['link'], article_page) def create_topics_list(config_dict): topics_list = config_dict['topics'] for topic in topics_list: topic['articles'] = [] for article in config_dict['articles']: if article['topic'] == topic['slug']: topic['articles'].append(article) for article in topic['articles']: article['link'] = create_link(article['source']) topic_folder = os.path.split(topic['articles'][0]['link'])[0] topic['link'] = os.path.join( topic_folder, '{}.html'.format(topic_folder), ) return topics_list if __name__ == '__main__': make_site() server = Server() server.watch('templates/*.html', make_site) server.serve(root='www/')
def live(): """Run livereload server""" from livereload import Server server = Server(app) # html for filepath in glob2.glob("application/templates/**/*.html"): server.watch(filepath) # css for filepath in glob2.glob("application/static/css/**/*.css"): server.watch(filepath) # js for filepath in glob2.glob("application/static/js/**/*.js"): server.watch(filepath) # image for filepath in glob2.glob("application/static/image/**/*.*"): server.watch(filepath) server.serve(port=PORT)
#from skimage.io import imread import matplotlib.pyplot as plt car_image = plt.imread(filename) from PIL import Image #car_image = Image.open(filename) car_image=Image.fromarray(car_image) car_image.save("static/car.png") car_image.save("car.png") import requests regions = ['fr', 'it'] with open('car.png', 'rb') as fp: response = requests.post( 'https://api.platerecognizer.com/v1/plate-reader/', data=dict(regions=regions), # Optional files=dict(upload=fp), headers={'Authorization': 'Token 2ec5878b06ca1be24f61f34142443cc5baa3194c'}) #print(response.json()) #print(response.json()['results'][0]['plate']) #plate_num=Detect(file) plate_num=response.json()['results'][0]['plate'] plate_num=plate_num.upper() #print(plate_num) return render_template('result.html', plate = plate_num) if __name__=='__main__': server = Server(app.wsgi_app) server.serve() server.watch('/Views/*') #app.config['TEMPLATES_AUTO_RELOAD'] = True app.run(debug=True)
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') 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') for item in self.site.config['GALLERY_FOLDERS']: server.watch(item, 'nikola build') for item in self.site.config['LISTINGS_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=port, host=None, root=out_folder, debug=True, open_url=browser)
def dev(): from livereload import Server live_server = Server(app.wsgi_app) live_server.watch("**/*.*") live_server.serve(open_url=True)
#!/usr/bin/env python from livereload import Server, shell server = Server() server.watch('docs/source/*.rst', shell('make html', cwd='docs')) server.serve(root='docs/build/html/')
def docs_serve(): server = Server() server.watch('docs/*.rst', shell('make html', cwd='docs')) server.serve(root='docs/_build/html', open_url=True)
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)) 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"])
#!/usr/bin/env python import os import sys from website.app import init_app if __name__ == "__main__": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings') from django.core.management import execute_from_command_line init_app(set_backends=True, routes=False, attach_request_handlers=False) if 'livereload' in sys.argv: from django.core.wsgi import get_wsgi_application from livereload import Server import django.conf as conf conf.settings.STATIC_URL = '/static/' application = get_wsgi_application() server = Server(application) server.watch('api/') server.serve(port=8000) else: execute_from_command_line(sys.argv)
def dev(): from livereload import Server live_server = Server(app.wsgi_app) live_server.watch('**/*.*') # 监测整个项目所有文件变化。可以加参数,不加就整个项目重加载,加的话就执行方法里的内容。 live_server.serve(open_url=True)
def _execute(self, options, args): """Start the watcher.""" try: from livereload import Server except ImportError: req_missing(['livereload'], 'use the "auto" command') return arguments = ['build'] if self.site.configuration_filename != 'conf.py': arguments = ['--conf=' + self.site.configuration_filename ] + arguments command_line = 'nikola ' + ' '.join(arguments) # Run an initial build so we are up-to-date subprocess.call(["nikola"] + arguments) port = options and options.get('port') server = Server() server.watch(self.site.configuration_filename, command_line) server.watch('themes/', command_line) server.watch('templates/', command_line) for item in self.site.config['post_pages']: server.watch(os.path.dirname(item[0]), command_line) for item in self.site.config['FILES_FOLDERS']: server.watch(item, command_line) for item in self.site.config['GALLERY_FOLDERS']: server.watch(item, command_line) for item in self.site.config['LISTINGS_FOLDERS']: server.watch(item, command_line) out_folder = self.site.config['OUTPUT_FOLDER'] if options and options.get('browser'): browser = True else: browser = False server.serve(port=port, host=None, root=out_folder, debug=True, open_url=browser)
""" Use livereload to serve, build, and reload the website when files change. Obtained from https://github.com/leouieda/cv """ from livereload import Server server = Server() files = [ "**/**.md", "_site.yml", "images/", "css/", "script.js", "_layouts/", "_python/", ] for filename in files: server.watch(filename, "urubu build") server.serve(root="_build", port="8008", host="localhost", open_url_delay=1)
import argparse import os import sys from livereload import Server def create_parser(): parser = argparse.ArgumentParser() parser.add_argument('-sd', '--site_dirpath', type=check_site_dirpath, required=True, help='path to root of the site directory') return parser def check_site_dirpath(dirpath): if not os.path.exists(dirpath): raise argparse.ArgumentTypeError("{} does not exists".format(dirpath)) return dirpath if __name__ == '__main__': parser = create_parser() namespace = parser.parse_args(sys.argv[1:]) server = Server() server.serve(root=namespace.site_dirpath)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['DEBUG'] = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['EXPLAIN_TEMPLATE_LOADING'] = True # db setup db = SQLAlchemy(app) db.init_app(app) @app.route('/') def default_index(): return render_template('home.html') # Blueprints setup app.register_blueprint(base64, url_prefix='/base64') # API setup api = Api(app) api.add_resource(Base64Controller, '/api/base64') api.add_resource(ExecuteRecipeController, '/api/lights/recipe') api.add_resource(ModeController, '/api/lights/mode') if __name__ == '__main__': server = Server(app.wsgi_app) server.serve(host='0.0.0.0', port=5000) app.run(debug=True, host='0.0.0.0', port=5000)
def live(): server = Server() server.watch('en', shell('paver build_html', cwd='.')) server.serve(root='_build/html', open_url=True)