コード例 #1
0
ファイル: websocketproxy.py プロジェクト: bkanuka/websockify
    def __init__(self, RequestHandlerClass=ProxyRequestHandler, **kwargs):
        # Save off proxy specific options
        self.target_host    = kwargs.pop('target_host', None)
        self.target_port    = kwargs.pop('target_port', None)
        self.wrap_cmd       = kwargs.pop('wrap_cmd', None)
        self.wrap_mode      = kwargs.pop('wrap_mode', None)
        self.unix_target    = kwargs.pop('unix_target', None)
        self.ssl_target     = kwargs.pop('ssl_target', None)
        self.target_cfg     = kwargs.pop('target_cfg', None)
        self.daemon = False
        self.target_cfg = None

        # Server configuration
        listen_host    = kwargs.pop('listen_host', '')
        listen_port    = kwargs.pop('listen_port', None)
        web            = kwargs.pop('web', '')

        # Configuration affecting base request handler
        self.only_upgrade   = not web
        self.verbose   = kwargs.pop('verbose', False)
        record = kwargs.pop('record', '')
        if record:
            self.record = os.path.abspath(record)
        self.run_once  = kwargs.pop('run_once', False)
        self.handler_id = 0

        for arg in kwargs.keys():
            print("warning: option %s ignored when using --libserver" % arg)

        if web:
            os.chdir(web)
            
        HTTPServer.__init__(self, (listen_host, listen_port), 
                            RequestHandlerClass)
コード例 #2
0
ファイル: rest.py プロジェクト: bthate/meds
 def __init__(self, *args, **kwargs):
     HTTPServer.__init__(self, *args, **kwargs)
     Object.__init__(self)
     self.host = args[0]
     self._status = "start"
     self._last = time.time()
     self._start = time.time()
コード例 #3
0
    def __init__(self, server_address, request_handler_class, logger=None):
        """
        Proxy constructor

        :param server_address: The server address
        :param request_handler_class: The request handler class
        :param logger: An optional logger, in case of ignored error
        """
        # Determine the address family
        addr_info = socket.getaddrinfo(server_address[0], server_address[1], 0,
                                       0, socket.SOL_TCP)

        # Change the address family before the socket is created
        # Get the family of the first possibility
        self.address_family = addr_info[0][0]

        # Set up the server, socket, ... but do not bind immediately
        HTTPServer.__init__(self, server_address, request_handler_class, False)

        if self.address_family == socket.AF_INET6:
            # Explicitly ask to be accessible both by IPv4 and IPv6
            try:
                pelix.ipv6utils.set_double_stack(self.socket)
            except AttributeError as ex:
                if logger is not None:
                    logger.exception("System misses IPv6 constant: %s", ex)
            except socket.error as ex:
                if logger is not None:
                    logger.exception("Error setting up IPv6 double stack: %s",
                                     ex)

        # Bind & accept
        self.server_bind()
        self.server_activate()
コード例 #4
0
	def __init__(self, server_address, RequestHandlerClass, maxthreads=100, pemfile=None, rest_handlers=None, userpass=None):
		try:
			if pemfile: #HTTPS server
				BaseServer.__init__(self, server_address, RequestHandlerClass)
				ctx = SSL.Context(SSL.SSLv23_METHOD)
				ctx.use_privatekey_file(pemfile)
				ctx.use_certificate_file(pemfile)
				self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
				self.server_bind()
				self.server_activate()
				self.httpstyle = "HTTPS"
			else: #HTTP server
				BaseHTTPServer.__init__(self, server_address, RequestHandlerClass)
				self.httpstyle = "HTTP"
		except socket.error as e:
			if e.errno == 98:
				logging.log(logging.ERROR, "Cannot start HTTP server, address already in use")
				return
			else:
				raise
		self.lock = thread.allocate_lock()
		self.maxthreads = maxthreads
		self.threads = 0
		self.rest_handlers = rest_handlers
		self.userpass = userpass
コード例 #5
0
ファイル: http.py プロジェクト: intari/KSP
	def __init__(self):
		if hasattr(config, 'disconnected') and config.disconnected:
			self._handlers = []
		else:
			self._handlers = self._setup_handlers()
		from server.http_handler import Handler
		HTTPServer.__init__(self, (config.server_host, config.server_port), Handler, False)
コード例 #6
0
 def __init__(self,server_addr=('', 8788),RequestHandlerClass=ProxyHandle, bind_and_activate=True,https=True):
     HTTPServer.__init__(self,server_addr,RequestHandlerClass,bind_and_activate)
     logging.info('HTTPServer is running at address( %s , %d )......'%(server_addr[0],server_addr[1]))
     self.req_plugs = []##请求拦截插件列表
     self.rsp_plugs = []##响应拦截插件列表
     self.ca = CAAuth(ca_file = "ca.pem", cert_file = 'ca.crt')
     self.https = https
コード例 #7
0
 def __init__(self, cups_conn, callback):
     HTTPServer.__init__(self, ('localhost', 9988), NotificationHandler)
     self._thread = None
     self._conn = cups_conn
     self.callback = callback
     self.notif_uri = 'rss://{}:{}'.format(self.server_address[0],
                                           self.server_address[1])
コード例 #8
0
ファイル: pfioh.py プロジェクト: rockash/pfioh
    def __init__(self, *args, **kwargs):
        """

        Holder for constructor of class -- allows for explicit setting
        of member 'self' variables.

        :return:
        """

        HTTPServer.__init__(self, *args, **kwargs)
        self.LC                                 = 40
        self.RC                                 = 40
        self.args                               = None
        self.str_desc                           = 'pfioh'
        self.str_name                           = self.str_desc
        self.str_version                        = ""
        self.str_fileBase                       = "received-"
        self.str_storeBase                      = ""
        self.b_createDirsAsNeeded               = False
        self.b_swiftStorage                     = False

        self.str_unpackDir                      = "/tmp/unpack"
        self.b_removeZip                        = False

        self.dp                                 = debug(verbosity=0, level=-1)
コード例 #9
0
ファイル: ServiceContainer.py プロジェクト: dlopes7/pysphere
 def __init__(self, server_address, services=[], RequestHandlerClass=SOAPRequestHandler):
     '''server_address --
        RequestHandlerClass --
     '''
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     self._nodes = self.NodeTree()
     [self.setNode(s) for s in services]
コード例 #10
0
ファイル: basic.py プロジェクト: ahmadshahwan/cohorte-runtime
    def __init__(self, server_address, request_handler_class, logger=None):
        """
        Proxy constructor

        :param server_address: The server address
        :param request_handler_class: The request handler class
        :param logger: An optional logger, in case of ignored error
        """
        # Determine the address family
        addr_info = socket.getaddrinfo(server_address[0], server_address[1],
                                       0, 0, socket.SOL_TCP)

        # Change the address family before the socket is created
        # Get the family of the first possibility
        self.address_family = addr_info[0][0]

        # Set up the server, socket, ... but do not bind immediately
        HTTPServer.__init__(self, server_address, request_handler_class, False)

        if self.address_family == socket.AF_INET6:
            # Explicitly ask to be accessible both by IPv4 and IPv6
            try:
                pelix.ipv6utils.set_double_stack(self.socket)
            except AttributeError as ex:
                if logger is not None:
                    logger.exception("System misses IPv6 constant: %s", ex)
            except socket.error as ex:
                if logger is not None:
                    logger.exception("Error setting up IPv6 double stack: %s",
                                     ex)

        # Bind & accept
        self.server_bind()
        self.server_activate()
コード例 #11
0
 def __init__(self, host='localhost',
              port=None,
              handler=LogginWebMonitorRequestHandler):
     if port is None:
         port = logging.handlers.DEFAULT_TCP_LOGGING_PORT + 1
     HTTPServer.__init__(self, (host, port), handler)
     self.starttime = datetime.datetime.now()
コード例 #12
0
 def __init__(self,
              IP,
              Port,
              faasPort,
              regServerIP,
              regServerPort,
              pause=10,
              maxrtt=5000,
              maxhop=64,
              bufsize=1):
     HTTPServer.__init__(self,
                         server_address=(IP, Port),
                         RequestHandlerClass=HTTPRequestHandler)
     self.IP = IP
     self.Port = Port
     self.faasPort = faasPort
     self.lock = Lock()
     self.regServerIP = regServerIP
     self.regServerPort = regServerPort
     self.hosts = []
     self.pause = pause  # seconds
     self.maxrtt = maxrtt
     self.maxhop = maxhop
     self.rtt = defaultdict(list)
     self.rttav = defaultdict(float)
     self.hop = defaultdict(list)
     self.hopav = defaultdict(float)
     self.bufsize = bufsize
     self.faasMetrics = defaultdict(dict)
     self.faasMetricsNames = ['inv_rate', 'rep_count', 'exec_time']
     self.bestHosts = defaultdict(str)
     self.handler = None
     self.isRunning = False
コード例 #13
0
 def __init__(self, host=str('localhost'), port=4080):
     self.files = {}
     self.log = []
     self.override_code = None
     self.readonly = False
     self.running = True
     HTTPServer.__init__(self, (host, port), TestHttpServerRequestHandler)
コード例 #14
0
    def __init__(self, address, handler, receiveQ, sendQ):
        HTTPServer.__init__(self, address, handler)
        self.receiveQ = receiveQ
        self.sendQ = sendQ
        self.currentTelemetry = {
            'Ranges': {
                'Left': 1,
                'Right': 2,
                'Forward': 3,
                'Back': 4,
                'Bottom': 5
            }
        }
        self.newTelemetry = True
        self.t0 = robtimer()
        self.motors_powered = 0
        self.telemetry_sent = 0
        self.heartbeat_thread = None
        self.heartbeat = False
        self.dockSignal_state = {
            'time_to_live': 3.0,
            'left': 0.0,  # timestamp of last left signal
            'right': 0.0,
        }

        self.set_security_mode()
コード例 #15
0
ファイル: httpd.py プロジェクト: saggim/SleekPubsub
	def __init__(self, server_address, RequestHandlerClass, maxthreads=100, pemfile=None, rest_handlers=None, userpass=None):
		try:
			if pemfile: #HTTPS server
				BaseServer.__init__(self, server_address, RequestHandlerClass)
				ctx = SSL.Context(SSL.SSLv23_METHOD)
				ctx.use_privatekey_file(pemfile)
				ctx.use_certificate_file(pemfile)
				self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
				self.server_bind()
				self.server_activate()
				self.httpstyle = "HTTPS"
			else: #HTTP server
				BaseHTTPServer.__init__(self, server_address, RequestHandlerClass)
				self.httpstyle = "HTTP"
		except socket.error as e:
			if e.errno == 98:
				logging.log(logging.ERROR, "Cannot start HTTP server, address already in use")
				return
			else:
				raise
		self.lock = thread.allocate_lock()
		self.maxthreads = maxthreads
		self.threads = 0
		self.rest_handlers = rest_handlers
		self.userpass = userpass
コード例 #16
0
ファイル: paradium.py プロジェクト: MrMoose/paradium
	def __init__(self, bind_address = "", port = 80):
	
		# Initialize server itself
		self.allow_reuse_address = True
		HTTPServer.__init__(self, (bind_address, port), ParadiumHandler)

		return
コード例 #17
0
 def __init__(self, external_env: ExternalEnv, address, port):
     socket_address = f'http://{address}:{port}'
     subprocess.Popen(
         [PATH_TO_IC20, '-t', '0', '-u', socket_address, '-o', '/dev/null'])
     handler = _make_handler(external_env, ControllerState(),
                             socket_address)
     HTTPServer.__init__(self, (address, port), handler)
コード例 #18
0
 def __init__(self, value):
     server_address = ('0.0.0.0', value['port'])
     self.mongoClient = pymongo.MongoClient(value['mongodbUri'])
     self.mongodbDB = value['mongodbDB']
     self.token = value['token']
     self.channelCodes = {}
     HTTPServer.__init__(self, server_address, HttpServerRequestHandle)
コード例 #19
0
ファイル: http_server.py プロジェクト: aaugustin/django-resto
 def __init__(self, host=str('localhost'), port=4080):
     self.files = {}
     self.log = []
     self.override_code = None
     self.readonly = False
     self.running = True
     HTTPServer.__init__(self, (host, port), TestHttpServerRequestHandler)
コード例 #20
0
 def __init__(self, server_address, RequestHandlerClass, websocket_address, multiple_instance, enable_file_cache, update_interval, *userdata):
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     self.websocket_address = websocket_address
     self.multiple_instance = multiple_instance
     self.enable_file_cache = enable_file_cache
     self.update_interval = update_interval
     self.userdata = userdata
コード例 #21
0
    def __init__(self, processes=max(2, cpu_count()), threads=64, daemon=False, kill=True, debug=False, logger=None):
        """

        Constructor

        :param processes: processes pool length
        :type processes: int
        :param threads: threads pool length for process
        :type threads: int
        :param daemon: True if daemon threads
        :type daemon: bool
        :param kill: True if kill main process when shutdown
        :type kill: bool
        :param debug: True if debug mode
        :type debug: bool
        :param logger: logger
        :type logger: logging.Logger

        """
        HTTPServer.__init__(self, ('127.0.0.1', 8888), MyTestHandler)
        self._process_n = processes
        self._thread_n = threads
        self._daemon = daemon
        self._kill = kill
        self._debug = debug
        self._logger = logger
        self._init_pool()
        print("listening on http://127.0.0.1:8888/")
コード例 #22
0
    def __init__(self, server_address, RequestHandlerClass, websocket_address,
                 auth, multiple_instance, enable_file_cache, update_interval,
                 websocket_timeout_timer_ms, host_name,
                 pending_messages_queue_length, *userdata):
        HTTPServer.__init__(self, server_address, RequestHandlerClass)
        self.websocket_address = websocket_address
        self.auth = auth
        self.multiple_instance = multiple_instance
        self.enable_file_cache = enable_file_cache
        self.update_interval = update_interval
        self.websocket_timeout_timer_ms = websocket_timeout_timer_ms
        self.host_name = host_name
        self.pending_messages_queue_length = pending_messages_queue_length
        self.userdata = userdata

        self.certfile = 'server.crt'
        self.keyfile = 'server.key'
        self.ssl_version = ssl.PROTOCOL_TLSv1_2
        bind_and_activate = True

        self.socket = ssl.wrap_socket(self.socket,
                                      keyfile=self.keyfile,
                                      certfile=self.certfile,
                                      server_side=True,
                                      ssl_version=self.ssl_version,
                                      do_handshake_on_connect=True)
コード例 #23
0
ファイル: pfioh.py プロジェクト: rob-baron/pfioh
    def __init__(self, *args, **kwargs):
        """

        Holder for constructor of class -- allows for explicit setting
        of member 'self' variables.

        :return:
        """

        HTTPServer.__init__(self, *args, **kwargs)
        self.LC = 40
        self.RC = 40
        self.args = None
        self.str_desc = 'pfioh'
        self.str_name = self.str_desc
        self.str_version = ""
        self.str_fileBase = "received-"
        self.str_storeBase = ""
        self.b_createDirsAsNeeded = False
        self.b_swiftStorage = False

        self.str_unpackDir = "/tmp/unpack"
        self.b_removeZip = False

        self.dp = debug(verbosity=0, level=-1)
コード例 #24
0
 def __init__(self,
              server_address=('', 0),
              RequestHandlerClass=RequestRecorder):
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     threading.Thread.__init__(self)
     self.setDaemon(True)
     self.requests = []
コード例 #25
0
ファイル: server.py プロジェクト: motleytech/remi
 def __init__(self, server_address, RequestHandlerClass, websocket_address, multiple_instance, enable_file_cache, update_interval, *userdata):
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     self.websocket_address = websocket_address
     self.multiple_instance = multiple_instance
     self.enable_file_cache = enable_file_cache
     self.update_interval = update_interval
     self.userdata = userdata
コード例 #26
0
    def __init__(self):
        self.hostName = socket.gethostbyname(socket.gethostname())
        self.hostPort = 8080
        HTTPServer.__init__(self, (self.hostName, self.hostPort), MyReqHandler)
        threading.Thread.__init__(self)

        self.rotX, self.rotY, self.rotZ = 20.0, 40.0, 30.0
コード例 #27
0
ファイル: pyfunnel.py プロジェクト: devil-d3/funnel
 def __init__(self, *args):
     # Create log file in current directory.
     if os.path.isfile('foo.log'):
         os.chmod('foo.log', 0o777)
         os.remove('foo.log')
     self.logger = os.fdopen(os.open('foo.log', os.O_CREAT | os.O_RDWR, 0), 'r+', 0)
     HTTPServer.__init__(self, *args)
コード例 #28
0
    def __init__(self, server_address, RequestHandlerClass, auth,
                 multiple_instance, enable_file_cache, update_interval,
                 websocket_timeout_timer_ms, pending_messages_queue_length,
                 title, server_starter_instance, certfile, keyfile,
                 ssl_version, *userdata):
        HTTPServer.__init__(self, server_address, RequestHandlerClass)
        self.auth = auth
        self.multiple_instance = multiple_instance
        self.enable_file_cache = enable_file_cache
        self.update_interval = update_interval
        self.websocket_timeout_timer_ms = websocket_timeout_timer_ms
        self.pending_messages_queue_length = pending_messages_queue_length
        self.title = title
        self.server_starter_instance = server_starter_instance
        self.userdata = userdata

        self.certfile = certfile
        self.keyfile = keyfile
        self.ssl_version = ssl_version
        if self.ssl_version != None:
            self.socket = ssl.wrap_socket(self.socket,
                                          keyfile=self.keyfile,
                                          certfile=self.certfile,
                                          server_side=True,
                                          ssl_version=self.ssl_version,
                                          do_handshake_on_connect=True)
コード例 #29
0
    def __init__(self, config_file, logger=sys.stderr):
        """
        Create a new server that acts like a homekit accessory.

        :param config_file: the file that contains the configuration data. Must be a string representing an absolute
        path to the file
        :param logger: this can be None to disable logging, sys.stderr to use the default behaviour of the python
        implementation or an instance of logging.Logger to use this.
        """
        if logger is None or logger == sys.stderr or isinstance(
                logger, logging.Logger):
            self.logger = logger
        else:
            raise Exception('Invalid logger given.')
        self.data = HomeKitServerData(config_file)
        self.data.increase_configuration_number()
        self.sessions = {}
        self.zeroconf = Zeroconf()
        self.mdns_type = '_hap._tcp.local.'
        self.mdns_name = self.data.name + '._hap._tcp.local.'

        self.accessories = Accessories()

        HTTPServer.__init__(self, (self.data.ip, self.data.port),
                            HomeKitRequestHandler)
コード例 #30
0
 def __init__(self, controller: BotRicarica, hook_url: str):
     """Constructor.  May be extended, do not override."""
     self.bot_controller = controller
     url = urlparse(hook_url)
     self.address = (url.hostname, url.port or 80)
     self.path = url.path
     HTTPServer.__init__(self, self.address, _BotRequestHandler, False)
コード例 #31
0
    def __init__(self, RequestHandlerClass=ProxyRequestHandler, **kwargs):
        # Save off proxy specific options
        self.target_host = kwargs.pop('target_host', None)
        self.target_port = kwargs.pop('target_port', None)
        self.wrap_cmd = kwargs.pop('wrap_cmd', None)
        self.wrap_mode = kwargs.pop('wrap_mode', None)
        self.unix_target = kwargs.pop('unix_target', None)
        self.ssl_target = kwargs.pop('ssl_target', None)
        self.target_cfg = kwargs.pop('target_cfg', None)
        self.daemon = False
        self.target_cfg = None

        # Server configuration
        listen_host = kwargs.pop('listen_host', '')
        listen_port = kwargs.pop('listen_port', None)
        web = kwargs.pop('web', '')

        # Configuration affecting base request handler
        self.only_upgrade = not web
        self.verbose = kwargs.pop('verbose', False)
        record = kwargs.pop('record', '')
        if record:
            self.record = os.path.abspath(record)
        self.run_once = kwargs.pop('run_once', False)
        self.handler_id = 0

        for arg in kwargs.keys():
            print("warning: option %s ignored when using --libserver" % arg)

        if web:
            os.chdir(web)

        HTTPServer.__init__(self, (listen_host, listen_port),
                            RequestHandlerClass)
コード例 #32
0
    def __init__(self, server, port):
        HTTPServer.__init__(self, ('', port), RequestHandler)
        self.server = server
        self.port = port

        # Marks the server for shutdown when possible
        self.shutdown = False
コード例 #33
0
 def __init__(self,
              server_address,
              RequestHandlerClass,
              bind_and_activate=True):
     HTTPServer.__init__(self, server_address, RequestHandlerClass,
                         bind_and_activate)
     ThreadingMixIn.__init__(self)
コード例 #34
0
ファイル: proxy.py プロジェクト: BLACKSNAKE77/BaseProxy
 def __init__(self,server_addr=('', 8788),RequestHandlerClass=ProxyHandle, bind_and_activate=True,https=True):
     HTTPServer.__init__(self,server_addr,RequestHandlerClass,bind_and_activate)
     logging.info('HTTPServer is running at address( %s , %d )......'%(server_addr[0],server_addr[1]))
     self.req_plugs = []##请求拦截插件列表
     self.rsp_plugs = []##响应拦截插件列表
     self.ca = CAAuth(ca_file = "ca.pem", cert_file = 'ca.crt')
     self.https = https
コード例 #35
0
 def __init__(self,
              base_path,
              server_address,
              RequestHandlerClass=HTTPHandler):
     self.base_path = base_path
     BaseHTTPServer.__init__(self, server_address,
                             RequestHandlerClass)
コード例 #36
0
ファイル: server.py プロジェクト: tfroehlich82/remi
 def __init__(
     self,
     server_address,
     RequestHandlerClass,
     websocket_address,
     auth,
     multiple_instance,
     enable_file_cache,
     update_interval,
     websocket_timeout_timer_ms,
     host_name,
     pending_messages_queue_length,
     title,
     *userdata
 ):
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     self.websocket_address = websocket_address
     self.auth = auth
     self.multiple_instance = multiple_instance
     self.enable_file_cache = enable_file_cache
     self.update_interval = update_interval
     self.websocket_timeout_timer_ms = websocket_timeout_timer_ms
     self.host_name = host_name
     self.pending_messages_queue_length = pending_messages_queue_length
     self.title = title
     self.userdata = userdata
コード例 #37
0
ファイル: onedriveapi.py プロジェクト: glaif/shrikebu
 def __init__(self, server_address, stop_event, RequestHandlerClass):
     print("INIT: server addr: %s:%d" %
           (server_address[0], server_address[1]))
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     print("HTTPServer INIT")
     self.__stop_event = stop_event
     self.__auth_resp = None
コード例 #38
0
 def __init__(self, server_address, services=[], RequestHandlerClass=SOAPRequestHandler):
     '''server_address -- 
        RequestHandlerClass -- 
     '''
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     self._nodes = self.NodeTree()
     list(map(lambda s: self.setNode(s), services))
コード例 #39
0
ファイル: http.py プロジェクト: clinton-chikwata/rapidpro
    def __init__(self):
        HTTPServer.__init__(self, ("localhost", 49999),
                            MockServerRequestHandler)

        self.base_url = "http://localhost:49999"
        self.mocked_requests = []
        self.unexpected_requests = []
コード例 #40
0
ファイル: ScanView.py プロジェクト: LegalizeAdulthood/clang
 def __init__(self, address, handler, root, reporters, options):
     HTTPServer.__init__(self, address, handler)
     self.root = root
     self.reporters = reporters
     self.options = options        
     self.halted = False
     self.config = None
     self.load_config()
コード例 #41
0
ファイル: msgserver.py プロジェクト: matrix1001/msgserver
 def __init__(self,
              server_address,
              RequestHandlerClass=RequestHandler,
              bind_and_activate=True):
     HTTPServer.__init__(self, server_address, RequestHandler,
                         bind_and_activate)
     self.commands = {}
     self.server_proc = None
コード例 #42
0
 def __init__(self, address, handler, root, reporters, options):
     HTTPServer.__init__(self, address, handler)
     self.root = root
     self.reporters = reporters
     self.options = options
     self.halted = False
     self.config = None
     self.load_config()
コード例 #43
0
ファイル: login.py プロジェクト: chazeon/Renren-ShareFetcher
 def __init__(self, funcs, *args, **kw):
     HTTPServer.__init__(self, *args, **kw)
     self.get_incode_func = funcs["get_incode_func"]
     self.do_login_func = funcs["do_login_func"]
     self.do_retrive_func = funcs["do_retrive_func"]
     fsock = open("mime.json", "r")
     self.mimetype_library = json.load(fsock)
     fsock.close()
コード例 #44
0
ファイル: api.py プロジェクト: dhozac/napkin
 def __init__(self, *args, **kwargs):
     self.timeout = 86400
     self.ssl_wrap_args = {'server_side': True}
     for i in ['keyfile', 'certfile', 'ca_certs', 'cert_reqs']:
         if i in kwargs:
             self.ssl_wrap_args[i] = kwargs[i]
             del kwargs[i]
     HTTPServer.__init__(self, *args, **kwargs)
コード例 #45
0
ファイル: api.py プロジェクト: plastyc/governor
 def __init__(self, governor, config):
     connect_address = (config.get('connect_address', None) or config['listen']).format(**os.environ)
     self.connection_string = 'http://{}/governor'.format(connect_address)
     host, port = config['listen'].split(':')
     HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
     Thread.__init__(self, target=self.serve_forever)
     self.governor = governor
     self.daemon = True
コード例 #46
0
 def __init__(self, grant_details: GrantDetails):
     HTTPServer.__init__(self, ("", grant_details.redirect_uri_port),
                         OAuth2ResponseHandler)
     self.timeout = grant_details.reception_timeout
     logger.debug(f"Timeout is set to {self.timeout} seconds.")
     self.grant_details = grant_details
     self.request_error = None
     self.grant = False
コード例 #47
0
ファイル: test_ssl.py プロジェクト: pracaas/python
            def __init__(self, server_address, RequestHandlerClass, certfile):

                HTTPServer.__init__(self, server_address, RequestHandlerClass)
                # we assume the certfile contains both private key and certificate
                self.certfile = certfile
                self.active = False
                self.active_lock = threading.Lock()
                self.allow_reuse_address = True
コード例 #48
0
 def __init__(self, *args):
     HTTPServer.__init__(self, *args)
     self.counter = 0
     self.items = [self.new_item() for x in range(5)]
     if args[0][0] and args[0][1]:
         print("Running on:", "{}:{}".format(args[0]))
     elif args[0][1]:
         print("Running on:", "localhost:{}".format(args[0][1]))
コード例 #49
0
ファイル: consumer.py プロジェクト: hbaojun/python3-openid
    def __init__(self, store, *args, **kwargs):
        HTTPServer.__init__(self, *args, **kwargs)
        self.sessions = {}
        self.store = store

        if self.server_port != 80:
            self.base_url = "http://%s:%s/" % (self.server_name, self.server_port)
        else:
            self.base_url = "http://%s/" % (self.server_name,)
コード例 #50
0
ファイル: server.py プロジェクト: ma1co/Sony-PMCA-RE
 def __init__(self, certFile, fakeHost, host='127.0.0.1', port=4443):
  HTTPServer.__init__(self, (host, port), HttpHandler)
  self.host = host
  self.port = port
  self.url = 'https://' + host + '/'
  self.fakeUrl = 'https://' + fakeHost + '/'
  self.apk = None
  self.result = None
  self.socket = ssl.wrap_socket(self.socket, certfile=certFile)
コード例 #51
0
ファイル: health.py プロジェクト: johannninja/saiki-buku
 def __init__(self):
     HTTPServer.__init__(self, ('0.0.0.0', int(getenv('HEALTH_SERVER_PORT'))), HealthHandler)
     Thread.__init__(self, target=self.serve_forever)
     self._set_fd_cloexec(self.socket)
     self.zk = get_zookeeper()
     self.daemon = True
     self._fetch_brokers = True
     self._fetch_brokers_time = time.time()
     self._bad_brokers = []
コード例 #52
0
ファイル: librarian_server.py プロジェクト: NiLuJe/librarian
 def __init__(self, server_address, RequestHandlerClass, allowed, library_dir, collections_json):
     HTTPServer.__init__(self, server_address, RequestHandlerClass)
     self.allowed = allowed
     # to make sure all goes well later when splitting and joining
     if not library_dir.endswith("/"):
         library_dir += "/"
     self.allowed_relative = [el.split(library_dir)[1] for el in allowed]
     self.library_dir = library_dir
     self.collections_json = collections_json
コード例 #53
0
ファイル: httpserver.py プロジェクト: limebot/LimeBot
 def __init__(self, address, protocol, callback):
     if protocol == 4:
         self.address_family = socket.AF_INET
     elif protocol == 6:
         self.address_family = socket.AF_INET6
     else:
         raise AssertionError(protocol)
     HTTPServer.__init__(self, address, callback)
     self.callbacks = {}
コード例 #54
0
ファイル: minihttp.py プロジェクト: smothiki/Moka5HttpServer
    def __init__(self, configfile):
        config = open(configfile)
        for line in config:
            key, value = line.strip().split("=")
            if key == "port":
                port = int(value)
            elif key == "root":
                self.root = value

        HTTPServer.__init__(self, ("127.0.0.1", port), RequestHandler)
コード例 #55
0
	def __init__(self, Parent):
		self.Parent = Parent
		self.Parent.Logs.log("Starting..")
		try:
			HTTPServer.__init__(self, (self.Parent.Configs.host, self.Parent.Configs.port), Handler)
			self.Parent.Logs.log("Running proxy on port "+str(self.Parent.Configs.port))
		except:
			self.Parent.Logs.log("ERROR: Port "+str(self.Parent.Configs.port)+" is already in use")
			self.Parent.Logs.log("Shutting down..")
			exit()
コード例 #56
0
ファイル: server.py プロジェクト: EremeykinS/bot
    def __init__(self, queue):
        class HTTPHandler(BaseHTTPRequestHandler):
            # def echo(self, text):
            #     self.wfile.write(bytes(text, "utf-8"))

            # def do_POST(self):
            #     uid = queue.get()
            #     print('POST processing...\n')
            #     length = int(self.headers.get('content-length'))
            #     field_data = self.rfile.read(length)
            #     fields = parse_qs(field_data)
            #     queue.put((uid, fields))

            def do_GET(self):
                #DB connection
                con = sqlite3.connect('/home/user/bot/users.sqlite')
                cur = con.cursor()
                p = urlparse(self.path)
                q = parse_qs(p.query)
                self.send_response(302, 'Found')
                if 'cid' in q:
                    scope = ['account-info', 'operation-history', 'payment-p2p']
                    auth_url = Wallet.build_obtain_token_url(config.client_id, config.redirect_uri, scope)
                    self.send_header('Location', auth_url)
                    if 'b' in q:
                        self.send_header("Set-Cookie", "cid=" + q['cid'][0] + '&b=1')
                    else:
                        self.send_header("Set-Cookie", "cid=" + q['cid'][0] + '&to=' + q['to'][0] + '&amount=' + q['amount'][0])
                elif 'code' in q:
                    access_token = Wallet.get_access_token(config.client_id, q['code'][0], config.redirect_uri, client_secret=None)
                    cookie = parse_qs(self.headers.get('Cookie'))
                    cid = cookie['cid'][0]
                    cur.execute('INSERT INTO users (cid, token) VALUES ("' + str(cid) +'", "' + access_token['access_token'] + '")')
                    con.commit()
                    wallet = Wallet(access_token['access_token'])
                    if 'b' in cookie:
                        queue.put({'cid': cid, 'b': wallet.account_info()['balance_details']['available']})
                    else:
                        to = cookie['to'][0]
                        amount = cookie['amount'][0]
                        request_options = {"pattern_id": "p2p", "to": to, "amount_due": amount, "comment": "переведено через бота", "message": "переведено через бота", "label": "testPayment"}
                        request_result = wallet.request_payment(request_options)
                        # check status
                        process_payment = wallet.process_payment({"request_id": request_result['request_id'],})
                        # check result
                        if process_payment['status'] == "success":
                            queue.put({'cid': cid, 'result':'+'})
                        else:
                            queue.put({'cid': cid, 'result':'-'})
                    self.send_header('Location', 'http://telegram.me/GodMoneyBot')
                self.end_headers()
                con.close()

        HTTPServer.__init__(self, (config.hostname, config.port), HTTPHandler)
        self.run()
コード例 #57
0
ファイル: web.py プロジェクト: dark-lbp/kitty
 def __init__(self, server_address, handler, interface):
     '''
     :param server_address: address of the server
     :param handler: handler for requests
     :param interface: reference to the interface object
     '''
     HTTPServer.__init__(self, server_address, handler)
     # kitty.interfaces... interface object
     self.interface = interface
     self.RequestHandlerClass.logger = interface.logger
     self.RequestHandlerClass.dataman = interface.dataman
コード例 #58
0
ファイル: srv.py プロジェクト: natemago/srv
 def __init__(self, server_address, RequestHandlerClass,
              bind_and_activate=True, handlers=[],
              srv_path=".",
              configuration={}):
     HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
     self.handlers = sorted(handlers, key=lambda k: k["weight"])
     self.srv_path = srv_path
     self.configuration = configuration
     self.logger = self.setup_logger()
     self.executor = ThreadPoolExecutor(max_workers=20)
     self.initialize_server()