Repository: bokeh/bokeh

Issue:
Remove serverconfig.py
I think all this functionality has moved to session.py

@hhuuggoo is this correct?



Discussion:
Does this imply we will have finally clear separation between `bokeh` and `bokeh.server` modules?

That's part of the intent. 

> On Jun 10, 2014, at 8:04, Mateusz Paprocki notifications@github.com wrote:
> 
> Does this imply we will have finally clear separation between bokeh and bokeh.server modules?
> 
> —
> Reply to this email directly or view it on GitHub.

Cool. So, there should be no more `Exception KeyError (...)` when quitting server.

^^ thank goodness. 

@bryevdv yes this file should not be needed anymore


Resolving patch:
diff --git a/bokeh/__init__.py b/bokeh/__init__.py
--- a/bokeh/__init__.py
+++ b/bokeh/__init__.py
@@ -78,7 +78,6 @@ def load_notebook(resources=None, verbose=False, force=False):
 
 from .settings import settings
 from . import sampledata
-from .serverconfig import Server, Cloud
 
 def _print_versions():
     """Returns all the versions of software that Bokeh relies on."""
diff --git a/bokeh/serverconfig.py b/bokeh/serverconfig.py
deleted file mode 100644
--- a/bokeh/serverconfig.py
+++ /dev/null
@@ -1,201 +0,0 @@
-from __future__ import absolute_import, print_function
-
-import json
-from os import makedirs
-from os.path import expanduser, exists, join
-import tempfile
-
-try:
-    import pandas as pd
-    import tables
-except ImportError as e:
-    pass
-
-from six.moves.urllib.parse import urljoin, urlencode
-
-from . import utils, browserlib
-from bokeh.objects import ServerDataSource
-bokeh_plots_url = "http://bokehplots.cloudapp.net/"
-
-
-class Server(object):
-    def __init__(self, name="http://localhost:5006/",
-                 root_url="http://localhost:5006/",
-                 userapikey="nokey",
-                 username="defaultuser",
-                 load_from_config=True,
-                 configdir=None
-                 ):
-        """name : name of server
-        root_url : root_url of server
-        load_from_config : whether or not to load login information
-        from config.  if False, then we may overwrite the users
-        config with this data
-        """
-        self.name = name
-        self.root_url = root_url
-        #single user mode case
-        self.userapikey = userapikey
-        self.username = username
-        self._configdir = None
-        if configdir:
-            self.configdir = configdir
-        if load_from_config:
-            self.load()
-
-    @property
-    def http_session(self):
-        if hasattr(self, "_http_session"):
-            return self._http_session
-        else:
-            import requests
-            self._http_session = requests.session()
-            return self._http_session
-
-    @property
-    def username(self):
-        return self.http_session.headers.get('BOKEHUSER')
-
-    @username.setter
-    def username(self, val):
-        self.http_session.headers.update({'BOKEHUSER': val})
-
-    @property
-    def userapikey(self):
-        return self.http_session.headers.get('BOKEHUSER-API-KEY')
-
-    @userapikey.setter
-    def userapikey(self, val):
-        self.http_session.headers.update({'BOKEHUSER-API-KEY': val})
-
-    @property
-    def configdir(self):
-        """filename where our config are stored"""
-        if self._configdir:
-            return self._configdir
-        bokehdir = join(expanduser("~"), ".bokeh")
-        if not exists(bokehdir):
-            makedirs(bokehdir)
-        return bokehdir
-
-    #for testing
-    @configdir.setter
-    def configdir(self, path):
-        self._configdir = path
-
-    @property
-    def configfile(self):
-        return join(self.configdir, "config.json")
-
-    def load_dict(self):
-        configfile = self.configfile
-        if not exists(configfile):
-            data = {}
-        else:
-            with open(configfile, "r") as f:
-                data = json.load(f)
-        return data
-
-    def load(self):
-        config_info = self.load_dict().get(self.name, {})
-        print("found config for %s" % self.name)
-        print(str(config_info))
-        print("loading it!")
-        print("if you don't wish to load this config, please pass load_from_config=False")
-        self.root_url = config_info.get('root_url', self.root_url)
-        self.userapikey = config_info.get('userapikey', self.userapikey)
-        self.username = config_info.get('username', self.username)
-
-    def save(self):
-        data = self.load_dict()
-        data[self.name] = {'root_url': self.root_url,
-                           'userapikey': self.userapikey,
-                           'username': self.username}
-        configfile = self.configfile
-        with open(configfile, "w+") as f:
-            json.dump(data, f)
-        return
-
-    def register(self, username, password):
-        url = urljoin(self.root_url, "bokeh/register")
-        result = self.http_session.post(url, data={
-                'username': username,
-                'password': password,
-                'api': 'true'
-                })
-        if result.status_code != 200:
-            raise RuntimeError("Unknown Error")
-        result = utils.get_json(result)
-        if result['status']:
-            self.username = username
-            self.userapikey = result['userapikey']
-            self.save()
-        else:
-            raise RuntimeError(result['error'])
-
-    def login(self, username, password):
-        url = urljoin(self.root_url, "bokeh/login")
-        result = self.http_session.post(url, data={
-                'username': username,
-                'password': password,
-                'api': 'true'
-                })
-        if result.status_code != 200:
-            raise RuntimeError("Unknown Error")
-        result = utils.get_json(result)
-        if result['status']:
-            self.username = username
-            self.userapikey = result['userapikey']
-            self.save()
-        else:
-            raise RuntimeError(result['error'])
-        self.save()
-
-    def browser_login(self):
-        controller = browserlib.get_browser_controller()
-        url = urljoin(self.root_url, "bokeh/loginfromapikey")
-        url += "?" + urlencode({'username': self.username,
-                                'userapikey': self.userapikey})
-        controller.open(url)
-        
-    def _prep_data_source_df(self, name, dataframe):
-        name = tempfile.NamedTemporaryFile(prefix="bokeh_data", 
-                                           suffix=".pandas").name
-        store = pd.HDFStore(name)
-        store.append("__data__", dataframe, format="table", data_columns=True)
-        store.close()
-        return name
-        
-    def _prep_data_source_numpy(self, name, arr):
-        name = tempfile.NamedTemporaryFile(prefix="bokeh_data", 
-                                           suffix=".table").name
-        store = tables.File(name, 'w')
-        store.createArray("/", "__data__", obj=arr)
-        store.close()
-        return name
-
-    def data_source(self, name, dataframe=None, array=None):
-        if dataframe is not None:
-            fname = self._prep_data_source_df(name, dataframe)
-            target_name = name + ".pandas"
-        else:
-            fname = self._prep_data_source_numpy(name, array)
-            target_name = name + ".table"
-        url = urljoin(self.root_url, 
-                      "bokeh/data/upload/%s/%s" % (self.username, target_name))
-        with open(fname) as f:
-            result = self.http_session.post(url, files={'file' : (target_name, f)})
-        return ServerDataSource(owner_username=self.username, data_url=result.content)
-
-    def list_data(self):
-        url = urljoin(self.root_url, "bokeh/data/" + self.username)
-        result = self.http_session.get(url)
-        result = utils.get_json(result)
-        sources = result['sources']
-        return sources
-
-
-class Cloud(Server):
-    def __init__(self):
-        super(Cloud, self).__init__(name="cloud",
-                                    root_url=bokeh_plots_url)


Test patch:
diff --git a/bokeh/server/tests/multiuser_auth_test.py b/bokeh/server/tests/multiuser_auth_test.py
--- a/bokeh/server/tests/multiuser_auth_test.py
+++ b/bokeh/server/tests/multiuser_auth_test.py
@@ -5,7 +5,7 @@
 from . import test_utils
 from ..app import bokeh_app
 from ..models import user
-from ...serverconfig import Server
+from ...session import Session
 from ...tests.test_utils import skipIfPy3, skipIfPyPy
 
 
@@ -105,7 +105,7 @@ def test_register(self):
         #create a dummy config file
         config = tempfile.mkdtemp()
         #create server
-        server = Server(name="foo", root_url="http://localhost:5006/",
+        server = Session(name="foo", root_url="http://localhost:5006/",
                         configdir=config
                         )
         assert server.userapikey == "nokey"
@@ -114,7 +114,7 @@ def test_register(self):
         assert server.userapikey and server.userapikey != "nokey"
         #create a second server configuration
         #make sure it loads the proper api key
-        server2 = Server(name="foo",
+        server2 = Session(name="foo",
                          configdir=config
                          )
         assert server2.userapikey == server.userapikey
@@ -125,7 +125,7 @@ def test_register(self):
     def test_login(self):
         #create a server config, register a user
         config1 = tempfile.mkdtemp()
-        server = Server(name="foo", root_url="http://localhost:5006/",
+        server = Session(name="foo", root_url="http://localhost:5006/",
                         configdir=config1
                         )
         assert server.userapikey == "nokey"
@@ -134,7 +134,7 @@ def test_login(self):
 
         #create a separate server config, login a user
         config2 = tempfile.mkdtemp()
-        server2 = Server(name="foo", root_url="http://localhost:5006/",
+        server2 = Session(name="foo", root_url="http://localhost:5006/",
                          configdir=config2
                          )
         assert server2.userapikey == "nokey"
diff --git a/bokeh/server/tests/remotedata_tests.py b/bokeh/server/tests/remotedata_tests.py
--- a/bokeh/server/tests/remotedata_tests.py
+++ b/bokeh/server/tests/remotedata_tests.py
@@ -11,7 +11,7 @@
 from unittest import skip
 
 from . import test_utils
-from ...serverconfig import Server
+from ...session import Session
 from ...tests.test_utils import skipIfPyPy
 from unittest import skipIf
 arraymanagement_missing = False
@@ -33,7 +33,7 @@ class RemoteDataTestCase(test_utils.BokehServerTestCase):
     @skipIfPyPy("gevent requires pypycore and pypy-hacks branch of gevent.")
     def test_list(self):
         config = tempfile.mkdtemp()
-        s = Server(configdir=config)
+        s = Session(configdir=config)
         sources = s.list_data()
         result = set(['/defaultuser/GOOG.hdf5',
                       '/defaultuser/FB.hdf5',
@@ -48,7 +48,7 @@ def test_list(self):
     @skipIfPyPy("gevent requires pypycore and pypy-hacks branch of gevent.")
     def test_line_downsample(self):
         config = tempfile.mkdtemp()
-        s = Server(configdir=config)
+        s = Session(configdir=config)
         url = "http://localhost:5006/bokeh/data/defaultuser/defaultuser/AAPL.hdf5"
         params = ('close', 'date', ['close', 'open', 'date'], 
                   [1000 * time.mktime(dt.datetime(2012,1,1).timetuple()),
@@ -78,7 +78,7 @@ def test_upload(self):
         
     @skipIf(arraymanagement_missing, "array management not installed")
     def test_client(self):
-        s = Server()
+        s = Session()
         fname = s._prep_data_source_numpy("foo", np.array([1,2,3,4,5]))
         assert exists(fname)
         data = pd.DataFrame({'a' : [1,2,3,4,5], 'b' :[1,2,3,4,5]})