Exemple #1
0
def skillTest1(request, username):
    # 测试socket
    print('999')
    count = 0

    if request.is_websocket:
        lock = threading.RLock()
        try:
            lock.acquire()#抢占资源
            s = {}
            if clients.get(username) != None:
                s[str(request.websocket)] = request.websocket
            else:
                count += 1
                s[str(request.str(request.websocket))] = request.websocket
                clients[username] = s
            print('用户人数', str(count))

            for message in request.websocket:
                if not message:
                    break
                else:
                    request.send(message)
        except:
            pass
        finally:
            # 通过用户名找到 连接信息 再通过 连接信息 k 找到 v (k就是连接信息)
            clients.get(username).pop(str(request.websocket))
            # 释放锁
            lock.release()
    def resolve(self, request, handler):
        qname = request.q.qname
        reply = request.reply()
        # Note responses have TTL 4, as in Amazon's Dynamo DNS
        print(qname)

        if qname == 'alternator':
            ip = random.choice(livenodes)
            reply.add_answer(
                *dnslib.RR.fromZone('{} 4 A {}'.format(qname, ip)))

        # Otherwise proxy
        if not reply.rr:
            try:
                if handler.protocol == 'udp':
                    proxy_r = request.send(self.address,
                                           self.port,
                                           timeout=self.timeout)
                else:
                    proxy_r = request.send(self.address,
                                           self.port,
                                           tcp=True,
                                           timeout=self.timeout)
                reply = DNSRecord.parse(proxy_r)
            except socket.timeout:
                reply.header.rcode = getattr(RCODE, 'NXDOMAIN')

        return reply
 def ERROR(request):
     global cmd_tic
     if (cmd_tic[:1] == 'L'):
         cmd_tic = ''
         print("Error")
         timer.cancel()
         request.send(bytes("E", "ascii"))
     else:
         cmd_tic = ''
def get_ephemerides():
    global datetime_initial
    global ephemerides_dict

    # horizons request
    request = horizons.HorizonsRequest("672@399", "599", datetime_initial,
                                       "2,20,21")
    request.send()
    ephemerides_dict = request.get_dictionary()
 def ERROR(request):
    global cmd_tic
    if (cmd_tic[:1] == 'L'):
       cmd_tic = ''
       log_file(self.data.decode("ascii") + "Error: Invalid TIC Load command")
       print("Error: Invalid TIC Load command")
       timer.cancel()
       request.send(bytes("E","ascii"))
    else:
       cmd_tic = ''
Exemple #6
0
 def run(self, view):
     if (self.view.file_name()):
         path = settings.get('path')
         hostname = settings.get('hostname')
         port = settings.get('port')
         endpoint = settings.get('endpoint')
         url = 'http://' + hostname + ':' + str(
             port) + endpoint + '?filePath=' + self.view.file_name(
             ).replace(path, '')
         print(url)
         data = self.view.substr(sublime.Region(0, self.view.size()))
         request = HttpAsyncRequest(url)
         request.set_content(str.encode(data))
         request.set_header('Content-type', 'text/plain')
         request.send()
def main():
    secretId = 123
    secretKey = 'test'
    params = {}
    request = Request(secretId, secretKey)
    print(request.generateUrl('cvm.api.qcloud.com', '/v2/index.php', params))
    print(request.send('cvm.api.qcloud.com', '/v2/index.php', params))
Exemple #8
0
 def cmd_camera_selection(monid, camid, request):
     THD_DIR = config.get("CONF", "DIR").strip('\"')
     FTHD_INF = config.get("CONF", "FILE_THD_INFO").strip('\"')
     try:
         pfcsv = open(THD_DIR + "/" + FTHD_INF, 'r')
         f1 = True
         for line in pfcsv:
             templist = []
             for a in line.split(","):
                 templist.append(a.rstrip("\n"))
             if monid == templist[3] and (camid == templist[1]
                                          or camid
                                          == templist[2]):
                 f1 = False
                 ip = config.get(
                     "PLATFORM_" + templist[0],
                     "TO_MONITOR_IP_ADDR").strip('\"')
                 if (templist[1] == camid):  #int(cam_i) == 1:
                     result_html = TRAIN_HOLD_ON(ip)
                     logs = result_html + " " + str(
                         today
                     ) + " Train Hold ON, selection Cam-ID :" + camid + " and Mon-ID :" + monid
                     log_file(logs)
                     update_log_to_SMMS(logs)
                 elif (templist[2] == camid):  #int(cam_i) == 2:
                     result_html = TRAIN_HOLD_OFF(ip)
                     logs = result_html + " " + str(
                         today
                     ) + " Train Hold OFF, selection Cam-ID :" + camid + " and Mon-ID :" + monid
                     log_file(logs)
                     update_log_to_SMMS(logs)
         if (
                 f1 == True
         ):  #((f1 == True and f2 == True) and (monid != templist[3])):
             print("monitor id :", monid, " camera id :", camid,
                   " is not matching")
             log_file(self.data + " monitor id :" + monid +
                      " camera id :" + camid +
                      "is not matching")
             request.send(bytes(self.data.upper()))
     finally:
         pfcsv.close()
Exemple #9
0
def how_about_it(request: Request, cmd: str = 'whoami', querys=None):
    request.update_command(cmd, querys)
    res = request.send()
    if isinstance(res, requests.RequestException):
        return res

    r_text = re.search(r'[-]{99,}\n(.*)', res.text)
    if r_text:
        result = r_text.group(1)
        result = result.replace('\\n', '\n').replace('\\t', '\t')
        result = re.sub('^\w?\'', '', result)
        result = re.sub('\'$', '', result).strip()
        return result
    return res
Exemple #10
0
def dns_alternative_response(request):
    ans_pkt = request.send(DNS_FORWARD)
    return DNSRecord.parse(ans_pkt)
Exemple #11
0
    def _build_response(self, resp, is_error=False):
        """Build internal :class:`Response <Response>` object
        from given response.
        """


        def build(resp):

            response = Response()

            # Pass settings over.
            response.config = self.config

            if resp:

                # Fallback to None if there's no staus_code, for whatever reason.
                response.status_code = getattr(resp, 'status', None)

                # Make headers case-insensitive.
                response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))

                # Start off with our local cookies.
                cookies = self.cookies or dict()

                # Add new cookies from the server.
                if 'set-cookie' in response.headers:
                    cookie_header = response.headers['set-cookie']

                    c = SimpleCookie()
                    c.load(cookie_header)

                    for k,v in list(c.items()):
                        cookies.update({k: v.value})

                # Save cookies in Response.
                response.cookies = cookies

            # Save original resopnse for later.
            response.raw = resp

            if is_error:
                response.error = resp

            response.url = self.full_url

            return response


        history = []

        r = build(resp)
        cookies = self.cookies
        self.cookies.update(r.cookies)

        if r.status_code in REDIRECT_STATI and not self.redirect:

            while (
                ('location' in r.headers) and
                ((r.status_code is codes.see_other) or (self.allow_redirects))
            ):

                if not len(history) < self.config.get('max_redirects'):
                    raise TooManyRedirects()

                history.append(r)

                url = r.headers['location']

                # Handle redirection without scheme (see: RFC 1808 Section 4)
                if url.startswith('//'):
                    parsed_rurl = urlparse(r.url)
                    url = '%s:%s' % (parsed_rurl.scheme, url)

                # Facilitate non-RFC2616-compliant 'location' headers
                # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
                if not urlparse(url).netloc:
                    url = urljoin(r.url, urllib.parse.quote(urllib.parse.unquote(url)))

                # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
                if r.status_code is codes.see_other:
                    method = 'GET'
                else:
                    method = self.method

                # Remove the cookie headers that were sent.
                headers = self.headers
                try:
                    del headers['Cookie']
                except KeyError:
                    pass

                request = Request(
                    url=url,
                    headers=headers,
                    files=self.files,
                    method=method,
                    params=self.session.params,
                    auth=self._auth,
                    cookies=cookies,
                    redirect=True,
                    config=self.config,
                    timeout=self.timeout,
                    _poolmanager=self._poolmanager,
                    proxies = self.proxies,
                )

                request.send()
                cookies.update(request.response.cookies)
                r = request.response
                self.cookies.update(r.cookies)

            r.history = history

        self.response = r
        self.response.request = self
        self.response.cookies.update(self.cookies)
Exemple #12
0
    def _build_response(self, resp, is_error=False):
        """Build internal :class:`Response <Response>` object
        from given response.
        """
        def build(resp):

            response = Response()

            # Pass settings over.
            response.config = self.config

            if resp:

                # Fallback to None if there's no staus_code, for whatever reason.
                response.status_code = getattr(resp, 'status', None)

                # Make headers case-insensitive.
                response.headers = CaseInsensitiveDict(
                    getattr(resp, 'headers', None))

                # Start off with our local cookies.
                cookies = self.cookies or dict()

                # Add new cookies from the server.
                if 'set-cookie' in response.headers:
                    cookie_header = response.headers['set-cookie']

                    c = SimpleCookie()
                    c.load(cookie_header)

                    for k, v in list(c.items()):
                        cookies.update({k: v.value})

                # Save cookies in Response.
                response.cookies = cookies

            # Save original resopnse for later.
            response.raw = resp

            if is_error:
                response.error = resp

            response.url = self.full_url

            return response

        history = []

        r = build(resp)
        cookies = self.cookies
        self.cookies.update(r.cookies)

        if r.status_code in REDIRECT_STATI and not self.redirect:

            while (('location' in r.headers)
                   and ((r.status_code is codes.see_other) or
                        (self.allow_redirects))):

                if not len(history) < self.config.get('max_redirects'):
                    raise TooManyRedirects()

                history.append(r)

                url = r.headers['location']

                # Handle redirection without scheme (see: RFC 1808 Section 4)
                if url.startswith('//'):
                    parsed_rurl = urlparse(r.url)
                    url = '%s:%s' % (parsed_rurl.scheme, url)

                # Facilitate non-RFC2616-compliant 'location' headers
                # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
                if not urlparse(url).netloc:
                    url = urljoin(
                        r.url, urllib.parse.quote(urllib.parse.unquote(url)))

                # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
                if r.status_code is codes.see_other:
                    method = 'GET'
                else:
                    method = self.method

                # Remove the cookie headers that were sent.
                headers = self.headers
                try:
                    del headers['Cookie']
                except KeyError:
                    pass

                request = Request(
                    url=url,
                    headers=headers,
                    files=self.files,
                    method=method,
                    params=self.session.params,
                    auth=self._auth,
                    cookies=cookies,
                    redirect=True,
                    config=self.config,
                    timeout=self.timeout,
                    _poolmanager=self._poolmanager,
                    proxies=self.proxies,
                )

                request.send()
                cookies.update(request.response.cookies)
                r = request.response
                self.cookies.update(r.cookies)

            r.history = history

        self.response = r
        self.response.request = self
        self.response.cookies.update(self.cookies)