Commits

Anonymous committed a92289b

prompt_choices changes

Comments (0)

Files changed (2)

examples/manage.py

 import pprint
 
 from flask import Flask, current_app
-from flaskext.script import Manager
+from flaskext.script import Manager, prompt_choices
 
 def create_app(config=None):
     app = Flask(__name__)
     "print name and url"
     print name, url
 
+@manager.command
+def getrolesimple():
+
+    choices = ("member", "moderator", "admin")
+
+    role = prompt_choices("role", choices=choices, default="member")
+    print "ROLE:", role
+
+@manager.command
+def getrole():
+
+    choices = (
+        (1, "member"),
+        (2, "moderator"),
+        (3, "admin"),
+    )
+
+    role = prompt_choices("role", choices=choices, resolve=int, default=1)
+    print "ROLE:", role
+
 @manager.option('-n', '--name', dest='name', help="your name")
 @manager.option('-u', '--url', dest='url', help="your url")
 def optional(name, url):

flaskext/script.py

 
 import sys
 import code
+import string
 import getpass
 import inspect
 import warnings
     no_choices = no_choices or ('n', 'no', '0', 'off', 'false', 'f')
     
     while True:
-        rv = prompt(name + '?', default and 'Y' or 'N')
+        rv = prompt(name + '?', default and yes_choices[0] or no_choices[0])
         if not rv:
             return default
         if rv.lower() in yes_choices:
             return False
 
 
-def prompt_choices(name, choices, default=None):
+def prompt_choices(name, choices, default=None, 
+    resolve=string.lower, 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
+    :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, basestring):
+            options.append(choice)
+        else:
+            options.append("%s [%s]" % (choice[1], choice[0]))
+            choice = choice[0]
+        _choices.append(choice)
 
-    if default is None:
-        default = choices[0]
     while True:
-        rv = prompt(name + '? - (%s)' % ', '.join(choices), default)
-        rv = rv.lower()
+        rv = prompt(name + '? - (%s)' % ', '.join(options), default)
         if not rv:
             return default
-        if rv in choices:
-            if rv == 'none':
-                return None
-            else:
-                return rv
+        rv = resolve(rv)
+        if rv in no_choice:
+            return None
+        if rv in _choices:
+            return rv
 
 
 class Option(object):