예제 #1
0
 def checkQuery(self, query):
     if not query:
         return
     key, value = [
         i.strip().strip('"').strip("'") for i in splitvalue(query)
     ]
     self.extra_info[key] = value
예제 #2
0
def extract_query(query_str):
    querys = {}
    for i in query_str.split('&'):
        key_value = splitvalue(i)
        querys[key_value[0]] = key_value[1]

    return querys
예제 #3
0
 def checkQuery(self, query):
     BasicUserCookie.checkQuery(self, query)
     if not query:
         return
     key, value = [i.strip().strip('"').strip("'") for i in splitvalue(query)]
     if key == 'main_login':
         self.main_login = value
     elif 'openid' in key:
         self.openid = value
     elif 'appid' in key:
         self.appid = value
     elif 'access_token' in key:
         self.access_token = value
     elif 'vuserid' in key:
         self.vuserid = value
     elif 'vusession' in key:
         self.vusession = value
예제 #4
0
def _parsePostedRequest(url):
    """
    如果下载需要使用POST请求,将参数写入Request Body传给服务器。
    url的形式类似:
    http://www.xxx.com/getres?resid=xxx&arg=xxx
    :return:
    """
    __qindex = url.find("?")
    if __qindex != -1:
        reqURL = url[0:__qindex]
        reqParams = url[__qindex + 1:]
        reqParamsData = {}
        for attr_str in reqParams.split("&"):
            attrs = parse.splitvalue(attr_str)
            reqParamsData[attrs[0]] = attrs[1]

        return reqURL, parse.urlencode(reqParamsData).encode("utf-8")
    return url, ""
예제 #5
0
 def open_ftp(self, url):
     """Use FTP protocol."""
     if not isinstance(url, str):
         raise IOError(
             'ftp error',
             'proxy support for ftp protocol currently not implemented')
     import mimetypes, mimetools
     try:
         from io import StringIO
     except ImportError:
         from io import StringIO
     host, path = splithost(url)
     if not host: raise IOError('ftp error', 'no host given')
     host, port = splitport(host)
     user, host = splituser(host)
     if user: user, passwd = splitpasswd(user)
     else: passwd = None
     host = unquote(host)
     user = unquote(user or '')
     passwd = unquote(passwd or '')
     host = socket.gethostbyname(host)
     if not port:
         from eventlib.green import ftplib
         port = ftplib.FTP_PORT
     else:
         port = int(port)
     path, attrs = splitattr(path)
     path = unquote(path)
     dirs = path.split('/')
     dirs, file = dirs[:-1], dirs[-1]
     if dirs and not dirs[0]: dirs = dirs[1:]
     if dirs and not dirs[0]: dirs[0] = '/'
     key = user, host, port, '/'.join(dirs)
     # XXX thread unsafe!
     if len(self.ftpcache) > MAXFTPCACHE:
         # Prune the cache, rather arbitrarily
         for k in list(self.ftpcache.keys()):
             if k != key:
                 v = self.ftpcache[k]
                 del self.ftpcache[k]
                 v.close()
     try:
         if not key in self.ftpcache:
             self.ftpcache[key] = \
                 ftpwrapper(user, passwd, host, port, dirs)
         if not file: type = 'D'
         else: type = 'I'
         for attr in attrs:
             attr, value = splitvalue(attr)
             if attr.lower() == 'type' and \
                value in ('a', 'A', 'i', 'I', 'd', 'D'):
                 type = value.upper()
         (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
         mtype = mimetypes.guess_type("ftp:" + url)[0]
         headers = ""
         if mtype:
             headers += "Content-Type: %s\n" % mtype
         if retrlen is not None and retrlen >= 0:
             headers += "Content-Length: %d\n" % retrlen
         headers = mimetools.Message(StringIO(headers))
         return addinfourl(fp, headers, "ftp:" + url)
     except ftperrors() as msg:
         raise IOError('ftp error', msg).with_traceback(sys.exc_info()[2])
예제 #6
0
    def ftp_open(self, req):
        """
        When ftp requests are made using this handler, this function gets
        called at some point, and it in turn calls the ``connect_ftp`` method.
        In this subclass's reimplementation of ``connect_ftp``, the FQDN of
        the request's host is needed for looking up login credentials in the
        password manager. However, by the time ``connect_ftp`` is called, that
        information has been stripped away, and the host argument passed to
        ``connect_ftp`` contains only the host's IP address instead of the
        FQDN. This reimplementation of ``ftp_open``, which is little more than
        a copy-and-paste from the superclass's implementation, captures the
        original host FQDN before it is replaced with the IP address and saves
        it for later use.

        This reimplementation also ensures that the file size appears in the
        response header by querying for it directly. For some FTP servers the
        original implementation should handle this (``retrlen`` should contain
        the file size). However, for others this can fail silently due to the
        server response not matching an anticipated regular expression.
        """

        import sys
        import email
        import socket
        from urllib.error import URLError
        from urllib.parse import splitattr, splitpasswd, splitvalue
        from urllib.response import addinfourl

        ####################################################
        #  COPIED FROM FTPHandler.ftp_open (PYTHON 3.6.6)  #
        #  WITH JUST A FEW ADDITIONS                       #
        ####################################################

        import ftplib
        import mimetypes
        host = req.host
        if not host:
            raise URLError('ftp error: no host given')
        host, port = splitport(host)
        if port is None:
            port = ftplib.FTP_PORT
        else:
            port = int(port)

        # username/password handling
        user, host = splituser(host)
        if user:
            user, passwd = splitpasswd(user)
        else:
            passwd = None
        host = unquote(host)
        user = user or ''
        passwd = passwd or ''

        ############################################
        # DIFFERENT FROM FTPHandler.ftp_open
        # save the host FQDN for later
        self.last_req_host = host
        ############################################
        try:
            host = socket.gethostbyname(host)
        except OSError as msg:
            raise URLError(msg)
        path, attrs = splitattr(req.selector)
        dirs = path.split('/')
        dirs = list(map(unquote, dirs))
        dirs, file = dirs[:-1], dirs[-1]
        if dirs and not dirs[0]:
            dirs = dirs[1:]
        try:
            fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
            type = file and 'I' or 'D'
            for attr in attrs:
                attr, value = splitvalue(attr)
                if attr.lower() == 'type' and \
                   value in ('a', 'A', 'i', 'I', 'd', 'D'):
                    type = value.upper()
            ############################################
            # DIFFERENT FROM FTPHandler.ftp_open
            size = fw.ftp.size(file)
            ############################################
            fp, retrlen = fw.retrfile(file, type)
            headers = ""
            mtype = mimetypes.guess_type(req.full_url)[0]
            if mtype:
                headers += "Content-type: %s\n" % mtype
            if retrlen is not None and retrlen >= 0:
                headers += "Content-length: %d\n" % retrlen
            ############################################
            # DIFFERENT FROM FTPHandler.ftp_open
            elif size is not None and size >= 0:
                headers += "Content-length: %d\n" % size
            ############################################
            headers = email.message_from_string(headers)
            return addinfourl(fp, headers, req.full_url)
        except ftplib.all_errors as exp:
            exc = URLError('ftp error: %r' % exp)
            raise exc.with_traceback(sys.exc_info()[2])