add Linux_i686
This commit is contained in:
parent
75f9a2fcbc
commit
95cd9b11f2
1644 changed files with 564260 additions and 0 deletions
416
Linux_i686/lib/python2.7/site-packages/flask_script/__init__.py
Normal file
416
Linux_i686/lib/python2.7/site-packages/flask_script/__init__.py
Normal file
|
|
@ -0,0 +1,416 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import types
|
||||
import warnings
|
||||
from gettext import gettext as _
|
||||
|
||||
import argparse
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from ._compat import iteritems
|
||||
from .commands import Group, Option, Command, Server, Shell
|
||||
from .cli import prompt, prompt_pass, prompt_bool, prompt_choices
|
||||
|
||||
__all__ = ["Command", "Shell", "Server", "Manager", "Group", "Option",
|
||||
"prompt", "prompt_pass", "prompt_bool", "prompt_choices"]
|
||||
|
||||
safe_actions = (argparse._StoreAction,
|
||||
argparse._StoreConstAction,
|
||||
argparse._StoreTrueAction,
|
||||
argparse._StoreFalseAction,
|
||||
argparse._AppendAction,
|
||||
argparse._AppendConstAction,
|
||||
argparse._CountAction)
|
||||
|
||||
|
||||
try:
|
||||
import argcomplete
|
||||
ARGCOMPLETE_IMPORTED = True
|
||||
except ImportError:
|
||||
ARGCOMPLETE_IMPORTED = False
|
||||
|
||||
def add_help(parser, help_args):
|
||||
if not help_args:
|
||||
return
|
||||
parser.add_argument(*help_args,
|
||||
action='help', default=argparse.SUPPRESS, help=_('show this help message and exit'))
|
||||
|
||||
class Manager(object):
|
||||
"""
|
||||
Controller class for handling a set of commands.
|
||||
|
||||
Typical usage::
|
||||
|
||||
class Print(Command):
|
||||
|
||||
def run(self):
|
||||
print "hello"
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
manager = Manager(app)
|
||||
manager.add_command("print", Print())
|
||||
|
||||
if __name__ == "__main__":
|
||||
manager.run()
|
||||
|
||||
On command line::
|
||||
|
||||
python manage.py print
|
||||
> hello
|
||||
|
||||
:param app: Flask instance, or callable returning a Flask instance.
|
||||
:param with_default_commands: load commands **runserver** and **shell**
|
||||
by default.
|
||||
:param disable_argcomplete: disable automatic loading of argcomplete.
|
||||
|
||||
"""
|
||||
help_args = ('-?','--help')
|
||||
|
||||
def __init__(self, app=None, with_default_commands=None, usage=None,
|
||||
help=None, description=None, disable_argcomplete=False):
|
||||
|
||||
self.app = app
|
||||
|
||||
self._commands = dict()
|
||||
self._options = list()
|
||||
|
||||
self.usage = usage
|
||||
self.help = help if help is not None else usage
|
||||
self.description = description if description is not None else usage
|
||||
self.disable_argcomplete = disable_argcomplete
|
||||
self.with_default_commands = with_default_commands
|
||||
|
||||
self.parent = None
|
||||
|
||||
def add_default_commands(self):
|
||||
"""
|
||||
Adds the shell and runserver default commands. To override these,
|
||||
simply add your own equivalents using add_command or decorators.
|
||||
"""
|
||||
|
||||
if "shell" not in self._commands:
|
||||
self.add_command("shell", Shell())
|
||||
if "runserver" not in self._commands:
|
||||
self.add_command("runserver", Server())
|
||||
|
||||
def add_option(self, *args, **kwargs):
|
||||
"""
|
||||
Adds a global option. This is useful if you want to set variables
|
||||
applying to the application setup, rather than individual commands.
|
||||
|
||||
For this to work, the manager must be initialized with a factory
|
||||
function rather than a Flask instance. Otherwise any options you set
|
||||
will be ignored.
|
||||
|
||||
The arguments are then passed to your function, e.g.::
|
||||
|
||||
def create_my_app(config=None):
|
||||
app = Flask(__name__)
|
||||
if config:
|
||||
app.config.from_pyfile(config)
|
||||
|
||||
return app
|
||||
|
||||
manager = Manager(create_my_app)
|
||||
manager.add_option("-c", "--config", dest="config", required=False)
|
||||
@manager.command
|
||||
def mycommand(app):
|
||||
app.do_something()
|
||||
|
||||
and are invoked like this::
|
||||
|
||||
> python manage.py -c dev.cfg mycommand
|
||||
|
||||
Any manager options passed on the command line will not be passed to
|
||||
the command.
|
||||
|
||||
Arguments for this function are the same as for the Option class.
|
||||
"""
|
||||
|
||||
self._options.append(Option(*args, **kwargs))
|
||||
|
||||
def __call__(self, app=None, **kwargs):
|
||||
"""
|
||||
This procedure is called with the App instance (if this is a
|
||||
sub-Manager) and any options.
|
||||
|
||||
If your sub-Manager does not override this, any values for options will get lost.
|
||||
"""
|
||||
if app is None:
|
||||
app = self.app
|
||||
if app is None:
|
||||
raise Exception("There is no app here. This is unlikely to work.")
|
||||
|
||||
if isinstance(app, Flask):
|
||||
if kwargs:
|
||||
import warnings
|
||||
warnings.warn("Options will be ignored.")
|
||||
return app
|
||||
|
||||
app = app(**kwargs)
|
||||
self.app = app
|
||||
return app
|
||||
|
||||
def create_app(self, *args, **kwargs):
|
||||
warnings.warn("create_app() is deprecated; use __call__().", warnings.DeprecationWarning)
|
||||
return self(*args,**kwargs)
|
||||
|
||||
def create_parser(self, prog, func_stack=(), parent=None):
|
||||
"""
|
||||
Creates an ArgumentParser instance from options returned
|
||||
by get_options(), and subparser for the given commands.
|
||||
"""
|
||||
prog = os.path.basename(prog)
|
||||
func_stack=func_stack+(self,)
|
||||
|
||||
options_parser = argparse.ArgumentParser(add_help=False)
|
||||
for option in self.get_options():
|
||||
options_parser.add_argument(*option.args, **option.kwargs)
|
||||
|
||||
parser = argparse.ArgumentParser(prog=prog, usage=self.usage,
|
||||
description=self.description,
|
||||
parents=[options_parser],
|
||||
add_help=False)
|
||||
add_help(parser, self.help_args)
|
||||
|
||||
self._patch_argparser(parser)
|
||||
|
||||
subparsers = parser.add_subparsers()
|
||||
|
||||
for name, command in self._commands.items():
|
||||
usage = getattr(command, 'usage', None)
|
||||
help = getattr(command, 'help', None)
|
||||
if help is None: help = command.__doc__
|
||||
description = getattr(command, 'description', None)
|
||||
if description is None: description = command.__doc__
|
||||
|
||||
command_parser = command.create_parser(name, func_stack=func_stack, parent=self)
|
||||
|
||||
subparser = subparsers.add_parser(name, usage=usage, help=help,
|
||||
description=description,
|
||||
parents=[command_parser],
|
||||
add_help=False)
|
||||
|
||||
if isinstance(command, Manager):
|
||||
self._patch_argparser(subparser)
|
||||
|
||||
## enable autocomplete only for parent parser when argcomplete is
|
||||
## imported and it is NOT disabled in constructor
|
||||
if parent is None and ARGCOMPLETE_IMPORTED \
|
||||
and not self.disable_argcomplete:
|
||||
argcomplete.autocomplete(parser, always_complete_options=True)
|
||||
|
||||
self.parser = parser
|
||||
return parser
|
||||
|
||||
# def foo(self, app, *args, **kwargs):
|
||||
# print(args)
|
||||
|
||||
def _patch_argparser(self, parser):
|
||||
"""
|
||||
Patches the parser to print the full help if no arguments are supplied
|
||||
"""
|
||||
|
||||
def _parse_known_args(self, arg_strings, *args, **kw):
|
||||
if not arg_strings:
|
||||
self.print_help()
|
||||
self.exit(2)
|
||||
|
||||
return self._parse_known_args2(arg_strings, *args, **kw)
|
||||
|
||||
parser._parse_known_args2 = parser._parse_known_args
|
||||
parser._parse_known_args = types.MethodType(_parse_known_args, parser)
|
||||
|
||||
def get_options(self):
|
||||
return self._options
|
||||
|
||||
def add_command(self, *args, **kwargs):
|
||||
"""
|
||||
Adds command to registry.
|
||||
|
||||
:param command: Command instance
|
||||
:param name: Name of the command (optional)
|
||||
:param namespace: Namespace of the command (optional; pass as kwarg)
|
||||
"""
|
||||
|
||||
if len(args) == 1:
|
||||
command = args[0]
|
||||
name = None
|
||||
|
||||
else:
|
||||
name, command = args
|
||||
|
||||
if name is None:
|
||||
if hasattr(command, 'name'):
|
||||
name = command.name
|
||||
|
||||
else:
|
||||
name = type(command).__name__.lower()
|
||||
name = re.sub(r'command$', '', name)
|
||||
|
||||
if isinstance(command, Manager):
|
||||
command.parent = self
|
||||
|
||||
if isinstance(command, type):
|
||||
command = command()
|
||||
|
||||
namespace = kwargs.get('namespace')
|
||||
if not namespace:
|
||||
namespace = getattr(command, 'namespace', None)
|
||||
|
||||
if namespace:
|
||||
if namespace not in self._commands:
|
||||
self.add_command(namespace, Manager())
|
||||
|
||||
self._commands[namespace]._commands[name] = command
|
||||
|
||||
else:
|
||||
self._commands[name] = command
|
||||
|
||||
def command(self, func):
|
||||
"""
|
||||
Decorator to add a command function to the registry.
|
||||
|
||||
:param func: command function.Arguments depend on the
|
||||
options.
|
||||
|
||||
"""
|
||||
|
||||
command = Command(func)
|
||||
self.add_command(func.__name__, command)
|
||||
|
||||
return func
|
||||
|
||||
def option(self, *args, **kwargs):
|
||||
"""
|
||||
Decorator to add an option to a function. Automatically registers the
|
||||
function - do not use together with ``@command``. You can add as many
|
||||
``@option`` calls as you like, for example::
|
||||
|
||||
@option('-n', '--name', dest='name')
|
||||
@option('-u', '--url', dest='url')
|
||||
def hello(name, url):
|
||||
print "hello", name, url
|
||||
|
||||
Takes the same arguments as the ``Option`` constructor.
|
||||
"""
|
||||
|
||||
option = Option(*args, **kwargs)
|
||||
|
||||
def decorate(func):
|
||||
name = func.__name__
|
||||
|
||||
if name not in self._commands:
|
||||
|
||||
command = Command()
|
||||
command.run = func
|
||||
command.__doc__ = func.__doc__
|
||||
command.option_list = []
|
||||
|
||||
self.add_command(name, command)
|
||||
|
||||
self._commands[name].option_list.append(option)
|
||||
return func
|
||||
return decorate
|
||||
|
||||
def shell(self, func):
|
||||
"""
|
||||
Decorator that wraps function in shell command. This is equivalent to::
|
||||
|
||||
def _make_context(app):
|
||||
return dict(app=app)
|
||||
|
||||
manager.add_command("shell", Shell(make_context=_make_context))
|
||||
|
||||
The decorated function should take a single "app" argument, and return
|
||||
a dict.
|
||||
|
||||
For more sophisticated usage use the Shell class.
|
||||
"""
|
||||
|
||||
self.add_command('shell', Shell(make_context=func))
|
||||
|
||||
return func
|
||||
|
||||
def set_defaults(self):
|
||||
if self.with_default_commands is None:
|
||||
self.with_default_commands = self.parent is None
|
||||
if self.with_default_commands:
|
||||
self.add_default_commands()
|
||||
self.with_default_commands = False
|
||||
|
||||
def handle(self, prog, args=None):
|
||||
self.set_defaults()
|
||||
app_parser = self.create_parser(prog)
|
||||
|
||||
args = list(args or [])
|
||||
app_namespace, remaining_args = app_parser.parse_known_args(args)
|
||||
|
||||
# get the handle function and remove it from parsed options
|
||||
kwargs = app_namespace.__dict__
|
||||
func_stack = kwargs.pop('func_stack', None)
|
||||
if not func_stack:
|
||||
app_parser.error('too few arguments')
|
||||
|
||||
last_func = func_stack[-1]
|
||||
if remaining_args and not getattr(last_func, 'capture_all_args', False):
|
||||
app_parser.error('too many arguments')
|
||||
|
||||
args = []
|
||||
for handle in func_stack:
|
||||
|
||||
# get only safe config options
|
||||
config_keys = [action.dest for action in handle.parser._actions
|
||||
if handle is last_func or action.__class__ in safe_actions]
|
||||
|
||||
# pass only safe app config keys
|
||||
config = dict((k, v) for k, v in iteritems(kwargs)
|
||||
if k in config_keys)
|
||||
|
||||
# remove application config keys from handle kwargs
|
||||
kwargs = dict((k, v) for k, v in iteritems(kwargs)
|
||||
if k not in config_keys)
|
||||
|
||||
if handle is last_func and getattr(last_func, 'capture_all_args', False):
|
||||
args.append(remaining_args)
|
||||
try:
|
||||
res = handle(*args, **config)
|
||||
except TypeError as err:
|
||||
err.args = ("{}: {}".format(handle,str(err)),)
|
||||
raise
|
||||
|
||||
args = [res]
|
||||
|
||||
assert not kwargs
|
||||
return res
|
||||
|
||||
def run(self, commands=None, default_command=None):
|
||||
"""
|
||||
Prepares manager to receive command line input. Usually run
|
||||
inside "if __name__ == "__main__" block in a Python script.
|
||||
|
||||
:param commands: optional dict of commands. Appended to any commands
|
||||
added using add_command().
|
||||
|
||||
:param default_command: name of default command to run if no
|
||||
arguments passed.
|
||||
"""
|
||||
|
||||
if commands:
|
||||
self._commands.update(commands)
|
||||
|
||||
if default_command is not None and len(sys.argv) == 1:
|
||||
sys.argv.append(default_command)
|
||||
|
||||
try:
|
||||
result = self.handle(sys.argv[0], sys.argv[1:])
|
||||
except SystemExit as e:
|
||||
result = e.code
|
||||
|
||||
sys.exit(result or 0)
|
||||
117
Linux_i686/lib/python2.7/site-packages/flask_script/_compat.py
Normal file
117
Linux_i686/lib/python2.7/site-packages/flask_script/_compat.py
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask_script._compat
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Some py2/py3 compatibility support based on a stripped down
|
||||
version of six so we don't have to depend on a specific version
|
||||
of it.
|
||||
|
||||
:copyright: (c) 2013 by Armin Ronacher.
|
||||
:license: BSD, see LICENSE for more details.
|
||||
"""
|
||||
import sys
|
||||
|
||||
PY2 = sys.version_info[0] == 2
|
||||
PYPY = hasattr(sys, 'pypy_translation_info')
|
||||
_identity = lambda x: x
|
||||
|
||||
|
||||
if not PY2:
|
||||
unichr = chr
|
||||
range_type = range
|
||||
text_type = str
|
||||
string_types = (str, )
|
||||
integer_types = (int, )
|
||||
|
||||
iterkeys = lambda d: iter(d.keys())
|
||||
itervalues = lambda d: iter(d.values())
|
||||
iteritems = lambda d: iter(d.items())
|
||||
|
||||
import pickle
|
||||
from io import BytesIO, StringIO
|
||||
NativeStringIO = StringIO
|
||||
|
||||
def reraise(tp, value, tb=None):
|
||||
if value.__traceback__ is not tb:
|
||||
raise value.with_traceback(tb)
|
||||
raise value
|
||||
|
||||
ifilter = filter
|
||||
imap = map
|
||||
izip = zip
|
||||
intern = sys.intern
|
||||
|
||||
implements_iterator = _identity
|
||||
implements_to_string = _identity
|
||||
encode_filename = _identity
|
||||
get_next = lambda x: x.__next__
|
||||
|
||||
input = input
|
||||
from string import ascii_lowercase
|
||||
|
||||
else:
|
||||
unichr = unichr
|
||||
text_type = unicode
|
||||
range_type = xrange
|
||||
string_types = (str, unicode)
|
||||
integer_types = (int, long)
|
||||
|
||||
iterkeys = lambda d: d.iterkeys()
|
||||
itervalues = lambda d: d.itervalues()
|
||||
iteritems = lambda d: d.iteritems()
|
||||
|
||||
import cPickle as pickle
|
||||
from cStringIO import StringIO as BytesIO, StringIO
|
||||
NativeStringIO = BytesIO
|
||||
|
||||
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
|
||||
|
||||
from itertools import imap, izip, ifilter
|
||||
intern = intern
|
||||
|
||||
def implements_iterator(cls):
|
||||
cls.next = cls.__next__
|
||||
del cls.__next__
|
||||
return cls
|
||||
|
||||
def implements_to_string(cls):
|
||||
cls.__unicode__ = cls.__str__
|
||||
cls.__str__ = lambda x: x.__unicode__().encode('utf-8')
|
||||
return cls
|
||||
|
||||
get_next = lambda x: x.next
|
||||
|
||||
def encode_filename(filename):
|
||||
if isinstance(filename, unicode):
|
||||
return filename.encode('utf-8')
|
||||
return filename
|
||||
|
||||
input = raw_input
|
||||
from string import lower as ascii_lowercase
|
||||
|
||||
|
||||
def with_metaclass(meta, *bases):
|
||||
# This requires a bit of explanation: the basic idea is to make a
|
||||
# dummy metaclass for one level of class instantiation that replaces
|
||||
# itself with the actual metaclass. Because of internal type checks
|
||||
# we also need to make sure that we downgrade the custom metaclass
|
||||
# for one level to something closer to type (that's why __call__ and
|
||||
# __init__ comes back from type etc.).
|
||||
#
|
||||
# This has the advantage over six.with_metaclass in that it does not
|
||||
# introduce dummy classes into the final MRO.
|
||||
class metaclass(meta):
|
||||
__call__ = type.__call__
|
||||
__init__ = type.__init__
|
||||
def __new__(cls, name, this_bases, d):
|
||||
if this_bases is None:
|
||||
return type.__new__(cls, name, (), d)
|
||||
return meta(name, bases, d)
|
||||
return metaclass('temporary_class', None, {})
|
||||
|
||||
|
||||
try:
|
||||
from urllib.parse import quote_from_bytes as url_quote
|
||||
except ImportError:
|
||||
from urllib import quote as url_quote
|
||||
97
Linux_i686/lib/python2.7/site-packages/flask_script/cli.py
Normal file
97
Linux_i686/lib/python2.7/site-packages/flask_script/cli.py
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import getpass
|
||||
from ._compat import string_types, ascii_lowercase, input
|
||||
|
||||
def prompt(name, default=None):
|
||||
"""
|
||||
Grab user input from command line.
|
||||
|
||||
:param name: prompt text
|
||||
:param default: default value if no input provided.
|
||||
"""
|
||||
|
||||
prompt = name + (default and ' [%s]' % default or '')
|
||||
prompt += name.endswith('?') and ' ' or ': '
|
||||
while True:
|
||||
rv = input(prompt)
|
||||
if rv:
|
||||
return rv
|
||||
if default is not None:
|
||||
return default
|
||||
|
||||
|
||||
def prompt_pass(name, default=None):
|
||||
"""
|
||||
Grabs hidden (password) input from command line.
|
||||
|
||||
:param name: prompt text
|
||||
:param default: default value if no input provided.
|
||||
"""
|
||||
|
||||
prompt = name + (default and ' [%s]' % default or '')
|
||||
prompt += name.endswith('?') and ' ' or ': '
|
||||
while True:
|
||||
rv = getpass.getpass(prompt)
|
||||
if rv:
|
||||
return rv
|
||||
if default is not None:
|
||||
return default
|
||||
|
||||
|
||||
def prompt_bool(name, default=False, yes_choices=None, no_choices=None):
|
||||
"""
|
||||
Grabs user input from command line and converts to boolean
|
||||
value.
|
||||
|
||||
:param name: prompt text
|
||||
:param default: default value if no input provided.
|
||||
:param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't'
|
||||
:param no_choices: default 'n', 'no', '0', 'off', 'false', 'f'
|
||||
"""
|
||||
|
||||
yes_choices = yes_choices or ('y', 'yes', '1', 'on', 'true', 't')
|
||||
no_choices = no_choices or ('n', 'no', '0', 'off', 'false', 'f')
|
||||
|
||||
while True:
|
||||
rv = prompt(name, default and yes_choices[0] or no_choices[0])
|
||||
if not rv:
|
||||
return default
|
||||
if rv.lower() in yes_choices:
|
||||
return True
|
||||
elif rv.lower() in no_choices:
|
||||
return False
|
||||
|
||||
|
||||
def prompt_choices(name, choices, default=None, resolve=ascii_lowercase,
|
||||
no_choice=('none',)):
|
||||
"""
|
||||
Grabs user input from command line from set of provided choices.
|
||||
|
||||
:param name: prompt text
|
||||
:param choices: list or tuple of available choices. Choices may be
|
||||
single strings or (key, value) tuples.
|
||||
:param default: default value if no input provided.
|
||||
:param no_choice: acceptable list of strings for "null choice"
|
||||
"""
|
||||
|
||||
_choices = []
|
||||
options = []
|
||||
|
||||
for choice in choices:
|
||||
if isinstance(choice, string_types):
|
||||
options.append(choice)
|
||||
else:
|
||||
options.append("%s [%s]" % (choice[1], choice[0]))
|
||||
choice = choice[0]
|
||||
_choices.append(choice)
|
||||
|
||||
while True:
|
||||
rv = prompt(name + ' - (%s)' % ', '.join(options), default)
|
||||
if not rv:
|
||||
return default
|
||||
rv = resolve(rv)
|
||||
if rv in no_choice:
|
||||
return None
|
||||
if rv in _choices:
|
||||
return rv
|
||||
517
Linux_i686/lib/python2.7/site-packages/flask_script/commands.py
Normal file
517
Linux_i686/lib/python2.7/site-packages/flask_script/commands.py
Normal file
|
|
@ -0,0 +1,517 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import code
|
||||
import warnings
|
||||
import string
|
||||
import inspect
|
||||
|
||||
import argparse
|
||||
|
||||
from flask import _request_ctx_stack
|
||||
|
||||
from .cli import prompt, prompt_pass, prompt_bool, prompt_choices
|
||||
from ._compat import izip, text_type
|
||||
|
||||
|
||||
class InvalidCommand(Exception):
|
||||
"""\
|
||||
This is a generic error for "bad" commands.
|
||||
It is not used in Flask-Script itself, but you should throw
|
||||
this error (or one derived from it) in your command handlers,
|
||||
and your main code should display this error's message without
|
||||
a stack trace.
|
||||
|
||||
This way, we maintain interoperability if some other plug-in code
|
||||
supplies Flask-Script hooks.
|
||||
"""
|
||||
pass
|
||||
|
||||
class Group(object):
|
||||
"""
|
||||
Stores argument groups and mutually exclusive groups for
|
||||
`ArgumentParser.add_argument_group <http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#argument-groups>`
|
||||
or `ArgumentParser.add_mutually_exclusive_group <http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#add_mutually_exclusive_group>`.
|
||||
|
||||
Note: The title and description params cannot be used with the exclusive
|
||||
or required params.
|
||||
|
||||
:param options: A list of Option classes to add to this group
|
||||
:param title: A string to use as the title of the argument group
|
||||
:param description: A string to use as the description of the argument
|
||||
group
|
||||
:param exclusive: A boolean indicating if this is an argument group or a
|
||||
mutually exclusive group
|
||||
:param required: A boolean indicating if this mutually exclusive group
|
||||
must have an option selected
|
||||
"""
|
||||
|
||||
def __init__(self, *options, **kwargs):
|
||||
self.option_list = options
|
||||
|
||||
self.title = kwargs.pop("title", None)
|
||||
self.description = kwargs.pop("description", None)
|
||||
self.exclusive = kwargs.pop("exclusive", None)
|
||||
self.required = kwargs.pop("required", None)
|
||||
|
||||
if ((self.title or self.description) and
|
||||
(self.required or self.exclusive)):
|
||||
raise TypeError("title and/or description cannot be used with "
|
||||
"required and/or exclusive.")
|
||||
|
||||
super(Group, self).__init__(**kwargs)
|
||||
|
||||
def get_options(self):
|
||||
"""
|
||||
By default, returns self.option_list. Override if you
|
||||
need to do instance-specific configuration.
|
||||
"""
|
||||
return self.option_list
|
||||
|
||||
|
||||
class Option(object):
|
||||
"""
|
||||
Stores positional and optional arguments for `ArgumentParser.add_argument
|
||||
<http://argparse.googlecode.com/svn/trunk/doc/add_argument.html>`_.
|
||||
|
||||
:param name_or_flags: Either a name or a list of option strings,
|
||||
e.g. foo or -f, --foo
|
||||
:param action: The basic type of action to be taken when this argument
|
||||
is encountered at the command-line.
|
||||
:param nargs: The number of command-line arguments that should be consumed.
|
||||
:param const: A constant value required by some action and nargs selections.
|
||||
:param default: The value produced if the argument is absent from
|
||||
the command-line.
|
||||
:param type: The type to which the command-line arg should be converted.
|
||||
:param choices: A container of the allowable values for the argument.
|
||||
:param required: Whether or not the command-line option may be omitted
|
||||
(optionals only).
|
||||
:param help: A brief description of what the argument does.
|
||||
:param metavar: A name for the argument in usage messages.
|
||||
:param dest: The name of the attribute to be added to the object
|
||||
returned by parse_args().
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
|
||||
|
||||
class Command(object):
|
||||
"""
|
||||
Base class for creating commands.
|
||||
|
||||
:param func: Initialize this command by introspecting the function.
|
||||
"""
|
||||
|
||||
option_list = ()
|
||||
help_args = None
|
||||
|
||||
def __init__(self, func=None):
|
||||
if func is None:
|
||||
if not self.option_list:
|
||||
self.option_list = []
|
||||
return
|
||||
|
||||
args, varargs, keywords, defaults = inspect.getargspec(func)
|
||||
if inspect.ismethod(func):
|
||||
args = args[1:]
|
||||
|
||||
options = []
|
||||
|
||||
# first arg is always "app" : ignore
|
||||
|
||||
defaults = defaults or []
|
||||
kwargs = dict(izip(*[reversed(l) for l in (args, defaults)]))
|
||||
|
||||
for arg in args:
|
||||
|
||||
if arg in kwargs:
|
||||
|
||||
default = kwargs[arg]
|
||||
|
||||
if isinstance(default, bool):
|
||||
options.append(Option('-%s' % arg[0],
|
||||
'--%s' % arg,
|
||||
action="store_true",
|
||||
dest=arg,
|
||||
required=False,
|
||||
default=default))
|
||||
else:
|
||||
options.append(Option('-%s' % arg[0],
|
||||
'--%s' % arg,
|
||||
dest=arg,
|
||||
type=text_type,
|
||||
required=False,
|
||||
default=default))
|
||||
|
||||
else:
|
||||
options.append(Option(arg, type=text_type))
|
||||
|
||||
self.run = func
|
||||
self.__doc__ = func.__doc__
|
||||
self.option_list = options
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
description = self.__doc__ or ''
|
||||
return description.strip()
|
||||
|
||||
def add_option(self, option):
|
||||
"""
|
||||
Adds Option to option list.
|
||||
"""
|
||||
self.option_list.append(option)
|
||||
|
||||
def get_options(self):
|
||||
"""
|
||||
By default, returns self.option_list. Override if you
|
||||
need to do instance-specific configuration.
|
||||
"""
|
||||
return self.option_list
|
||||
|
||||
def create_parser(self, *args, **kwargs):
|
||||
func_stack = kwargs.pop('func_stack',())
|
||||
parent = kwargs.pop('parent',None)
|
||||
parser = argparse.ArgumentParser(*args, add_help=False, **kwargs)
|
||||
help_args = self.help_args
|
||||
while help_args is None and parent is not None:
|
||||
help_args = parent.help_args
|
||||
parent = getattr(parent,'parent',None)
|
||||
|
||||
if help_args:
|
||||
from flask_script import add_help
|
||||
add_help(parser,help_args)
|
||||
|
||||
for option in self.get_options():
|
||||
if isinstance(option, Group):
|
||||
if option.exclusive:
|
||||
group = parser.add_mutually_exclusive_group(
|
||||
required=option.required,
|
||||
)
|
||||
else:
|
||||
group = parser.add_argument_group(
|
||||
title=option.title,
|
||||
description=option.description,
|
||||
)
|
||||
for opt in option.get_options():
|
||||
group.add_argument(*opt.args, **opt.kwargs)
|
||||
else:
|
||||
parser.add_argument(*option.args, **option.kwargs)
|
||||
|
||||
parser.set_defaults(func_stack=func_stack+(self,))
|
||||
|
||||
self.parser = parser
|
||||
self.parent = parent
|
||||
return parser
|
||||
|
||||
def __call__(self, app=None, *args, **kwargs):
|
||||
"""
|
||||
Handles the command with the given app.
|
||||
Default behaviour is to call ``self.run`` within a test request context.
|
||||
"""
|
||||
with app.test_request_context():
|
||||
return self.run(*args, **kwargs)
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
Runs a command. This must be implemented by the subclass. Should take
|
||||
arguments as configured by the Command options.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
class Shell(Command):
|
||||
"""
|
||||
Runs a Python shell inside Flask application context.
|
||||
|
||||
:param banner: banner appearing at top of shell when started
|
||||
:param make_context: a callable returning a dict of variables
|
||||
used in the shell namespace. By default
|
||||
returns a dict consisting of just the app.
|
||||
:param use_bpython: use BPython shell if available, ignore if not.
|
||||
The BPython shell can be turned off in command
|
||||
line by passing the **--no-bpython** flag.
|
||||
:param use_ipython: use IPython shell if available, ignore if not.
|
||||
The IPython shell can be turned off in command
|
||||
line by passing the **--no-ipython** flag.
|
||||
"""
|
||||
|
||||
banner = ''
|
||||
|
||||
help = description = 'Runs a Python shell inside Flask application context.'
|
||||
|
||||
def __init__(self, banner=None, make_context=None, use_ipython=True,
|
||||
use_bpython=True):
|
||||
|
||||
self.banner = banner or self.banner
|
||||
self.use_ipython = use_ipython
|
||||
self.use_bpython = use_bpython
|
||||
|
||||
if make_context is None:
|
||||
make_context = lambda: dict(app=_request_ctx_stack.top.app)
|
||||
|
||||
self.make_context = make_context
|
||||
|
||||
def get_options(self):
|
||||
return (
|
||||
Option('--no-ipython',
|
||||
action="store_true",
|
||||
dest='no_ipython',
|
||||
default=not(self.use_ipython),
|
||||
help="Do not use the BPython shell"),
|
||||
Option('--no-bpython',
|
||||
action="store_true",
|
||||
dest='no_bpython',
|
||||
default=not(self.use_bpython),
|
||||
help="Do not use the IPython shell"),
|
||||
)
|
||||
|
||||
def get_context(self):
|
||||
"""
|
||||
Returns a dict of context variables added to the shell namespace.
|
||||
"""
|
||||
return self.make_context()
|
||||
|
||||
def run(self, no_ipython, no_bpython):
|
||||
"""
|
||||
Runs the shell. If no_bpython is False or use_bpython is True, then
|
||||
a BPython shell is run (if installed). Else, if no_ipython is False or
|
||||
use_python is True then a IPython shell is run (if installed).
|
||||
"""
|
||||
|
||||
context = self.get_context()
|
||||
|
||||
if not no_bpython:
|
||||
# Try BPython
|
||||
try:
|
||||
from bpython import embed
|
||||
embed(banner=self.banner, locals_=context)
|
||||
return
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
if not no_ipython:
|
||||
# Try IPython
|
||||
try:
|
||||
try:
|
||||
# 0.10.x
|
||||
from IPython.Shell import IPShellEmbed
|
||||
ipshell = IPShellEmbed(banner=self.banner)
|
||||
ipshell(global_ns=dict(), local_ns=context)
|
||||
except ImportError:
|
||||
# 0.12+
|
||||
from IPython import embed
|
||||
embed(banner1=self.banner, user_ns=context)
|
||||
return
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Use basic python shell
|
||||
code.interact(self.banner, local=context)
|
||||
|
||||
|
||||
class Server(Command):
|
||||
"""
|
||||
Runs the Flask development server i.e. app.run()
|
||||
|
||||
:param host: server host
|
||||
:param port: server port
|
||||
:param use_debugger: if False, will no longer use Werkzeug debugger.
|
||||
This can be overriden in the command line
|
||||
by passing the **-d** flag.
|
||||
:param use_reloader: if False, will no longer use auto-reloader.
|
||||
This can be overriden in the command line by
|
||||
passing the **-r** flag.
|
||||
:param threaded: should the process handle each request in a separate
|
||||
thread?
|
||||
:param processes: number of processes to spawn
|
||||
:param passthrough_errors: disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.)
|
||||
:param options: :func:`werkzeug.run_simple` options.
|
||||
"""
|
||||
|
||||
help = description = 'Runs the Flask development server i.e. app.run()'
|
||||
|
||||
def __init__(self, host='127.0.0.1', port=5000, use_debugger=True,
|
||||
use_reloader=True, threaded=False, processes=1,
|
||||
passthrough_errors=False, **options):
|
||||
|
||||
self.port = port
|
||||
self.host = host
|
||||
self.use_debugger = use_debugger
|
||||
self.use_reloader = use_reloader
|
||||
self.server_options = options
|
||||
self.threaded = threaded
|
||||
self.processes = processes
|
||||
self.passthrough_errors = passthrough_errors
|
||||
|
||||
def get_options(self):
|
||||
|
||||
options = (
|
||||
Option('-h', '--host',
|
||||
dest='host',
|
||||
default=self.host),
|
||||
|
||||
Option('-p', '--port',
|
||||
dest='port',
|
||||
type=int,
|
||||
default=self.port),
|
||||
|
||||
Option('--threaded',
|
||||
dest='threaded',
|
||||
action='store_true',
|
||||
default=self.threaded),
|
||||
|
||||
Option('--processes',
|
||||
dest='processes',
|
||||
type=int,
|
||||
default=self.processes),
|
||||
|
||||
Option('--passthrough-errors',
|
||||
action='store_true',
|
||||
dest='passthrough_errors',
|
||||
default=self.passthrough_errors),
|
||||
)
|
||||
|
||||
if self.use_debugger:
|
||||
options += (Option('-d', '--debug',
|
||||
action='store_true',
|
||||
dest='use_debugger',
|
||||
help="(no-op for compatibility)"),)
|
||||
options += (Option('-D', '--no-debug',
|
||||
action='store_false',
|
||||
dest='use_debugger',
|
||||
default=self.use_debugger),)
|
||||
|
||||
else:
|
||||
options += (Option('-d', '--debug',
|
||||
action='store_true',
|
||||
dest='use_debugger',
|
||||
default=self.use_debugger),)
|
||||
options += (Option('-D', '--no-debug',
|
||||
action='store_false',
|
||||
dest='use_debugger',
|
||||
help="(no-op for compatibility)"),)
|
||||
|
||||
if self.use_reloader:
|
||||
options += (Option('-r', '--reload',
|
||||
action='store_true',
|
||||
dest='use_reloader',
|
||||
help="(no-op for compatibility)"),)
|
||||
options += (Option('-R', '--no-reload',
|
||||
action='store_false',
|
||||
dest='use_reloader',
|
||||
default=self.use_reloader),)
|
||||
|
||||
else:
|
||||
options += (Option('-r', '--reload',
|
||||
action='store_true',
|
||||
dest='use_reloader',
|
||||
default=self.use_reloader),)
|
||||
options += (Option('-R', '--no-reload',
|
||||
action='store_false',
|
||||
dest='use_reloader',
|
||||
help="(no-op for compatibility)"),)
|
||||
|
||||
return options
|
||||
|
||||
def __call__(self, app, host, port, use_debugger, use_reloader,
|
||||
threaded, processes, passthrough_errors):
|
||||
# we don't need to run the server in request context
|
||||
# so just run it directly
|
||||
|
||||
app.run(host=host,
|
||||
port=port,
|
||||
debug=use_debugger,
|
||||
use_debugger=use_debugger,
|
||||
use_reloader=use_reloader,
|
||||
threaded=threaded,
|
||||
processes=processes,
|
||||
passthrough_errors=passthrough_errors,
|
||||
**self.server_options)
|
||||
|
||||
|
||||
class Clean(Command):
|
||||
"Remove *.pyc and *.pyo files recursively starting at current directory"
|
||||
def run(self):
|
||||
for dirpath, dirnames, filenames in os.walk('.'):
|
||||
for filename in filenames:
|
||||
if filename.endswith('.pyc') or filename.endswith('.pyo'):
|
||||
full_pathname = os.path.join(dirpath, filename)
|
||||
print('Removing %s' % full_pathname)
|
||||
os.remove(full_pathname)
|
||||
|
||||
|
||||
class ShowUrls(Command):
|
||||
"""
|
||||
Displays all of the url matching routes for the project
|
||||
"""
|
||||
def __init__(self, order='rule'):
|
||||
self.order = order
|
||||
|
||||
def get_options(self):
|
||||
return (
|
||||
Option('url',
|
||||
nargs='?',
|
||||
help='Url to test (ex. /static/image.png)'),
|
||||
Option('--order',
|
||||
dest='order',
|
||||
default=self.order,
|
||||
help='Property on Rule to order by (default: %s)' % self.order)
|
||||
)
|
||||
|
||||
return options
|
||||
|
||||
def run(self, url, order):
|
||||
from flask import current_app
|
||||
from werkzeug.exceptions import NotFound, MethodNotAllowed
|
||||
|
||||
rows = []
|
||||
column_length = 0
|
||||
column_headers = ('Rule', 'Endpoint', 'Arguments')
|
||||
|
||||
if url:
|
||||
try:
|
||||
rule, arguments = current_app.url_map \
|
||||
.bind('localhost') \
|
||||
.match(url, return_rule=True)
|
||||
rows.append((rule.rule, rule.endpoint, arguments))
|
||||
column_length = 3
|
||||
except (NotFound, MethodNotAllowed) as e:
|
||||
rows.append(("<%s>" % e, None, None))
|
||||
column_length = 1
|
||||
else:
|
||||
rules = sorted(current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order))
|
||||
for rule in rules:
|
||||
rows.append((rule.rule, rule.endpoint, None))
|
||||
column_length = 2
|
||||
|
||||
str_template = ''
|
||||
table_width = 0
|
||||
|
||||
if column_length >= 1:
|
||||
max_rule_length = max(len(r[0]) for r in rows)
|
||||
max_rule_length = max_rule_length if max_rule_length > 4 else 4
|
||||
str_template += '%-' + str(max_rule_length) + 's'
|
||||
table_width += max_rule_length
|
||||
|
||||
if column_length >= 2:
|
||||
max_endpoint_length = max(len(str(r[1])) for r in rows)
|
||||
# max_endpoint_length = max(rows, key=len)
|
||||
max_endpoint_length = max_endpoint_length if max_endpoint_length > 8 else 8
|
||||
str_template += ' %-' + str(max_endpoint_length) + 's'
|
||||
table_width += 2 + max_endpoint_length
|
||||
|
||||
if column_length >= 3:
|
||||
max_arguments_length = max(len(str(r[2])) for r in rows)
|
||||
max_arguments_length = max_arguments_length if max_arguments_length > 9 else 9
|
||||
str_template += ' %-' + str(max_arguments_length) + 's'
|
||||
table_width += 2 + max_arguments_length
|
||||
|
||||
print(str_template % (column_headers[:column_length]))
|
||||
print('-' * table_width)
|
||||
|
||||
for row in rows:
|
||||
print(str_template % row[:column_length])
|
||||
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue