本文整理汇总了Python中server.server.Server类的典型用法代码示例。如果您正苦于以下问题:Python Server类的具体用法?Python Server怎么用?Python Server使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Server类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TransmitterLogging
class TransmitterLogging(TransmitterBase):
def setUp(self):
self.server = Server()
self.server.setLogTarget("/dev/null")
self.server.setLogLevel(0)
super(TransmitterLogging, self).setUp()
def testLogTarget(self):
logTargets = []
for _ in xrange(3):
tmpFile = tempfile.mkstemp("fail2ban", "transmitter")
logTargets.append(tmpFile[1])
os.close(tmpFile[0])
for logTarget in logTargets:
self.setGetTest("logtarget", logTarget)
# If path is invalid, do not change logtarget
value = "/this/path/should/not/exist"
self.setGetTestNOK("logtarget", value)
self.transm.proceed(["set", "/dev/null"])
for logTarget in logTargets:
os.remove(logTarget)
self.setGetTest("logtarget", "STDOUT")
self.setGetTest("logtarget", "STDERR")
self.setGetTest("logtarget", "SYSLOG")
def testLogLevel(self):
self.setGetTest("loglevel", "4", 4)
self.setGetTest("loglevel", "2", 2)
self.setGetTest("loglevel", "-1", -1)
self.setGetTest("loglevel", "0", 0)
self.setGetTestNOK("loglevel", "Bird")
示例2: main
def main():
parser = argparse.ArgumentParser(description='Tic Tac Toe')
subparsers = parser.add_subparsers(title='module', dest='module')
subparsers.required = True
subparsers.add_parser('server', help='start the server')
subparsers.add_parser('client', help='start a client')
args = parser.parse_args()
if args.module == 'server':
server = Server()
try:
server.start()
except BaseException as e:
logger.error('Process interrupted, stopping the server', exc_info=e)
finally:
server.stop()
elif args.module == 'client':
client = Client()
try:
client.connect()
client.run()
except BaseException as e:
logger.error('Process interrupted, disconnecting the client', exc_info=e)
finally:
client.disconnect()
else:
print('unknown module {}'.format(args.module), file=sys.stderr)
示例3: __init__
def __init__(self, port, ds_host, ds_port):
super(FileService, self).__init__()
self.dir = ''
self.port = port
self.ds_host = ds_host
self.ds_port = ds_port
self.server = Server(port, self._handler)
示例4: setUp
def setUp(self):
"""Call before every test case."""
self.__server = Server()
self.__transm = self.__server._Server__transm
self.__server.setLogTarget("/dev/null")
self.__server.setLogLevel(0)
sock_fd, sock_name = tempfile.mkstemp('fail2ban.sock', 'transmitter')
os.close(sock_fd)
pidfile_fd, pidfile_name = tempfile.mkstemp(
'fail2ban.pid', 'transmitter')
os.close(pidfile_fd)
self.__server.start(sock_name, pidfile_name, force=False)
self.jailName = "TestJail1"
self.__server.addJail(self.jailName, "auto")
示例5: FileService
class FileService(object):
"""docstring for FileService"""
def __init__(self, port, ds_host, ds_port):
super(FileService, self).__init__()
self.dir = ''
self.port = port
self.ds_host = ds_host
self.ds_port = ds_port
self.server = Server(port, self._handler)
def announce_server(self):
sock = self.server.send_as_client(self.ds_host, self.ds_port, "INSERT " + self.server.host + ":" + str(self.port) + " " + "1")
data = sock.recv(1024)
if data.decode('utf-8') != response200():
print("Error with Directory Server: ", data)
sock.shutdown(socket.SHUT_WR)
sock.close()
#TODO Add to allow exsting files or remove
def _open_handler(self, conn, path):
filename = self.dir + path
if not os.path.isfile(filename):
self.server.error(conn, 404, response404())
else:
f = open(filename, "rb")
pdb.set_trace()
self.server.send_file(conn, f)
conn.shutdown(socket.SHUT_WR)
conn.close()
def _create_handler(self, conn, path):
file_path = os.path.dirname(path)
if not os.path.isdir(file_path):
self.server.error(conn, 405, response405())
else:
self.server.respond(conn, response200())
exists = os.path.isfile(self.dir + path)
f = open(self.dir + path, "wb")
conn.recv_file(f)
f.close()
self.server.respond(conn, response200())
# TODO: send to other replication managers
# if not exists:
#
def _mkdir_handler(self, conn, path):
newdir = str(self.dir + path.strip('/'))
basedir = os.path.dirname(newdir)
if not os.path.isdir(basedir):
self.server.error(conn, 404, response404())
else:
try:
os.makedirs(newdir)
self.server.respond(conn, response200())
# self._advertise_buffer.add(path.strip('/'), ObjectBuffer.Type.directory)
# TODO: send to replication manager
except Exception as e:
if e.errno != errno.EEXIST:
raise
else:
conn.send()
def _delete_handler(self, conn, path):
pdb.set_trace()
obj = str(self.dir + path).rstrip('/')
if os.path.isdir(obj):
shutil.rmtree(obj)
self.server.respond(conn, response200())
# self._advertise_buffer.add(path, ObjectBuffer.Type.deleteDirectory)
elif os.path.isfile(obj):
os.remove(obj)
self.server.respond(conn, response200())
# self._advertise_buffer.add(path, ObjectBuffer.Type.deleteFile)
else:
self.server.error(conn, 404, "not found!")
def _handler(self, sock):
LF = "\n"
try:
data = sock.recv(1024)
msg = data.decode('utf-8')
msg = msg.replace('$', ' ')
if 'KILL_SERVICE' in msg:
exit()
elif msg[:4] == "HELO":
response = ["IP:" + self.server.host, "Port:" + str(self.port), "StudentID:" + self.server.studentId]
fullResponse = msg + LF.join(response)
print(response)
sock.send(fullResponse.encode('utf-8'))
elif msg[:4] == "OPEN":
temp = msg.split()
self._open_handler(sock, temp[1])
elif msg[:6] == "CREATE":
temp = msg.split()
self._create_handler(sock, temp[1])
elif msg[:5] == "MKDIR":
temp = msg.split()
self._mkdir_handler(sock, temp[1])
elif msg[:6] == "DELETE":
#.........这里部分代码省略.........
示例6: __init__
def __init__(self, port):
super(LockService, self).__init__()
self.port = port
self._create_tables()
self.server = Server(port, self._handler)
示例7: setUp
def setUp(self):
self.server = Server()
self.server.setLogTarget("/dev/null")
self.server.setLogLevel(0)
super(TransmitterLogging, self).setUp()
示例8: StartStop
class StartStop(unittest.TestCase):
def setUp(self):
"""Call before every test case."""
self.__server = Server()
self.__server.setLogLevel(0)
self.__server.start(False)
def tearDown(self):
"""Call after every test case."""
self.__server.quit()
def testStartStopJail(self):
name = "TestCase"
self.__server.addJail(name)
self.__server.startJail(name)
time.sleep(1)
self.__server.stopJail(name)
示例9: Tree
"""Script to launch the Python Aboard server."""
import os
import sys
from command.tree import Tree
from server.server import Server
from model import Model
from system import *
from tools.console import Console
commands = Tree()
commands.add_default_commands()
command, args = commands.process(sys.argv[1:])
source_directory = get_source_directory()
if command:
directory = args.path
server = Server(directory, check_dir=command.project_created)
server.source_directory = source_directory
if command.project_created and not command.children:
server.load_configurations()
server.prepare()
server.load_bundles()
command.server = server
command.execute(args)
if command.project_created:
Model.data_connector.repository_manager.save()
示例10: test_get_routers
def test_get_routers(self):
routers = Server.get_routers()
assert len(routers) != 0
assert isinstance(routers[0], Router)
示例11: serverStartWithParams
def serverStartWithParams():
Server.start(debug_mode=True, config_path="../tests/config", vlan_activate=False)
示例12: Server
#!/usr/bin/env python3
from server.server import Server
if __name__ == "__main__":
server = Server(host='', port=8080)
server.run()
示例13:
#!/usr/bin/env python3
from server.server import Server
Server.start()
示例14: LockService
class LockService(Database):
"""
LockService provdes functionality to lock access to a particular file on the fileservers.
Every service that writes to file uses the lockService, every read of a file checks if the particular file is locked.
The lockservice provides rudimentary acknowledgments on all operations
"""
DATABASE = "sql.db"
def __init__(self, port):
super(LockService, self).__init__()
self.port = port
self._create_tables()
self.server = Server(port, self._handler)
def _lock_file(self, file_name):
is_locked = self._check_if_locked(file_name)
if is_locked:
return False
insert = self.execute_sql("insert into locks (file_name) values (?)", (file_name,), exclusive=True)
if insert:
return True
else:
return False
def _unlock_file(self, file_name):
delete = self.execute_sql("delete from locks where file_name = ?", (file_name,), exclusive=True)
if delete:
return True
else:
return False
def _check_if_locked(self, file_name):
data = self.fetch_sql("select * from locks where file_name=?", (file_name,))
if file_name in data:
return True
else:
return False
def _handler(self, sock):
try:
data = sock.recv(1024)
msg = data.decode('utf-8')
msg = msg.replace('$', ' ')
if 'KILL_SERVICE' in msg:
exit()
elif msg[:4] == "LOCK":
temp = msg.split()
is_locked = self._unlock_file(temp[1])
if is_locked:
self.server.respond(sock, response200())
else:
self.server.respond(sock, response604())
elif msg[:6] == "UNLOCK":
temp = msg.split()
is_unlocked = self._unlock_file( temp[1])
if is_unlocked:
self.server.respond(sock, response200())
else:
self.server.respond(sock, response604())
elif msg[:5] == "CHECK":
temp = msg.split()
locked = self._check_if_locked(temp[1])
if locked:
self.server.respond(sock, responseLocked())
else:
self.server.respond(sock, responseUnlocked())
else:
self.server.error(sock, 0, responseErrParse())
except sock.error as e:
err = e.args[0]
self.server.error(sock, 0, e.args[1])
def _create_tables(self):
conn = sqlite3.connect(self.DATABASE)
cur = conn.cursor()
cur.executescript("""
create table if not exists locks(
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_name TEXT
);""")
示例15: TransmitterLogging
class TransmitterLogging(TransmitterBase):
def setUp(self):
self.server = Server()
self.server.setLogTarget("/dev/null")
self.server.setLogLevel(0)
super(TransmitterLogging, self).setUp()
def testLogTarget(self):
logTargets = []
for _ in xrange(3):
tmpFile = tempfile.mkstemp("fail2ban", "transmitter")
logTargets.append(tmpFile[1])
os.close(tmpFile[0])
for logTarget in logTargets:
self.setGetTest("logtarget", logTarget)
# If path is invalid, do not change logtarget
value = "/this/path/should/not/exist"
self.setGetTestNOK("logtarget", value)
self.transm.proceed(["set", "/dev/null"])
for logTarget in logTargets:
os.remove(logTarget)
self.setGetTest("logtarget", "STDOUT")
self.setGetTest("logtarget", "STDERR")
if sys.platform.lower().startswith('linux'):
self.setGetTest("logtarget", "SYSLOG")
def testLogLevel(self):
self.setGetTest("loglevel", "4", 4)
self.setGetTest("loglevel", "3", 3)
self.setGetTest("loglevel", "2", 2)
self.setGetTest("loglevel", "1", 1)
self.setGetTest("loglevel", "-1", -1)
self.setGetTest("loglevel", "0", 0)
self.setGetTestNOK("loglevel", "Bird")
def testFlushLogs(self):
self.assertEqual(self.transm.proceed(["flushlogs"]), (0, "rolled over"))
try:
f, fn = tempfile.mkstemp("fail2ban.log")
os.close(f)
self.server.setLogLevel(2)
self.assertEqual(self.transm.proceed(["set", "logtarget", fn]), (0, fn))
logSys.warn("Before file moved")
try:
f2, fn2 = tempfile.mkstemp("fail2ban.log")
os.close(f2)
os.rename(fn, fn2)
logSys.warn("After file moved")
self.assertEqual(self.transm.proceed(["flushlogs"]), (0, "rolled over"))
logSys.warn("After flushlogs")
# >py2.4: with open(fn2, 'r') as f:
f = open(fn2, 'r');
if True:
self.assertTrue(f.next().endswith("Before file moved\n"))
self.assertTrue(f.next().endswith("After file moved\n"))
self.assertRaises(StopIteration, f.next)
f.close()
# >py2.4: with open(fn, 'r') as f:
f = open(fn, 'r');
if True:
self.assertTrue(f.next().endswith("After flushlogs\n"))
self.assertRaises(StopIteration, f.next)
f.close()
finally:
os.remove(fn2)
finally:
os.remove(fn)
self.assertEqual(self.transm.proceed(["set", "logtarget", "STDERR"]), (0, "STDERR"))
self.assertEqual(self.transm.proceed(["flushlogs"]), (0, "flushed"))