We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
flattenEvent() fails with "'ascii' codec can't encode character" in Python 2.7
|[<img alt="znerol's avatar" src="https://avatars.githubusercontent.com/u/23288?s=50" width="50" height="50">](https://github.com/znerol)| @znerol reported|
|-|-|
|Trac ID|trac#8699|
|Type|defect|
|Created|2016-07-28 05:59:35Z|

backtrace ends in _flatten.py

```
twisted/logger/_flatten.py(119)flattenEvent()
-> flattenedValue = conversionFunction(fieldValue)
(Pdb) conversionFunction
<type 'str'>
```

I guess conversionFunction should be unicode in Python 2.7 and str in Python 3.

<details><summary>Searchable metadata</summary>

```
trac-id__8699 8699
type__defect defect
reporter__znerol znerol
priority__normal normal
milestone__None None
branch__ 
branch_author__ 
status__closed closed
resolution__fixed fixed
component__core core
keywords__None None
time__1469685575533160 1469685575533160
changetime__1470085969851774 1470085969851774
version__None None
owner__Craig_Rodrigues__rodrigc_____ Craig Rodrigues <rodrigc@...>

```
</details>


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `twisted/logger/_flatten.py`
Content:
```
1 # -*- test-case-name: twisted.logger.test.test_flatten -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
4 
5 """
6 Code related to "flattening" events; that is, extracting a description of all
7 relevant fields from the format string and persisting them for later
8 examination.
9 """
10 
11 from string import Formatter
12 from collections import defaultdict
13 
14 from twisted.python.compat import unicode
15 
16 aFormatter = Formatter()
17 
18 
19 
20 class KeyFlattener(object):
21     """
22     A L{KeyFlattener} computes keys for the things within curly braces in
23     PEP-3101-style format strings as parsed by L{string.Formatter.parse}.
24     """
25 
26     def __init__(self):
27         """
28         Initialize a L{KeyFlattener}.
29         """
30         self.keys = defaultdict(lambda: 0)
31 
32 
33     def flatKey(self, fieldName, formatSpec, conversion):
34         """
35         Compute a string key for a given field/format/conversion.
36 
37         @param fieldName: A format field name.
38         @type fieldName: L{str}
39 
40         @param formatSpec: A format spec.
41         @type formatSpec: L{str}
42 
43         @param conversion: A format field conversion type.
44         @type conversion: L{str}
45 
46         @return: A key specific to the given field, format and conversion, as
47             well as the occurrence of that combination within this
48             L{KeyFlattener}'s lifetime.
49         @rtype: L{str}
50         """
51         result = (
52             "{fieldName}!{conversion}:{formatSpec}"
53             .format(
54                 fieldName=fieldName,
55                 formatSpec=(formatSpec or ""),
56                 conversion=(conversion or ""),
57             )
58         )
59         self.keys[result] += 1
60         n = self.keys[result]
61         if n != 1:
62             result += "/" + str(self.keys[result])
63         return result
64 
65 
66 
67 def flattenEvent(event):
68     """
69     Flatten the given event by pre-associating format fields with specific
70     objects and callable results in a L{dict} put into the C{"log_flattened"}
71     key in the event.
72 
73     @param event: A logging event.
74     @type event: L{dict}
75     """
76     if "log_format" not in event:
77         return
78 
79     if "log_flattened" in event:
80         fields = event["log_flattened"]
81     else:
82         fields = {}
83 
84     keyFlattener = KeyFlattener()
85 
86     for (literalText, fieldName, formatSpec, conversion) in (
87         aFormatter.parse(event["log_format"])
88     ):
89         if fieldName is None:
90             continue
91 
92         if conversion != "r":
93             conversion = "s"
94 
95         flattenedKey = keyFlattener.flatKey(fieldName, formatSpec, conversion)
96         structuredKey = keyFlattener.flatKey(fieldName, formatSpec, "")
97 
98         if flattenedKey in fields:
99             # We've already seen and handled this key
100             continue
101 
102         if fieldName.endswith(u"()"):
103             fieldName = fieldName[:-2]
104             callit = True
105         else:
106             callit = False
107 
108         field = aFormatter.get_field(fieldName, (), event)
109         fieldValue = field[0]
110 
111         if conversion == "r":
112             conversionFunction = repr
113         else:  # Above: if conversion is not "r", it's "s"
114             conversionFunction = str
115 
116         if callit:
117             fieldValue = fieldValue()
118 
119         flattenedValue = conversionFunction(fieldValue)
120         fields[flattenedKey] = flattenedValue
121         fields[structuredKey] = fieldValue
122 
123     if fields:
124         event["log_flattened"] = fields
125 
126 
127 
128 def extractField(field, event):
129     """
130     Extract a given format field from the given event.
131 
132     @param field: A string describing a format field or log key.  This is the
133         text that would normally fall between a pair of curly braces in a
134         format string: for example, C{"key[2].attribute"}.  If a conversion is
135         specified (the thing after the C{"!"} character in a format field) then
136         the result will always be L{unicode}.
137     @type field: L{str} (native string)
138 
139     @param event: A log event.
140     @type event: L{dict}
141 
142     @return: A value extracted from the field.
143     @rtype: L{object}
144 
145     @raise KeyError: if the field is not found in the given event.
146     """
147     keyFlattener = KeyFlattener()
148     [[literalText, fieldName, formatSpec, conversion]] = aFormatter.parse(
149         "{" + field + "}"
150     )
151     key = keyFlattener.flatKey(fieldName, formatSpec, conversion)
152     if "log_flattened" not in event:
153         flattenEvent(event)
154     return event["log_flattened"][key]
155 
156 
157 
158 def flatFormat(event):
159     """
160     Format an event which has been flattened with L{flattenEvent}.
161 
162     @param event: A logging event.
163     @type event: L{dict}
164 
165     @return: A formatted string.
166     @rtype: L{unicode}
167     """
168     fieldValues = event["log_flattened"]
169     s = []
170     keyFlattener = KeyFlattener()
171     formatFields = aFormatter.parse(event["log_format"])
172     for literalText, fieldName, formatSpec, conversion in formatFields:
173         s.append(literalText)
174         if fieldName is not None:
175             key = keyFlattener.flatKey(
176                     fieldName, formatSpec, conversion or "s")
177             s.append(unicode(fieldValues[key]))
178     return u"".join(s)
179
```
--- 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/twisted/logger/_flatten.py b/twisted/logger/_flatten.py
--- a/twisted/logger/_flatten.py
+++ b/twisted/logger/_flatten.py
@@ -111,7 +111,7 @@
         if conversion == "r":
             conversionFunction = repr
         else:  # Above: if conversion is not "r", it's "s"
-            conversionFunction = str
+            conversionFunction = unicode
 
         if callit:
             fieldValue = fieldValue()

{"golden_diff": "diff --git a/twisted/logger/_flatten.py b/twisted/logger/_flatten.py\n--- a/twisted/logger/_flatten.py\n+++ b/twisted/logger/_flatten.py\n@@ -111,7 +111,7 @@\n         if conversion == \"r\":\n             conversionFunction = repr\n         else:  # Above: if conversion is not \"r\", it's \"s\"\n-            conversionFunction = str\n+            conversionFunction = unicode\n \n         if callit:\n             fieldValue = fieldValue()\n", "issue": "flattenEvent() fails with \"'ascii' codec can't encode character\" in Python 2.7\n|[<img alt=\"znerol's avatar\" src=\"https://avatars.githubusercontent.com/u/23288?s=50\" width=\"50\" height=\"50\">](https://github.com/znerol)| @znerol reported|\n|-|-|\n|Trac ID|trac#8699|\n|Type|defect|\n|Created|2016-07-28 05:59:35Z|\n\nbacktrace ends in _flatten.py\n\n```\ntwisted/logger/_flatten.py(119)flattenEvent()\n-> flattenedValue = conversionFunction(fieldValue)\n(Pdb) conversionFunction\n<type 'str'>\n```\n\nI guess conversionFunction should be unicode in Python 2.7 and str in Python 3.\n\n<details><summary>Searchable metadata</summary>\n\n```\ntrac-id__8699 8699\ntype__defect defect\nreporter__znerol znerol\npriority__normal normal\nmilestone__None None\nbranch__ \nbranch_author__ \nstatus__closed closed\nresolution__fixed fixed\ncomponent__core core\nkeywords__None None\ntime__1469685575533160 1469685575533160\nchangetime__1470085969851774 1470085969851774\nversion__None None\nowner__Craig_Rodrigues__rodrigc_____ Craig Rodrigues <rodrigc@...>\n\n```\n</details>\n\n", "before_files": [{"content": "# -*- test-case-name: twisted.logger.test.test_flatten -*-\n# Copyright (c) Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nCode related to \"flattening\" events; that is, extracting a description of all\nrelevant fields from the format string and persisting them for later\nexamination.\n\"\"\"\n\nfrom string import Formatter\nfrom collections import defaultdict\n\nfrom twisted.python.compat import unicode\n\naFormatter = Formatter()\n\n\n\nclass KeyFlattener(object):\n    \"\"\"\n    A L{KeyFlattener} computes keys for the things within curly braces in\n    PEP-3101-style format strings as parsed by L{string.Formatter.parse}.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"\n        Initialize a L{KeyFlattener}.\n        \"\"\"\n        self.keys = defaultdict(lambda: 0)\n\n\n    def flatKey(self, fieldName, formatSpec, conversion):\n        \"\"\"\n        Compute a string key for a given field/format/conversion.\n\n        @param fieldName: A format field name.\n        @type fieldName: L{str}\n\n        @param formatSpec: A format spec.\n        @type formatSpec: L{str}\n\n        @param conversion: A format field conversion type.\n        @type conversion: L{str}\n\n        @return: A key specific to the given field, format and conversion, as\n            well as the occurrence of that combination within this\n            L{KeyFlattener}'s lifetime.\n        @rtype: L{str}\n        \"\"\"\n        result = (\n            \"{fieldName}!{conversion}:{formatSpec}\"\n            .format(\n                fieldName=fieldName,\n                formatSpec=(formatSpec or \"\"),\n                conversion=(conversion or \"\"),\n            )\n        )\n        self.keys[result] += 1\n        n = self.keys[result]\n        if n != 1:\n            result += \"/\" + str(self.keys[result])\n        return result\n\n\n\ndef flattenEvent(event):\n    \"\"\"\n    Flatten the given event by pre-associating format fields with specific\n    objects and callable results in a L{dict} put into the C{\"log_flattened\"}\n    key in the event.\n\n    @param event: A logging event.\n    @type event: L{dict}\n    \"\"\"\n    if \"log_format\" not in event:\n        return\n\n    if \"log_flattened\" in event:\n        fields = event[\"log_flattened\"]\n    else:\n        fields = {}\n\n    keyFlattener = KeyFlattener()\n\n    for (literalText, fieldName, formatSpec, conversion) in (\n        aFormatter.parse(event[\"log_format\"])\n    ):\n        if fieldName is None:\n            continue\n\n        if conversion != \"r\":\n            conversion = \"s\"\n\n        flattenedKey = keyFlattener.flatKey(fieldName, formatSpec, conversion)\n        structuredKey = keyFlattener.flatKey(fieldName, formatSpec, \"\")\n\n        if flattenedKey in fields:\n            # We've already seen and handled this key\n            continue\n\n        if fieldName.endswith(u\"()\"):\n            fieldName = fieldName[:-2]\n            callit = True\n        else:\n            callit = False\n\n        field = aFormatter.get_field(fieldName, (), event)\n        fieldValue = field[0]\n\n        if conversion == \"r\":\n            conversionFunction = repr\n        else:  # Above: if conversion is not \"r\", it's \"s\"\n            conversionFunction = str\n\n        if callit:\n            fieldValue = fieldValue()\n\n        flattenedValue = conversionFunction(fieldValue)\n        fields[flattenedKey] = flattenedValue\n        fields[structuredKey] = fieldValue\n\n    if fields:\n        event[\"log_flattened\"] = fields\n\n\n\ndef extractField(field, event):\n    \"\"\"\n    Extract a given format field from the given event.\n\n    @param field: A string describing a format field or log key.  This is the\n        text that would normally fall between a pair of curly braces in a\n        format string: for example, C{\"key[2].attribute\"}.  If a conversion is\n        specified (the thing after the C{\"!\"} character in a format field) then\n        the result will always be L{unicode}.\n    @type field: L{str} (native string)\n\n    @param event: A log event.\n    @type event: L{dict}\n\n    @return: A value extracted from the field.\n    @rtype: L{object}\n\n    @raise KeyError: if the field is not found in the given event.\n    \"\"\"\n    keyFlattener = KeyFlattener()\n    [[literalText, fieldName, formatSpec, conversion]] = aFormatter.parse(\n        \"{\" + field + \"}\"\n    )\n    key = keyFlattener.flatKey(fieldName, formatSpec, conversion)\n    if \"log_flattened\" not in event:\n        flattenEvent(event)\n    return event[\"log_flattened\"][key]\n\n\n\ndef flatFormat(event):\n    \"\"\"\n    Format an event which has been flattened with L{flattenEvent}.\n\n    @param event: A logging event.\n    @type event: L{dict}\n\n    @return: A formatted string.\n    @rtype: L{unicode}\n    \"\"\"\n    fieldValues = event[\"log_flattened\"]\n    s = []\n    keyFlattener = KeyFlattener()\n    formatFields = aFormatter.parse(event[\"log_format\"])\n    for literalText, fieldName, formatSpec, conversion in formatFields:\n        s.append(literalText)\n        if fieldName is not None:\n            key = keyFlattener.flatKey(\n                    fieldName, formatSpec, conversion or \"s\")\n            s.append(unicode(fieldValues[key]))\n    return u\"\".join(s)\n", "path": "twisted/logger/_flatten.py"}], "after_files": [{"content": "# -*- test-case-name: twisted.logger.test.test_flatten -*-\n# Copyright (c) Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nCode related to \"flattening\" events; that is, extracting a description of all\nrelevant fields from the format string and persisting them for later\nexamination.\n\"\"\"\n\nfrom string import Formatter\nfrom collections import defaultdict\n\nfrom twisted.python.compat import unicode\n\naFormatter = Formatter()\n\n\n\nclass KeyFlattener(object):\n    \"\"\"\n    A L{KeyFlattener} computes keys for the things within curly braces in\n    PEP-3101-style format strings as parsed by L{string.Formatter.parse}.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"\n        Initialize a L{KeyFlattener}.\n        \"\"\"\n        self.keys = defaultdict(lambda: 0)\n\n\n    def flatKey(self, fieldName, formatSpec, conversion):\n        \"\"\"\n        Compute a string key for a given field/format/conversion.\n\n        @param fieldName: A format field name.\n        @type fieldName: L{str}\n\n        @param formatSpec: A format spec.\n        @type formatSpec: L{str}\n\n        @param conversion: A format field conversion type.\n        @type conversion: L{str}\n\n        @return: A key specific to the given field, format and conversion, as\n            well as the occurrence of that combination within this\n            L{KeyFlattener}'s lifetime.\n        @rtype: L{str}\n        \"\"\"\n        result = (\n            \"{fieldName}!{conversion}:{formatSpec}\"\n            .format(\n                fieldName=fieldName,\n                formatSpec=(formatSpec or \"\"),\n                conversion=(conversion or \"\"),\n            )\n        )\n        self.keys[result] += 1\n        n = self.keys[result]\n        if n != 1:\n            result += \"/\" + str(self.keys[result])\n        return result\n\n\n\ndef flattenEvent(event):\n    \"\"\"\n    Flatten the given event by pre-associating format fields with specific\n    objects and callable results in a L{dict} put into the C{\"log_flattened\"}\n    key in the event.\n\n    @param event: A logging event.\n    @type event: L{dict}\n    \"\"\"\n    if \"log_format\" not in event:\n        return\n\n    if \"log_flattened\" in event:\n        fields = event[\"log_flattened\"]\n    else:\n        fields = {}\n\n    keyFlattener = KeyFlattener()\n\n    for (literalText, fieldName, formatSpec, conversion) in (\n        aFormatter.parse(event[\"log_format\"])\n    ):\n        if fieldName is None:\n            continue\n\n        if conversion != \"r\":\n            conversion = \"s\"\n\n        flattenedKey = keyFlattener.flatKey(fieldName, formatSpec, conversion)\n        structuredKey = keyFlattener.flatKey(fieldName, formatSpec, \"\")\n\n        if flattenedKey in fields:\n            # We've already seen and handled this key\n            continue\n\n        if fieldName.endswith(u\"()\"):\n            fieldName = fieldName[:-2]\n            callit = True\n        else:\n            callit = False\n\n        field = aFormatter.get_field(fieldName, (), event)\n        fieldValue = field[0]\n\n        if conversion == \"r\":\n            conversionFunction = repr\n        else:  # Above: if conversion is not \"r\", it's \"s\"\n            conversionFunction = unicode\n\n        if callit:\n            fieldValue = fieldValue()\n\n        flattenedValue = conversionFunction(fieldValue)\n        fields[flattenedKey] = flattenedValue\n        fields[structuredKey] = fieldValue\n\n    if fields:\n        event[\"log_flattened\"] = fields\n\n\n\ndef extractField(field, event):\n    \"\"\"\n    Extract a given format field from the given event.\n\n    @param field: A string describing a format field or log key.  This is the\n        text that would normally fall between a pair of curly braces in a\n        format string: for example, C{\"key[2].attribute\"}.  If a conversion is\n        specified (the thing after the C{\"!\"} character in a format field) then\n        the result will always be L{unicode}.\n    @type field: L{str} (native string)\n\n    @param event: A log event.\n    @type event: L{dict}\n\n    @return: A value extracted from the field.\n    @rtype: L{object}\n\n    @raise KeyError: if the field is not found in the given event.\n    \"\"\"\n    keyFlattener = KeyFlattener()\n    [[literalText, fieldName, formatSpec, conversion]] = aFormatter.parse(\n        \"{\" + field + \"}\"\n    )\n    key = keyFlattener.flatKey(fieldName, formatSpec, conversion)\n    if \"log_flattened\" not in event:\n        flattenEvent(event)\n    return event[\"log_flattened\"][key]\n\n\n\ndef flatFormat(event):\n    \"\"\"\n    Format an event which has been flattened with L{flattenEvent}.\n\n    @param event: A logging event.\n    @type event: L{dict}\n\n    @return: A formatted string.\n    @rtype: L{unicode}\n    \"\"\"\n    fieldValues = event[\"log_flattened\"]\n    s = []\n    keyFlattener = KeyFlattener()\n    formatFields = aFormatter.parse(event[\"log_format\"])\n    for literalText, fieldName, formatSpec, conversion in formatFields:\n        s.append(literalText)\n        if fieldName is not None:\n            key = keyFlattener.flatKey(\n                    fieldName, formatSpec, conversion or \"s\")\n            s.append(unicode(fieldValues[key]))\n    return u\"\".join(s)\n", "path": "twisted/logger/_flatten.py"}]}