Ticket #11730: trac_11730_pkg_resources_sagenb.patch

File trac_11730_pkg_resources_sagenb.patch, 15.2 KB (added by Julian Rüth, 11 years ago)

patch for sagenb

  • sagenb/misc/misc.py

    exporting patch:
    # HG changeset patch
    # User Julian Rüth <julian.rueth@gmail.com>
    Trac 11730: remove pkg_resource import from sage startup
    
    diff --git a/sagenb/misc/misc.py b/sagenb/misc/misc.py
    index 635ed3b..9611ed0 100644
    a b Miscellaneous Notebook Functions 
    1010#                  http://www.gnu.org/licenses/
    1111#############################################################################
    1212
    13 from pkg_resources import resource_filename
    14 
    1513def stub(f):
    1614    def g(*args, **kwds):
    1715        print "Stub: ", f.func_name
    def pad_zeros(s, size=3): 
    159157    """   
    160158    return "0"*(size-len(str(s))) + str(s)
    161159
    162 DATA = os.path.join(os.path.split(resource_filename(__name__, ''))[0], 'data')
     160def DATA():
     161    r"""
     162    Returns the sage nootebook data directory.
     163
     164    TESTS::
     165
     166        sage: import os.path
     167        sage: os.path.exists(sagenb.misc.misc.DATA())
     168        True
     169    """
     170    # the import of pkg_resources takes a considerable amount of time (see #11730)
     171    # therefore we do not want a global DATA variable which is initialized on every sage startup
     172    from pkg_resources import resource_filename
     173    return os.path.join(os.path.split(resource_filename(__name__, ''))[0], 'data')
    163174
    164175if os.environ.has_key('DOT_SAGENB'):
    165176    DOT_SAGENB = os.environ['DOT_SAGENB']
    except ImportError: 
    312323        # todo -- do we need this?
    313324        return code
    314325
    315 try:
    316     from pkg_resources import Requirement, working_set
    317     SAGENB_VERSION = working_set.find(Requirement.parse('sagenb')).version
    318 except AttributeError:
    319     SAGENB_VERSION = ""
     326def SAGENB_VERSION():
     327    r"""
     328    The current version of the sage notebook.
    320329
    321 try:
    322     import sage.version
    323     SAGE_VERSION=sage.version.version
    324 except ImportError:
    325     SAGE_VERSION=""
     330    TESTS::
     331
     332        sage: isinstance(sagenb.misc.misc.SAGENB_VERSION(),type(''))
     333        True
     334    """
     335    try:
     336        # the import of pkg_resources takes a considerable amount of time (see #11730)
     337        # therefore we do not want a global SAGENB_VERSION variable which is initialized on every sage startup
     338        from pkg_resources import Requirement, working_set
     339        return working_set.find(Requirement.parse('sagenb')).version
     340    except AttributeError:
     341        return ""
     342
     343def SAGE_VERSION():
     344    r"""
     345    The current version of sage.
     346
     347    TESTS::
     348
     349        sage: isinstance(sagenb.misc.misc.SAGE_VERSION(),type(''))
     350        True
     351    """
     352    # for consistency with SAGENB_VERSION this is a function and not a global variable
     353    try:
     354        import sage.version
     355        return sage.version.version
     356    except ImportError:
     357        return ""
    326358
    327359try:
    328360    from sage.plot.colors import Color
  • sagenb/notebook/notebook.py

    diff --git a/sagenb/notebook/notebook.py b/sagenb/notebook/notebook.py
    index 5924aa7..bfba26d 100644
    a b from sagenb.misc.misc import (pad_zeros, cputime, tmp_dir, load, save, 
    3636                              ignore_nonexistent_files, unicode_str)
    3737
    3838# Sage Notebook
    39 import css          # style
    40 import js           # javascript
    41 import worksheet    # individual worksheets (which make up a notebook)
    42 import config       # internal configuration stuff (currently, just keycodes)
    4339import keyboards    # keyboard layouts
    4440import server_conf  # server configuration
    4541import user_conf    # user configuration
    4642import user         # users
    47 from   template import template, prettify_time_ago
    4843
    4944
    5045try:
    class Notebook(object): 
    10121007        return id_number
    10131008
    10141009    def new_worksheet_with_title_from_text(self, text, owner):
     1010        import worksheet
    10151011        name, _ = worksheet.extract_name(text)
    10161012        W = self.create_new_worksheet(name, owner)
    10171013        return W
    class Notebook(object): 
    12981294            W.quit()
    12991295
    13001296    def update_worksheet_processes(self):
     1297        import worksheet
    13011298        worksheet.update_worksheets()
    13021299
    13031300    def quit_idle_worksheet_processes(self):
    class Notebook(object): 
    13681365        """
    13691366        data = worksheet.snapshot_data()  # pairs ('how long ago', key)
    13701367
     1368        from template import template
    13711369        return template(os.path.join("html", "notebook", "worksheet_revision_list.html"),
    13721370                        data = data, worksheet = worksheet,
    13731371                        notebook = self,
    class Notebook(object): 
    13911389        - a string - the revision rendered as HTML
    13921390        """
    13931391        t = time.time() - float(rev[:-4])
     1392        from template import prettify_time_ago
    13941393        time_ago = prettify_time_ago(t)
    13951394
    13961395        filename = ws.get_snapshot_text_filename(rev)
    class Notebook(object): 
    14101409                    next_rev = data[i+1][1]
    14111410                break
    14121411
     1412        from template import template
    14131413        return template(os.path.join("html", "notebook", "specific_revision.html"),
    14141414                        worksheet = ws,
    14151415                        username = username, rev = rev, prev_rev = prev_rev,
    class Notebook(object): 
    14401440        other_users = [x for x, u in U.iteritems() if not u.is_guest() and not u.username() in [username, 'pub', '_sage_']]
    14411441        other_users.sort(lambda x,y: cmp(x.lower(), y.lower()))
    14421442
     1443        from template import template
    14431444        return template(os.path.join("html", "notebook", "worksheet_share.html"),
    14441445                        worksheet = worksheet,
    14451446                        notebook = self,
    class Notebook(object): 
    14781479            file_is_text = True
    14791480            text_file_content = open(os.path.join(ws.data_directory(), filename)).read()
    14801481
     1482        from template import template
    14811483        return template(os.path.join("html", "notebook", "download_or_delete_datafile.html"),
    14821484                        worksheet = ws, notebook = self,
    14831485                        username = username,
    class Notebook(object): 
    15971599        plain_text = worksheet.plain_text(prompts=True, banner=False)
    15981600        plain_text = escape(plain_text).strip()
    15991601
     1602        from template import template
    16001603        return template(os.path.join("html", "notebook", "plain_text_window.html"),
    16011604                        worksheet = worksheet,
    16021605                        notebook = self,
    class Notebook(object): 
    16251628            u'...textarea class="plaintextedit"...{{{id=1|...//...}}}...'
    16261629        """
    16271630
     1631        from template import template
    16281632        return template(os.path.join("html", "notebook", "edit_window.html"),
    16291633                        worksheet = worksheet,
    16301634                        notebook = self,
    class Notebook(object): 
    16621666        <input type="checkbox" name="auto" style="margin-left:13px" /> Automatically re-publish when changes are made
    16631667        </form>
    16641668        """
     1669        from template import template
    16651670        return template(os.path.join("html", "notebook", "beforepublish_window.html"),
    16661671                        worksheet = worksheet,
    16671672                        notebook = self,
    class Notebook(object): 
    16901695        from time import strftime
    16911696        time = strftime("%B %d, %Y %I:%M %p", dtime)
    16921697
     1698        from template import template
    16931699        return template(os.path.join("html", "notebook", "afterpublish_window.html"),
    16941700                        worksheet = worksheet,
    16951701                        notebook = self,
    class Notebook(object): 
    17161722            sage: nb.html_upload_data_window(W, 'admin')
    17171723            u'...Upload or Create Data File...Browse...url...name of a new...'
    17181724        """
     1725        from template import template
    17191726        return template(os.path.join("html", "notebook", "upload_data_window.html"),
    17201727                        worksheet = ws, username = username)
    17211728
    class Notebook(object): 
    17621769        elif W.is_published() or self.user_is_guest(username):
    17631770            template_page = os.path.join('html', 'notebook', 'guest_worksheet_page.html')
    17641771
     1772        from template import template
    17651773        return template(template_page, worksheet = W,
    17661774                        notebook = self, do_print=do_print,
    17671775                        username = username, show_debug = show_debug)
  • sagenb/notebook/template.py

    diff --git a/sagenb/notebook/template.py b/sagenb/notebook/template.py
    index ab1148e..8d132bb 100644
    a b from sagenb.notebook.jsmath import math_parse 
    2727if os.environ.has_key('SAGENB_TEMPLATE_PATH'):
    2828    TEMPLATE_PATH = os.environ['SAGENB_TEMPLATE_PATH']
    2929else:
    30     TEMPLATE_PATH = os.path.join(DATA, 'sage')
     30    TEMPLATE_PATH = os.path.join(DATA(), 'sage')
    3131env = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATE_PATH))
    3232
    3333css_illegal_re = re.compile(r'[^-A-Za-z_0-9]')
    def template(filename, **user_context): 
    143143    from twist import notebook
    144144    #A dictionary containing the default context
    145145    default_context = {'sitename': 'Sage Notebook',
    146                        'sage_version': SAGE_VERSION,
     146                       'sage_version': SAGE_VERSION(),
    147147                       'JSMATH': JSMATH,
    148148                       'JEDITABLE_TINYMCE': JEDITABLE_TINYMCE,
    149149                       'conf': notebook.conf() if notebook else None}
  • sagenb/notebook/twist.py

    diff --git a/sagenb/notebook/twist.py b/sagenb/notebook/twist.py
    index 8ad287c..71769ad 100644
    a b from sagenb.misc.misc import (SAGE_DOC, DATA, SAGE_VERSION, walltime, 
    5757                              tmp_filename, tmp_dir, is_package_installed,
    5858                              jsmath_macros, encoded_str, unicode_str)
    5959
    60 css_path             = os.path.join(DATA, "sage", "css")
    61 image_path           = os.path.join(DATA, "sage", "images")
    62 javascript_path      = os.path.join(DATA)
    63 sage_javascript_path = os.path.join(DATA, 'sage', 'js')
    64 java_path            = os.path.join(DATA)
     60css_path             = os.path.join(DATA(), "sage", "css")
     61image_path           = os.path.join(DATA(), "sage", "images")
     62javascript_path      = os.path.join(DATA())
     63sage_javascript_path = os.path.join(DATA(), 'sage', 'js')
     64java_path            = os.path.join(DATA())
    6565
    6666jsmath_image_fonts = is_package_installed("jsmath-image-fonts")
    6767
    class RegistrationPage(resource.PostableResource): 
    23382338                         'default_user': notebook.default_user(),
    23392339                         'welcome': username,
    23402340                         'recovery': notebook.conf()['email'],
    2341                          'sage_version': SAGE_VERSION}
     2341                         'sage_version': SAGE_VERSION()}
    23422342
    23432343        form = template(os.path.join('html', 'login.html'), **template_dict)
    23442344        return HTMLResponse(stream = form)
    class Toplevel(resource.PostableResource): 
    25172517        template_dict = {'accounts': notebook.get_accounts(),
    25182518                         'default_user': notebook.default_user(),
    25192519                         'recovery': notebook.conf()['email'],
    2520                          'sage_version':SAGE_VERSION}
     2520                         'sage_version':SAGE_VERSION()}
    25212521        return HTMLResponse(stream=template(os.path.join('html', 'login.html'), **template_dict))
    25222522
    25232523    def userchildFactory(self, request, name):
    class LoginResourceClass(resource.Resource): 
    25332533        template_dict = {'accounts': notebook.get_accounts(),
    25342534                         'default_user': notebook.default_user(),
    25352535                         'recovery': notebook.conf()['email'],
    2536                          'sage_version':SAGE_VERSION}
     2536                         'sage_version':SAGE_VERSION()}
    25372537        return HTMLResponse(stream=template(os.path.join('html', 'login.html'), **template_dict))
    25382538
    25392539    def childFactory(self, request, name):
    class AnonymousToplevel(Toplevel): 
    25532553    child_javascript = Javascript()
    25542554    child_java = Java()
    25552555    child_logout = LogoutRedirectLogin()
    2556     child_static = static.File(DATA)
     2556    child_static = static.File(DATA())
    25572557
    25582558    def userchildFactory(self, request, name):
    25592559        # This is called from Toplevel above
    class AnonymousToplevel(Toplevel): 
    25722572        template_dict = {'accounts': notebook.get_accounts(),
    25732573                         'default_user': notebook.default_user(),
    25742574                         'recovery': notebook.conf()['email'],
    2575                          'sage_version':SAGE_VERSION}
     2575                         'sage_version':SAGE_VERSION()}
    25762576        response = HTMLResponse(stream=template(os.path.join('html', 'login.html'), **template_dict))
    25772577        response.headers.setHeader("set-cookie", [http_headers.Cookie('cookie_test_%s' % notebook.port, 'cookie_test')])
    25782578        return response
    class FailedToplevel(Toplevel): 
    25922592                             'default_user': notebook.default_user(),
    25932593                             'username_error': True,
    25942594                             'recovery': notebook.conf()['email'],
    2595                              'sage_version':SAGE_VERSION}
     2595                             'sage_version':SAGE_VERSION()}
    25962596            return HTMLResponse(stream=template(os.path.join('html', 'login.html'), **template_dict))
    25972597        elif self.problem == 'password':
    25982598            template_dict = {'accounts': notebook.get_accounts(),
    25992599                             'default_user': self.username,
    26002600                             'password_error': True,
    26012601                             'recovery': notebook.conf()['email'],
    2602                              'sage_version':SAGE_VERSION}
     2602                             'sage_version':SAGE_VERSION()}
    26032603            return HTMLResponse(stream=template(os.path.join('html', 'login.html'), **template_dict))
    26042604        elif self.problem == 'suspended':
    26052605            return HTMLResponse(stream = message("Your account is currently suspended."))
    class UserToplevel(Toplevel): 
    26152615    child_css = CSS()
    26162616    child_javascript = Javascript()
    26172617    child_java = Java()
    2618     child_static = static.File(DATA)
     2618    child_static = static.File(DATA())
    26192619
    26202620    child_logout = Logout()
    26212621
  • sagenb/notebook/worksheet.py

    diff --git a/sagenb/notebook/worksheet.py b/sagenb/notebook/worksheet.py
    index f15a1ab..072736c 100644
    a b import string 
    3636import time
    3737import traceback
    3838
    39 from twisted.internet.defer import Deferred
    40 
    4139# General sage library code
    4240from sagenb.misc.misc import (cython, load, save,
    4341                              alarm, cancel_alarm, verbose, DOT_SAGENB,
    except (KeyError, IOError): 
    31583156        S = self.__sage
    31593157        S.interrupt()
    31603158       
     3159        from twisted.internet.defer import Deferred
    31613160        deferred = Deferred()
    31623161        deferred.addCallback(callback)
    31633162       
  • sagenb/testing/HTMLTestRunner.py

    diff --git a/sagenb/testing/HTMLTestRunner.py b/sagenb/testing/HTMLTestRunner.py
    index 3eb1718..60da67d 100644
    a b class HTMLTestRunner(object): 
    408408
    409409        template_dict['title'] = jinja2.escape(self.title)
    410410        template_dict['description'] = jinja2.escape(self.description)
    411         template_dict['sagenb_version'] = SAGENB_VERSION
     411        template_dict['sagenb_version'] = SAGENB_VERSION()
    412412        template_dict['environment'] = self.extra_args.get('environment')
    413413        template_dict['start_time'] = str(self.start_time)[:19]
    414414        template_dict['stop_time'] = str(self.stop_time)[:19]