def to_Option(option, typemap={"int": int, "float": float, "string": str}): kwargs = vars(option) # convert type strings to real types. type_ = kwargs["type"] kwargs["type"] = typemap.get(type_) or type_ # callback not supported by argparse, must use type|action instead. cb = kwargs.pop("callback", None) cb_args = kwargs.pop("callback_args", None) or () cb_kwargs = kwargs.pop("callback_kwargs", None) or {} # action specific conversions action = kwargs["action"] if action == "store_true": map(kwargs.pop, ("const", "type", "nargs", "metavar", "choices")) elif action == "store": kwargs.pop("nargs") if kwargs["default"] == ("NO", "DEFAULT"): kwargs["default"] = None if action == "callback": class _action_cls(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): return cb(*cb_args, **cb_kwargs) kwargs["action"] = _action_cls kwargs.setdefault("nargs", 0) args = kwargs.pop("_short_opts") + kwargs.pop("_long_opts") return script.Option(*args, **kwargs)
def get_options(self): options = super().get_options() # Add an additional option that allows for piping of input # to the shell. options += script.Option('--pipe', action="store_true", dest='pipe'), return options
class RunCherryPyCommand(script.Command): option_list = [ script.Option('--port', '-p', dest='port', type=int), ] def handle(self, app, port): import cherrypy.wsgiserver listen = ('127.0.0.1', port) wsgi_app = ReverseProxied(app.wsgi_app) server = cherrypy.wsgiserver.CherryPyWSGIServer(listen, wsgi_app) try: server.start() except KeyboardInterrupt: server.stop()
class Server(script.Server): name = 'run' option_list = script.Server.option_list + ( script.Option('--mode', '-m', dest='mode', action='store', required=False, default="werkzeug"), ) def __init__(self, *args, **kwargs): # Set all defaults to None as they will be defaulted in handle # when we have access to an application. kwargs.setdefault('port', None) kwargs.setdefault('host', None) kwargs.setdefault('use_debugger', None) kwargs.setdefault('use_reloader', None) kwargs.setdefault('threaded', None) kwargs.setdefault('processes', None) super(Server, self).__init__(*args, **kwargs) def __call__(self, app, **kwargs): # Collect default server configuration from the application config. config = app.config kwargs = {k: v for k, v in kwargs.items() if v is not None} kwargs.setdefault('host', config.get('SERVER_HOST', "127.0.0.1")) kwargs.setdefault('port', config.get('SERVER_PORT', 5000)) kwargs.setdefault('use_debugger', config.get('SERVER_DEBUG')) kwargs.setdefault('use_reloader', config.get('SERVER_RELOAD')) kwargs.setdefault('threaded', config.get('SERVER_THREADED')) kwargs.setdefault('processes', config.get('SERVER_PROCESSES', 1)) # Spin up the server. mode = kwargs.get("mode", "werkzeug") if mode == "werkzeug": processes = kwargs["processes"] run_simple(kwargs["host"], kwargs["port"], app, use_debugger=kwargs["use_debugger"], use_reloader=kwargs["use_reloader"], threaded=kwargs["threaded"], processes=(False if processes == 1 else processes))
class _AddAPIUser(script.Command): option_list = script.Option("username") def __init__(self, app): super(script.Command.__init__()) self.app = app def run(self, username): while True: password = getpass.getpass(prompt="Enter Password: "******"Confirm Password: "******"Passwords did not match. Please try again.") create_db() api_profile = models.APIProfile(username=username) api_profile.set_password(password) with app.app_context(): flask.g.db.session.add(api_profile) flask.g.db.session.commit() print("An API Profile was succesfully created for username, %s." % username)
class Populate(script.Command): """Populate the database with data given from a list of losses form zKB.""" option_list = ( script.Option('--file', '-f', dest='kill_file', required=True), script.Option('--users', '-u', dest='num_users', default=5, type=int), script.Option('--divisions', '-d', dest='num_divisions', default=3, type=int), ) def run(self, kill_file, num_users, num_divisions, **kwargs): # Set up users, divisions and permissions users = [] for user_num, authmethod in zip( range(num_users), cycle(flask.current_app.config['SRP_AUTH_METHODS'])): user_name = u'User {}'.format(user_num) user = auth.models.User.query.filter_by(name=user_name).first() if user is None: user = auth.models.User(user_name, authmethod.name) db.session.add(user) users.append(user) divisions = [] for division_num in range(num_divisions): division_name = u'Division {}'.format(division_num) division = auth.models.Division.query.filter_by( name=division_name).first() if division is None: division = auth.models.Division(division_name) db.session.add(division) divisions.append(division) db.session.add_all(divisions) for user in users: for division in divisions: perm = auth.models.Permission.query.filter_by( division=division, permission=auth.PermissionType.submit, entity=user).first() if perm is None: auth.models.Permission(division, auth.PermissionType.submit, user) db.session.commit() # load and start processing killmails with open(kill_file, 'r') as f: kills = json.load(f) for user, division, kill_info in zip(cycle(users), cycle(divisions), kills): victim = kill_info[u'victim'] # Skip corp-level kills (towers, pocos, etc) if victim['characterID'] == '0': continue # make sure a Pilot exists for this killmail pilot = auth.models.Pilot.query.get(victim['characterID']) if pilot is None: pilot = auth.models.Pilot(user, victim['characterName'], int(victim['characterID'])) db.session.commit() pilot_user = pilot.user # create a Killmail args = dict(kill_id=int(kill_info[u'killID']), pilot_id=int(victim[u'characterID']), pilot=victim[u'characterName'], corp_id=int(victim[u'corporationID']), corp=victim[u'corporationName'], ship_id=int(victim[u'shipTypeID']), system_id=int(kill_info[u'solarSystemID']), verified=True) if victim[u'allianceID'] != '0': args['alliance_id'] = int(victim[u'allianceID']) args['alliance'] = victim[u'allianceName'] time_struct = time.strptime(kill_info[u'killTime'], '%Y-%m-%d %H:%M:%S') args['timestamp'] = dt.datetime(*(time_struct[0:6]), tzinfo=utc) args['url'] = u'https://zkillboard.com/kill/{}'.format( args['kill_id']) try: args['value'] = Decimal(kill_info[u'zkb'][u'totalValue']) except KeyError: args['value'] = Decimal(0) killmail = PopulatedKillmail(**args) try: killmail.ship except KeyError: continue # Create a request for this killmail models.Request(pilot_user, unicode(killmail), division, killmail) db.session.commit()