datasette/datasette/cli.py

103 wiersze
3.1 KiB
Python
Czysty Zwykły widok Historia

import click
from click_default_group import DefaultGroup
import json
import os
import shutil
from subprocess import call
import sys
import tempfile
from .app import Datasette
from .utils import make_dockerfile
@click.group(cls=DefaultGroup, default='serve', default_if_no_args=True)
def cli():
"""
2017-11-10 18:38:35 +00:00
Datasette!
"""
@cli.command()
@click.argument('files', type=click.Path(exists=True), nargs=-1)
@click.option('--inspect-file', default='inspect-data.json')
def build(files, inspect_file):
app = Datasette(files)
open(inspect_file, 'w').write(json.dumps(app.inspect(), indent=2))
@cli.command()
@click.argument('files', type=click.Path(exists=True), nargs=-1)
@click.option(
'-n', '--name', default='datasette',
help='Application name to use when deploying to Now'
)
@click.option(
'-m', '--metadata', type=click.File(mode='r'),
help='Path to JSON file containing metadata to publish'
)
def publish(files, name, metadata):
if not shutil.which('now'):
click.secho(
' The publish command requires "now" to be installed and configured ',
bg='red',
fg='white',
bold=True,
err=True,
)
click.echo('Follow the instructions at https://zeit.co/now#whats-now', err=True)
sys.exit(1)
tmp = tempfile.TemporaryDirectory()
# We create a datasette folder in there to get a nicer now deploy name
datasette_dir = os.path.join(tmp.name, name)
os.mkdir(datasette_dir)
saved_cwd = os.getcwd()
file_paths = [
os.path.join(saved_cwd, name)
for name in files
]
file_names = [os.path.split(f)[-1] for f in files]
try:
dockerfile = make_dockerfile(file_names, metadata and 'metadata.json')
os.chdir(datasette_dir)
open('Dockerfile', 'w').write(dockerfile)
if metadata:
open('metadata.json', 'w').write(metadata.read())
for path, filename in zip(file_paths, file_names):
os.link(path, os.path.join(datasette_dir, filename))
call('now')
finally:
tmp.cleanup()
os.chdir(saved_cwd)
@cli.command()
@click.argument('files', type=click.Path(exists=True), nargs=-1)
@click.option('-h', '--host', default='0.0.0.0')
@click.option('-p', '--port', default=8001)
@click.option('--debug', is_flag=True)
@click.option('--reload', is_flag=True)
@click.option('--inspect-file')
@click.option('-m', '--metadata', type=click.File(mode='r'))
def serve(files, host, port, debug, reload, inspect_file, metadata):
"""Serve up specified database files with a web UI"""
if reload:
import hupper
2017-11-10 18:38:35 +00:00
hupper.start_reloader('datasette.cli.serve')
inspect_data = None
if inspect_file:
inspect_data = json.load(open(inspect_file))
metadata_data = None
if metadata:
metadata_data = json.loads(metadata.read())
click.echo('Serve! files={} on port {}'.format(files, port))
app = Datasette(
files,
cache_headers=not debug and not reload,
inspect_data=inspect_data,
metadata=metadata_data,
).app()
app.run(host=host, port=port, debug=debug)