当前位置: 首页>>代码示例>>Python>>正文


Python Server.shutdown方法代码示例

本文整理汇总了Python中server.Server.shutdown方法的典型用法代码示例。如果您正苦于以下问题:Python Server.shutdown方法的具体用法?Python Server.shutdown怎么用?Python Server.shutdown使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在server.Server的用法示例。


在下文中一共展示了Server.shutdown方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Listener

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import shutdown [as 别名]

#.........这里部分代码省略.........
    def assign_session_id(self, pkg):
        '''
        Assign current session id to the package. Session id is selected from
        database. For every device id (first elemen of the package) attach
        current session id.
        Args:
            pkg: dict. Package.
        Returns:
            Package (dict) or None.
        '''
        if not pkg:
            return False
        ses_id = self.database.select(
                'connections', ['ses_id'], 
                {'device_id': pkg['device_id']}
        )

        if len(ses_id):
            pkg['ses_id'] = ses_id[0][0]
            return True
        else:
            logging.debug('Fail to find session assigned to device id {} .'.format(
                pkg['device_id']))

        return False

    def insert_to_db(self, pkg):
        '''
        Load package to database.
        Args:
            pkg: dict, with parsed data
        '''
        # Load package data to database
        if pkg['type'] == 'D':
            # There is need to change package structure
            if not self.database.insert(expand_pkg_struct(), 
                    [data_for_db(pkg, expand_pkg_struct())], 'packages'):
                logging.info('Fail to load package to database.')
        elif pkg['type'] == 'T':
            msg_s = msg_structure + ['ses_id']
            if not self.database.insert(msg_s, 
                    [[pkg[item] for item in msg_s],], 'messages'):
                logging.info('Fail to load package to database.')
        elif pkg['type'] == 'I':
            pass
        else:
            logging.info('Unkonwn type of the packages. Skipping. Package '
                    'already saved.')


    def save_pkg(self, pkg):
        '''
        Saves package to session file.
        Args:
            pkg: dict, with parsed data
        '''
        if pkg['type'] == 'E':
            filename = '{}/{}'.format(config['data_storage'], 
                                      config['corrupted_storage'])
        else:
            filename = '{}/{}.txt'.format(config['data_storage'], pkg['ses_id'])

        # Create server's data directory if doesn't exist
        try:
            if not os.path.exists(config['data_storage']):
                os.makedirs(config['data_storage'], 0o755)
        except OSError as exp:
            logging.error(('Fail to create data storage directory. Exception:'
                           '{}').format(exp))

        # Write package to file
        with open(filename, 'a+') as _file:
            _file.write(pkg['original'])
            _file.write('\n')

    def is_session_created(self, session):
        '''
        Check in database if session with this id already created or not.
        Args:
            session: string or integer
        Returns:
            True if created, otherwise False.
        '''
        status = self.database.select('sessions', ['ses_id'], 
                {'ses_id': session})

        return True if status else False

    def stop(self):
        '''
        Stop main loop in this thread.
        '''
        logging.info('Stop.')
        # Stop socket server
        self.server.shutdown()
        self.server.server_close()
        # Close database connection
        self.database.close()

        sys.exit(0)
开发者ID:alberand,项目名称:database,代码行数:104,代码来源:listener.py

示例2: Server

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import shutdown [as 别名]
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import socket
import time

from select import select

import config
from server import Server
import channel
import user

if __name__ == "__main__":
    server = Server()
    try:
        server.run()
    #except Exception, e:
    #    print e
    except KeyboardInterrupt:
        pass
    finally:
        server.shutdown()
开发者ID:carriercomm,项目名称:omgircd,代码行数:32,代码来源:ircd.py

示例3: sighandle

# 需要导入模块: from server import Server [as 别名]
# 或者: from server.Server import shutdown [as 别名]
class Application:
	""" Main application class. """
	server = None

	def sighandle(self, signum, frame):
		""" Used for asynchronous signal handling. """
		print(' ')
		print('Killing ScalyMUCK server...')
		self.server.shutdown()	
		logging.shutdown()

	def __init__(self, workdir, is_daemon=False):
		""" Called by main() or by the daemoniser code. """	
		workdir += '/'

		home_path = os.path.expanduser('~')
		data_path = '%s/.scalyMUCK/' % (home_path)

		config = settings.Settings('%sconfig/settings_server.cfg' % (workdir))

		# Make sure the folder exists. (doesn't cause any issues if it already exists)
		os.system('mkdir %s' % (data_path))

		# Reset any logs
		if (config.get_index('ClearLogsOnStart', bool) is True):
			if ('win' in sys.platform):
				os.system('del %s*.txt' % (data_path))
			elif ('linux' in sys.platform):
				os.system('rm %s*.txt' % (data_path))
			
		# Prepare the server log
		# NOTE: This code looks sucky, could it be improved to look better?
		formatting = logging.Formatter('%(levelname)s (%(asctime)s): %(message)s', '%d/%m/%y at %I:%M:%S %p')
		console_handle = logging.StreamHandler()
		if (config.get_index(index='LogConnections', datatype=bool)):
			logger = logging.getLogger('Connections')
			logger.setLevel(logging.INFO)

			file_handle = logging.FileHandler('%sconnection_log.txt' % (data_path))
			file_handle.setLevel(logging.DEBUG)
			file_handle.setFormatter(formatting)

			logger.info('ScalyMUCK Server Server Start')
			logger.addHandler(file_handle)
			if (is_daemon is False):
				logger.addHandler(console_handle)

		if (config.get_index(index='LogServer', datatype=bool)):
			logger = logging.getLogger('Server')
			logger.setLevel(logging.INFO)

			file_handle = logging.FileHandler('%sserver_log.txt' % (data_path))
			file_handle.setLevel(logging.INFO)
			file_handle.setFormatter(formatting)			

			logger.addHandler(file_handle)
			if (is_daemon is False):
				logger.addHandler(console_handle)
			logger.info('ScalyMUCK Server Server Start')

		# Check for if we're trying to run as root (if we're on linux)
		if ('linux' in sys.platform):
			run_as_root = config.get_index(index='I_DONT_KNOW_HOW_TO_SECURITY_LET_ME_RUN_AS_ROOT',datatype=bool)
			if (os.geteuid() == 0 and run_as_root is False):
				logger.error('FATAL -- You should not run this application as root!')
				return
			elif (os.geteuid() == 0 and run_as_root):
				logger.warn('WARNING -- It is your death wish running this application as root.')

		# Prepare the other logs
		if (config.get_index(index='LogMods', datatype=bool)):
			logger = logging.getLogger('Mods')
			logger.setLevel(logging.INFO)

			file_handle = logging.FileHandler('%smod_log.txt' % (data_path))
			file_handle.setLevel(logging.INFO)
			file_handle.setFormatter(formatting)

			logger.info('ScalyMUCK Server Server Start')
			logger.addHandler(file_handle)
			if (is_daemon is False):
				logger.addHandler(console_handle)

		self.server = Server(config=config, path=data_path, workdir=workdir)

		# Set the signals for asynchronous events
		signal.signal(signal.SIGINT, self.sighandle)
		signal.signal(signal.SIGTERM, self.sighandle)

		while (self.server.is_running):
			self.server.update()

		print(' ')
		print('Killing ScalyMUCK server ...')
		self.server.shutdown()	
		logging.shutdown()
开发者ID:Ragora,项目名称:ScalyMUCK,代码行数:98,代码来源:main.py


注:本文中的server.Server.shutdown方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。