Python parse.unquote方法代码示例

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

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

示例1: handle_starttag

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def handle_starttag(self, tag, attrs):
        if re.match("h[1-6]", tag) is not None:
            self.ishead = True
        elif tag in self.inde:
            self.isinde = True
        elif tag in self.pref:
            self.ispref = True
        elif tag in self.bull:
            self.isbull = True
        elif tag in self.hide:
            self.ishidden = True
        elif tag == "sup":
            self.text[-1] += "^{"
        elif tag == "sub":
            self.text[-1] += "_{"
        elif tag == "image":
            for i in attrs:
                if i[0] == "xlink:href":
                    self.text.append("[IMG:{}]".format(len(self.imgs)))
                    self.imgs.append(unquote(i[1])) 
开发者ID:wustho,项目名称:epr,代码行数:22,代码来源:epr.py


示例2: test_file_response_custom_filename

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_response_custom_filename(
    app, source, dest, static_file_directory
):
    @app.route("/files/<filename>", methods=["GET"])
    def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        return file(file_path, filename=dest)
    request, response = app.test_client.get(f"/files/{source}")
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, source)
    assert (
        response.headers["Content-Disposition"]
        == f'attachment; filename="{dest}"'
    ) 
开发者ID:huge-success,项目名称:sanic,代码行数:18,代码来源:test_response.py


示例3: test_file_stream_response_custom_filename

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_stream_response_custom_filename(
    app, source, dest, static_file_directory
):
    @app.route("/files/<filename>", methods=["GET"])
    def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        return file_stream(file_path, chunk_size=32, filename=dest)
    request, response = app.test_client.get(f"/files/{source}")
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, source)
    assert (
        response.headers["Content-Disposition"]
        == f'attachment; filename="{dest}"'
    ) 
开发者ID:huge-success,项目名称:sanic,代码行数:18,代码来源:test_response.py


示例4: fwd_normalize

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def fwd_normalize(fwd: OptionsIterable) -> Options:
    """Normalize and convert values extracted from forwarded headers."""
    ret: Dict[str, Union[int, str]] = {}
    for key, val in fwd:
        if val is not None:
            try:
                if key in ("by", "for"):
                    ret[key] = fwd_normalize_address(val)
                elif key in ("host", "proto"):
                    ret[key] = val.lower()
                elif key == "port":
                    ret[key] = int(val)
                elif key == "path":
                    ret[key] = unquote(val)
                else:
                    ret[key] = val
            except ValueError:
                pass
    return ret 
开发者ID:huge-success,项目名称:sanic,代码行数:21,代码来源:headers.py


示例5: put

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def put(url, data):
        url = unquote(url)
        match, project = Cache.match(url)
        if match:
            path = Cache.path(url, project, include_file=True, makedirs=True)
            ttl = Cache.PATTERNS[match]
            if ttl == 0:
                return data
            # Since urlopen does not return a seekable stream it cannot be reset
            # after writing to cache. As such a wrapper must be used. This could
            # be replaced with urlopen('file://...') to be consistent, but until
            # the need arrises BytesIO has less overhead.
            text = data.read()
            data = BytesIO(text)
            if conf.config['debug']: print('CACHE_PUT', url, project, file=sys.stderr)
            f = open(path, 'wb')
            f.write(text)
            f.close()
        return data 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:24,代码来源:cache.py


示例6: delete

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def delete(url):
        url = unquote(url)
        match, project = Cache.match(url)
        if match:
            path = Cache.path(url, project, include_file=True)
            # Rather then wait for last updated statistics to expire, remove the
            # project cache if applicable.
            if project:
                apiurl, _ = Cache.spliturl(url)
                if project.isdigit():
                    # Clear target project cache upon request acceptance.
                    project = osc.core.get_request(apiurl, project).actions[0].tgt_project
                Cache.delete_project(apiurl, project)
            if os.path.exists(path):
                if conf.config['debug']: print('CACHE_DELETE', url, file=sys.stderr)
                os.remove(path)
        # Also delete version without query. This does not handle other
        # variations using different query strings. Handy for PUT with ?force=1.
        o = urlsplit(url)
        if o.query != '':
            url_plain = SplitResult(o.scheme, o.netloc, o.path, '', o.fragment).geturl()
            Cache.delete(url_plain) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:27,代码来源:cache.py


示例7: find_file

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def find_file(self, filename):
        # Get rid of special characters
        filename = unquote(filename)
        # First, look for the file in the root of the book
        if filename in self.file_list:
            return filename
        # Then search for it elsewhere
        else:
            file_basename = os.path.basename(filename)
            for i in self.file_list:
                if os.path.basename(i) == file_basename:
                    return i
        # If the file isn't found
        logger.warning(filename + ' not found in ' + self.book_filename)
        return False 
开发者ID:BasioMeusPuga,项目名称:Lector,代码行数:20,代码来源:read_epub.py


示例8: test_form_link

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_form_link(self):
        data = {
            'pid': 99,
            'account': 79000000000,
            'amount': 123,
            'comment': 'Hey, it works!'
        }
        paylink = pyqiwi.generate_form_link(**data)
        result = url_params(unquote(paylink))
        data.pop('pid') # It is not on params, it's in URL
        # Qiwi requires for amount to be split into integer and fraction
        data = merge_dicts(data, split_float(data.get('amount')))
        data.pop('amount')
        # unquote won't process + to <Space>, but Qiwi should
        if result.get("extra['comment']"):
            result["extra['comment']"] = result["extra['comment']"].replace('+', ' ')
        for key in data:
            if key == 'account':
                assert result["extra['account']"] == str(data[key])
            elif key == 'comment':
                assert result["extra['comment']"] == str(data[key]) 
开发者ID:mostm,项目名称:pyqiwi,代码行数:23,代码来源:test_wallet.py


示例9: getguild

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def getguild(self, request: web.Request):
        guild = int(request.match_info['guild'])
        req = f"""SELECT info FROM guilddata WHERE UUID = $1"""
        async with self.bot.db._conn.acquire() as connection:
            response = await connection.fetchval(req, guild)
        if response:
            data = json.loads(response)
            fdata = data
            if request.match_info['tail']:
                for item in request.match_info['tail'].split("/"):
                    if not item:
                        continue
                    try:
                        key = unquote(item)
                        if isinstance(fdata, list):
                            key = int(key)
                        fdata = fdata[key]
                    except:
                        raise web.HTTPNotFound()
            return web.json_response(fdata)
        raise web.HTTPForbidden()
    # @server.route("/", methods=["GET"]) 
开发者ID:henry232323,项目名称:RPGBot,代码行数:27,代码来源:server.py


示例10: __init__

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def __init__(self, url):
        super(ElasticDB, self).__init__()
        self.username = ''
        self.password = ''
        self.hosts = None
        if '@' in url.netloc:
            username, hostname = url.netloc.split('@', 1)
            if ':' in username:
                self.username, self.password = (unquote(val) for val in
                                                username.split(':', 1))
            else:
                self.username = unquote(username)
            if hostname:
                self.hosts = [hostname]
        elif url.netloc:
            self.hosts = [url.netloc]
        index_prefix = url.path.lstrip('/')
        if index_prefix:
            self.index_prefix = index_prefix + '-'
        else:
            self.index_prefix = 'ivre-'
        self.params = dict(x.split('=', 1) if '=' in x else (x, None)
                           for x in url.query.split('&') if x) 
开发者ID:cea-sec,项目名称:ivre,代码行数:25,代码来源:elastic.py


示例11: article

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def article(
            self,
            title: str,
            ns: WikiNamespace = Namespace.MAIN,
            unquote: bool = False
    ) -> 'WikipediaPage':
        """
        Constructs Wikipedia page with title `title`.
        This function is an alias for :func:`page`
        :param title: page title as used in Wikipedia URL
        :param ns: :class:`WikiNamespace`
        :param unquote: if true it will unquote title
        :return: object representing :class:`WikipediaPage`
        """
        return self.page(
            title=title,
            ns=ns,
            unquote=unquote,
        ) 
开发者ID:martin-majlis,项目名称:Wikipedia-API,代码行数:23,代码来源:__init__.py


示例12: translate_path

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def translate_path(self, path):
        """
        Translate a /-separated PATH to the local filename syntax.
        Components that mean special things to the local file system
        (e.g. drive or directory names) are ignored.  (XXX They should
        probably be diagnosed.)
        """
        # abandon query parameters
        path = urlparse(to_text(path))[2]
        path = posixpath.normpath(unquote(path))
        words = path.split('/')
        words = list(filter(None, words))
        path = self.server.cwd
        for word in words:
            _, word = os.path.splitdrive(word)
            _, word = os.path.split(word)
            if word in (os.curdir, os.pardir):
                continue
            path = os.path.join(path, word)
        return path 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:24,代码来源:http_server.py


示例13: ECitMatch

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def ECitMatch(self, bdata, **kargs):
        r"""
        :param bdata: Citation strings. Each input citation must
            be represented by a citation string in the following format::
                journal_title|year|volume|first_page|author_name|your_key|
            Multiple citation strings may be provided by separating the
            strings with a carriage return character (%0D) or simply \\r or \\n.
            The your_key value is an arbitrary label provided by the user
            that may serve as a local identifier for the citation,
            and it will be included in the output.
            all spaces must be replaced by + symbols and that citation
            strings should end with a final vertical bar |.
        Only xml supported at the time of this implementation.
        ::
            from bioservices import EUtils
            s = EUtils()
            print(s.ECitMatch("proc+natl+acad+sci+u+s+a|1991|88|3248|mann+bj|Art1|%0Dscience|1987|235|182|palmenberg+ac|Art2|"))
        """
        # Fixes https://github.com/cokelaer/bioservices/issues/169
        from urllib.parse import unquote
        params = {'bdata': unquote(bdata), "retmode": "xml"}
        # note here, we use .cgi not .fcgi
        query = "ecitmatch.cgi?db=pubmed&retmode=xml"
        ret = self.http_get(query, None,  params=params)
        try: ret = ret.content
        except: pass
        return ret 
开发者ID:cokelaer,项目名称:bioservices,代码行数:42,代码来源:eutils.py


示例14: connect

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def connect(self):
        netloc = unquote(urlparse(self.usbmux_socket_url).netloc)
        udid, port = splitport(netloc)
        if not port:
            port = 8100 # WDA Default port
        _device = _usbmux.device(udid)
        conn = _device.create_inner_connection(int(port))
        self.sock = conn._sock
        self.sock.settimeout(self.timeout) 
开发者ID:openatx,项目名称:facebook-wda,代码行数:12,代码来源:requests_usbmux.py


示例15: create_cookies

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def create_cookies(self, cookie):
        cookies = dict()
        cookies_list = cookie[0:cookie.find(';')].split("=")
        cookies[cookies_list[0]] = cookies_list[1]
        cookies['netcraft_js_verification_response'] = hashlib.sha1(urllib.unquote(cookies_list[1])).hexdigest()
        return cookies 
开发者ID:kp625544,项目名称:subtake,代码行数:8,代码来源:sublist3r.py


示例16: handle_startendtag

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def handle_startendtag(self, tag, attrs):
        if tag == "br":
            self.text += [""]
        elif tag in {"img", "image"}:
            for i in attrs:
                if (tag == "img" and i[0] == "src") or (tag == "image" and i[0] == "xlink:href"):
                    self.text.append("[IMG:{}]".format(len(self.imgs)))
                    self.imgs.append(unquote(i[1]))
                    self.text.append("") 
开发者ID:wustho,项目名称:epr,代码行数:11,代码来源:epr.py


示例17: make_test_headers_path_and_query_string

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def make_test_headers_path_and_query_string(
    app: "Quart",
    path: str,
    headers: Optional[Union[dict, Headers]] = None,
    query_string: Optional[dict] = None,
) -> Tuple[Headers, str, bytes]:
    """Make the headers and path with defaults for testing.
    Arguments:
        app: The application to test against.
        path: The path to request. If the query_string argument is not
            defined this argument will be partitioned on a '?' with
            the following part being considered the query_string.
        headers: Initial headers to send.
        query_string: To send as a dictionary, alternatively the
            query_string can be determined from the path.
    """
    if headers is None:
        headers = Headers()
    elif isinstance(headers, Headers):
        headers = headers
    elif headers is not None:
        headers = Headers(headers)
    headers.setdefault("Remote-Addr", "127.0.0.1")
    headers.setdefault("User-Agent", "Quart")
    headers.setdefault("host", app.config["SERVER_NAME"] or "localhost")
    if "?" in path and query_string is not None:
        raise ValueError("Query string is defined in the path and as an argument")
    if query_string is None:
        path, _, query_string_raw = path.partition("?")
    else:
        query_string_raw = urlencode(query_string, doseq=True)
    query_string_bytes = query_string_raw.encode("ascii")
    return headers, unquote(path), query_string_bytes 
开发者ID:pgjones,项目名称:quart,代码行数:36,代码来源:testing.py


示例18: urldecode

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def urldecode(str) :
	return urlparse.unquote(str) 
开发者ID:jojoin,项目名称:cutout,代码行数:4,代码来源:util.py


示例19: _parse

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def _parse(application_endpoint: str) -> Tuple[str, str, str]:
        url, valid = LuisApplication._try_parse_url(application_endpoint)
        if not valid:
            raise ValueError(
                f"{application_endpoint} is not a valid LUIS application endpoint."
            )
        segments = PurePosixPath(unquote(url.path)).parts
        application_id = segments[-1] if segments else None
        qs_parsed_result = parse_qs(url.query)
        endpoint_key = qs_parsed_result.get("subscription-key", [None])[0]
        parts_for_base_url = url.scheme, url.netloc, "", None, None, None
        endpoint = urlunparse(parts_for_base_url)
        return (application_id, endpoint_key, endpoint) 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:17,代码来源:luis_application.py


示例20: test_file_response

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_response(app, file_name, static_file_directory, status):
    @app.route("/files/<filename>", methods=["GET"])
    def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        return file(
            file_path,
            status=status,
            mime_type=guess_type(file_path)[0] or "text/plain",
        )
    request, response = app.test_client.get(f"/files/{file_name}")
    assert response.status == status
    assert response.body == get_file_content(static_file_directory, file_name)
    assert "Content-Disposition" not in response.headers 
开发者ID:huge-success,项目名称:sanic,代码行数:17,代码来源:test_response.py


示例21: test_file_head_response

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_head_response(app, file_name, static_file_directory):
    @app.route("/files/<filename>", methods=["GET", "HEAD"])
    async def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        stats = await async_os.stat(file_path)
        headers = dict()
        headers["Accept-Ranges"] = "bytes"
        headers["Content-Length"] = str(stats.st_size)
        if request.method == "HEAD":
            return HTTPResponse(
                headers=headers,
                content_type=guess_type(file_path)[0] or "text/plain",
            )
        else:
            return file(
                file_path,
                headers=headers,
                mime_type=guess_type(file_path)[0] or "text/plain",
            )
    request, response = app.test_client.head(f"/files/{file_name}")
    assert response.status == 200
    assert "Accept-Ranges" in response.headers
    assert "Content-Length" in response.headers
    assert int(response.headers["Content-Length"]) == len(
        get_file_content(static_file_directory, file_name)
    ) 
开发者ID:huge-success,项目名称:sanic,代码行数:30,代码来源:test_response.py


示例22: test_file_stream_response

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_stream_response(app, file_name, static_file_directory):
    @app.route("/files/<filename>", methods=["GET"])
    def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        return file_stream(
            file_path,
            chunk_size=32,
            mime_type=guess_type(file_path)[0] or "text/plain",
        )
    request, response = app.test_client.get(f"/files/{file_name}")
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)
    assert "Content-Disposition" not in response.headers 
开发者ID:huge-success,项目名称:sanic,代码行数:17,代码来源:test_response.py


示例23: test_file_stream_response_range

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def test_file_stream_response_range(
    app, file_name, static_file_directory, size, start, end
):
    Range = namedtuple("Range", ["size", "start", "end", "total"])
    total = len(get_file_content(static_file_directory, file_name))
    range = Range(size=size, start=start, end=end, total=total)
    @app.route("/files/<filename>", methods=["GET"])
    def file_route(request, filename):
        file_path = os.path.join(static_file_directory, filename)
        file_path = os.path.abspath(unquote(file_path))
        return file_stream(
            file_path,
            chunk_size=32,
            mime_type=guess_type(file_path)[0] or "text/plain",
            _range=range,
        )
    request, response = app.test_client.get(f"/files/{file_name}")
    assert response.status == 206
    assert "Content-Range" in response.headers
    assert (
        response.headers["Content-Range"]
        == f"bytes {range.start}-{range.end}/{range.total}"
    ) 
开发者ID:huge-success,项目名称:sanic,代码行数:28,代码来源:test_response.py


示例24: normalise

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def normalise(self, url):
        """
        Convert the URL into an equivalent which is more suitable for comparison and ranks.
        """
        if 'babel.hathitrust.org' in url:
            return unquote(re.sub(r"https://babel\.hathitrust\.org/cgi/imgsrv/download/pdf\?id=([^;]+).*",
                          r"https://hdl.handle.net/2027/\1",
                          url))
        return url 
开发者ID:dissemin,项目名称:oabot,代码行数:11,代码来源:arguments.py


示例25: setcookie

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def setcookie(self,cookiestring):
        cookie = {}
        if cookiestring is not None:
            for onecookiestring in cookiestring.split(";"):
                tmp = onecookiestring.split("=")
                if len(tmp)!=2:
                    continue
                a, b = tmp
                a = quote(unquote(a).strip())
                cookie.update({a: b})
            self.s.cookies.update(cookie) 
开发者ID:zjuchenyuan,项目名称:cc98,代码行数:13,代码来源:EasyLogin.py


示例26: unquote_py3

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def unquote_py3(x):
        return parse.unquote(x) 
开发者ID:typeintandem,项目名称:tandem,代码行数:4,代码来源:diff_match_patch.py


示例27: unquote_py2

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote [as 别名]
def unquote_py2(x):
        return parse.unquote(x.encode('utf-8')).decode('utf-8') 
开发者ID:typeintandem,项目名称:tandem,代码行数:4,代码来源:diff_match_patch.py



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