Python os.path.split() Examples

The following are code examples for showing how to use os.path.split(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_path_base(cls, path, special=False, handle_image=False):
        # Extract basename, without file extension, from URL path
        # If not special, return None if non-html file or index.html
        if ('/'+FILES_PATH) in path:
            return None

        if handle_image:
            imatch = cls.image_path.match(path)
            if imatch:
                return imatch.group(2)

        if not special and not path.endswith('.html'):
            return None
        basename = path.split('/')[-1]
        if '.' in basename:
            basename, sep, suffix = basename.rpartition('.')
        if not special and basename == 'index':
            return None
        return basename 
Example 2
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getPluginMethod(self, pluginName, pluginMethodName):
        if pluginName not in self.pluginInstances:
            pluginModule = getattr(plugins, pluginName, None)
            if not pluginModule:
                raise Exception('Plugin '+pluginName+' not loaded!')
            pluginClass = getattr(pluginModule, pluginName)
            if not pluginClass:
                raise Exception('Plugin class '+pluginName+'.'+pluginName+' not defined!')
            try:
                pluginPath = self.pathUser[0]
                if Options['site_name']:
                    pluginPath = '/'.join( pluginPath.split('/')[1:] )
                if pluginPath.startswith(PRIVATE_PATH+'/'):
                    pluginPath = '/'.join( pluginPath.split('/')[1:] )
                self.pluginInstances[pluginName] = pluginClass(PluginManager.getManager(pluginName), pluginPath, self.pathUser[1], self.userRole)
            except Exception, err:
                raise Exception('Error in creating instance of plugin '+pluginName+': '+err.message) 
Example 3
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def renew_ssl(force=False):
    outText = ''
    if not force:
        days_left = cert_daysleft()
        if days_left is None or days_left <= -9999 or days_left >= 30:
            return outText
        print >> sys.stderr, 'sdserver: Reloading after renewing SSL cert', days_left, 'days before expiry:', sliauth.iso_date(nosubsec=True)

    try:
        server_domain = Options['server_url'].split('//')[1].split(':')[0]
        cmd = ['certbot', 'certonly', '-n', '--webroot', '--config-dir', './certbot/config', '--logs-dir', './certbot/log', '--work-dir', './certbot/work', '-w', './acme-web', '-d', server_domain]

        print >> sys.stderr, 'Executing: '+' '.join(cmd)
        outText += 'Executing: '+' '.join(cmd) + '\n'
        certOutput = subprocess.check_output(cmd)

        print >> sys.stderr, 'Output:\n%s' % certOutput
        outText += 'Renewal status:\n'+certOutput
    except Exception, excp:
        errMsg = 'Error in renewal of SSL cert: '+str(excp)
        print >> sys.stderr, errMsg
        outText += errMsg + '\n' 
Example 4
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def update_site_roles(self, siteName, adminIds, graderIds, guestIds):
        roles = (sdproxy.ADMIN_ROLE, sdproxy.GRADER_ROLE, '')
        idLists = [adminIds, graderIds, guestIds]
        self.site_roles[siteName] = {}
        self.site_special_users[siteName] = set()

        for j, role in enumerate(roles):
            for userId in idLists[j].split(','):
                userId = userId.strip()
                if not userId:
                    continue
                if userId in self.root_role:
                    if role != self.root_role[userId]:
                        print >> sys.stderr, 'WARNING: User %s already has global %s role' % (userId, self.root_role[userId])
                    continue
                if userId in self.site_roles[siteName]:
                    print >> sys.stderr, 'WARNING: User %s already has site %s role in %s' % (userId, self.site_roles[siteName][userId], siteName)
                    continue
                self.site_roles[siteName][userId] = role
                self.site_special_users[siteName].add(userId) 
Example 5
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_session_props(cls):
        propStr = Global.site_settings.get('session_properties','')
        if propStr.strip():
            propsList = propStr.strip().split(';')
        else:
            propsList = cls.defaultSessionTypes
        propsDict = OrderedDict()
        for sessionProp in propsList:
            comps = sessionProp.strip().split(':')
            sessionName = comps[0].strip()
            if sessionName:
                props = {}
                if len(comps) > 1 and comps[1].strip().isdigit():
                    props['pace'] = int(comps[1].strip())
                else:
                    props['pace'] = 0

                props['access'] = comps[2].strip().lower() if len(comps) > 2 else ''
                props['description'] = comps[3].strip() if len(comps) > 3 else ''
                    
                propsDict[sessionName] = props
        return propsDict 
Example 6
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def update_session_settings(site_settings):
    # For single or secondary server (NOT CURRENTLY USED)

    Global.session_options = {}
    for key in site_settings:
        smatch = SESSION_OPTS_RE.match(key)
        if smatch:
            # Default session options
            sessionName = smatch.group(1)
            opts_dict = {}
            opts = [x.lstrip('-') for x in site_settings[key].split()]
            for opt in opts:
                name, sep, value = opt.partition('=')
                if not sep:
                    opts_dict[name] = True
                else:
                    if value.startswith("'"):
                        value = value.strip("'")
                    elif value.startswith('"'):
                        value = value.strip('"')
                    if isdigit(value):
                        value = int(value)
                    opts_dict[name] = value
            Global.session_options[sessionName] = opts_dict 
Example 7
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/' + script_name
        if not self.has_metadata(script):
            raise ResolutionError(
                "Script {script!r} not found in metadata at {self.egg_info!r}"
                .format(**locals()),
            )
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename, 'exec')
            exec(script_code, namespace, namespace) 
Example 8
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 9
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def _by_version_descending(names):
    """
    Given a list of filenames, return them in descending order
    by version number.

    >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
    >>> _by_version_descending(names)
    ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
    """
    def _by_version(name):
        """
        Parse each component of the filename
        """
        name, ext = os.path.splitext(name)
        parts = itertools.chain(name.split('-'), [ext])
        return [packaging.version.parse(part) for part in parts]

    return sorted(names, key=_by_version, reverse=True) 
Example 10
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 11
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/' + script_name
        if not self.has_metadata(script):
            raise ResolutionError(
                "Script {script!r} not found in metadata at {self.egg_info!r}"
                .format(**locals()),
            )
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename, 'exec')
            exec(script_code, namespace, namespace) 
Example 12
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 13
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def _by_version_descending(names):
    """
    Given a list of filenames, return them in descending order
    by version number.

    >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
    >>> _by_version_descending(names)
    ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
    """
    def _by_version(name):
        """
        Parse each component of the filename
        """
        name, ext = os.path.splitext(name)
        parts = itertools.chain(name.split('-'), [ext])
        return [packaging.version.parse(part) for part in parts]

    return sorted(names, key=_by_version, reverse=True) 
Example 14
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 15
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: homebrew.py    MIT License 6 votes vote down vote up
def _current_package_is_installed(self):
        if not self.valid_package(self.current_package):
            self.failed = True
            self.message = 'Invalid package: {0}.'.format(self.current_package)
            raise HomebrewException(self.message)

        cmd = [
            "{brew_path}".format(brew_path=self.brew_path),
            "info",
            self.current_package,
        ]
        rc, out, err = self.module.run_command(cmd)
        for line in out.split('\n'):
            if (
                re.search(r'Built from source', line)
                or re.search(r'Poured from bottle', line)
            ):
                return True

        return False 
Example 16
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 6 votes vote down vote up
def _macosx_vers(_cache=[]):
    if not _cache:
        import platform
        version = platform.mac_ver()[0]
        # fallback for MacPorts
        if version == '':
            import plistlib
            plist = '/System/Library/CoreServices/SystemVersion.plist'
            if os.path.exists(plist):
                if hasattr(plistlib, 'readPlist'):
                    plist_content = plistlib.readPlist(plist)
                    if 'ProductVersion' in plist_content:
                        version = plist_content['ProductVersion']

        _cache.append(version.split('.'))
    return _cache[0] 
Example 17
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 6 votes vote down vote up
def run_script(self,script_name,namespace):
        script = 'scripts/'+script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n','\n')
        script_text = script_text.replace('\r','\n')
        script_filename = self._fn(self.egg_info,script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            execfile(script_filename, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text,script_filename,'exec')
            exec(script_code, namespace, namespace) 
Example 18
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 19
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra,reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':',1)
                            if invalid_marker(marker):
                                reqs=[] # XXX warn
                            elif not evaluate_marker(marker):
                                reqs=[]
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra,[]).extend(parse_requirements(reqs))
            return dm 
Example 20
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 6 votes vote down vote up
def _macosx_vers(_cache=[]):
    if not _cache:
        import platform
        version = platform.mac_ver()[0]
        # fallback for MacPorts
        if version == '':
            import plistlib
            plist = '/System/Library/CoreServices/SystemVersion.plist'
            if os.path.exists(plist):
                if hasattr(plistlib, 'readPlist'):
                    plist_content = plistlib.readPlist(plist)
                    if 'ProductVersion' in plist_content:
                        version = plist_content['ProductVersion']

        _cache.append(version.split('.'))
    return _cache[0] 
Example 21
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 22
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def config_dict(filename):
    """Convert content of config-file into dictionary."""
    f = open(filename, "r")
    cfglines = f.readlines()
    f.close()
    cfgdict = {}
    for line in cfglines:
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        try:
            key, value = line.split("=")
        except:
            print "Bad line in config-file %s:\n%s" % (filename,line)
            continue
        key = key.strip()
        value = value.strip()
        if value in ["True", "False", "None", "''", '""']:
            value = eval(value)
        else:
            try:
                if "." in value:
                    value = float(value)
                else:
                    value = int(value)
            except:
                pass # value need not be converted
        cfgdict[key] = value
    return cfgdict 
Example 23
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def readconfig(cfgdict):
    """Read config-files, change configuration-dict accordingly.

    If there is a turtle.cfg file in the current working directory,
    read it from there. If this contains an importconfig-value,
    say 'myway', construct filename turtle_mayway.cfg else use
    turtle.cfg and read it from the import-directory, where
    turtle.py is located.
    Update configuration dictionary first according to config-file,
    in the import directory, then according to config-file in the
    current working directory.
    If no config-file is found, the default configuration is used.
    """
    default_cfg = "turtle.cfg"
    cfgdict1 = {}
    cfgdict2 = {}
    if isfile(default_cfg):
        cfgdict1 = config_dict(default_cfg)
        #print "1. Loading config-file %s from: %s" % (default_cfg, os.getcwd())
    if "importconfig" in cfgdict1:
        default_cfg = "turtle_%s.cfg" % cfgdict1["importconfig"]
    try:
        head, tail = split(__file__)
        cfg_file2 = join(head, default_cfg)
    except:
        cfg_file2 = ""
    if isfile(cfg_file2):
        #print "2. Loading config-file %s:" % cfg_file2
        cfgdict2 = config_dict(cfg_file2)
##    show(_CFG)
##    show(cfgdict2)
    _CFG.update(cfgdict2)
##    show(_CFG)
##    show(cfgdict1)
    _CFG.update(cfgdict1)
##    show(_CFG) 
Example 24
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def write_docstringdict(filename="turtle_docstringdict"):
    """Create and write docstring-dictionary to file.

    Optional argument:
    filename -- a string, used as filename
                default value is turtle_docstringdict

    Has to be called explicitly, (not used by the turtle-graphics classes)
    The docstring dictionary will be written to the Python script <filname>.py
    It is intended to serve as a template for translation of the docstrings
    into different languages.
    """
    docsdict = {}

    for methodname in _tg_screen_functions:
        key = "_Screen."+methodname
        docsdict[key] = eval(key).__doc__
    for methodname in _tg_turtle_functions:
        key = "Turtle."+methodname
        docsdict[key] = eval(key).__doc__

    f = open("%s.py" % filename,"w")
    keys = sorted([x for x in docsdict.keys()
                        if x.split('.')[1] not in _alias_list])
    f.write('docsdict = {\n\n')
    for key in keys[:-1]:
        f.write('%s :\n' % repr(key))
        f.write('        """%s\n""",\n\n' % docsdict[key])
    key = keys[-1]
    f.write('%s :\n' % repr(key))
    f.write('        """%s\n"""\n\n' % docsdict[key])
    f.write("}\n")
    f.close() 
Example 25
Project: AutoDL   Author: tanguofu   File: response.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def file(
        location, mime_type=None, headers=None, filename=None, _range=None):
    """Return a response object with file data.

    :param location: Location of file on system.
    :param mime_type: Specific mime_type.
    :param headers: Custom Headers.
    :param filename: Override filename.
    :param _range:
    """
    headers = headers or {}
    if filename:
        headers.setdefault(
            'Content-Disposition',
            'attachment; filename="{}"'.format(filename))
    filename = filename or path.split(location)[-1]

    async with open_async(location, mode='rb') as _file:
        if _range:
            await _file.seek(_range.start)
            out_stream = await _file.read(_range.size)
            headers['Content-Range'] = 'bytes %s-%s/%s' % (
                _range.start, _range.end, _range.total)
        else:
            out_stream = await _file.read()

    mime_type = mime_type or guess_type(filename)[0] or 'text/plain'
    return HTTPResponse(status=200,
                        headers=headers,
                        content_type=mime_type,
                        body_bytes=out_stream) 
Example 26
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def revert_to_plain_user(self):
        username = self.get_id_from_cookie()
        role, sites = Global.userRoles.id_role_sites(username)
        if role:
            # Global role; switch to guest in all sites
            plainSites = ','.join(Options['site_list'])
        else:
            # Site roles; switch to guest in sites
            plainSites = ','.join(site.split('+')[0] for site in sites.split(','))

        name = self.get_id_from_cookie(name=True)
        data = self.get_id_from_cookie(data=True)
        self.set_id(username, displayName=name, role='', sites=plainSites, email=self.get_id_from_cookie(email=True), data=data) 
Example 27
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_id_from_cookie(self, role=False, for_site='', sites=False, name=False, email=False, altid=False, data=False):
        # If for_site and site name does not appear in cookie.sites, None will be returned for role
        # Null string will be returned for role, if site name is present
        cookieStr = self.get_user_cookie()
        if not cookieStr:
            return None
        try:
            comps = [urllib.unquote(x) for x in cookieStr.split(':')]
            ##if Options['debug']:
                ##print >> sys.stderr, "DEBUG: sdserver.UserIdMixin.get_id_from_cookie", comps
            userId, userRole, userSites, token, data_json = comps[:5]
            userData = json.loads(base64.b64decode(data_json))

            if role:
                if not userRole and for_site:
                    if not userSites:
                        return None
                    return sdproxy.getSiteRole(for_site, userSites)
                return userRole

            if sites:
                return userSites
            if name:
                return userData.get('name', '')
            if email:
                return userData.get('email', '')
            if altid:
                return userData.get('altid', '')
            if data:
                return userData
            return userId
        except Exception, err:
            print >> sys.stderr, 'sdserver: COOKIE ERROR - '+str(err)
            self.clear_user_cookie()
            return None 
Example 28
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def batch_login(self, site_name=''):
        # Batch auto login for localhost through query parameter: ...?auth=userId:token
        # To print exams using headless browser: ...?auth=userId:token&print=1
        site_key = sliauth.gen_site_key(Options['root_auth_key'], site_name) if site_name else Options['root_auth_key']
        upload_key = sliauth.gen_hmac_token(site_key, 'upload:')

        userId, batchMode, siteRole, cookieData = None, None, None, None
        query = self.request.query
        if query.startswith('auth='):
            query = query.split('&')[0]
            qauth = urllib.unquote(query[len('auth='):])
            temUserId, token = qauth.split(':')
            nonce = self.use_nonce(site_name, temUserId)
            if nonce:
                batchToken = sliauth.gen_hmac_token(upload_key, 'batch:'+temUserId+':'+nonce)
                if token == upload_key or token == batchToken:
                    batchMode = site_name or '_root'
                    cookieData = {'batch': batchMode}
                elif token == gen_proxy_auth_token(temUserId, root=True):
                    cookieData = {}
                else:
                    print >> sys.stderr, 'sdserver: Invalid auth= for temUserId '+temUserId
                    temUserId = None

                if temUserId is not None:
                    userId = temUserId
                    print >> sys.stderr, "UserIdMixin.batch_login: BATCH ACCESS", self.request.path, site_name, userId
                    self.set_id(userId, displayName=userId, data=cookieData)
        return userId, batchMode, siteRole, cookieData 
Example 29
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def displaySheet(self, sessionName, download=False, allUsers=False, keepHidden=False):
            sheet = sdproxy.getSheet(sessionName, display=True)
            if not sheet:
                self.displayMessage('Unable to retrieve sheet '+sessionName)
                return
            lastname_col, firstname_col, midname_col, id_col, email_col, altid_col = Options["roster_columns"].split(',')
            timestamp = ''
            if sessionName.endswith('_answers') or sessionName.endswith('_correct') or sessionName.endswith('_stats'):
                try:
                    timestamp = sliauth.iso_date(sdproxy.lookupValues('_average', ['Timestamp'], sessionName)['Timestamp'])
                except Exception, excp:
                    pass 
Example 30
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self):
        temUser = self.get_argument('username', '')
        dispName = self.get_argument('dispname', '')
        accessToken = self.get_argument('token', '')
        print >> sys.stderr, "UnauthMessageHandler.post", temUser

        comps = accessToken.split(':')
        if len(comps) != 3:
            raise Exception('Invalid access token for user '+temUser)
        temSiteName, sessionName, _ = comps
        if not self.check_locked_token(temUser, accessToken, temSiteName, sessionName):
            raise Exception('Invalid access token for user '+temUser)
        userId = temUser
        userRole = ''
        choice = self.get_argument('choice', '')
        number = self.get_argument('number', '')
        message = self.get_argument('message', '')
        source = self.get_argument('source', 'interact')
        if choice:
            message = choice + ' ' + message
        elif number:
            message = number + ' ' + message

        status = WSHandler.processMessage(userId, userRole, dispName or userId, message, allStatus=True, source=source, adminBroadcast=True)
        if not status:
            status = 'Accepted answer: '+message

        self.set_header('Content-Type', 'application/json')
        self.write( json.dumps( {'result': 'success', 'status': status} ) ) 
Example 31
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def updateImportParams(paramStr, prevParams={'importKey':'', 'keyColName':'', 'skipKeys':''}):
    params = prevParams.copy()
    if paramStr:
        comps = [x.strip() for x in paramStr.split(';')]
        if len(comps) > 0 and comps[0] and not params['importKey']:
            params['importKey'] = comps[0]
        if len(comps) > 1 and comps[1] and not params['keyColName']:
            params['keyColName'] = comps[1]
        if len(comps) > 2 and not params['skipKeys']:
            params['skipKeys'] = ';'.join(comps[2:])
    return params 
Example 32
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cert_daysleft():
    if not Options['ssl_options'] or not Options['ssl_options']['certfile'].startswith('certbot/'):
        return None
    try:
        cmd = ['openssl', 'x509', '-enddate', '-noout', '-in', Options['ssl_options']['certfile']]
        expdatestr = subprocess.check_output(cmd).split('=')[-1].strip()
        expdate = datetime.datetime.strptime(expdatestr,'%b %d %H:%M:%S %Y %Z')
        return (expdate - datetime.datetime.today()).days
    except Exception, excp:
        print >> sys.stderr, 'sdserver/cert_daysleft: ERROR: '+' '.join(cmd) + ': '+ str(excp)
        return -9999 
Example 33
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def root_start_secondary(site_number, site_name, site_settings={}):
    # Return error message or null string
    # site_settings should be specified for transient (no conf file) sites
    if not SiteOpts.get(site_name):
        raise Exception('ERROR: Cannot start site %s not found in root site list %s' % (site_name, Options['site_list']))
    if site_name != SiteOpts.keys()[site_number-1]:
        raise Exception('ERROR: Inconsistent name %s for site number %d: expecting %s' % (site_name, site_number, SiteOpts.keys()[site_number-1]))

    child = Global.child_procs.get(site_name)
    if child and child.proc.poll() is None:
        # Running process
        raise Exception('ERROR: Site %s process still running' % site_name)

    mod_args = sys.argv[:1]
    for arg in sys.argv[1:]:
        argname, _, val = arg.lstrip('-').partition('=')
        if argname != 'sites' and argname not in site_settings:
            mod_args.append(arg)
    mod_args += ['--multisite']
    mod_args += ['--server_version='+sliauth.get_version()]
    mod_args += ['--server_nonce='+Options['server_nonce']]
    mod_args += ['--config_digest='+Global.config_digest]
    mod_args += ['--site_number='+str(site_number)]
    mod_args += ['--site_name='+site_name]
    if site_settings:
        mod_args += ['--%s=%s' % (key, site_settings[key]) for key in SITE_OPTS if key in site_settings]
    else:
        for key in SITE_OPTS:
            # Handle split options for backwards compatibility
            if key in Global.split_site_opts and site_name in Global.split_site_opts[key]:
                mod_args += ['--%s=%s' % (key, Global.split_site_opts[key][site_name]) ]

    Global.child_procs[site_name] = tornado.process.Subprocess(mod_args) 
Example 34
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def site_server_setup():
    # For single or secondary server
    if Options['auth_type'] != 'none':
        # Copy server options to proxy
        sdproxy.copyServerOptions(Options)

        # Copy site config to proxy
        sdproxy.copySiteConfig(Global.site_settings)

        update_session_settings(Global.site_settings)

    sdproxy.initProxy(gradebookActive=('gradebook' in SiteProps.get_site_menu()),
                      accessCodeCallback=checkAccessCode, teamSetupCallback=WSHandler.teamNotify, discussPostCallback=WSHandler.postNotify)

    bak_dir = getBakDir(Options['site_name'])
    if bak_dir:
        restoreSite(bak_dir)

    if Options['twitter_config']:
        comps = [x.strip() for x in Options['twitter_config'].split(',')]
        Global.twitter_params = {
            'screen_name': comps[0],
            'consumer_token': {'consumer_key': comps[1], 'consumer_secret': comps[2]},
            'access_token': {'key': comps[3], 'secret': comps[4]}
            }

        Global.twitter_params['site_twitter'] = Global.twitter_params['screen_name']
        if sdproxy.Settings['no_roster']:
            Global.twitter_params['site_twitter'] = '@' + Global.twitter_params['site_twitter']

        import sdstream
        Global.twitterStream = sdstream.TwitterStreamReader(Global.twitter_params, processTwitterMessage,
                                                     allow_replies=Options['allow_replies'])
        Global.twitterStream.start_stream() 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _macosx_vers(_cache=[]):
    if not _cache:
        version = platform.mac_ver()[0]
        # fallback for MacPorts
        if version == '':
            plist = '/System/Library/CoreServices/SystemVersion.plist'
            if os.path.exists(plist):
                if hasattr(plistlib, 'readPlist'):
                    plist_content = plistlib.readPlist(plist)
                    if 'ProductVersion' in plist_content:
                        version = plist_content['ProductVersion']

        _cache.append(version.split('.'))
    return _cache[0] 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _fn(self, base, resource_name):
        if resource_name:
            return os.path.join(base, *resource_name.split('/'))
        return base 
Example 37
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _setup_prefix(self):
        # we assume here that our metadata may be nested inside a "basket"
        # of multiple eggs; that's why we use module_path instead of .archive
        path = self.module_path
        old = None
        while path != old:
            if _is_egg_path(path):
                self.egg_name = os.path.basename(path)
                self.egg_info = os.path.join(path, 'EGG-INFO')
                self.egg_root = path
                break
            old = path
            path, base = os.path.split(path) 
Example 38
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _rebuild_mod_path(orig_path, package_name, module):
    """
    Rebuild module.__path__ ensuring that all entries are ordered
    corresponding to their sys.path order
    """
    sys_path = [_normalize_cached(p) for p in sys.path]

    def safe_sys_path_index(entry):
        """
        Workaround for #520 and #513.
        """
        try:
            return sys_path.index(entry)
        except ValueError:
            return float('inf')

    def position_in_sys_path(path):
        """
        Return the ordinal of the path based on its position in sys.path
        """
        path_parts = path.split(os.sep)
        module_parts = package_name.count('.') + 1
        parts = path_parts[:-module_parts]
        return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))

    if not isinstance(orig_path, list):
        # Is this behavior useful when module.__path__ is not a list?
        return

    orig_path.sort(key=position_in_sys_path)
    module.__path__[:] = [_normalize_cached(p) for p in orig_path] 
Example 39
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def declare_namespace(packageName):
    """Declare that package 'packageName' is a namespace package"""

    _imp.acquire_lock()
    try:
        if packageName in _namespace_packages:
            return

        path, parent = sys.path, None
        if '.' in packageName:
            parent = '.'.join(packageName.split('.')[:-1])
            declare_namespace(parent)
            if parent not in _namespace_packages:
                __import__(parent)
            try:
                path = sys.modules[parent].__path__
            except AttributeError:
                raise TypeError("Not a package:", parent)

        # Track what packages are namespaces, so when new path items are added,
        # they can be updated
        _namespace_packages.setdefault(parent, []).append(packageName)
        _namespace_packages.setdefault(packageName, [])

        for path_item in path:
            # Ensure all the parent's path items are reflected in the child,
            # if they apply
            _handle_ns(packageName, path_item)

    finally:
        _imp.release_lock() 
Example 40
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def file_ns_handler(importer, path_item, packageName, module):
    """Compute an ns-package subpath for a filesystem or zipfile importer"""

    subpath = os.path.join(path_item, packageName.split('.')[-1])
    normalized = _normalize_cached(subpath)
    for item in module.__path__:
        if _normalize_cached(item) == normalized:
            break
    else:
        # Only return the path if it's not already there
        return subpath 
Example 41
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def clone(self, **kw):
        """Copy this distribution, substituting in any changed keyword args"""
        names = 'project_name version py_version platform location precedence'
        for attr in names.split():
            kw.setdefault(attr, getattr(self, attr, None))
        kw.setdefault('metadata', self._provider)
        return self.__class__(**kw) 
Example 42
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _bypass_ensure_directory(path):
    """Sandbox-bypassing version of ensure_directory()"""
    if not WRITE_SUPPORT:
        raise IOError('"os.mkdir" not supported on this platform.')
    dirname, filename = split(path)
    if dirname and filename and not isdir(dirname):
        _bypass_ensure_directory(dirname)
        mkdir(dirname, 0o755) 
Example 43
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _macosx_vers(_cache=[]):
    if not _cache:
        version = platform.mac_ver()[0]
        # fallback for MacPorts
        if version == '':
            plist = '/System/Library/CoreServices/SystemVersion.plist'
            if os.path.exists(plist):
                if hasattr(plistlib, 'readPlist'):
                    plist_content = plistlib.readPlist(plist)
                    if 'ProductVersion' in plist_content:
                        version = plist_content['ProductVersion']

        _cache.append(version.split('.'))
    return _cache[0] 
Example 44
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _setup_prefix(self):
        # we assume here that our metadata may be nested inside a "basket"
        # of multiple eggs; that's why we use module_path instead of .archive
        path = self.module_path
        old = None
        while path != old:
            if _is_egg_path(path):
                self.egg_name = os.path.basename(path)
                self.egg_info = os.path.join(path, 'EGG-INFO')
                self.egg_root = path
                break
            old = path
            path, base = os.path.split(path) 
Example 45
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _parts(self, zip_path):
        # Convert a zipfile subpath into an egg-relative path part list.
        # pseudo-fs path
        fspath = self.zip_pre + zip_path
        if fspath.startswith(self.egg_root + os.sep):
            return fspath[len(self.egg_root) + 1:].split(os.sep)
        raise AssertionError(
            "%s is not a subpath of %s" % (fspath, self.egg_root)
        ) 
Example 46
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _rebuild_mod_path(orig_path, package_name, module):
    """
    Rebuild module.__path__ ensuring that all entries are ordered
    corresponding to their sys.path order
    """
    sys_path = [_normalize_cached(p) for p in sys.path]

    def safe_sys_path_index(entry):
        """
        Workaround for #520 and #513.
        """
        try:
            return sys_path.index(entry)
        except ValueError:
            return float('inf')

    def position_in_sys_path(path):
        """
        Return the ordinal of the path based on its position in sys.path
        """
        path_parts = path.split(os.sep)
        module_parts = package_name.count('.') + 1
        parts = path_parts[:-module_parts]
        return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))

    if not isinstance(orig_path, list):
        # Is this behavior useful when module.__path__ is not a list?
        return

    orig_path.sort(key=position_in_sys_path)
    module.__path__[:] = [_normalize_cached(p) for p in orig_path] 
Example 47
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def file_ns_handler(importer, path_item, packageName, module):
    """Compute an ns-package subpath for a filesystem or zipfile importer"""

    subpath = os.path.join(path_item, packageName.split('.')[-1])
    normalized = _normalize_cached(subpath)
    for item in module.__path__:
        if _normalize_cached(item) == normalized:
            break
    else:
        # Only return the path if it's not already there
        return subpath 
Example 48
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _set_parent_ns(packageName):
    parts = packageName.split('.')
    name = parts.pop()
    if parts:
        parent = '.'.join(parts)
        setattr(sys.modules[parent], name, sys.modules[packageName]) 
Example 49
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def clone(self, **kw):
        """Copy this distribution, substituting in any changed keyword args"""
        names = 'project_name version py_version platform location precedence'
        for attr in names.split():
            kw.setdefault(attr, getattr(self, attr, None))
        kw.setdefault('metadata', self._provider)
        return self.__class__(**kw) 
Example 50
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def _bypass_ensure_directory(path):
    """Sandbox-bypassing version of ensure_directory()"""
    if not WRITE_SUPPORT:
        raise IOError('"os.mkdir" not supported on this platform.')
    dirname, filename = split(path)
    if dirname and filename and not isdir(dirname):
        _bypass_ensure_directory(dirname)
        mkdir(dirname, 0o755)