We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
"st2 key delete" does not obey interface and populate user query params
st2 --debug  key delete  -s user -u stanley netdev_servicewrapper_address
2016-09-23 17:13:48,545  DEBUG - Using cached token from file "/home/vagrant/.st2/token-st2admin"

curl -X GET -H  'Connection: keep-alive' -H  'Accept-Encoding: gzip, deflate' -H  'Accept: _/_' -H  'User-Agent: python-requests/2.11.1' -H  'X-Auth-Token: 235ca028e8e545efbd28806090ca3bd6' 'http://127.0.0.1:9101/v1/keys/netdev_servicewrapper_address?scope=user'

{
    "faultstring": "KeyValuePair with name: st2admin:netdev_servicewrapper_address and scope: user not found in db."
}


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `st2client/st2client/commands/keyvalue.py`
Content:
```
1 # Licensed to the StackStorm, Inc ('StackStorm') under one or more
2 # contributor license agreements.  See the NOTICE file distributed with
3 # this work for additional information regarding copyright ownership.
4 # The ASF licenses this file to You under the Apache License, Version 2.0
5 # (the "License"); you may not use this file except in compliance with
6 # the License.  You may obtain a copy of the License at
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 import os
17 import json
18 import logging
19 from os.path import join as pjoin
20 
21 from st2client.commands import resource
22 from st2client.commands.noop import NoopCommand
23 from st2client.commands.resource import add_auth_token_to_kwargs_from_cli
24 from st2client.formatters import table
25 from st2client.models.keyvalue import KeyValuePair
26 from st2client.utils.date import format_isodate_for_user_timezone
27 
28 LOG = logging.getLogger(__name__)
29 
30 DEFAULT_SCOPE = 'system'
31 
32 
33 class KeyValuePairBranch(resource.ResourceBranch):
34 
35     def __init__(self, description, app, subparsers, parent_parser=None):
36         super(KeyValuePairBranch, self).__init__(
37             KeyValuePair, description, app, subparsers,
38             parent_parser=parent_parser,
39             commands={
40                 'list': KeyValuePairListCommand,
41                 'get': KeyValuePairGetCommand,
42                 'delete': KeyValuePairDeleteCommand,
43                 'create': NoopCommand,
44                 'update': NoopCommand
45             })
46 
47         # Registers extended commands
48         self.commands['set'] = KeyValuePairSetCommand(self.resource, self.app,
49                                                       self.subparsers)
50         self.commands['load'] = KeyValuePairLoadCommand(
51             self.resource, self.app, self.subparsers)
52         self.commands['delete_by_prefix'] = KeyValuePairDeleteByPrefixCommand(
53             self.resource, self.app, self.subparsers)
54 
55         # Remove unsupported commands
56         # TODO: Refactor parent class and make it nicer
57         del self.commands['create']
58         del self.commands['update']
59 
60 
61 class KeyValuePairListCommand(resource.ResourceListCommand):
62     display_attributes = ['name', 'value', 'secret', 'encrypted', 'scope', 'user',
63                           'expire_timestamp']
64     attribute_transform_functions = {
65         'expire_timestamp': format_isodate_for_user_timezone,
66     }
67 
68     def __init__(self, *args, **kwargs):
69         super(KeyValuePairListCommand, self).__init__(*args, **kwargs)
70 
71         # Filter options
72         self.parser.add_argument('--prefix', help=('Only return values which name starts with the '
73                                                    ' provided prefix.'))
74         self.parser.add_argument('--decrypt', action='store_true',
75                                  help='Decrypt secrets and display plain text.')
76         self.parser.add_argument('-s', '--scope', default='system', dest='scope',
77                                  help='Scope item is under. Example: "user".')
78         self.parser.add_argument('-u', '--user', dest='user', default=None,
79                                  help='User for user scoped items (admin only).')
80 
81     def run_and_print(self, args, **kwargs):
82         if args.prefix:
83             kwargs['prefix'] = args.prefix
84 
85         decrypt = getattr(args, 'decrypt', False)
86         kwargs['params'] = {'decrypt': str(decrypt).lower()}
87         scope = getattr(args, 'scope', DEFAULT_SCOPE)
88         kwargs['params']['scope'] = scope
89         kwargs['params']['user'] = args.user
90 
91         instances = self.run(args, **kwargs)
92         self.print_output(reversed(instances), table.MultiColumnTable,
93                           attributes=args.attr, widths=args.width,
94                           json=args.json,
95                           yaml=args.yaml,
96                           attribute_transform_functions=self.attribute_transform_functions)
97 
98 
99 class KeyValuePairGetCommand(resource.ResourceGetCommand):
100     pk_argument_name = 'name'
101     display_attributes = ['name', 'value', 'secret', 'encrypted', 'scope', 'expire_timestamp']
102 
103     def __init__(self, kv_resource, *args, **kwargs):
104         super(KeyValuePairGetCommand, self).__init__(kv_resource, *args, **kwargs)
105         self.parser.add_argument('-d', '--decrypt', action='store_true',
106                                  help='Decrypt secret if encrypted and show plain text.')
107         self.parser.add_argument('-s', '--scope', default=DEFAULT_SCOPE, dest='scope',
108                                  help='Scope item is under. Example: "user".')
109 
110     @resource.add_auth_token_to_kwargs_from_cli
111     def run(self, args, **kwargs):
112         resource_name = getattr(args, self.pk_argument_name, None)
113         decrypt = getattr(args, 'decrypt', False)
114         scope = getattr(args, 'scope', DEFAULT_SCOPE)
115         kwargs['params'] = {'decrypt': str(decrypt).lower()}
116         kwargs['params']['scope'] = scope
117         return self.get_resource_by_id(id=resource_name, **kwargs)
118 
119 
120 class KeyValuePairSetCommand(resource.ResourceCommand):
121     display_attributes = ['name', 'value', 'expire_timestamp']
122 
123     def __init__(self, resource, *args, **kwargs):
124         super(KeyValuePairSetCommand, self).__init__(
125             resource, 'set',
126             'Set an existing %s.' % resource.get_display_name().lower(),
127             *args, **kwargs
128         )
129 
130         self.parser.add_argument('name',
131                                  metavar='name',
132                                  help='Name of the key value pair.')
133         self.parser.add_argument('value', help='Value paired with the key.')
134         self.parser.add_argument('-l', '--ttl', dest='ttl', type=int, default=None,
135                                  help='TTL (in seconds) for this value.')
136         self.parser.add_argument('-e', '--encrypt', dest='secret',
137                                  action='store_true',
138                                  help='Encrypt value before saving the value.')
139         self.parser.add_argument('-s', '--scope', dest='scope', default=DEFAULT_SCOPE,
140                                  help='Specify the scope under which you want ' +
141                                       'to place the item.')
142         self.parser.add_argument('-u', '--user', dest='user', default=None,
143                                  help='User for user scoped items (admin only).')
144 
145     @add_auth_token_to_kwargs_from_cli
146     def run(self, args, **kwargs):
147         instance = KeyValuePair()
148         instance.id = args.name  # TODO: refactor and get rid of id
149         instance.name = args.name
150         instance.value = args.value
151         instance.scope = args.scope
152         instance.user = args.user
153 
154         if args.secret:
155             instance.secret = args.secret
156 
157         if args.ttl:
158             instance.ttl = args.ttl
159 
160         return self.manager.update(instance, **kwargs)
161 
162     def run_and_print(self, args, **kwargs):
163         instance = self.run(args, **kwargs)
164         self.print_output(instance, table.PropertyValueTable,
165                           attributes=self.display_attributes, json=args.json,
166                           yaml=args.yaml)
167 
168 
169 class KeyValuePairDeleteCommand(resource.ResourceDeleteCommand):
170     pk_argument_name = 'name'
171 
172     def __init__(self, resource, *args, **kwargs):
173         super(KeyValuePairDeleteCommand, self).__init__(resource, *args, **kwargs)
174 
175         self.parser.add_argument('-s', '--scope', dest='scope', default=DEFAULT_SCOPE,
176                                  help='Specify the scope under which you want ' +
177                                       'to place the item.')
178         self.parser.add_argument('-u', '--user', dest='user', default=None,
179                                  help='User for user scoped items (admin only).')
180 
181     @add_auth_token_to_kwargs_from_cli
182     def run(self, args, **kwargs):
183         resource_id = getattr(args, self.pk_argument_name, None)
184         scope = getattr(args, 'scope', DEFAULT_SCOPE)
185         kwargs['params'] = {}
186         kwargs['params']['scope'] = scope
187         instance = self.get_resource(resource_id, **kwargs)
188 
189         if not instance:
190             raise resource.ResourceNotFoundError('KeyValuePair with id "%s" not found', resource_id)
191 
192         instance.id = resource_id  # TODO: refactor and get rid of id
193         self.manager.delete(instance, **kwargs)
194 
195 
196 class KeyValuePairDeleteByPrefixCommand(resource.ResourceCommand):
197     """
198     Commands which delete all the key value pairs which match the provided
199     prefix.
200     """
201     def __init__(self, resource, *args, **kwargs):
202         super(KeyValuePairDeleteByPrefixCommand, self).__init__(resource, 'delete_by_prefix',
203             'Delete KeyValue pairs which match the provided prefix', *args, **kwargs)
204 
205         self.parser.add_argument('-p', '--prefix', required=True,
206                                  help='Name prefix (e.g. twitter.TwitterSensor:)')
207 
208     @add_auth_token_to_kwargs_from_cli
209     def run(self, args, **kwargs):
210         prefix = args.prefix
211         key_pairs = self.manager.get_all(prefix=prefix)
212 
213         to_delete = []
214         for key_pair in key_pairs:
215             key_pair.id = key_pair.name
216             to_delete.append(key_pair)
217 
218         deleted = []
219         for key_pair in to_delete:
220             self.manager.delete(instance=key_pair, **kwargs)
221             deleted.append(key_pair)
222 
223         return deleted
224 
225     def run_and_print(self, args, **kwargs):
226         # TODO: Need to use args, instead of kwargs (args=) because of bad API
227         # FIX ME
228         deleted = self.run(args, **kwargs)
229         key_ids = [key_pair.id for key_pair in deleted]
230 
231         print('Deleted %s keys' % (len(deleted)))
232         print('Deleted key ids: %s' % (', '.join(key_ids)))
233 
234 
235 class KeyValuePairLoadCommand(resource.ResourceCommand):
236     pk_argument_name = 'name'
237     display_attributes = ['name', 'value']
238 
239     def __init__(self, resource, *args, **kwargs):
240         help_text = ('Load a list of %s from file.' %
241                      resource.get_plural_display_name().lower())
242         super(KeyValuePairLoadCommand, self).__init__(resource, 'load',
243             help_text, *args, **kwargs)
244 
245         self.parser.add_argument(
246             'file', help=('JSON file containing the %s to create.'
247                           % resource.get_plural_display_name().lower()))
248 
249     @add_auth_token_to_kwargs_from_cli
250     def run(self, args, **kwargs):
251         file_path = os.path.normpath(pjoin(os.getcwd(), args.file))
252 
253         if not os.path.exists(args.file):
254             raise ValueError('File "%s" doesn\'t exist' % (file_path))
255 
256         if not os.path.isfile(args.file):
257             raise ValueError('"%s" is not a file' % (file_path))
258 
259         with open(file_path, 'r') as f:
260             kvps = json.loads(f.read())
261 
262         instances = []
263         for item in kvps:
264             name = item['name']
265             value = item['value']
266 
267             instance = KeyValuePair()
268             instance.id = name  # TODO: refactor and get rid of id
269             instance.name = name
270             instance.value = value
271 
272             self.manager.update(instance, **kwargs)
273             instances.append(instance)
274         return instances
275 
276     def run_and_print(self, args, **kwargs):
277         instances = self.run(args, **kwargs)
278         self.print_output(instances, table.MultiColumnTable,
279                           attributes=['id', 'name', 'value'], json=args.json, yaml=args.yaml)
280
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/st2client/st2client/commands/keyvalue.py b/st2client/st2client/commands/keyvalue.py
--- a/st2client/st2client/commands/keyvalue.py
+++ b/st2client/st2client/commands/keyvalue.py
@@ -184,6 +184,7 @@
         scope = getattr(args, 'scope', DEFAULT_SCOPE)
         kwargs['params'] = {}
         kwargs['params']['scope'] = scope
+        kwargs['params']['user'] = args.user
         instance = self.get_resource(resource_id, **kwargs)
 
         if not instance:

{"golden_diff": "diff --git a/st2client/st2client/commands/keyvalue.py b/st2client/st2client/commands/keyvalue.py\n--- a/st2client/st2client/commands/keyvalue.py\n+++ b/st2client/st2client/commands/keyvalue.py\n@@ -184,6 +184,7 @@\n         scope = getattr(args, 'scope', DEFAULT_SCOPE)\n         kwargs['params'] = {}\n         kwargs['params']['scope'] = scope\n+        kwargs['params']['user'] = args.user\n         instance = self.get_resource(resource_id, **kwargs)\n \n         if not instance:\n", "issue": "\"st2 key delete\" does not obey interface and populate user query params\nst2 --debug  key delete  -s user -u stanley netdev_servicewrapper_address\n2016-09-23 17:13:48,545  DEBUG - Using cached token from file \"/home/vagrant/.st2/token-st2admin\"\n\ncurl -X GET -H  'Connection: keep-alive' -H  'Accept-Encoding: gzip, deflate' -H  'Accept: _/_' -H  'User-Agent: python-requests/2.11.1' -H  'X-Auth-Token: 235ca028e8e545efbd28806090ca3bd6' 'http://127.0.0.1:9101/v1/keys/netdev_servicewrapper_address?scope=user'\n\n{\n    \"faultstring\": \"KeyValuePair with name: st2admin:netdev_servicewrapper_address and scope: user not found in db.\"\n}\n\n", "before_files": [{"content": "# Licensed to the StackStorm, Inc ('StackStorm') under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport json\nimport logging\nfrom os.path import join as pjoin\n\nfrom st2client.commands import resource\nfrom st2client.commands.noop import NoopCommand\nfrom st2client.commands.resource import add_auth_token_to_kwargs_from_cli\nfrom st2client.formatters import table\nfrom st2client.models.keyvalue import KeyValuePair\nfrom st2client.utils.date import format_isodate_for_user_timezone\n\nLOG = logging.getLogger(__name__)\n\nDEFAULT_SCOPE = 'system'\n\n\nclass KeyValuePairBranch(resource.ResourceBranch):\n\n    def __init__(self, description, app, subparsers, parent_parser=None):\n        super(KeyValuePairBranch, self).__init__(\n            KeyValuePair, description, app, subparsers,\n            parent_parser=parent_parser,\n            commands={\n                'list': KeyValuePairListCommand,\n                'get': KeyValuePairGetCommand,\n                'delete': KeyValuePairDeleteCommand,\n                'create': NoopCommand,\n                'update': NoopCommand\n            })\n\n        # Registers extended commands\n        self.commands['set'] = KeyValuePairSetCommand(self.resource, self.app,\n                                                      self.subparsers)\n        self.commands['load'] = KeyValuePairLoadCommand(\n            self.resource, self.app, self.subparsers)\n        self.commands['delete_by_prefix'] = KeyValuePairDeleteByPrefixCommand(\n            self.resource, self.app, self.subparsers)\n\n        # Remove unsupported commands\n        # TODO: Refactor parent class and make it nicer\n        del self.commands['create']\n        del self.commands['update']\n\n\nclass KeyValuePairListCommand(resource.ResourceListCommand):\n    display_attributes = ['name', 'value', 'secret', 'encrypted', 'scope', 'user',\n                          'expire_timestamp']\n    attribute_transform_functions = {\n        'expire_timestamp': format_isodate_for_user_timezone,\n    }\n\n    def __init__(self, *args, **kwargs):\n        super(KeyValuePairListCommand, self).__init__(*args, **kwargs)\n\n        # Filter options\n        self.parser.add_argument('--prefix', help=('Only return values which name starts with the '\n                                                   ' provided prefix.'))\n        self.parser.add_argument('--decrypt', action='store_true',\n                                 help='Decrypt secrets and display plain text.')\n        self.parser.add_argument('-s', '--scope', default='system', dest='scope',\n                                 help='Scope item is under. Example: \"user\".')\n        self.parser.add_argument('-u', '--user', dest='user', default=None,\n                                 help='User for user scoped items (admin only).')\n\n    def run_and_print(self, args, **kwargs):\n        if args.prefix:\n            kwargs['prefix'] = args.prefix\n\n        decrypt = getattr(args, 'decrypt', False)\n        kwargs['params'] = {'decrypt': str(decrypt).lower()}\n        scope = getattr(args, 'scope', DEFAULT_SCOPE)\n        kwargs['params']['scope'] = scope\n        kwargs['params']['user'] = args.user\n\n        instances = self.run(args, **kwargs)\n        self.print_output(reversed(instances), table.MultiColumnTable,\n                          attributes=args.attr, widths=args.width,\n                          json=args.json,\n                          yaml=args.yaml,\n                          attribute_transform_functions=self.attribute_transform_functions)\n\n\nclass KeyValuePairGetCommand(resource.ResourceGetCommand):\n    pk_argument_name = 'name'\n    display_attributes = ['name', 'value', 'secret', 'encrypted', 'scope', 'expire_timestamp']\n\n    def __init__(self, kv_resource, *args, **kwargs):\n        super(KeyValuePairGetCommand, self).__init__(kv_resource, *args, **kwargs)\n        self.parser.add_argument('-d', '--decrypt', action='store_true',\n                                 help='Decrypt secret if encrypted and show plain text.')\n        self.parser.add_argument('-s', '--scope', default=DEFAULT_SCOPE, dest='scope',\n                                 help='Scope item is under. Example: \"user\".')\n\n    @resource.add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        resource_name = getattr(args, self.pk_argument_name, None)\n        decrypt = getattr(args, 'decrypt', False)\n        scope = getattr(args, 'scope', DEFAULT_SCOPE)\n        kwargs['params'] = {'decrypt': str(decrypt).lower()}\n        kwargs['params']['scope'] = scope\n        return self.get_resource_by_id(id=resource_name, **kwargs)\n\n\nclass KeyValuePairSetCommand(resource.ResourceCommand):\n    display_attributes = ['name', 'value', 'expire_timestamp']\n\n    def __init__(self, resource, *args, **kwargs):\n        super(KeyValuePairSetCommand, self).__init__(\n            resource, 'set',\n            'Set an existing %s.' % resource.get_display_name().lower(),\n            *args, **kwargs\n        )\n\n        self.parser.add_argument('name',\n                                 metavar='name',\n                                 help='Name of the key value pair.')\n        self.parser.add_argument('value', help='Value paired with the key.')\n        self.parser.add_argument('-l', '--ttl', dest='ttl', type=int, default=None,\n                                 help='TTL (in seconds) for this value.')\n        self.parser.add_argument('-e', '--encrypt', dest='secret',\n                                 action='store_true',\n                                 help='Encrypt value before saving the value.')\n        self.parser.add_argument('-s', '--scope', dest='scope', default=DEFAULT_SCOPE,\n                                 help='Specify the scope under which you want ' +\n                                      'to place the item.')\n        self.parser.add_argument('-u', '--user', dest='user', default=None,\n                                 help='User for user scoped items (admin only).')\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        instance = KeyValuePair()\n        instance.id = args.name  # TODO: refactor and get rid of id\n        instance.name = args.name\n        instance.value = args.value\n        instance.scope = args.scope\n        instance.user = args.user\n\n        if args.secret:\n            instance.secret = args.secret\n\n        if args.ttl:\n            instance.ttl = args.ttl\n\n        return self.manager.update(instance, **kwargs)\n\n    def run_and_print(self, args, **kwargs):\n        instance = self.run(args, **kwargs)\n        self.print_output(instance, table.PropertyValueTable,\n                          attributes=self.display_attributes, json=args.json,\n                          yaml=args.yaml)\n\n\nclass KeyValuePairDeleteCommand(resource.ResourceDeleteCommand):\n    pk_argument_name = 'name'\n\n    def __init__(self, resource, *args, **kwargs):\n        super(KeyValuePairDeleteCommand, self).__init__(resource, *args, **kwargs)\n\n        self.parser.add_argument('-s', '--scope', dest='scope', default=DEFAULT_SCOPE,\n                                 help='Specify the scope under which you want ' +\n                                      'to place the item.')\n        self.parser.add_argument('-u', '--user', dest='user', default=None,\n                                 help='User for user scoped items (admin only).')\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        resource_id = getattr(args, self.pk_argument_name, None)\n        scope = getattr(args, 'scope', DEFAULT_SCOPE)\n        kwargs['params'] = {}\n        kwargs['params']['scope'] = scope\n        instance = self.get_resource(resource_id, **kwargs)\n\n        if not instance:\n            raise resource.ResourceNotFoundError('KeyValuePair with id \"%s\" not found', resource_id)\n\n        instance.id = resource_id  # TODO: refactor and get rid of id\n        self.manager.delete(instance, **kwargs)\n\n\nclass KeyValuePairDeleteByPrefixCommand(resource.ResourceCommand):\n    \"\"\"\n    Commands which delete all the key value pairs which match the provided\n    prefix.\n    \"\"\"\n    def __init__(self, resource, *args, **kwargs):\n        super(KeyValuePairDeleteByPrefixCommand, self).__init__(resource, 'delete_by_prefix',\n            'Delete KeyValue pairs which match the provided prefix', *args, **kwargs)\n\n        self.parser.add_argument('-p', '--prefix', required=True,\n                                 help='Name prefix (e.g. twitter.TwitterSensor:)')\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        prefix = args.prefix\n        key_pairs = self.manager.get_all(prefix=prefix)\n\n        to_delete = []\n        for key_pair in key_pairs:\n            key_pair.id = key_pair.name\n            to_delete.append(key_pair)\n\n        deleted = []\n        for key_pair in to_delete:\n            self.manager.delete(instance=key_pair, **kwargs)\n            deleted.append(key_pair)\n\n        return deleted\n\n    def run_and_print(self, args, **kwargs):\n        # TODO: Need to use args, instead of kwargs (args=) because of bad API\n        # FIX ME\n        deleted = self.run(args, **kwargs)\n        key_ids = [key_pair.id for key_pair in deleted]\n\n        print('Deleted %s keys' % (len(deleted)))\n        print('Deleted key ids: %s' % (', '.join(key_ids)))\n\n\nclass KeyValuePairLoadCommand(resource.ResourceCommand):\n    pk_argument_name = 'name'\n    display_attributes = ['name', 'value']\n\n    def __init__(self, resource, *args, **kwargs):\n        help_text = ('Load a list of %s from file.' %\n                     resource.get_plural_display_name().lower())\n        super(KeyValuePairLoadCommand, self).__init__(resource, 'load',\n            help_text, *args, **kwargs)\n\n        self.parser.add_argument(\n            'file', help=('JSON file containing the %s to create.'\n                          % resource.get_plural_display_name().lower()))\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        file_path = os.path.normpath(pjoin(os.getcwd(), args.file))\n\n        if not os.path.exists(args.file):\n            raise ValueError('File \"%s\" doesn\\'t exist' % (file_path))\n\n        if not os.path.isfile(args.file):\n            raise ValueError('\"%s\" is not a file' % (file_path))\n\n        with open(file_path, 'r') as f:\n            kvps = json.loads(f.read())\n\n        instances = []\n        for item in kvps:\n            name = item['name']\n            value = item['value']\n\n            instance = KeyValuePair()\n            instance.id = name  # TODO: refactor and get rid of id\n            instance.name = name\n            instance.value = value\n\n            self.manager.update(instance, **kwargs)\n            instances.append(instance)\n        return instances\n\n    def run_and_print(self, args, **kwargs):\n        instances = self.run(args, **kwargs)\n        self.print_output(instances, table.MultiColumnTable,\n                          attributes=['id', 'name', 'value'], json=args.json, yaml=args.yaml)\n", "path": "st2client/st2client/commands/keyvalue.py"}], "after_files": [{"content": "# Licensed to the StackStorm, Inc ('StackStorm') under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport json\nimport logging\nfrom os.path import join as pjoin\n\nfrom st2client.commands import resource\nfrom st2client.commands.noop import NoopCommand\nfrom st2client.commands.resource import add_auth_token_to_kwargs_from_cli\nfrom st2client.formatters import table\nfrom st2client.models.keyvalue import KeyValuePair\nfrom st2client.utils.date import format_isodate_for_user_timezone\n\nLOG = logging.getLogger(__name__)\n\nDEFAULT_SCOPE = 'system'\n\n\nclass KeyValuePairBranch(resource.ResourceBranch):\n\n    def __init__(self, description, app, subparsers, parent_parser=None):\n        super(KeyValuePairBranch, self).__init__(\n            KeyValuePair, description, app, subparsers,\n            parent_parser=parent_parser,\n            commands={\n                'list': KeyValuePairListCommand,\n                'get': KeyValuePairGetCommand,\n                'delete': KeyValuePairDeleteCommand,\n                'create': NoopCommand,\n                'update': NoopCommand\n            })\n\n        # Registers extended commands\n        self.commands['set'] = KeyValuePairSetCommand(self.resource, self.app,\n                                                      self.subparsers)\n        self.commands['load'] = KeyValuePairLoadCommand(\n            self.resource, self.app, self.subparsers)\n        self.commands['delete_by_prefix'] = KeyValuePairDeleteByPrefixCommand(\n            self.resource, self.app, self.subparsers)\n\n        # Remove unsupported commands\n        # TODO: Refactor parent class and make it nicer\n        del self.commands['create']\n        del self.commands['update']\n\n\nclass KeyValuePairListCommand(resource.ResourceListCommand):\n    display_attributes = ['name', 'value', 'secret', 'encrypted', 'scope', 'user',\n                          'expire_timestamp']\n    attribute_transform_functions = {\n        'expire_timestamp': format_isodate_for_user_timezone,\n    }\n\n    def __init__(self, *args, **kwargs):\n        super(KeyValuePairListCommand, self).__init__(*args, **kwargs)\n\n        # Filter options\n        self.parser.add_argument('--prefix', help=('Only return values which name starts with the '\n                                                   ' provided prefix.'))\n        self.parser.add_argument('--decrypt', action='store_true',\n                                 help='Decrypt secrets and display plain text.')\n        self.parser.add_argument('-s', '--scope', default='system', dest='scope',\n                                 help='Scope item is under. Example: \"user\".')\n        self.parser.add_argument('-u', '--user', dest='user', default=None,\n                                 help='User for user scoped items (admin only).')\n\n    def run_and_print(self, args, **kwargs):\n        if args.prefix:\n            kwargs['prefix'] = args.prefix\n\n        decrypt = getattr(args, 'decrypt', False)\n        kwargs['params'] = {'decrypt': str(decrypt).lower()}\n        scope = getattr(args, 'scope', DEFAULT_SCOPE)\n        kwargs['params']['scope'] = scope\n        kwargs['params']['user'] = args.user\n\n        instances = self.run(args, **kwargs)\n        self.print_output(reversed(instances), table.MultiColumnTable,\n                          attributes=args.attr, widths=args.width,\n                          json=args.json,\n                          yaml=args.yaml,\n                          attribute_transform_functions=self.attribute_transform_functions)\n\n\nclass KeyValuePairGetCommand(resource.ResourceGetCommand):\n    pk_argument_name = 'name'\n    display_attributes = ['name', 'value', 'secret', 'encrypted', 'scope', 'expire_timestamp']\n\n    def __init__(self, kv_resource, *args, **kwargs):\n        super(KeyValuePairGetCommand, self).__init__(kv_resource, *args, **kwargs)\n        self.parser.add_argument('-d', '--decrypt', action='store_true',\n                                 help='Decrypt secret if encrypted and show plain text.')\n        self.parser.add_argument('-s', '--scope', default=DEFAULT_SCOPE, dest='scope',\n                                 help='Scope item is under. Example: \"user\".')\n\n    @resource.add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        resource_name = getattr(args, self.pk_argument_name, None)\n        decrypt = getattr(args, 'decrypt', False)\n        scope = getattr(args, 'scope', DEFAULT_SCOPE)\n        kwargs['params'] = {'decrypt': str(decrypt).lower()}\n        kwargs['params']['scope'] = scope\n        return self.get_resource_by_id(id=resource_name, **kwargs)\n\n\nclass KeyValuePairSetCommand(resource.ResourceCommand):\n    display_attributes = ['name', 'value', 'expire_timestamp']\n\n    def __init__(self, resource, *args, **kwargs):\n        super(KeyValuePairSetCommand, self).__init__(\n            resource, 'set',\n            'Set an existing %s.' % resource.get_display_name().lower(),\n            *args, **kwargs\n        )\n\n        self.parser.add_argument('name',\n                                 metavar='name',\n                                 help='Name of the key value pair.')\n        self.parser.add_argument('value', help='Value paired with the key.')\n        self.parser.add_argument('-l', '--ttl', dest='ttl', type=int, default=None,\n                                 help='TTL (in seconds) for this value.')\n        self.parser.add_argument('-e', '--encrypt', dest='secret',\n                                 action='store_true',\n                                 help='Encrypt value before saving the value.')\n        self.parser.add_argument('-s', '--scope', dest='scope', default=DEFAULT_SCOPE,\n                                 help='Specify the scope under which you want ' +\n                                      'to place the item.')\n        self.parser.add_argument('-u', '--user', dest='user', default=None,\n                                 help='User for user scoped items (admin only).')\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        instance = KeyValuePair()\n        instance.id = args.name  # TODO: refactor and get rid of id\n        instance.name = args.name\n        instance.value = args.value\n        instance.scope = args.scope\n        instance.user = args.user\n\n        if args.secret:\n            instance.secret = args.secret\n\n        if args.ttl:\n            instance.ttl = args.ttl\n\n        return self.manager.update(instance, **kwargs)\n\n    def run_and_print(self, args, **kwargs):\n        instance = self.run(args, **kwargs)\n        self.print_output(instance, table.PropertyValueTable,\n                          attributes=self.display_attributes, json=args.json,\n                          yaml=args.yaml)\n\n\nclass KeyValuePairDeleteCommand(resource.ResourceDeleteCommand):\n    pk_argument_name = 'name'\n\n    def __init__(self, resource, *args, **kwargs):\n        super(KeyValuePairDeleteCommand, self).__init__(resource, *args, **kwargs)\n\n        self.parser.add_argument('-s', '--scope', dest='scope', default=DEFAULT_SCOPE,\n                                 help='Specify the scope under which you want ' +\n                                      'to place the item.')\n        self.parser.add_argument('-u', '--user', dest='user', default=None,\n                                 help='User for user scoped items (admin only).')\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        resource_id = getattr(args, self.pk_argument_name, None)\n        scope = getattr(args, 'scope', DEFAULT_SCOPE)\n        kwargs['params'] = {}\n        kwargs['params']['scope'] = scope\n        kwargs['params']['user'] = args.user\n        instance = self.get_resource(resource_id, **kwargs)\n\n        if not instance:\n            raise resource.ResourceNotFoundError('KeyValuePair with id \"%s\" not found', resource_id)\n\n        instance.id = resource_id  # TODO: refactor and get rid of id\n        self.manager.delete(instance, **kwargs)\n\n\nclass KeyValuePairDeleteByPrefixCommand(resource.ResourceCommand):\n    \"\"\"\n    Commands which delete all the key value pairs which match the provided\n    prefix.\n    \"\"\"\n    def __init__(self, resource, *args, **kwargs):\n        super(KeyValuePairDeleteByPrefixCommand, self).__init__(resource, 'delete_by_prefix',\n            'Delete KeyValue pairs which match the provided prefix', *args, **kwargs)\n\n        self.parser.add_argument('-p', '--prefix', required=True,\n                                 help='Name prefix (e.g. twitter.TwitterSensor:)')\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        prefix = args.prefix\n        key_pairs = self.manager.get_all(prefix=prefix)\n\n        to_delete = []\n        for key_pair in key_pairs:\n            key_pair.id = key_pair.name\n            to_delete.append(key_pair)\n\n        deleted = []\n        for key_pair in to_delete:\n            self.manager.delete(instance=key_pair, **kwargs)\n            deleted.append(key_pair)\n\n        return deleted\n\n    def run_and_print(self, args, **kwargs):\n        # TODO: Need to use args, instead of kwargs (args=) because of bad API\n        # FIX ME\n        deleted = self.run(args, **kwargs)\n        key_ids = [key_pair.id for key_pair in deleted]\n\n        print('Deleted %s keys' % (len(deleted)))\n        print('Deleted key ids: %s' % (', '.join(key_ids)))\n\n\nclass KeyValuePairLoadCommand(resource.ResourceCommand):\n    pk_argument_name = 'name'\n    display_attributes = ['name', 'value']\n\n    def __init__(self, resource, *args, **kwargs):\n        help_text = ('Load a list of %s from file.' %\n                     resource.get_plural_display_name().lower())\n        super(KeyValuePairLoadCommand, self).__init__(resource, 'load',\n            help_text, *args, **kwargs)\n\n        self.parser.add_argument(\n            'file', help=('JSON file containing the %s to create.'\n                          % resource.get_plural_display_name().lower()))\n\n    @add_auth_token_to_kwargs_from_cli\n    def run(self, args, **kwargs):\n        file_path = os.path.normpath(pjoin(os.getcwd(), args.file))\n\n        if not os.path.exists(args.file):\n            raise ValueError('File \"%s\" doesn\\'t exist' % (file_path))\n\n        if not os.path.isfile(args.file):\n            raise ValueError('\"%s\" is not a file' % (file_path))\n\n        with open(file_path, 'r') as f:\n            kvps = json.loads(f.read())\n\n        instances = []\n        for item in kvps:\n            name = item['name']\n            value = item['value']\n\n            instance = KeyValuePair()\n            instance.id = name  # TODO: refactor and get rid of id\n            instance.name = name\n            instance.value = value\n\n            self.manager.update(instance, **kwargs)\n            instances.append(instance)\n        return instances\n\n    def run_and_print(self, args, **kwargs):\n        instances = self.run(args, **kwargs)\n        self.print_output(instances, table.MultiColumnTable,\n                          attributes=['id', 'name', 'value'], json=args.json, yaml=args.yaml)\n", "path": "st2client/st2client/commands/keyvalue.py"}]}