We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
blaze.server does not allow CORS
`blaze.server` sticks with same origin policy so it does not enable CORS requests.. This is an issue for users using bokeh `BlazeDataSources` to map to a blaze server and update data directly on the browser without `bokeh.server` because this `blaze.server` (well, Flask default) configuration will raise an error. Something like:

```
  XMLHttpRequest cannot load http://domain:9000/compute.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain:5006' is therefore not allowed access.
```

.

This issue can be fixed by setting (injecting) the CORS policies on `blaze.server`. For instance:

``` Python
        server = blaze.Server({'dat': gauss})

        def add_crossdomain_headers(response):
            response.headers.add('Access-Control-Allow-Origin', '*')
            response.headers.add('Access-Control-Allow-Methods', 'GET,POST')
            response.headers.add('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept")

            return response

        server.app.after_request(add_crossdomain_headers)
        server.run(host="127.0.0.1", port=9000)

```

But a probably better solution would be to have some kind of configuration on `blaze.server` itself so users don't have to bother too much trying to find the solution. 

NOTE: Flask does expose a `crossdomain` decorator that can be used to decorate views (and that may be a better solution) but I didn't figure out a quick way of using it within `blaze.server` before the views are declared (I may be overlooking something trivial, I honestly didn't have much time to dig in 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: `blaze/server/server.py`
Content:
```
1 from __future__ import absolute_import, division, print_function
2 
3 import socket
4 
5 import flask
6 from flask import Blueprint, Flask, request
7 
8 from toolz import assoc
9 
10 from datashape.predicates import iscollection, isscalar
11 from odo import odo
12 
13 import blaze
14 from blaze import compute
15 from blaze.expr import utils as expr_utils
16 from blaze.compute import compute_up
17 
18 from .serialization import json
19 from ..interactive import InteractiveSymbol, coerce_scalar
20 from ..expr import Expr, symbol
21 
22 from datashape import Mono, discover
23 
24 
25 __all__ = 'Server', 'to_tree', 'from_tree'
26 
27 # http://www.speedguide.net/port.php?port=6363
28 # http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
29 DEFAULT_PORT = 6363
30 
31 
32 api = Blueprint('api', __name__)
33 pickle_extension_api = Blueprint('pickle_extension_api', __name__)
34 
35 
36 def _get_option(option, options):
37     try:
38         return options[option]
39     except KeyError:
40         # Provides a more informative error message.
41         raise TypeError(
42             'The blaze api must be registered with {option}'.format(
43                 option=option,
44             ),
45         )
46 
47 
48 def _register_api(app, options, first_registration=False):
49     """
50     Register the data with the blueprint.
51     """
52     _get_data.cache[app] = _get_option('data', options)
53     _get_format.cache[app] = dict(
54         (f.name, f) for f in _get_option('formats', options)
55     )
56     # Call the original register function.
57     Blueprint.register(api, app, options, first_registration)
58 
59 api.register = _register_api
60 
61 
62 def _get_data():
63     """
64     Retrieve the current application's data for use in the blaze server
65     endpoints.
66     """
67     return _get_data.cache[flask.current_app]
68 _get_data.cache = {}
69 
70 
71 def _get_format(name):
72     return _get_format.cache[flask.current_app][name]
73 _get_format.cache = {}
74 
75 
76 class Server(object):
77 
78     """ Blaze Data Server
79 
80     Host local data through a web API
81 
82     Parameters
83     ----------
84     data : ``dict`` or ``None``, optional
85         A dictionary mapping dataset name to any data format that blaze
86         understands.
87 
88     formats : ``iterable[SerializationFormat]``, optional
89         An iterable of supported serialization formats. By default, the
90         server will support JSON.
91         A serialization format is an object that supports:
92         name, loads, and dumps.
93 
94     Examples
95     --------
96     >>> from pandas import DataFrame
97     >>> df = DataFrame([[1, 'Alice',   100],
98     ...                 [2, 'Bob',    -200],
99     ...                 [3, 'Alice',   300],
100     ...                 [4, 'Dennis',  400],
101     ...                 [5,  'Bob',   -500]],
102     ...                columns=['id', 'name', 'amount'])
103 
104     >>> server = Server({'accounts': df})
105     >>> server.run() # doctest: +SKIP
106     """
107     __slots__ = 'app', 'data', 'port'
108 
109     def __init__(self, data=None, formats=None):
110         app = self.app = Flask('blaze.server.server')
111         if data is None:
112             data = dict()
113         app.register_blueprint(
114             api,
115             data=data,
116             formats=formats if formats is not None else (json,),
117         )
118         self.data = data
119 
120     def run(self, *args, **kwargs):
121         """Run the server"""
122         port = kwargs.pop('port', DEFAULT_PORT)
123         self.port = port
124         try:
125             self.app.run(*args, port=port, **kwargs)
126         except socket.error:
127             print("\tOops, couldn't connect on port %d.  Is it busy?" % port)
128             if kwargs.get('retry', True):
129                 # Attempt to start the server on a new port.
130                 self.run(*args, **assoc(kwargs, 'port', port + 1))
131 
132 
133 @api.route('/datashape')
134 def dataset():
135     return str(discover(_get_data()))
136 
137 
138 def to_tree(expr, names=None):
139     """ Represent Blaze expression with core data structures
140 
141     Transform a Blaze expression into a form using only strings, dicts, lists
142     and base types (int, float, datetime, ....)  This form can be useful for
143     serialization.
144 
145     Parameters
146     ----------
147 
148     expr: Blaze Expression
149 
150     Examples
151     --------
152 
153     >>> t = symbol('t', 'var * {x: int32, y: int32}')
154     >>> to_tree(t) # doctest: +SKIP
155     {'op': 'Symbol',
156      'args': ['t', 'var * { x : int32, y : int32 }', False]}
157 
158 
159     >>> to_tree(t.x.sum()) # doctest: +SKIP
160     {'op': 'sum',
161      'args': [
162          {'op': 'Column',
163          'args': [
164              {
165               'op': 'Symbol'
166               'args': ['t', 'var * { x : int32, y : int32 }', False]
167              }
168              'x']
169          }]
170      }
171 
172     Simplify expresion using explicit ``names`` dictionary.  In the example
173     below we replace the ``Symbol`` node with the string ``'t'``.
174 
175     >>> tree = to_tree(t.x, names={t: 't'})
176     >>> tree # doctest: +SKIP
177     {'op': 'Column', 'args': ['t', 'x']}
178 
179     >>> from_tree(tree, namespace={'t': t})
180     t.x
181 
182     See Also
183     --------
184 
185     blaze.server.server.from_tree
186     """
187     if names and expr in names:
188         return names[expr]
189     if isinstance(expr, tuple):
190         return [to_tree(arg, names=names) for arg in expr]
191     if isinstance(expr, expr_utils._slice):
192         return to_tree(expr.as_slice(), names=names)
193     if isinstance(expr, slice):
194         return {'op': 'slice',
195                 'args': [to_tree(arg, names=names) for arg in
196                          [expr.start, expr.stop, expr.step]]}
197     elif isinstance(expr, Mono):
198         return str(expr)
199     elif isinstance(expr, InteractiveSymbol):
200         return to_tree(symbol(expr._name, expr.dshape), names)
201     elif isinstance(expr, Expr):
202         return {'op': type(expr).__name__,
203                 'args': [to_tree(arg, names) for arg in expr._args]}
204     else:
205         return expr
206 
207 
208 def expression_from_name(name):
209     """
210 
211     >>> expression_from_name('By')
212     <class 'blaze.expr.split_apply_combine.By'>
213 
214     >>> expression_from_name('And')
215     <class 'blaze.expr.arithmetic.And'>
216     """
217     import blaze
218     if hasattr(blaze, name):
219         return getattr(blaze, name)
220     if hasattr(blaze.expr, name):
221         return getattr(blaze.expr, name)
222     for signature, func in compute_up.funcs.items():
223         try:
224             if signature[0].__name__ == name:
225                 return signature[0]
226         except TypeError:
227             pass
228     raise ValueError('%s not found in compute_up' % name)
229 
230 
231 def from_tree(expr, namespace=None):
232     """ Convert core data structures to Blaze expression
233 
234     Core data structure representations created by ``to_tree`` are converted
235     back into Blaze expressions.
236 
237     Parameters
238     ----------
239     expr : dict
240 
241     Examples
242     --------
243 
244     >>> t = symbol('t', 'var * {x: int32, y: int32}')
245     >>> tree = to_tree(t)
246     >>> tree # doctest: +SKIP
247     {'op': 'Symbol',
248      'args': ['t', 'var * { x : int32, y : int32 }', False]}
249 
250     >>> from_tree(tree)
251     t
252 
253     >>> tree = to_tree(t.x.sum())
254     >>> tree # doctest: +SKIP
255     {'op': 'sum',
256      'args': [
257          {'op': 'Field',
258          'args': [
259              {
260               'op': 'Symbol'
261               'args': ['t', 'var * { x : int32, y : int32 }', False]
262              }
263              'x']
264          }]
265      }
266 
267     >>> from_tree(tree)
268     sum(t.x)
269 
270     Simplify expresion using explicit ``names`` dictionary.  In the example
271     below we replace the ``Symbol`` node with the string ``'t'``.
272 
273     >>> tree = to_tree(t.x, names={t: 't'})
274     >>> tree # doctest: +SKIP
275     {'op': 'Field', 'args': ['t', 'x']}
276 
277     >>> from_tree(tree, namespace={'t': t})
278     t.x
279 
280     See Also
281     --------
282 
283     blaze.server.server.to_tree
284     """
285     if isinstance(expr, dict):
286         op, args = expr['op'], expr['args']
287         if 'slice' == op:
288             return expr_utils._slice(*[from_tree(arg, namespace)
289                                        for arg in args])
290         if hasattr(blaze.expr, op):
291             cls = getattr(blaze.expr, op)
292         else:
293             cls = expression_from_name(op)
294         if 'Symbol' in op:
295             children = [from_tree(arg) for arg in args]
296         else:
297             children = [from_tree(arg, namespace) for arg in args]
298         return cls(*children)
299     elif isinstance(expr, list):
300         return tuple(from_tree(arg, namespace) for arg in expr)
301     if namespace and expr in namespace:
302         return namespace[expr]
303     else:
304         return expr
305 
306 
307 @api.route('/compute.<serial_format>', methods=['POST', 'PUT', 'GET'])
308 def compserver(serial_format):
309     try:
310         serial = _get_format(serial_format)
311     except KeyError:
312         return 'Unsupported serialization format', 404
313 
314     try:
315         payload = serial.loads(request.data)
316     except ValueError:
317         return ("Bad data.  Got %s " % request.data, 400)  # 400: Bad Request
318 
319     ns = payload.get('namespace', dict())
320     dataset = _get_data()
321     ns[':leaf'] = symbol('leaf', discover(dataset))
322 
323     expr = from_tree(payload['expr'], namespace=ns)
324     assert len(expr._leaves()) == 1
325     leaf = expr._leaves()[0]
326 
327     try:
328         result = compute(expr, {leaf: dataset})
329 
330         if iscollection(expr.dshape):
331             result = odo(result, list)
332         elif isscalar(expr.dshape):
333             result = coerce_scalar(result, str(expr.dshape))
334     except NotImplementedError as e:
335         # 501: Not Implemented
336         return ("Computation not supported:\n%s" % e, 501)
337     except Exception as e:
338         # 500: Internal Server Error
339         return ("Computation failed with message:\n%s" % e, 500)
340 
341     return serial.dumps({
342         'datashape': str(expr.dshape),
343         'data': result,
344         'names': expr.fields
345     })
346
```
--- 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/blaze/server/server.py b/blaze/server/server.py
--- a/blaze/server/server.py
+++ b/blaze/server/server.py
@@ -1,12 +1,25 @@
 from __future__ import absolute_import, division, print_function
 
 import socket
+import functools
 
 import flask
 from flask import Blueprint, Flask, request
 
+try:
+    from bokeh.server.crossdomain import crossdomain
+except ImportError:
+    def crossdomain(*args, **kwargs):
+        def wrapper(f):
+            @functools.wraps(f)
+            def wrapped(*a, **k):
+                return f(*a, **k)
+            return wrapped
+        return wrapper
+
 from toolz import assoc
 
+from datashape import Mono, discover
 from datashape.predicates import iscollection, isscalar
 from odo import odo
 
@@ -19,8 +32,6 @@
 from ..interactive import InteractiveSymbol, coerce_scalar
 from ..expr import Expr, symbol
 
-from datashape import Mono, discover
-
 
 __all__ = 'Server', 'to_tree', 'from_tree'
 
@@ -130,8 +141,9 @@
                 self.run(*args, **assoc(kwargs, 'port', port + 1))
 
 
-@api.route('/datashape')
-def dataset():
+@api.route('/datashape', methods=['GET'])
+@crossdomain(origin='*', methods=['GET'])
+def shape():
     return str(discover(_get_data()))
 
 
@@ -144,8 +156,8 @@
 
     Parameters
     ----------
-
-    expr: Blaze Expression
+    expr : Expr
+        A Blaze expression
 
     Examples
     --------
@@ -304,7 +316,9 @@
         return expr
 
 
-@api.route('/compute.<serial_format>', methods=['POST', 'PUT', 'GET'])
+@api.route('/compute.<serial_format>',
+           methods=['POST', 'GET', 'HEAD', 'OPTIONS'])
+@crossdomain(origin='*', methods=['POST', 'GET', 'HEAD', 'OPTIONS'])
 def compserver(serial_format):
     try:
         serial = _get_format(serial_format)

{"golden_diff": "diff --git a/blaze/server/server.py b/blaze/server/server.py\n--- a/blaze/server/server.py\n+++ b/blaze/server/server.py\n@@ -1,12 +1,25 @@\n from __future__ import absolute_import, division, print_function\n \n import socket\n+import functools\n \n import flask\n from flask import Blueprint, Flask, request\n \n+try:\n+    from bokeh.server.crossdomain import crossdomain\n+except ImportError:\n+    def crossdomain(*args, **kwargs):\n+        def wrapper(f):\n+            @functools.wraps(f)\n+            def wrapped(*a, **k):\n+                return f(*a, **k)\n+            return wrapped\n+        return wrapper\n+\n from toolz import assoc\n \n+from datashape import Mono, discover\n from datashape.predicates import iscollection, isscalar\n from odo import odo\n \n@@ -19,8 +32,6 @@\n from ..interactive import InteractiveSymbol, coerce_scalar\n from ..expr import Expr, symbol\n \n-from datashape import Mono, discover\n-\n \n __all__ = 'Server', 'to_tree', 'from_tree'\n \n@@ -130,8 +141,9 @@\n                 self.run(*args, **assoc(kwargs, 'port', port + 1))\n \n \n-@api.route('/datashape')\n-def dataset():\n+@api.route('/datashape', methods=['GET'])\n+@crossdomain(origin='*', methods=['GET'])\n+def shape():\n     return str(discover(_get_data()))\n \n \n@@ -144,8 +156,8 @@\n \n     Parameters\n     ----------\n-\n-    expr: Blaze Expression\n+    expr : Expr\n+        A Blaze expression\n \n     Examples\n     --------\n@@ -304,7 +316,9 @@\n         return expr\n \n \n-@api.route('/compute.<serial_format>', methods=['POST', 'PUT', 'GET'])\n+@api.route('/compute.<serial_format>',\n+           methods=['POST', 'GET', 'HEAD', 'OPTIONS'])\n+@crossdomain(origin='*', methods=['POST', 'GET', 'HEAD', 'OPTIONS'])\n def compserver(serial_format):\n     try:\n         serial = _get_format(serial_format)\n", "issue": "blaze.server does not allow CORS\n`blaze.server` sticks with same origin policy so it does not enable CORS requests.. This is an issue for users using bokeh `BlazeDataSources` to map to a blaze server and update data directly on the browser without `bokeh.server` because this `blaze.server` (well, Flask default) configuration will raise an error. Something like:\n\n```\n  XMLHttpRequest cannot load http://domain:9000/compute.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain:5006' is therefore not allowed access.\n```\n\n.\n\nThis issue can be fixed by setting (injecting) the CORS policies on `blaze.server`. For instance:\n\n``` Python\n        server = blaze.Server({'dat': gauss})\n\n        def add_crossdomain_headers(response):\n            response.headers.add('Access-Control-Allow-Origin', '*')\n            response.headers.add('Access-Control-Allow-Methods', 'GET,POST')\n            response.headers.add('Access-Control-Allow-Headers', \"Origin, X-Requested-With, Content-Type, Accept\")\n\n            return response\n\n        server.app.after_request(add_crossdomain_headers)\n        server.run(host=\"127.0.0.1\", port=9000)\n\n```\n\nBut a probably better solution would be to have some kind of configuration on `blaze.server` itself so users don't have to bother too much trying to find the solution. \n\nNOTE: Flask does expose a `crossdomain` decorator that can be used to decorate views (and that may be a better solution) but I didn't figure out a quick way of using it within `blaze.server` before the views are declared (I may be overlooking something trivial, I honestly didn't have much time to dig in details).\n\n", "before_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport socket\n\nimport flask\nfrom flask import Blueprint, Flask, request\n\nfrom toolz import assoc\n\nfrom datashape.predicates import iscollection, isscalar\nfrom odo import odo\n\nimport blaze\nfrom blaze import compute\nfrom blaze.expr import utils as expr_utils\nfrom blaze.compute import compute_up\n\nfrom .serialization import json\nfrom ..interactive import InteractiveSymbol, coerce_scalar\nfrom ..expr import Expr, symbol\n\nfrom datashape import Mono, discover\n\n\n__all__ = 'Server', 'to_tree', 'from_tree'\n\n# http://www.speedguide.net/port.php?port=6363\n# http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers\nDEFAULT_PORT = 6363\n\n\napi = Blueprint('api', __name__)\npickle_extension_api = Blueprint('pickle_extension_api', __name__)\n\n\ndef _get_option(option, options):\n    try:\n        return options[option]\n    except KeyError:\n        # Provides a more informative error message.\n        raise TypeError(\n            'The blaze api must be registered with {option}'.format(\n                option=option,\n            ),\n        )\n\n\ndef _register_api(app, options, first_registration=False):\n    \"\"\"\n    Register the data with the blueprint.\n    \"\"\"\n    _get_data.cache[app] = _get_option('data', options)\n    _get_format.cache[app] = dict(\n        (f.name, f) for f in _get_option('formats', options)\n    )\n    # Call the original register function.\n    Blueprint.register(api, app, options, first_registration)\n\napi.register = _register_api\n\n\ndef _get_data():\n    \"\"\"\n    Retrieve the current application's data for use in the blaze server\n    endpoints.\n    \"\"\"\n    return _get_data.cache[flask.current_app]\n_get_data.cache = {}\n\n\ndef _get_format(name):\n    return _get_format.cache[flask.current_app][name]\n_get_format.cache = {}\n\n\nclass Server(object):\n\n    \"\"\" Blaze Data Server\n\n    Host local data through a web API\n\n    Parameters\n    ----------\n    data : ``dict`` or ``None``, optional\n        A dictionary mapping dataset name to any data format that blaze\n        understands.\n\n    formats : ``iterable[SerializationFormat]``, optional\n        An iterable of supported serialization formats. By default, the\n        server will support JSON.\n        A serialization format is an object that supports:\n        name, loads, and dumps.\n\n    Examples\n    --------\n    >>> from pandas import DataFrame\n    >>> df = DataFrame([[1, 'Alice',   100],\n    ...                 [2, 'Bob',    -200],\n    ...                 [3, 'Alice',   300],\n    ...                 [4, 'Dennis',  400],\n    ...                 [5,  'Bob',   -500]],\n    ...                columns=['id', 'name', 'amount'])\n\n    >>> server = Server({'accounts': df})\n    >>> server.run() # doctest: +SKIP\n    \"\"\"\n    __slots__ = 'app', 'data', 'port'\n\n    def __init__(self, data=None, formats=None):\n        app = self.app = Flask('blaze.server.server')\n        if data is None:\n            data = dict()\n        app.register_blueprint(\n            api,\n            data=data,\n            formats=formats if formats is not None else (json,),\n        )\n        self.data = data\n\n    def run(self, *args, **kwargs):\n        \"\"\"Run the server\"\"\"\n        port = kwargs.pop('port', DEFAULT_PORT)\n        self.port = port\n        try:\n            self.app.run(*args, port=port, **kwargs)\n        except socket.error:\n            print(\"\\tOops, couldn't connect on port %d.  Is it busy?\" % port)\n            if kwargs.get('retry', True):\n                # Attempt to start the server on a new port.\n                self.run(*args, **assoc(kwargs, 'port', port + 1))\n\n\n@api.route('/datashape')\ndef dataset():\n    return str(discover(_get_data()))\n\n\ndef to_tree(expr, names=None):\n    \"\"\" Represent Blaze expression with core data structures\n\n    Transform a Blaze expression into a form using only strings, dicts, lists\n    and base types (int, float, datetime, ....)  This form can be useful for\n    serialization.\n\n    Parameters\n    ----------\n\n    expr: Blaze Expression\n\n    Examples\n    --------\n\n    >>> t = symbol('t', 'var * {x: int32, y: int32}')\n    >>> to_tree(t) # doctest: +SKIP\n    {'op': 'Symbol',\n     'args': ['t', 'var * { x : int32, y : int32 }', False]}\n\n\n    >>> to_tree(t.x.sum()) # doctest: +SKIP\n    {'op': 'sum',\n     'args': [\n         {'op': 'Column',\n         'args': [\n             {\n              'op': 'Symbol'\n              'args': ['t', 'var * { x : int32, y : int32 }', False]\n             }\n             'x']\n         }]\n     }\n\n    Simplify expresion using explicit ``names`` dictionary.  In the example\n    below we replace the ``Symbol`` node with the string ``'t'``.\n\n    >>> tree = to_tree(t.x, names={t: 't'})\n    >>> tree # doctest: +SKIP\n    {'op': 'Column', 'args': ['t', 'x']}\n\n    >>> from_tree(tree, namespace={'t': t})\n    t.x\n\n    See Also\n    --------\n\n    blaze.server.server.from_tree\n    \"\"\"\n    if names and expr in names:\n        return names[expr]\n    if isinstance(expr, tuple):\n        return [to_tree(arg, names=names) for arg in expr]\n    if isinstance(expr, expr_utils._slice):\n        return to_tree(expr.as_slice(), names=names)\n    if isinstance(expr, slice):\n        return {'op': 'slice',\n                'args': [to_tree(arg, names=names) for arg in\n                         [expr.start, expr.stop, expr.step]]}\n    elif isinstance(expr, Mono):\n        return str(expr)\n    elif isinstance(expr, InteractiveSymbol):\n        return to_tree(symbol(expr._name, expr.dshape), names)\n    elif isinstance(expr, Expr):\n        return {'op': type(expr).__name__,\n                'args': [to_tree(arg, names) for arg in expr._args]}\n    else:\n        return expr\n\n\ndef expression_from_name(name):\n    \"\"\"\n\n    >>> expression_from_name('By')\n    <class 'blaze.expr.split_apply_combine.By'>\n\n    >>> expression_from_name('And')\n    <class 'blaze.expr.arithmetic.And'>\n    \"\"\"\n    import blaze\n    if hasattr(blaze, name):\n        return getattr(blaze, name)\n    if hasattr(blaze.expr, name):\n        return getattr(blaze.expr, name)\n    for signature, func in compute_up.funcs.items():\n        try:\n            if signature[0].__name__ == name:\n                return signature[0]\n        except TypeError:\n            pass\n    raise ValueError('%s not found in compute_up' % name)\n\n\ndef from_tree(expr, namespace=None):\n    \"\"\" Convert core data structures to Blaze expression\n\n    Core data structure representations created by ``to_tree`` are converted\n    back into Blaze expressions.\n\n    Parameters\n    ----------\n    expr : dict\n\n    Examples\n    --------\n\n    >>> t = symbol('t', 'var * {x: int32, y: int32}')\n    >>> tree = to_tree(t)\n    >>> tree # doctest: +SKIP\n    {'op': 'Symbol',\n     'args': ['t', 'var * { x : int32, y : int32 }', False]}\n\n    >>> from_tree(tree)\n    t\n\n    >>> tree = to_tree(t.x.sum())\n    >>> tree # doctest: +SKIP\n    {'op': 'sum',\n     'args': [\n         {'op': 'Field',\n         'args': [\n             {\n              'op': 'Symbol'\n              'args': ['t', 'var * { x : int32, y : int32 }', False]\n             }\n             'x']\n         }]\n     }\n\n    >>> from_tree(tree)\n    sum(t.x)\n\n    Simplify expresion using explicit ``names`` dictionary.  In the example\n    below we replace the ``Symbol`` node with the string ``'t'``.\n\n    >>> tree = to_tree(t.x, names={t: 't'})\n    >>> tree # doctest: +SKIP\n    {'op': 'Field', 'args': ['t', 'x']}\n\n    >>> from_tree(tree, namespace={'t': t})\n    t.x\n\n    See Also\n    --------\n\n    blaze.server.server.to_tree\n    \"\"\"\n    if isinstance(expr, dict):\n        op, args = expr['op'], expr['args']\n        if 'slice' == op:\n            return expr_utils._slice(*[from_tree(arg, namespace)\n                                       for arg in args])\n        if hasattr(blaze.expr, op):\n            cls = getattr(blaze.expr, op)\n        else:\n            cls = expression_from_name(op)\n        if 'Symbol' in op:\n            children = [from_tree(arg) for arg in args]\n        else:\n            children = [from_tree(arg, namespace) for arg in args]\n        return cls(*children)\n    elif isinstance(expr, list):\n        return tuple(from_tree(arg, namespace) for arg in expr)\n    if namespace and expr in namespace:\n        return namespace[expr]\n    else:\n        return expr\n\n\n@api.route('/compute.<serial_format>', methods=['POST', 'PUT', 'GET'])\ndef compserver(serial_format):\n    try:\n        serial = _get_format(serial_format)\n    except KeyError:\n        return 'Unsupported serialization format', 404\n\n    try:\n        payload = serial.loads(request.data)\n    except ValueError:\n        return (\"Bad data.  Got %s \" % request.data, 400)  # 400: Bad Request\n\n    ns = payload.get('namespace', dict())\n    dataset = _get_data()\n    ns[':leaf'] = symbol('leaf', discover(dataset))\n\n    expr = from_tree(payload['expr'], namespace=ns)\n    assert len(expr._leaves()) == 1\n    leaf = expr._leaves()[0]\n\n    try:\n        result = compute(expr, {leaf: dataset})\n\n        if iscollection(expr.dshape):\n            result = odo(result, list)\n        elif isscalar(expr.dshape):\n            result = coerce_scalar(result, str(expr.dshape))\n    except NotImplementedError as e:\n        # 501: Not Implemented\n        return (\"Computation not supported:\\n%s\" % e, 501)\n    except Exception as e:\n        # 500: Internal Server Error\n        return (\"Computation failed with message:\\n%s\" % e, 500)\n\n    return serial.dumps({\n        'datashape': str(expr.dshape),\n        'data': result,\n        'names': expr.fields\n    })\n", "path": "blaze/server/server.py"}], "after_files": [{"content": "from __future__ import absolute_import, division, print_function\n\nimport socket\nimport functools\n\nimport flask\nfrom flask import Blueprint, Flask, request\n\ntry:\n    from bokeh.server.crossdomain import crossdomain\nexcept ImportError:\n    def crossdomain(*args, **kwargs):\n        def wrapper(f):\n            @functools.wraps(f)\n            def wrapped(*a, **k):\n                return f(*a, **k)\n            return wrapped\n        return wrapper\n\nfrom toolz import assoc\n\nfrom datashape import Mono, discover\nfrom datashape.predicates import iscollection, isscalar\nfrom odo import odo\n\nimport blaze\nfrom blaze import compute\nfrom blaze.expr import utils as expr_utils\nfrom blaze.compute import compute_up\n\nfrom .serialization import json\nfrom ..interactive import InteractiveSymbol, coerce_scalar\nfrom ..expr import Expr, symbol\n\n\n__all__ = 'Server', 'to_tree', 'from_tree'\n\n# http://www.speedguide.net/port.php?port=6363\n# http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers\nDEFAULT_PORT = 6363\n\n\napi = Blueprint('api', __name__)\npickle_extension_api = Blueprint('pickle_extension_api', __name__)\n\n\ndef _get_option(option, options):\n    try:\n        return options[option]\n    except KeyError:\n        # Provides a more informative error message.\n        raise TypeError(\n            'The blaze api must be registered with {option}'.format(\n                option=option,\n            ),\n        )\n\n\ndef _register_api(app, options, first_registration=False):\n    \"\"\"\n    Register the data with the blueprint.\n    \"\"\"\n    _get_data.cache[app] = _get_option('data', options)\n    _get_format.cache[app] = dict(\n        (f.name, f) for f in _get_option('formats', options)\n    )\n    # Call the original register function.\n    Blueprint.register(api, app, options, first_registration)\n\napi.register = _register_api\n\n\ndef _get_data():\n    \"\"\"\n    Retrieve the current application's data for use in the blaze server\n    endpoints.\n    \"\"\"\n    return _get_data.cache[flask.current_app]\n_get_data.cache = {}\n\n\ndef _get_format(name):\n    return _get_format.cache[flask.current_app][name]\n_get_format.cache = {}\n\n\nclass Server(object):\n\n    \"\"\" Blaze Data Server\n\n    Host local data through a web API\n\n    Parameters\n    ----------\n    data : ``dict`` or ``None``, optional\n        A dictionary mapping dataset name to any data format that blaze\n        understands.\n\n    formats : ``iterable[SerializationFormat]``, optional\n        An iterable of supported serialization formats. By default, the\n        server will support JSON.\n        A serialization format is an object that supports:\n        name, loads, and dumps.\n\n    Examples\n    --------\n    >>> from pandas import DataFrame\n    >>> df = DataFrame([[1, 'Alice',   100],\n    ...                 [2, 'Bob',    -200],\n    ...                 [3, 'Alice',   300],\n    ...                 [4, 'Dennis',  400],\n    ...                 [5,  'Bob',   -500]],\n    ...                columns=['id', 'name', 'amount'])\n\n    >>> server = Server({'accounts': df})\n    >>> server.run() # doctest: +SKIP\n    \"\"\"\n    __slots__ = 'app', 'data', 'port'\n\n    def __init__(self, data=None, formats=None):\n        app = self.app = Flask('blaze.server.server')\n        if data is None:\n            data = dict()\n        app.register_blueprint(\n            api,\n            data=data,\n            formats=formats if formats is not None else (json,),\n        )\n        self.data = data\n\n    def run(self, *args, **kwargs):\n        \"\"\"Run the server\"\"\"\n        port = kwargs.pop('port', DEFAULT_PORT)\n        self.port = port\n        try:\n            self.app.run(*args, port=port, **kwargs)\n        except socket.error:\n            print(\"\\tOops, couldn't connect on port %d.  Is it busy?\" % port)\n            if kwargs.get('retry', True):\n                # Attempt to start the server on a new port.\n                self.run(*args, **assoc(kwargs, 'port', port + 1))\n\n\n@api.route('/datashape', methods=['GET'])\n@crossdomain(origin='*', methods=['GET'])\ndef shape():\n    return str(discover(_get_data()))\n\n\ndef to_tree(expr, names=None):\n    \"\"\" Represent Blaze expression with core data structures\n\n    Transform a Blaze expression into a form using only strings, dicts, lists\n    and base types (int, float, datetime, ....)  This form can be useful for\n    serialization.\n\n    Parameters\n    ----------\n    expr : Expr\n        A Blaze expression\n\n    Examples\n    --------\n\n    >>> t = symbol('t', 'var * {x: int32, y: int32}')\n    >>> to_tree(t) # doctest: +SKIP\n    {'op': 'Symbol',\n     'args': ['t', 'var * { x : int32, y : int32 }', False]}\n\n\n    >>> to_tree(t.x.sum()) # doctest: +SKIP\n    {'op': 'sum',\n     'args': [\n         {'op': 'Column',\n         'args': [\n             {\n              'op': 'Symbol'\n              'args': ['t', 'var * { x : int32, y : int32 }', False]\n             }\n             'x']\n         }]\n     }\n\n    Simplify expresion using explicit ``names`` dictionary.  In the example\n    below we replace the ``Symbol`` node with the string ``'t'``.\n\n    >>> tree = to_tree(t.x, names={t: 't'})\n    >>> tree # doctest: +SKIP\n    {'op': 'Column', 'args': ['t', 'x']}\n\n    >>> from_tree(tree, namespace={'t': t})\n    t.x\n\n    See Also\n    --------\n\n    blaze.server.server.from_tree\n    \"\"\"\n    if names and expr in names:\n        return names[expr]\n    if isinstance(expr, tuple):\n        return [to_tree(arg, names=names) for arg in expr]\n    if isinstance(expr, expr_utils._slice):\n        return to_tree(expr.as_slice(), names=names)\n    if isinstance(expr, slice):\n        return {'op': 'slice',\n                'args': [to_tree(arg, names=names) for arg in\n                         [expr.start, expr.stop, expr.step]]}\n    elif isinstance(expr, Mono):\n        return str(expr)\n    elif isinstance(expr, InteractiveSymbol):\n        return to_tree(symbol(expr._name, expr.dshape), names)\n    elif isinstance(expr, Expr):\n        return {'op': type(expr).__name__,\n                'args': [to_tree(arg, names) for arg in expr._args]}\n    else:\n        return expr\n\n\ndef expression_from_name(name):\n    \"\"\"\n\n    >>> expression_from_name('By')\n    <class 'blaze.expr.split_apply_combine.By'>\n\n    >>> expression_from_name('And')\n    <class 'blaze.expr.arithmetic.And'>\n    \"\"\"\n    import blaze\n    if hasattr(blaze, name):\n        return getattr(blaze, name)\n    if hasattr(blaze.expr, name):\n        return getattr(blaze.expr, name)\n    for signature, func in compute_up.funcs.items():\n        try:\n            if signature[0].__name__ == name:\n                return signature[0]\n        except TypeError:\n            pass\n    raise ValueError('%s not found in compute_up' % name)\n\n\ndef from_tree(expr, namespace=None):\n    \"\"\" Convert core data structures to Blaze expression\n\n    Core data structure representations created by ``to_tree`` are converted\n    back into Blaze expressions.\n\n    Parameters\n    ----------\n    expr : dict\n\n    Examples\n    --------\n\n    >>> t = symbol('t', 'var * {x: int32, y: int32}')\n    >>> tree = to_tree(t)\n    >>> tree # doctest: +SKIP\n    {'op': 'Symbol',\n     'args': ['t', 'var * { x : int32, y : int32 }', False]}\n\n    >>> from_tree(tree)\n    t\n\n    >>> tree = to_tree(t.x.sum())\n    >>> tree # doctest: +SKIP\n    {'op': 'sum',\n     'args': [\n         {'op': 'Field',\n         'args': [\n             {\n              'op': 'Symbol'\n              'args': ['t', 'var * { x : int32, y : int32 }', False]\n             }\n             'x']\n         }]\n     }\n\n    >>> from_tree(tree)\n    sum(t.x)\n\n    Simplify expresion using explicit ``names`` dictionary.  In the example\n    below we replace the ``Symbol`` node with the string ``'t'``.\n\n    >>> tree = to_tree(t.x, names={t: 't'})\n    >>> tree # doctest: +SKIP\n    {'op': 'Field', 'args': ['t', 'x']}\n\n    >>> from_tree(tree, namespace={'t': t})\n    t.x\n\n    See Also\n    --------\n\n    blaze.server.server.to_tree\n    \"\"\"\n    if isinstance(expr, dict):\n        op, args = expr['op'], expr['args']\n        if 'slice' == op:\n            return expr_utils._slice(*[from_tree(arg, namespace)\n                                       for arg in args])\n        if hasattr(blaze.expr, op):\n            cls = getattr(blaze.expr, op)\n        else:\n            cls = expression_from_name(op)\n        if 'Symbol' in op:\n            children = [from_tree(arg) for arg in args]\n        else:\n            children = [from_tree(arg, namespace) for arg in args]\n        return cls(*children)\n    elif isinstance(expr, list):\n        return tuple(from_tree(arg, namespace) for arg in expr)\n    if namespace and expr in namespace:\n        return namespace[expr]\n    else:\n        return expr\n\n\n@api.route('/compute.<serial_format>',\n           methods=['POST', 'GET', 'HEAD', 'OPTIONS'])\n@crossdomain(origin='*', methods=['POST', 'GET', 'HEAD', 'OPTIONS'])\ndef compserver(serial_format):\n    try:\n        serial = _get_format(serial_format)\n    except KeyError:\n        return 'Unsupported serialization format', 404\n\n    try:\n        payload = serial.loads(request.data)\n    except ValueError:\n        return (\"Bad data.  Got %s \" % request.data, 400)  # 400: Bad Request\n\n    ns = payload.get('namespace', dict())\n    dataset = _get_data()\n    ns[':leaf'] = symbol('leaf', discover(dataset))\n\n    expr = from_tree(payload['expr'], namespace=ns)\n    assert len(expr._leaves()) == 1\n    leaf = expr._leaves()[0]\n\n    try:\n        result = compute(expr, {leaf: dataset})\n\n        if iscollection(expr.dshape):\n            result = odo(result, list)\n        elif isscalar(expr.dshape):\n            result = coerce_scalar(result, str(expr.dshape))\n    except NotImplementedError as e:\n        # 501: Not Implemented\n        return (\"Computation not supported:\\n%s\" % e, 501)\n    except Exception as e:\n        # 500: Internal Server Error\n        return (\"Computation failed with message:\\n%s\" % e, 500)\n\n    return serial.dumps({\n        'datashape': str(expr.dshape),\n        'data': result,\n        'names': expr.fields\n    })\n", "path": "blaze/server/server.py"}]}