import click from flask import render_template_string, current_app from flask.cli import AppGroup SERIALIZER_TEMPLATE = """ flask_serializer import Serializer class {{ model }}Serializer(Serializer): def __init__(self, obj): self.id = obj.id """[1:] # strips initial newline create_cli = AppGroup('create', help="Create various components from templates.") @create_cli.command('serializer') @click.argument('name') def create_serializer(name): """Create serializer for model of the given name. Usage: flask create serializer notification If name starts with a capital it is used as is. If it doesn't title case is used. """ if name[0].isupper(): model_name = name
import click import os import time from flask.cli import AppGroup from flask import current_app from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from XNBackend.models import SwitchPanel systemd = AppGroup('systemd') ENGINE = create_engine( 'mysql+pymysql://xn:[email protected]:3306/xn?charset=utf8mb4') Session = sessionmaker(bind=ENGINE) session = Session() @systemd.command() @click.option('--code', type=click.Choice( ['start', 'stop', 'restart', 'enable', 'status', 'disable']), required=True, help='start or stop celery worker') def control(code): Panels = session.query(SwitchPanel) ip_list = [] for p in Panels: if p.tcp_config and p.tcp_config.ip not in ip_list: ip_list.append(p.tcp_config.ip) os.system('sudo systemctl {} [email protected]'.format(code))
from flask.cli import AppGroup from app.models import db, List, Task, Comment seed_commands = AppGroup('seed') @seed_commands.command('all') def seed(): #Generate Lists programming_list = List(name='Programming') chores_list = List(name='Chores') misc_list = List(name='Misc') db.session.add(programming_list) db.session.add(chores_list) db.session.add(misc_list) db.session.commit() #Generate Tasks task_info = [{ 'name': 'hack the mainframe', 'description': '1) Watch Hackers; 2) Pwn the world', 'org_list': 'programming', 'comments': ['I need to listen to some Prodigy first', 'lulz'] }, { 'name': 'figure out how to invert binary tree', 'description': "don't ask me how to invert a binary tree", 'org_list': 'programming', 'comments': ['seriously, I dont know yet'] }, { 'name': 'finish this coding project',
import click import os from flask.cli import AppGroup from flask_migrate.cli import migrate, upgrade from sqlalchemy import inspect from sqlalchemy.exc import IntegrityError, InvalidRequestError from app import app, db poll_cli = AppGroup('poll') def _get_table_states(results): """ :param results: A dictionary mapping poll names to Result models :return: A dictionary mapping poll names to a boolean value that indicates whether the database table for the corresponding Result model has been created """ table_states = {} for k, r in results.items(): i = inspect(r) table_states[k] = all([db.engine.has_table(t.name) for t in i.tables]) return table_states @poll_cli.command('import') @click.argument('json_file_path', type=click.Path(exists=True, dir_okay=False)) @click.argument('name', type=click.STRING, required=False)
import click from flask.cli import AppGroup, pass_script_info # XXX: Do not import any other indico modules here! # If any import from this module triggers an exception the dev server # will die while an exception only happening during app creation will # be handled gracefully. from indico.cli.util import IndicoFlaskGroup, LazyGroup __all__ = ('cli_command', 'cli_group') # We never use the group but expose cli_command and cli_group for # plugins to have access to the flask-enhanced command and group # decorators that use the app context by default _cli = AppGroup() cli_command = _cli.command cli_group = _cli.group del _cli def _get_indico_version(ctx, param, value): if not value or ctx.resilient_parsing: return import indico message = f'Indico v{indico.__version__}' click.echo(message, ctx.color) ctx.exit() @click.group(cls=IndicoFlaskGroup)
from getpass import getpass import click from flask.cli import AppGroup from models.user import User from database import commit_to_db from authz import Roles users_cli = AppGroup("users") @users_cli.command("create") def create(): """ Run: 'flask users create $name' Create a normal user, skip email confirmation. """ _create_user(Roles.user) @users_cli.command("create_superadmin") def create_superadmin(): """ Run: 'flask users create_superadmin' Create a superadmin user, skip email confirmation. """ _create_user(Roles.superadmin) def _create_user(role): """ Run: 'flask users create_superadmin'
from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_marshmallow import Marshmallow from auth1.config import Config # Import application config db = SQLAlchemy() mg = Migrate() ma = Marshmallow() apiv1_bp = Blueprint("apiv1", __name__, url_prefix="/api/v1") # Create /api/v1 endpoint apiv1 = Api(apiv1_bp)#Create API for /api/v1 endpoint app_cli = AppGroup("app", help="Application related commands.") from auth1 import command from auth1 import resource def create_app(): app = Flask(__name__) # Create application instance #app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/auth1' app.config.from_object(Config) # Set application configuration test!!!!!! db.init_app(app) mg.init_app(app, db)#inputs:reads config from app and connets to db ma.init_app(app) app.register_blueprint(apiv1_bp) #register /api/v1 to application app.cli.add_command(app_cli) return app # Return application instance to caller
import click from flask.cli import AppGroup from variance.extensions import db from variance.models.equipment import EquipmentModel equipment_cli = AppGroup("equipment") equipment_mod_cli = AppGroup("mod") equipment_cli.add_command(equipment_mod_cli) @equipment_cli.command("get") @click.argument("name") def cli_equipment_get(name): u = EquipmentModel.query.filter_by(name=name).first() if u is None: click.echo("No equipment with that name found!") return -1 click.echo("Equipment ID: %u" % u.id) @equipment_cli.command("list") def cli_equipment_list(): e_list = EquipmentModel.query.all() if e_list is None: click.echo("Equipment list is empty!") return -1 for a in e_list: click.echo("%u : %s - %s" % (a.id, a.name, a.description))
create_device_stats, create_receiver_stats, create_relation_stats, create_country_stats, update_qualities, update_receivers as update_receivers_command, update_devices as update_devices_command, update_device_stats_jumps, ) from app.collect.ognrange import update_entries as update_receiver_coverages from app.model import Device from app import db user_cli = AppGroup("stats") user_cli.help = "Handling of statistical data." @user_cli.command("create") @click.argument("start") @click.argument("end") def create(start, end): """Create DeviceStats, ReceiverStats and RelationStats.""" days = get_database_days(start, end) pbar = tqdm(days) for single_date in pbar: pbar.set_description(datetime.strftime(single_date, "%Y-%m-%d")) result = create_device_stats(session=db.session, date=single_date)
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from flask.cli import AppGroup from globomap_api import config as app_config from globomap_api import exceptions from globomap_api.models.constructor import Constructor from globomap_api.wsgi import application meta_cli = AppGroup('meta') @meta_cli.command('create') def create_meta_collections(): """Creates meta collections.""" constructor = Constructor() try: constructor.factory(kind='Collection', create=True, name=app_config.META_COLLECTION, create_indexes=False) except exceptions.CollectionAlreadyExist: pass try:
current app status is used! """ @app.context_processor def utility_processor(): return { 'app_version': __version__, 'app_copyright': '2019-2020 by {}'.format(__author__), 'activity': activity, 'app_name': 'Rayqueue' } # here are the definitions for the CLI extensions user_cli = AppGroup('app') """ """ @user_cli.command('check') @click.argument('action') def check_app(action): print(action) app.cli.add_command(check_app) # some specials for the gunicorn logger used in production #if __name__ != '__main__':
from click import argument from flask.cli import AppGroup from redash import models manager = AppGroup(help="Organization management commands.") @manager.command() @argument("domains") def set_google_apps_domains(domains): """ Sets the allowable domains to the comma separated list DOMAINS. """ organization = models.Organization.query.first() k = models.Organization.SETTING_GOOGLE_APPS_DOMAINS organization.settings[k] = domains.split(",") models.db.session.add(organization) models.db.session.commit() print( "Updated list of allowed domains to: {}".format( organization.google_apps_domains ) ) @manager.command() def show_google_apps_domains(): organization = models.Organization.query.first() print( "Current list of Google Apps domains: {}".format(
import click from flask.cli import AppGroup from flask_security import hash_password from .extensions import user_datastore from .models import db stoplist_cli = AppGroup('stoplist') @stoplist_cli.command('createsuperuser') @click.argument('login') @click.password_option() def create_superuser(login: str, password: str): admin_role = user_datastore.find_or_create_role('admin') user = user_datastore.create_user( login=login, password=hash_password(password), active=True, roles=[admin_role] ) db.session.add(user) db.session.commit() click.echo("Superuser {} successfully created.".format(login)) @stoplist_cli.command('generateroles') def generate_roles(): roles = [ user_datastore.find_or_create_role(name=name, description=description) for name, description in (('admin', 'Administrateur'), ('staff', 'Employé')) ] for role in roles: db.session.add(role)
from flask.cli import AppGroup from .hawk_api_request import hawk_api_request as hawk_api_request_command cmd_group = AppGroup('generic', help='Generic commands') cmd_group.add_command(hawk_api_request_command)
import time from click import argument, option from flask.cli import AppGroup from flask_migrate import stamp import sqlalchemy from sqlalchemy.exc import DatabaseError from sqlalchemy.sql import select from sqlalchemy_utils.types.encrypted.encrypted_type import FernetEngine from redash import settings from redash.models.base import Column from redash.models.types import EncryptedConfiguration from redash.utils.configuration import ConfigurationContainer manager = AppGroup(help="Manage the database (create/drop tables. reencrypt data.).") def _wait_for_db_connection(db): retried = False while not retried: try: db.engine.execute("SELECT 1;") return except DatabaseError: time.sleep(30) retried = True def is_db_empty():
from pathlib import Path import click from flask.cli import AppGroup from variance.extensions import db from variance.models.unit import UnitModel from variance.schemas.unit import UnitSchema from variance.models.muscle import MuscleModel from variance.schemas.muscle import MuscleSchema from variance.models.nutrition import NutrientInfoModel, ConsumableModel, RecipeModel from variance.schemas.nutrition import NutrientInfoSchema, ConsumableSchema, RecipeSchema export_cli = AppGroup("export") @export_cli.command("all") def cli_export_list(): click.echo("Not implemented yet.") return @export_cli.command("units") def cli_export_list(): u_list = UnitModel.query.all() if u_list is None: click.echo("Unit list is empty!") return -1 export_dir = Path("exported")
def get_db(): if 'db' not in g: connection = TinyMongoClient(current_app.config['DATABASE']) g.db = connection.spellvardetection return g.db def close_db(e=None): db = g.pop('db', None) ### CLI for database management db_cli = AppGroup( 'db', short_help='Administrate the database used by SpellvarDetection.') @db_cli.command('clear') def clear_db_command(): """Clear the existing data.""" try: shutil.rmtree(current_app.config['DATABASE']) except OSError: pass click.echo('Database cleared.') @db_cli.command('add-dictionary')
from datetime import datetime import subprocess import click from flask import current_app from flask.cli import AppGroup from sqlalchemy import create_engine TIME_FORMAT = "%y%m%d%H%M" # -------------------------------------------------------------------------- -- # backup legacy commands: restore (+ backup == to be implemented and tested) backup_cmds = AppGroup("backup", help="Manage database-specific backups") @backup_cmds.command("restore", help="Restore a MySQL backup file.") @click.option("--file", help="name of the MySQL backup file") def restore_mysql_command(file): """ Restore MySQL backups.""" try: current_app.echo("Restoring legacy database ...", v=1) restore_mysql_database(filename=file) current_app.echo("Finished", v=1) except Exception as exx: current_app.echo(f"Failed to restore MySQL backup: {exx!r}") sys.exit(1)
import click from flask import Flask from flask.cli import AppGroup from depobs.website.do import create_app from depobs.worker import tasks app = create_app() npm_cli = AppGroup("npm") @npm_cli.command("scan") @click.argument("package_name", envvar="PACKAGE_NAME") @click.argument("package_version", envvar="PACKAGE_VERSION") def scan_npm_package(package_name: str, package_version: str) -> None: """ Help! """ tasks.scan_npm_package_then_build_report_tree(package_name, package_version) @npm_cli.command("advisories") @click.argument("package_name", envvar="PACKAGE_NAME") def get_package_advisories(package_name: str) -> None: """ Get GitHub Advisories for a specific package """ tasks.get_github_advisories(package_name)
#!/usr/bin/env ipython import click from flask import Flask from flask.cli import AppGroup from flask_app import app from server import utils dns_cli = AppGroup("dns", help="Add/Delete subdomains in the config") def abort_if_false(ctx, param, value): if not value: ctx.abort() @dns_cli.command("add") @click.argument("subdomain") @click.option( "--secret", default=None, help="API secret for the subdomain. If non given it will be generated", ) @click.option("--length", default=25, help="Length of the secret to generate (default:25)") def create_dns_entry(subdomain, secret, length): """Add a new subdomain to the config """ print(f"[!] Adding {subdomain} as subdomain") if secret is None:
import click from flask import current_app as app from flask.cli import AppGroup from flask.cli import with_appcontext from depc.extensions.encrypted_dict import FlaskEncryptedDict key_cli = AppGroup("key", help="Manage database key.") @key_cli.command("generate") def generate_key(): """Generate a 256-bit hex key to encrypt database.""" click.echo(FlaskEncryptedDict.generate_key()) @key_cli.command("change") @with_appcontext @click.option("--old-key", default=None, required=True, type=str) @click.option("--new-key", default=None, required=True, type=str) def change_key(old_key, new_key): """Change the 256-bit hex key to encrypt database.""" if old_key is None: old_key = app.config.get("DB_ENCRYPTION_KEY") FlaskEncryptedDict.change_key(old_key, new_key) click.echo("Database key has been changed") click.echo("Add this key to depc.{env}.yml as DB_ENCRYPTION_KEY") click.echo(new_key)
import click from flask.cli import AppGroup from dbfread import DBF from app import create_app, db, cli dbf_cli = AppGroup('dbf') app = create_app() @dbf_cli.command('read') @click.argument('table') def read_table(table): print(table.upper()) dbf = DBF('../penjualan/DATA92016B/' + table.lower()) for r in dbf: print(r) app.cli.add_command(dbf_cli)
import traceback import os import time import socket import click from flask.cli import AppGroup from shadow import app from .models import JobType cli = AppGroup('schedule') logger = logging.getLogger(__name__) @cli.command('start-schedule') def schedule(): logger.info('schedule process is starting...') logger.info('pid:%s', os.getpid()) from .dispatcher import preprocess, dispatch, result funcs = [preprocess, dispatch, result] for func in funcs: th = threading.Thread(target=func)
import typing import click import os from colocalization.model_db import ColocalizationDB from flask.cli import AppGroup, with_appcontext data_cli = AppGroup('data') @data_cli.command("init") @with_appcontext def init() -> None: db_url = os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:////tmp/tmp.db') colocalization_db = ColocalizationDB(db_url=db_url) colocalization_db.create_schema() @data_cli.command("harness") @with_appcontext def harness() -> None: import pdb pdb.set_trace() @data_cli.command("load") @click.argument("path") @with_appcontext def cli_load(path: str) -> None: db_url = os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:////tmp/tmp.db') colocalization_db = ColocalizationDB(db_url=db_url) colocalization_db.load_data(path)
import click from flask import current_app from flask.cli import AppGroup, with_appcontext from . import generate as _generate from . import clean as _clean from . import export as _export hexo_cli = AppGroup("hexo") @hexo_cli.command("g") @with_appcontext def generate(): """export all posts into database""" _generate() @hexo_cli.command("c") @with_appcontext def clean(): """Clean all posts in database""" _clean() @hexo_cli.command('e') @with_appcontext def export(): """Export all posts to dir""" _export()
import click from flask.cli import AppGroup from app.models import Sub, SubSubscriber recount = AppGroup('recount', help="Re-count various internal counters") @recount.command(help="Rebuilds all sub's subscriber counters") @click.option( '--save/--dry-run', default=True, help= 'Use --save (the default) to fix the counts, or --dry-run to just print them.' ) def subscribers(save): """Update subscriber counts for all the subs.""" if save: print('Name Before After') else: print('Name Current Correct') subs = Sub.select(Sub.sid, Sub.name, Sub.subscribers).order_by(Sub.name) for sub in subs: count = SubSubscriber.select().where( (SubSubscriber.sid == sub.sid) & (SubSubscriber.status == 1)).count() print(f'{sub.name:32}{sub.subscribers:7}{count:8}') if save: Sub.update(subscribers=SubSubscriber.select().where( (SubSubscriber.sid == sub.sid) & (SubSubscriber.status == 1)).count()).where(
from flask.cli import AppGroup import click from app.blueprints.auth.models.role_model import RoleModel from app.blueprints.employee.models.employee_model import EmployeeModel from app.blueprints.service.models.service_model import ServiceModel from app.extensions.db_ext import db db_cli = AppGroup('database_cmd', help="Database related tasks") @db_cli.command() def init_db(): """Init db""" db.create_all() return None @db_cli.command() def drop_db(): """Drop db""" db.drop_all() return None @db_cli.command() def seed_admin(): """Seed db with admin""" role = RoleModel.find_by_identity("admin")
from sys import exit from sqlalchemy.orm.exc import NoResultFound from flask.cli import AppGroup from click import argument, option from redash import models manager = AppGroup(help="Groups management commands.") @manager.command() @argument("name") @option( "--org", "organization", default="default", help="The organization the user belongs to (leave blank for " "'default').", ) @option( "--permissions", default=None, help="Comma separated list of permissions ('create_dashboard'," " 'create_query', 'edit_dashboard', 'edit_query', " "'view_query', 'view_source', 'execute_query', 'list_users'," " 'schedule_query', 'list_dashboards', 'list_alerts'," " 'list_data_sources') (leave blank for default).", ) def create(name, permissions=None, organization="default"): print("Creating group (%s)..." % (name))
from flask.cli import AppGroup cli_command = AppGroup('cli', help='Command Line Interface') from . import SampleCommand, CreateUserCommand
import click from flask.cli import AppGroup from app.utils.csv import get_coi_csv cmd_group = AppGroup('csv', help='Commands to generate csv') @cmd_group.command('generate_coi_csv') @click.option( '--output-filename', type=str, help=f"CSV file name", default='coi_data.csv', ) @click.option( '--limit', type=int, help=f"Row limit", default=None, ) def generate_coi_csv(output_filename, limit): with open(output_filename, 'w') as f: get_coi_csv(f, limit=limit) click.echo(f'\n{output_filename} generated')