We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Dynamodb has_item causes scan problems
Calling `has_item` for an item that doesn't exist, and then calling `scan()` causes `AttributeError: 'dict' object has no attribute 'attrs'`

Example of behaviour that causes this:

``` python
from moto import mock_dynamodb
import boto


with mock_dynamodb():
    conn = boto.connect_dynamodb()
    table = conn.create_table(
        name='mytable',
        schema=conn.create_schema(
            hash_key_name='name',
            hash_key_proto_value=str,
        ),
        read_units=1,
        write_units=1
    )
    print(list(table.scan()))
    table.has_item('something')
    print(list(table.scan()))
```

`has_item` calls down to `Table.get_item` in `dynamodb/models.py`. This accesses `self.items`, which is a `defaultdict` whose default value is an empty dict. This results in an empty dict being set in `self.items`. The `scan()` call in `dynamodb/responses.py` does not handle dicts (or anything other than an Item)

Replacing the error line in `dynamodb/responses.py` with the following code appears to work:

``` python
"Items": [item.attrs for item in items if item],
```

I'm not very familiar with this library (only started using it today) but happy to submit a PR if that seems like the right thing to do.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `moto/dynamodb/responses.py`
Content:
```
1 from __future__ import unicode_literals
2 import json
3 import six
4 
5 from moto.core.responses import BaseResponse
6 from moto.core.utils import camelcase_to_underscores
7 from .models import dynamodb_backend, dynamo_json_dump
8 
9 
10 GET_SESSION_TOKEN_RESULT = """
11 <GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
12  <GetSessionTokenResult>
13  <Credentials>
14  <SessionToken>
15  AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/L
16  To6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3z
17  rkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtp
18  Z3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE
19  </SessionToken>
20  <SecretAccessKey>
21  wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY
22  </SecretAccessKey>
23  <Expiration>2011-07-11T19:55:29.611Z</Expiration>
24  <AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>
25  </Credentials>
26  </GetSessionTokenResult>
27  <ResponseMetadata>
28  <RequestId>58c5dbae-abef-11e0-8cfe-09039844ac7d</RequestId>
29  </ResponseMetadata>
30 </GetSessionTokenResponse>"""
31 
32 
33 def sts_handler():
34     return GET_SESSION_TOKEN_RESULT
35 
36 
37 class DynamoHandler(BaseResponse):
38 
39     def get_endpoint_name(self, headers):
40         """Parses request headers and extracts part od the X-Amz-Target
41         that corresponds to a method of DynamoHandler
42 
43         ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables
44         """
45         # Headers are case-insensitive. Probably a better way to do this.
46         match = headers.get('x-amz-target') or headers.get('X-Amz-Target')
47         if match:
48             return match.split(".")[1]
49 
50     def error(self, type_, status=400):
51         return status, self.response_headers, dynamo_json_dump({'__type': type_})
52 
53     def call_action(self):
54         body = self.body.decode('utf-8')
55         if 'GetSessionToken' in body:
56             return 200, self.response_headers, sts_handler()
57 
58         self.body = json.loads(body or '{}')
59         endpoint = self.get_endpoint_name(self.headers)
60         if endpoint:
61             endpoint = camelcase_to_underscores(endpoint)
62             response = getattr(self, endpoint)()
63             if isinstance(response, six.string_types):
64                 return 200, self.response_headers, response
65 
66             else:
67                 status_code, new_headers, response_content = response
68                 self.response_headers.update(new_headers)
69                 return status_code, self.response_headers, response_content
70         else:
71             return 404, self.response_headers, ""
72 
73     def list_tables(self):
74         body = self.body
75         limit = body.get('Limit')
76         if body.get("ExclusiveStartTableName"):
77             last = body.get("ExclusiveStartTableName")
78             start = list(dynamodb_backend.tables.keys()).index(last) + 1
79         else:
80             start = 0
81         all_tables = list(dynamodb_backend.tables.keys())
82         if limit:
83             tables = all_tables[start:start + limit]
84         else:
85             tables = all_tables[start:]
86         response = {"TableNames": tables}
87         if limit and len(all_tables) > start + limit:
88             response["LastEvaluatedTableName"] = tables[-1]
89         return dynamo_json_dump(response)
90 
91     def create_table(self):
92         body = self.body
93         name = body['TableName']
94 
95         key_schema = body['KeySchema']
96         hash_hey = key_schema['HashKeyElement']
97         hash_key_attr = hash_hey['AttributeName']
98         hash_key_type = hash_hey['AttributeType']
99 
100         range_hey = key_schema.get('RangeKeyElement', {})
101         range_key_attr = range_hey.get('AttributeName')
102         range_key_type = range_hey.get('AttributeType')
103 
104         throughput = body["ProvisionedThroughput"]
105         read_units = throughput["ReadCapacityUnits"]
106         write_units = throughput["WriteCapacityUnits"]
107 
108         table = dynamodb_backend.create_table(
109             name,
110             hash_key_attr=hash_key_attr,
111             hash_key_type=hash_key_type,
112             range_key_attr=range_key_attr,
113             range_key_type=range_key_type,
114             read_capacity=int(read_units),
115             write_capacity=int(write_units),
116         )
117         return dynamo_json_dump(table.describe)
118 
119     def delete_table(self):
120         name = self.body['TableName']
121         table = dynamodb_backend.delete_table(name)
122         if table:
123             return dynamo_json_dump(table.describe)
124         else:
125             er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'
126             return self.error(er)
127 
128     def update_table(self):
129         name = self.body['TableName']
130         throughput = self.body["ProvisionedThroughput"]
131         new_read_units = throughput["ReadCapacityUnits"]
132         new_write_units = throughput["WriteCapacityUnits"]
133         table = dynamodb_backend.update_table_throughput(name, new_read_units, new_write_units)
134         return dynamo_json_dump(table.describe)
135 
136     def describe_table(self):
137         name = self.body['TableName']
138         try:
139             table = dynamodb_backend.tables[name]
140         except KeyError:
141             er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'
142             return self.error(er)
143         return dynamo_json_dump(table.describe)
144 
145     def put_item(self):
146         name = self.body['TableName']
147         item = self.body['Item']
148         result = dynamodb_backend.put_item(name, item)
149         if result:
150             item_dict = result.to_json()
151             item_dict['ConsumedCapacityUnits'] = 1
152             return dynamo_json_dump(item_dict)
153         else:
154             er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'
155             return self.error(er)
156 
157     def batch_write_item(self):
158         table_batches = self.body['RequestItems']
159 
160         for table_name, table_requests in table_batches.items():
161             for table_request in table_requests:
162                 request_type = list(table_request)[0]
163                 request = list(table_request.values())[0]
164 
165                 if request_type == 'PutRequest':
166                     item = request['Item']
167                     dynamodb_backend.put_item(table_name, item)
168                 elif request_type == 'DeleteRequest':
169                     key = request['Key']
170                     hash_key = key['HashKeyElement']
171                     range_key = key.get('RangeKeyElement')
172                     item = dynamodb_backend.delete_item(table_name, hash_key, range_key)
173 
174         response = {
175             "Responses": {
176                 "Thread": {
177                     "ConsumedCapacityUnits": 1.0
178                 },
179                 "Reply": {
180                     "ConsumedCapacityUnits": 1.0
181                 }
182             },
183             "UnprocessedItems": {}
184         }
185 
186         return dynamo_json_dump(response)
187 
188     def get_item(self):
189         name = self.body['TableName']
190         key = self.body['Key']
191         hash_key = key['HashKeyElement']
192         range_key = key.get('RangeKeyElement')
193         attrs_to_get = self.body.get('AttributesToGet')
194         try:
195             item = dynamodb_backend.get_item(name, hash_key, range_key)
196         except ValueError:
197             er = 'com.amazon.coral.validate#ValidationException'
198             return self.error(er, status=400)
199         if item:
200             item_dict = item.describe_attrs(attrs_to_get)
201             item_dict['ConsumedCapacityUnits'] = 0.5
202             return dynamo_json_dump(item_dict)
203         else:
204             # Item not found
205             er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'
206             return self.error(er, status=404)
207 
208     def batch_get_item(self):
209         table_batches = self.body['RequestItems']
210 
211         results = {
212             "Responses": {
213                 "UnprocessedKeys": {}
214             }
215         }
216 
217         for table_name, table_request in table_batches.items():
218             items = []
219             keys = table_request['Keys']
220             attributes_to_get = table_request.get('AttributesToGet')
221             for key in keys:
222                 hash_key = key["HashKeyElement"]
223                 range_key = key.get("RangeKeyElement")
224                 item = dynamodb_backend.get_item(table_name, hash_key, range_key)
225                 if item:
226                     item_describe = item.describe_attrs(attributes_to_get)
227                     items.append(item_describe)
228             results["Responses"][table_name] = {"Items": items, "ConsumedCapacityUnits": 1}
229         return dynamo_json_dump(results)
230 
231     def query(self):
232         name = self.body['TableName']
233         hash_key = self.body['HashKeyValue']
234         range_condition = self.body.get('RangeKeyCondition')
235         if range_condition:
236             range_comparison = range_condition['ComparisonOperator']
237             range_values = range_condition['AttributeValueList']
238         else:
239             range_comparison = None
240             range_values = []
241 
242         items, last_page = dynamodb_backend.query(name, hash_key, range_comparison, range_values)
243 
244         if items is None:
245             er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'
246             return self.error(er)
247 
248         result = {
249             "Count": len(items),
250             "Items": [item.attrs for item in items],
251             "ConsumedCapacityUnits": 1,
252         }
253 
254         # Implement this when we do pagination
255         # if not last_page:
256         #     result["LastEvaluatedKey"] = {
257         #         "HashKeyElement": items[-1].hash_key,
258         #         "RangeKeyElement": items[-1].range_key,
259         #     }
260         return dynamo_json_dump(result)
261 
262     def scan(self):
263         name = self.body['TableName']
264 
265         filters = {}
266         scan_filters = self.body.get('ScanFilter', {})
267         for attribute_name, scan_filter in scan_filters.items():
268             # Keys are attribute names. Values are tuples of (comparison, comparison_value)
269             comparison_operator = scan_filter["ComparisonOperator"]
270             comparison_values = scan_filter.get("AttributeValueList", [])
271             filters[attribute_name] = (comparison_operator, comparison_values)
272 
273         items, scanned_count, last_page = dynamodb_backend.scan(name, filters)
274 
275         if items is None:
276             er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'
277             return self.error(er)
278 
279         result = {
280             "Count": len(items),
281             "Items": [item.attrs for item in items],
282             "ConsumedCapacityUnits": 1,
283             "ScannedCount": scanned_count
284         }
285 
286         # Implement this when we do pagination
287         # if not last_page:
288         #     result["LastEvaluatedKey"] = {
289         #         "HashKeyElement": items[-1].hash_key,
290         #         "RangeKeyElement": items[-1].range_key,
291         #     }
292         return dynamo_json_dump(result)
293 
294     def delete_item(self):
295         name = self.body['TableName']
296         key = self.body['Key']
297         hash_key = key['HashKeyElement']
298         range_key = key.get('RangeKeyElement')
299         return_values = self.body.get('ReturnValues', '')
300         item = dynamodb_backend.delete_item(name, hash_key, range_key)
301         if item:
302             if return_values == 'ALL_OLD':
303                 item_dict = item.to_json()
304             else:
305                 item_dict = {'Attributes': []}
306             item_dict['ConsumedCapacityUnits'] = 0.5
307             return dynamo_json_dump(item_dict)
308         else:
309             er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'
310             return self.error(er)
311
```
--- 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/moto/dynamodb/responses.py b/moto/dynamodb/responses.py
--- a/moto/dynamodb/responses.py
+++ b/moto/dynamodb/responses.py
@@ -278,7 +278,7 @@
 
         result = {
             "Count": len(items),
-            "Items": [item.attrs for item in items],
+            "Items": [item.attrs for item in items if item],
             "ConsumedCapacityUnits": 1,
             "ScannedCount": scanned_count
         }

{"golden_diff": "diff --git a/moto/dynamodb/responses.py b/moto/dynamodb/responses.py\n--- a/moto/dynamodb/responses.py\n+++ b/moto/dynamodb/responses.py\n@@ -278,7 +278,7 @@\n \n         result = {\n             \"Count\": len(items),\n-            \"Items\": [item.attrs for item in items],\n+            \"Items\": [item.attrs for item in items if item],\n             \"ConsumedCapacityUnits\": 1,\n             \"ScannedCount\": scanned_count\n         }\n", "issue": "Dynamodb has_item causes scan problems\nCalling `has_item` for an item that doesn't exist, and then calling `scan()` causes `AttributeError: 'dict' object has no attribute 'attrs'`\n\nExample of behaviour that causes this:\n\n``` python\nfrom moto import mock_dynamodb\nimport boto\n\n\nwith mock_dynamodb():\n    conn = boto.connect_dynamodb()\n    table = conn.create_table(\n        name='mytable',\n        schema=conn.create_schema(\n            hash_key_name='name',\n            hash_key_proto_value=str,\n        ),\n        read_units=1,\n        write_units=1\n    )\n    print(list(table.scan()))\n    table.has_item('something')\n    print(list(table.scan()))\n```\n\n`has_item` calls down to `Table.get_item` in `dynamodb/models.py`. This accesses `self.items`, which is a `defaultdict` whose default value is an empty dict. This results in an empty dict being set in `self.items`. The `scan()` call in `dynamodb/responses.py` does not handle dicts (or anything other than an Item)\n\nReplacing the error line in `dynamodb/responses.py` with the following code appears to work:\n\n``` python\n\"Items\": [item.attrs for item in items if item],\n```\n\nI'm not very familiar with this library (only started using it today) but happy to submit a PR if that seems like the right thing to do.\n\n", "before_files": [{"content": "from __future__ import unicode_literals\nimport json\nimport six\n\nfrom moto.core.responses import BaseResponse\nfrom moto.core.utils import camelcase_to_underscores\nfrom .models import dynamodb_backend, dynamo_json_dump\n\n\nGET_SESSION_TOKEN_RESULT = \"\"\"\n<GetSessionTokenResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\">\n <GetSessionTokenResult>\n <Credentials>\n <SessionToken>\n AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/L\n To6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3z\n rkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtp\n Z3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE\n </SessionToken>\n <SecretAccessKey>\n wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY\n </SecretAccessKey>\n <Expiration>2011-07-11T19:55:29.611Z</Expiration>\n <AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>\n </Credentials>\n </GetSessionTokenResult>\n <ResponseMetadata>\n <RequestId>58c5dbae-abef-11e0-8cfe-09039844ac7d</RequestId>\n </ResponseMetadata>\n</GetSessionTokenResponse>\"\"\"\n\n\ndef sts_handler():\n    return GET_SESSION_TOKEN_RESULT\n\n\nclass DynamoHandler(BaseResponse):\n\n    def get_endpoint_name(self, headers):\n        \"\"\"Parses request headers and extracts part od the X-Amz-Target\n        that corresponds to a method of DynamoHandler\n\n        ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables\n        \"\"\"\n        # Headers are case-insensitive. Probably a better way to do this.\n        match = headers.get('x-amz-target') or headers.get('X-Amz-Target')\n        if match:\n            return match.split(\".\")[1]\n\n    def error(self, type_, status=400):\n        return status, self.response_headers, dynamo_json_dump({'__type': type_})\n\n    def call_action(self):\n        body = self.body.decode('utf-8')\n        if 'GetSessionToken' in body:\n            return 200, self.response_headers, sts_handler()\n\n        self.body = json.loads(body or '{}')\n        endpoint = self.get_endpoint_name(self.headers)\n        if endpoint:\n            endpoint = camelcase_to_underscores(endpoint)\n            response = getattr(self, endpoint)()\n            if isinstance(response, six.string_types):\n                return 200, self.response_headers, response\n\n            else:\n                status_code, new_headers, response_content = response\n                self.response_headers.update(new_headers)\n                return status_code, self.response_headers, response_content\n        else:\n            return 404, self.response_headers, \"\"\n\n    def list_tables(self):\n        body = self.body\n        limit = body.get('Limit')\n        if body.get(\"ExclusiveStartTableName\"):\n            last = body.get(\"ExclusiveStartTableName\")\n            start = list(dynamodb_backend.tables.keys()).index(last) + 1\n        else:\n            start = 0\n        all_tables = list(dynamodb_backend.tables.keys())\n        if limit:\n            tables = all_tables[start:start + limit]\n        else:\n            tables = all_tables[start:]\n        response = {\"TableNames\": tables}\n        if limit and len(all_tables) > start + limit:\n            response[\"LastEvaluatedTableName\"] = tables[-1]\n        return dynamo_json_dump(response)\n\n    def create_table(self):\n        body = self.body\n        name = body['TableName']\n\n        key_schema = body['KeySchema']\n        hash_hey = key_schema['HashKeyElement']\n        hash_key_attr = hash_hey['AttributeName']\n        hash_key_type = hash_hey['AttributeType']\n\n        range_hey = key_schema.get('RangeKeyElement', {})\n        range_key_attr = range_hey.get('AttributeName')\n        range_key_type = range_hey.get('AttributeType')\n\n        throughput = body[\"ProvisionedThroughput\"]\n        read_units = throughput[\"ReadCapacityUnits\"]\n        write_units = throughput[\"WriteCapacityUnits\"]\n\n        table = dynamodb_backend.create_table(\n            name,\n            hash_key_attr=hash_key_attr,\n            hash_key_type=hash_key_type,\n            range_key_attr=range_key_attr,\n            range_key_type=range_key_type,\n            read_capacity=int(read_units),\n            write_capacity=int(write_units),\n        )\n        return dynamo_json_dump(table.describe)\n\n    def delete_table(self):\n        name = self.body['TableName']\n        table = dynamodb_backend.delete_table(name)\n        if table:\n            return dynamo_json_dump(table.describe)\n        else:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n    def update_table(self):\n        name = self.body['TableName']\n        throughput = self.body[\"ProvisionedThroughput\"]\n        new_read_units = throughput[\"ReadCapacityUnits\"]\n        new_write_units = throughput[\"WriteCapacityUnits\"]\n        table = dynamodb_backend.update_table_throughput(name, new_read_units, new_write_units)\n        return dynamo_json_dump(table.describe)\n\n    def describe_table(self):\n        name = self.body['TableName']\n        try:\n            table = dynamodb_backend.tables[name]\n        except KeyError:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n        return dynamo_json_dump(table.describe)\n\n    def put_item(self):\n        name = self.body['TableName']\n        item = self.body['Item']\n        result = dynamodb_backend.put_item(name, item)\n        if result:\n            item_dict = result.to_json()\n            item_dict['ConsumedCapacityUnits'] = 1\n            return dynamo_json_dump(item_dict)\n        else:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n    def batch_write_item(self):\n        table_batches = self.body['RequestItems']\n\n        for table_name, table_requests in table_batches.items():\n            for table_request in table_requests:\n                request_type = list(table_request)[0]\n                request = list(table_request.values())[0]\n\n                if request_type == 'PutRequest':\n                    item = request['Item']\n                    dynamodb_backend.put_item(table_name, item)\n                elif request_type == 'DeleteRequest':\n                    key = request['Key']\n                    hash_key = key['HashKeyElement']\n                    range_key = key.get('RangeKeyElement')\n                    item = dynamodb_backend.delete_item(table_name, hash_key, range_key)\n\n        response = {\n            \"Responses\": {\n                \"Thread\": {\n                    \"ConsumedCapacityUnits\": 1.0\n                },\n                \"Reply\": {\n                    \"ConsumedCapacityUnits\": 1.0\n                }\n            },\n            \"UnprocessedItems\": {}\n        }\n\n        return dynamo_json_dump(response)\n\n    def get_item(self):\n        name = self.body['TableName']\n        key = self.body['Key']\n        hash_key = key['HashKeyElement']\n        range_key = key.get('RangeKeyElement')\n        attrs_to_get = self.body.get('AttributesToGet')\n        try:\n            item = dynamodb_backend.get_item(name, hash_key, range_key)\n        except ValueError:\n            er = 'com.amazon.coral.validate#ValidationException'\n            return self.error(er, status=400)\n        if item:\n            item_dict = item.describe_attrs(attrs_to_get)\n            item_dict['ConsumedCapacityUnits'] = 0.5\n            return dynamo_json_dump(item_dict)\n        else:\n            # Item not found\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er, status=404)\n\n    def batch_get_item(self):\n        table_batches = self.body['RequestItems']\n\n        results = {\n            \"Responses\": {\n                \"UnprocessedKeys\": {}\n            }\n        }\n\n        for table_name, table_request in table_batches.items():\n            items = []\n            keys = table_request['Keys']\n            attributes_to_get = table_request.get('AttributesToGet')\n            for key in keys:\n                hash_key = key[\"HashKeyElement\"]\n                range_key = key.get(\"RangeKeyElement\")\n                item = dynamodb_backend.get_item(table_name, hash_key, range_key)\n                if item:\n                    item_describe = item.describe_attrs(attributes_to_get)\n                    items.append(item_describe)\n            results[\"Responses\"][table_name] = {\"Items\": items, \"ConsumedCapacityUnits\": 1}\n        return dynamo_json_dump(results)\n\n    def query(self):\n        name = self.body['TableName']\n        hash_key = self.body['HashKeyValue']\n        range_condition = self.body.get('RangeKeyCondition')\n        if range_condition:\n            range_comparison = range_condition['ComparisonOperator']\n            range_values = range_condition['AttributeValueList']\n        else:\n            range_comparison = None\n            range_values = []\n\n        items, last_page = dynamodb_backend.query(name, hash_key, range_comparison, range_values)\n\n        if items is None:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n        result = {\n            \"Count\": len(items),\n            \"Items\": [item.attrs for item in items],\n            \"ConsumedCapacityUnits\": 1,\n        }\n\n        # Implement this when we do pagination\n        # if not last_page:\n        #     result[\"LastEvaluatedKey\"] = {\n        #         \"HashKeyElement\": items[-1].hash_key,\n        #         \"RangeKeyElement\": items[-1].range_key,\n        #     }\n        return dynamo_json_dump(result)\n\n    def scan(self):\n        name = self.body['TableName']\n\n        filters = {}\n        scan_filters = self.body.get('ScanFilter', {})\n        for attribute_name, scan_filter in scan_filters.items():\n            # Keys are attribute names. Values are tuples of (comparison, comparison_value)\n            comparison_operator = scan_filter[\"ComparisonOperator\"]\n            comparison_values = scan_filter.get(\"AttributeValueList\", [])\n            filters[attribute_name] = (comparison_operator, comparison_values)\n\n        items, scanned_count, last_page = dynamodb_backend.scan(name, filters)\n\n        if items is None:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n        result = {\n            \"Count\": len(items),\n            \"Items\": [item.attrs for item in items],\n            \"ConsumedCapacityUnits\": 1,\n            \"ScannedCount\": scanned_count\n        }\n\n        # Implement this when we do pagination\n        # if not last_page:\n        #     result[\"LastEvaluatedKey\"] = {\n        #         \"HashKeyElement\": items[-1].hash_key,\n        #         \"RangeKeyElement\": items[-1].range_key,\n        #     }\n        return dynamo_json_dump(result)\n\n    def delete_item(self):\n        name = self.body['TableName']\n        key = self.body['Key']\n        hash_key = key['HashKeyElement']\n        range_key = key.get('RangeKeyElement')\n        return_values = self.body.get('ReturnValues', '')\n        item = dynamodb_backend.delete_item(name, hash_key, range_key)\n        if item:\n            if return_values == 'ALL_OLD':\n                item_dict = item.to_json()\n            else:\n                item_dict = {'Attributes': []}\n            item_dict['ConsumedCapacityUnits'] = 0.5\n            return dynamo_json_dump(item_dict)\n        else:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n", "path": "moto/dynamodb/responses.py"}], "after_files": [{"content": "from __future__ import unicode_literals\nimport json\nimport six\n\nfrom moto.core.responses import BaseResponse\nfrom moto.core.utils import camelcase_to_underscores\nfrom .models import dynamodb_backend, dynamo_json_dump\n\n\nGET_SESSION_TOKEN_RESULT = \"\"\"\n<GetSessionTokenResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\">\n <GetSessionTokenResult>\n <Credentials>\n <SessionToken>\n AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/L\n To6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3z\n rkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtp\n Z3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE\n </SessionToken>\n <SecretAccessKey>\n wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY\n </SecretAccessKey>\n <Expiration>2011-07-11T19:55:29.611Z</Expiration>\n <AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>\n </Credentials>\n </GetSessionTokenResult>\n <ResponseMetadata>\n <RequestId>58c5dbae-abef-11e0-8cfe-09039844ac7d</RequestId>\n </ResponseMetadata>\n</GetSessionTokenResponse>\"\"\"\n\n\ndef sts_handler():\n    return GET_SESSION_TOKEN_RESULT\n\n\nclass DynamoHandler(BaseResponse):\n\n    def get_endpoint_name(self, headers):\n        \"\"\"Parses request headers and extracts part od the X-Amz-Target\n        that corresponds to a method of DynamoHandler\n\n        ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables\n        \"\"\"\n        # Headers are case-insensitive. Probably a better way to do this.\n        match = headers.get('x-amz-target') or headers.get('X-Amz-Target')\n        if match:\n            return match.split(\".\")[1]\n\n    def error(self, type_, status=400):\n        return status, self.response_headers, dynamo_json_dump({'__type': type_})\n\n    def call_action(self):\n        body = self.body.decode('utf-8')\n        if 'GetSessionToken' in body:\n            return 200, self.response_headers, sts_handler()\n\n        self.body = json.loads(body or '{}')\n        endpoint = self.get_endpoint_name(self.headers)\n        if endpoint:\n            endpoint = camelcase_to_underscores(endpoint)\n            response = getattr(self, endpoint)()\n            if isinstance(response, six.string_types):\n                return 200, self.response_headers, response\n\n            else:\n                status_code, new_headers, response_content = response\n                self.response_headers.update(new_headers)\n                return status_code, self.response_headers, response_content\n        else:\n            return 404, self.response_headers, \"\"\n\n    def list_tables(self):\n        body = self.body\n        limit = body.get('Limit')\n        if body.get(\"ExclusiveStartTableName\"):\n            last = body.get(\"ExclusiveStartTableName\")\n            start = list(dynamodb_backend.tables.keys()).index(last) + 1\n        else:\n            start = 0\n        all_tables = list(dynamodb_backend.tables.keys())\n        if limit:\n            tables = all_tables[start:start + limit]\n        else:\n            tables = all_tables[start:]\n        response = {\"TableNames\": tables}\n        if limit and len(all_tables) > start + limit:\n            response[\"LastEvaluatedTableName\"] = tables[-1]\n        return dynamo_json_dump(response)\n\n    def create_table(self):\n        body = self.body\n        name = body['TableName']\n\n        key_schema = body['KeySchema']\n        hash_hey = key_schema['HashKeyElement']\n        hash_key_attr = hash_hey['AttributeName']\n        hash_key_type = hash_hey['AttributeType']\n\n        range_hey = key_schema.get('RangeKeyElement', {})\n        range_key_attr = range_hey.get('AttributeName')\n        range_key_type = range_hey.get('AttributeType')\n\n        throughput = body[\"ProvisionedThroughput\"]\n        read_units = throughput[\"ReadCapacityUnits\"]\n        write_units = throughput[\"WriteCapacityUnits\"]\n\n        table = dynamodb_backend.create_table(\n            name,\n            hash_key_attr=hash_key_attr,\n            hash_key_type=hash_key_type,\n            range_key_attr=range_key_attr,\n            range_key_type=range_key_type,\n            read_capacity=int(read_units),\n            write_capacity=int(write_units),\n        )\n        return dynamo_json_dump(table.describe)\n\n    def delete_table(self):\n        name = self.body['TableName']\n        table = dynamodb_backend.delete_table(name)\n        if table:\n            return dynamo_json_dump(table.describe)\n        else:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n    def update_table(self):\n        name = self.body['TableName']\n        throughput = self.body[\"ProvisionedThroughput\"]\n        new_read_units = throughput[\"ReadCapacityUnits\"]\n        new_write_units = throughput[\"WriteCapacityUnits\"]\n        table = dynamodb_backend.update_table_throughput(name, new_read_units, new_write_units)\n        return dynamo_json_dump(table.describe)\n\n    def describe_table(self):\n        name = self.body['TableName']\n        try:\n            table = dynamodb_backend.tables[name]\n        except KeyError:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n        return dynamo_json_dump(table.describe)\n\n    def put_item(self):\n        name = self.body['TableName']\n        item = self.body['Item']\n        result = dynamodb_backend.put_item(name, item)\n        if result:\n            item_dict = result.to_json()\n            item_dict['ConsumedCapacityUnits'] = 1\n            return dynamo_json_dump(item_dict)\n        else:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n    def batch_write_item(self):\n        table_batches = self.body['RequestItems']\n\n        for table_name, table_requests in table_batches.items():\n            for table_request in table_requests:\n                request_type = list(table_request)[0]\n                request = list(table_request.values())[0]\n\n                if request_type == 'PutRequest':\n                    item = request['Item']\n                    dynamodb_backend.put_item(table_name, item)\n                elif request_type == 'DeleteRequest':\n                    key = request['Key']\n                    hash_key = key['HashKeyElement']\n                    range_key = key.get('RangeKeyElement')\n                    item = dynamodb_backend.delete_item(table_name, hash_key, range_key)\n\n        response = {\n            \"Responses\": {\n                \"Thread\": {\n                    \"ConsumedCapacityUnits\": 1.0\n                },\n                \"Reply\": {\n                    \"ConsumedCapacityUnits\": 1.0\n                }\n            },\n            \"UnprocessedItems\": {}\n        }\n\n        return dynamo_json_dump(response)\n\n    def get_item(self):\n        name = self.body['TableName']\n        key = self.body['Key']\n        hash_key = key['HashKeyElement']\n        range_key = key.get('RangeKeyElement')\n        attrs_to_get = self.body.get('AttributesToGet')\n        try:\n            item = dynamodb_backend.get_item(name, hash_key, range_key)\n        except ValueError:\n            er = 'com.amazon.coral.validate#ValidationException'\n            return self.error(er, status=400)\n        if item:\n            item_dict = item.describe_attrs(attrs_to_get)\n            item_dict['ConsumedCapacityUnits'] = 0.5\n            return dynamo_json_dump(item_dict)\n        else:\n            # Item not found\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er, status=404)\n\n    def batch_get_item(self):\n        table_batches = self.body['RequestItems']\n\n        results = {\n            \"Responses\": {\n                \"UnprocessedKeys\": {}\n            }\n        }\n\n        for table_name, table_request in table_batches.items():\n            items = []\n            keys = table_request['Keys']\n            attributes_to_get = table_request.get('AttributesToGet')\n            for key in keys:\n                hash_key = key[\"HashKeyElement\"]\n                range_key = key.get(\"RangeKeyElement\")\n                item = dynamodb_backend.get_item(table_name, hash_key, range_key)\n                if item:\n                    item_describe = item.describe_attrs(attributes_to_get)\n                    items.append(item_describe)\n            results[\"Responses\"][table_name] = {\"Items\": items, \"ConsumedCapacityUnits\": 1}\n        return dynamo_json_dump(results)\n\n    def query(self):\n        name = self.body['TableName']\n        hash_key = self.body['HashKeyValue']\n        range_condition = self.body.get('RangeKeyCondition')\n        if range_condition:\n            range_comparison = range_condition['ComparisonOperator']\n            range_values = range_condition['AttributeValueList']\n        else:\n            range_comparison = None\n            range_values = []\n\n        items, last_page = dynamodb_backend.query(name, hash_key, range_comparison, range_values)\n\n        if items is None:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n        result = {\n            \"Count\": len(items),\n            \"Items\": [item.attrs for item in items],\n            \"ConsumedCapacityUnits\": 1,\n        }\n\n        # Implement this when we do pagination\n        # if not last_page:\n        #     result[\"LastEvaluatedKey\"] = {\n        #         \"HashKeyElement\": items[-1].hash_key,\n        #         \"RangeKeyElement\": items[-1].range_key,\n        #     }\n        return dynamo_json_dump(result)\n\n    def scan(self):\n        name = self.body['TableName']\n\n        filters = {}\n        scan_filters = self.body.get('ScanFilter', {})\n        for attribute_name, scan_filter in scan_filters.items():\n            # Keys are attribute names. Values are tuples of (comparison, comparison_value)\n            comparison_operator = scan_filter[\"ComparisonOperator\"]\n            comparison_values = scan_filter.get(\"AttributeValueList\", [])\n            filters[attribute_name] = (comparison_operator, comparison_values)\n\n        items, scanned_count, last_page = dynamodb_backend.scan(name, filters)\n\n        if items is None:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n\n        result = {\n            \"Count\": len(items),\n            \"Items\": [item.attrs for item in items if item],\n            \"ConsumedCapacityUnits\": 1,\n            \"ScannedCount\": scanned_count\n        }\n\n        # Implement this when we do pagination\n        # if not last_page:\n        #     result[\"LastEvaluatedKey\"] = {\n        #         \"HashKeyElement\": items[-1].hash_key,\n        #         \"RangeKeyElement\": items[-1].range_key,\n        #     }\n        return dynamo_json_dump(result)\n\n    def delete_item(self):\n        name = self.body['TableName']\n        key = self.body['Key']\n        hash_key = key['HashKeyElement']\n        range_key = key.get('RangeKeyElement')\n        return_values = self.body.get('ReturnValues', '')\n        item = dynamodb_backend.delete_item(name, hash_key, range_key)\n        if item:\n            if return_values == 'ALL_OLD':\n                item_dict = item.to_json()\n            else:\n                item_dict = {'Attributes': []}\n            item_dict['ConsumedCapacityUnits'] = 0.5\n            return dynamo_json_dump(item_dict)\n        else:\n            er = 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'\n            return self.error(er)\n", "path": "moto/dynamodb/responses.py"}]}