Python socket.gethostname() Examples

The following are 30 code examples of socket.gethostname(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: cb_tools.py    From Forager with MIT License 7 votes vote down vote up
def run_feed_server():
    #stands up the feed server, points to the CB/json_feeds dir
    chdir('data/json_feeds/')
    port = 8000
    handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("", port), handler)

    try:
        print((Fore.GREEN + '\n[+]' + Fore.RESET), end=' ')
        print(('Feed Server listening at http://%s:8000' % gethostname()))
        httpd.serve_forever()
    except:
        print((Fore.RED + '\n[-]' + Fore.RESET), end=' ')
        print("Server exited")

    return 
Example #2
Source File: distributed.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def host_is_local(hostname, port=22): # no port specified, just use the ssh port
    """
    Returns True if the hostname points to the localhost, otherwise False.
    """
    hostname = socket.getfqdn(hostname)
    if hostname in ("localhost", "0.0.0.0", "127.0.0.1", "1.0.0.127.in-addr.arpa",
                    "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa"):
        return True
    localhost = socket.gethostname()
    if hostname == localhost:
        return True
    localaddrs = socket.getaddrinfo(localhost, port)
    targetaddrs = socket.getaddrinfo(hostname, port)
    for (ignored_family, ignored_socktype, ignored_proto, ignored_canonname,
         sockaddr) in localaddrs:
        for (ignored_rfamily, ignored_rsocktype, ignored_rproto,
             ignored_rcanonname, rsockaddr) in targetaddrs:
            if rsockaddr[0] == sockaddr[0]:
                return True
    return False 
Example #3
Source File: redis.py    From dino with Apache License 2.0 6 votes vote down vote up
def __init__(self, env, host: str, port: int = 6379, db: int = 0):
        if env.config.get(ConfigKeys.TESTING, False) or host == 'mock':
            from fakeredis import FakeStrictRedis

            self.redis_pool = None
            self.redis_instance = FakeStrictRedis(host=host, port=port, db=db)
        else:
            self.redis_pool = redis.ConnectionPool(host=host, port=port, db=db)
            self.redis_instance = None

        self.cache = MemoryCache()

        args = sys.argv
        for a in ['--bind', '-b']:
            bind_arg_pos = [i for i, x in enumerate(args) if x == a]
            if len(bind_arg_pos) > 0:
                bind_arg_pos = bind_arg_pos[0]
                break

        self.listen_port = 'standalone'
        if bind_arg_pos is not None and not isinstance(bind_arg_pos, list):
            self.listen_port = args[bind_arg_pos + 1].split(':')[1]

        self.listen_host = socket.gethostname().split('.')[0] 
Example #4
Source File: gsm19protocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(outputdir, sensorid, filedate, bindata, header):
    # File Operations
    try:
        hostname = socket.gethostname()
        path = os.path.join(outputdir,hostname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("Protocol: Error while saving file")        


## GEM -GSM19 protocol
## 
Example #5
Source File: client-test2.py    From The-chat-room with MIT License 6 votes vote down vote up
def video_invite():
    global IsOpen, Version, AudioOpen
    if Version == 4:
        host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
    else:
        host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
            -1]

    invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
    s.send(invite.encode())
    if not IsOpen:
        vserver = vachat.Video_Server(10087, Version)
        if AudioOpen:
            aserver = vachat.Audio_Server(10088, Version)
            aserver.start()
        vserver.start()
        IsOpen = True 
Example #6
Source File: client.py    From The-chat-room with MIT License 6 votes vote down vote up
def video_invite():
    global IsOpen, Version, AudioOpen
    if Version == 4:
        host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
    else:
        host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
            -1]

    invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
    s.send(invite.encode())
    if not IsOpen:
        vserver = vachat.Video_Server(10087, Version)
        if AudioOpen:
            aserver = vachat.Audio_Server(10088, Version)
            aserver.start()
        vserver.start()
        IsOpen = True 
Example #7
Source File: csprotocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(outputdir, sensorid, filedate, bindata, header):
    # File Operations
    try:
        hostname = socket.gethostname()
        path = os.path.join(outputdir,hostname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("OW - Protocol: Error while saving file")


## Caesium protocol
## 
Example #8
Source File: client-test.py    From The-chat-room with MIT License 6 votes vote down vote up
def video_invite():
    global IsOpen, Version, AudioOpen
    if Version == 4:
        host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
    else:
        host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
            -1]

    invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
    s.send(invite.encode())
    if not IsOpen:
        vserver = vachat.Video_Server(10087, Version)
        if AudioOpen:
            aserver = vachat.Audio_Server(10088, Version)
            aserver.start()
        vserver.start()
        IsOpen = True 
Example #9
Source File: crypto.py    From aegea with Apache License 2.0 6 votes vote down vote up
def ensure_ssh_key(name=None, base_name=__name__, verify_pem_file=True):
    if name is None:
        from getpass import getuser
        from socket import gethostname
        name = base_name + "." + getuser() + "." + gethostname().split(".")[0]

    try:
        ec2_key_pairs = list(resources.ec2.key_pairs.filter(KeyNames=[name]))
        if verify_pem_file and not os.path.exists(get_ssh_key_path(name)):
            msg = "Key {} found in EC2, but not in ~/.ssh."
            msg += " Delete the key in EC2, copy it to {}, or specify another key."
            raise KeyError(msg.format(name, get_ssh_key_path(name)))
    except ClientError as e:
        expect_error_codes(e, "InvalidKeyPair.NotFound")
        ec2_key_pairs = None

    if not ec2_key_pairs:
        ssh_key = ensure_local_ssh_key(name)
        resources.ec2.import_key_pair(KeyName=name,
                                      PublicKeyMaterial=get_public_key_from_pair(ssh_key))
        logger.info("Imported SSH key %s", get_ssh_key_path(name))
    add_ssh_key_to_agent(name)
    return name 
Example #10
Source File: getmetrics_hadoop.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    """Sends metric data to InsightFinder backend"""
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example #11
Source File: getmetrics_nfdump.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def sendData(metricData):
    sendDataTime = time.time()
    # prepare data for metric streaming agent
    toSendDataDict = {}
    toSendDataDict["metricData"] = json.dumps(metricData)
    toSendDataDict["licenseKey"] = agentConfigVars['licenseKey']
    toSendDataDict["projectName"] = agentConfigVars['projectName']
    toSendDataDict["userName"] = agentConfigVars['userName']
    toSendDataDict["instanceName"] = socket.gethostname().partition(".")[0]
    toSendDataDict["samplingInterval"] = str(int(reportingConfigVars['reporting_interval'] * 60))
    toSendDataDict["agentType"] = "nfdump"

    toSendDataJSON = json.dumps(toSendDataDict)
    logger.debug("TotalData: " + str(len(bytearray(toSendDataJSON))))

    #send the data
    postUrl = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(postUrl, data=json.loads(toSendDataJSON))
    if response.status_code == 200:
        logger.info(str(len(bytearray(toSendDataJSON))) + " bytes of data are reported.")
        updateLastSentFiles(pcapFileList)
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - sendDataTime)) 
Example #12
Source File: getlogs_Pufa.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    #for backend so this is the camel case in to_send_data_dict
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = config_vars['license_key']
    to_send_data_dict["projectName"] = config_vars['project_name']
    to_send_data_dict["userName"] = config_vars['user_name']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(config_vars['sampling_interval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['server_url'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.error("Failed to send data.")
    logger.info("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example #13
Source File: getmetrics_opentsdb.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example #14
Source File: cobs_ws_protocols.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(sensorid, filedate, bindata, header):
    # File Operations
    try:
        subdirname = socket.gethostname()
        path = os.path.join(outputdir,subdirname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("OW - Protocol: Error while saving file") 
Example #15
Source File: statsd.py    From dino with Apache License 2.0 6 votes vote down vote up
def __init__(self, env):
        self.env = env

        conf = env.config.get(ConfigKeys.STATS_SERVICE)
        host = conf.get(ConfigKeys.HOST)

        if env.config.get(ConfigKeys.TESTING, False) or host == 'mock':
            self.statsd = MockStatsd()
        else:
            import statsd

            port = conf.get(ConfigKeys.PORT)
            prefix = 'dino'
            if ConfigKeys.PREFIX in conf:
                prefix = conf.get(ConfigKeys.PREFIX)
            if ConfigKeys.INCLUDE_HOST_NAME in conf:
                include_host_name = conf.get(ConfigKeys.INCLUDE_HOST_NAME)
                if include_host_name is not None and str(include_host_name).strip().lower() in ['yes', '1', 'true']:
                    import socket
                    prefix = '%s.%s' % (prefix, socket.gethostname())

            self.statsd = statsd.StatsClient(host, int(port), prefix=prefix) 
Example #16
Source File: envprotocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(outputdir, sensorid, filedate, bindata, header):
    # File Operations
    try:
        hostname = socket.gethostname()
        path = os.path.join(outputdir,hostname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("OW - Protocol: Error while saving file")


## Environment protocol
## -------------------- 
Example #17
Source File: test_distributed.py    From neat-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_host_is_local():
    """test for neat.distributed.host_is_local"""
    tests = (
        # (hostname or ip, expected value)
        ("localhost", True),
        ("0.0.0.0", True),
        ("127.0.0.1", True),
        # ("::1", True), # depends on IP, etc setup on host to work right
        (socket.gethostname(), True),
        (socket.getfqdn(), True),
        ("github.com", False),
        ("google.de", False),
    )
    for hostname, islocal in tests:
        try:
            result = neat.host_is_local(hostname)
        except EnvironmentError:  # give more feedback
            print("test_host_is_local: Error with hostname {0!r} (expected {1!r})".format(hostname,
                                                                                          islocal))
            raise
        else:  # if do not want to do 'raise' above for some cases
            assert result == islocal, "Hostname/IP: {h}; Expected: {e}; Got: {r!r}".format(
                h=hostname, e=islocal, r=result) 
Example #18
Source File: arduinoprotocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(outputdir, sensorid, filedate, bindata, header):
    # File Operations
    try:
        hostname = socket.gethostname()
        path = os.path.join(outputdir,hostname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("Arduino - Protocol: Error while saving file")


## Arduino protocol
## -------------------- 
Example #19
Source File: bm35protocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(outputdir, sensorid, filedate, bindata, header):
    # File Operations
    try:
        hostname = socket.gethostname()
        path = os.path.join(outputdir,hostname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("Protocol: Error while saving file")        


## meteolabor BM35 protocol
## 
Example #20
Source File: identity.py    From glazier with Apache License 2.0 6 votes vote down vote up
def set_hostname(hostname: Optional[Text] = None) -> Text:
  """Sets the hostname in the registry.

   Gets hostname from socket.hostname if no hostname is passed.

  Args:
    hostname: Value to set as the hostname in registry.

  Returns:
    hostname: The determined hostname.

  Raise:
    Error: Failed to set hostname in registry.
  """
  if not hostname:
    hostname = socket.gethostname()

  hostname = hostname.strip()

  try:
    registry.set_value('Name', hostname)
  except registry.Error as e:
    raise Error(str(e))

  return hostname 
Example #21
Source File: kernprotocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(outputdir, sensorid, filedate, bindata, header):
    # File Operations
    try:
        hostname = socket.gethostname()
        path = os.path.join(outputdir,hostname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("KERN - Protocol: Error while saving file")        


## Environment protocol
## -------------------- 
Example #22
Source File: metricd.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def _configure(self):
        member_id = (
            "%s.%s.%s" % (socket.gethostname(),
                          self.worker_id,
                          # NOTE(jd) Still use a uuid here so we're
                          # sure there's no conflict in case of
                          # crash/restart
                          str(uuid.uuid4()))
        ).encode()
        self.coord = get_coordinator_and_start(member_id,
                                               self.conf.coordination_url)
        self.store = storage.get_driver(self.conf)
        self.incoming = incoming.get_driver(self.conf)
        self.index = indexer.get_driver(self.conf)
        self.chef = chef.Chef(self.coord, self.incoming,
                              self.index, self.store) 
Example #23
Source File: palmacqprotocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dataToFile(outputdir, sensorid, filedate, bindata, header):
    # File Operations
    try:
        hostname = socket.gethostname()
        path = os.path.join(outputdir,hostname,sensorid)
        # outputdir defined in main options class
        if not os.path.exists(path):
            os.makedirs(path)
        savefile = os.path.join(path, sensorid+'_'+filedate+".bin")
        if not os.path.isfile(savefile):
            with open(savefile, "wb") as myfile:
                myfile.write(header + "\n")
                myfile.write(bindata + "\n")
        else:
            with open(savefile, "a") as myfile:
                myfile.write(bindata + "\n")
    except:
        log.err("PalmAcq - Protocol: Error while saving file")


## PalmAcq protocol
## -------------------- 
Example #24
Source File: worker.py    From connecting_the_dots with MIT License 5 votes vote down vote up
def setup_experiment(self):
    self.exp_out_root = self.out_root / self.experiment_name
    self.exp_out_root.mkdir(parents=True, exist_ok=True)

    if logging.root: del logging.root.handlers[:]
    logging.basicConfig(
      level=logging.INFO,
      handlers=[
        logging.FileHandler( str(self.exp_out_root / 'train.log') ),
        logging.StreamHandler()
      ],
      format='%(relativeCreated)d:%(levelname)s:%(process)d-%(processName)s: %(message)s'
    )

    logging.info('='*80)
    logging.info(f'Start of experiment: {self.experiment_name}')
    logging.info(socket.gethostname())
    self.log_datetime()
    logging.info('='*80)

    self.metric_path = self.exp_out_root / 'metrics.json'
    if self.metric_path.exists():
      with open(str(self.metric_path), 'r') as fp:
        self.metric_data = json.load(fp)
    else:
      self.metric_data = {}

    self.init_seed() 
Example #25
Source File: io.py    From nsf with MIT License 5 votes vote down vote up
def on_cluster():
    hostname = socket.gethostname()
    return False if hostname == 'coldingham' else True 
Example #26
Source File: palmacqprotocol.py    From magpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, wsMcuFactory, sensor, outputdir):
        self.wsMcuFactory = wsMcuFactory
        self.sensorid = sensor
        self.hostname = socket.gethostname()
        self.outputdir = outputdir
        self.sensor = ''
        self.sensordict = {}
        self.ConversionConstant = 40/4/float(int("0x800000",16))
        eventstring = "evt0,evt1,evt3,evt11,evt12,evt13,evt32,evt60,evt99"
        self.eventlist = eventstring.split(',') 
Example #27
Source File: core.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def message_suffix(action, message=None):
    if not message:
        message = '{} by OSRT tools'.format(action)

    message += ' (host {})'.format(socket.gethostname())
    return message 
Example #28
Source File: core.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def message_suffix(action, message=None):
    if not message:
        message = '{} by OSRT tools'.format(action)

    message += ' (host {})'.format(socket.gethostname())
    return message 
Example #29
Source File: __init__.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example #30
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def fake_logout(request):
    """
    Fake logout view for devel without access to the fake CAS server
    """
    import socket
    hostname = socket.gethostname()
    if settings.DEPLOY_MODE == 'production' or hostname.startswith('courses'):
        # make sure we're not in production
        raise NotImplementedError
    
    from django.contrib.auth import logout
    logout(request)
    return HttpResponseRedirect('/')