当前位置: 首页>>代码示例>>Python>>正文


Python utils.quote方法代码示例

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


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

示例1: getTranslation

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def getTranslation(sentence):
    global counter, sourceLang, targetLang

    url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceLang
    url = url + "&tl=" + targetLang + "&dt=t&q=" + quote(sentence);

    print('Request# ' + str(counter) + ': ' + url)
    counter += 1

    page = requests.get(url)

    # strip the response to extract urdu text along with quotes
    translation = page.content
    translation = translation[3:]
    removeLast = 16 + len(sentence)
    translation = translation[:-removeLast]

    # still has a trailing comma
    if (translation[-1] == ','):
        translation = translation[:-1]

    return translation 
开发者ID:emadehsan,项目名称:ieighteen,代码行数:24,代码来源:translate.py

示例2: _request

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def _request(self, method, uri, path_params=None, flatten_params=True, **kwargs):
        if path_params:
            # Ensure path param is encoded.
            path_params = {key: quote(str(value), safe=u'') for key, value in path_params.items()}
            uri %= path_params

        # Custom nested object flattening
        if flatten_params and 'params' in kwargs:
            kwargs['params'] = self._flatten_param(kwargs['params'])

        full_uri = self._endpoint + uri

        response = self._session.request(method, full_uri, **kwargs)
        log_message = format_request(response)

        logging.info(log_message)
        if not 200 <= response.status_code <= 299:
            logging.error(log_message)

        return response

    # Delayed qualifying decorator as staticmethod. This is a workaround to error raised from using a decorator
    # decorated by @staticmethod. 
开发者ID:tenable,项目名称:Tenable.io-SDK-for-Python,代码行数:25,代码来源:client.py

示例3: load_queries_from_csv

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def load_queries_from_csv(self, csvf):
    '''
    Loads a list of queries from a CSV file

    :param csvf: file object containing a CSV file with one query per line
    :type csvf: file

    :returns: a list of queries, processed to be insertable into REST API (GET) calls
    :rtype: list
    '''

    csvf.seek(0)
    csvreader = reader(csvf, delimiter=',')
    queries = []
    for line in csvreader:
      #Build search query (assume 1st column is queries)
      query = quote(line[0])
      query = query.split()
      query = '+'.join(query)

      final_query = query
      queries.append(final_query)
    return queries 
开发者ID:olivettigroup,项目名称:article-downloader,代码行数:25,代码来源:articledownloader.py

示例4: require_login_frontend

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def require_login_frontend(only_if=True):
    """
    Same logic as the API require_login, but this decorator is intended for use for frontend interfaces.
    It returns a redirect to the login page, along with a post-login redirect_url as a GET parameter.

    :param only_if: Optionally specify a boolean condition that needs to be true for the frontend login to be required.
                    This is semantically equivalent to "require login for this view endpoint only if <condition>,
                    otherwise, no login is required"
    """
    def decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if not current_user.is_authenticated and only_if:
                return redirect(UserLoginInterfaceURI.uri(redirect_url=quote(request.url, safe='')))
            return func(*args, **kwargs)
        return decorated_view
    return decorator 
开发者ID:LINKIWI,项目名称:modern-paste,代码行数:19,代码来源:decorators.py

示例5: bulkget

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def bulkget(self, locations, args=None, depth=1):
        """Returns the value(s) of one or more object attributes.

        If multiple arguments, this method returns a dictionary of argument
        names mapped to the value returned by each argument.

        If a single argument is given, then the response is a list of values
        for that argument.

        Arguments:
        handle -- Handle that identifies object to get info for.
        args  -- Zero or more attributes or relationships.


        """
        self._check_session()
        status, data = self._rest.bulk_get_request('bulk/objects', quote(locations), args, depth)
        return data 
开发者ID:Spirent,项目名称:py-stcrestclient,代码行数:20,代码来源:stchttp.py

示例6: _append_query_parms

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def _append_query_parms(self, query_parms, prop_name, prop_match):
        if isinstance(prop_match, (list, tuple)):
            for pm in prop_match:
                self._append_query_parms(query_parms, prop_name, pm)
        else:
            # Just in case, we also escape the property name
            parm_name = quote(prop_name, safe='')
            parm_value = quote(str(prop_match), safe='')
            qp = '{}={}'.format(parm_name, parm_value)
            query_parms.append(qp) 
开发者ID:zhmcclient,项目名称:python-zhmcclient,代码行数:12,代码来源:_manager.py

示例7: forgot_password

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def forgot_password(request):
    request_json = json.loads(request.body)
    if not request_json.get('email'):
        return create_json_response({}, status=400, reason='Email is required')

    users = User.objects.filter(email__iexact=request_json['email'])
    if users.count() != 1:
        return create_json_response({}, status=400, reason='No account found for this email')
    user = users.first()

    email_content = """
        Hi there {full_name}--

        Please click this link to reset your seqr password:
        {base_url}users/set_password/{password_token}?reset=true
        """.format(
        full_name=user.get_full_name(),
        base_url=BASE_URL,
        password_token=quote(user.password, safe=''),
    )

    try:
        user.email_user('Reset your seqr password', email_content, fail_silently=False)
    except AnymailError as e:
        return create_json_response({}, status=getattr(e, 'status_code', None) or 400, reason=str(e))

    return create_json_response({'success': True}) 
开发者ID:macarthur-lab,项目名称:seqr,代码行数:29,代码来源:users_api.py

示例8: last_on_branch

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def last_on_branch(cls, project_id, branch, api):
        info = api.call(GET(
            '/projects/{project_id}/repository/branches/{branch}'.format(
                project_id=project_id,
                branch=quote(branch, safe=''),
            ),
        ))['commit']
        return cls(api, info) 
开发者ID:smarkets,项目名称:marge-bot,代码行数:10,代码来源:commit.py

示例9: get_keywords

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def get_keywords(cls, video):

        """ 解析视频名
        Args:
            video: Video 对象
        Return:
            keywords: list
        """

        keywords = []

        info_dict = video.info
        title = info_dict["title"]
        keywords.append(title)

        if info_dict.get("season"):
            keywords.append("s%s" % str(info_dict["season"]).zfill(2))

        if info_dict.get("year") and info_dict.get("type") == "movie":
            keywords.append(str(info_dict["year"]))  # 若为电影添加年份

        if info_dict.get("episode"):
            keywords.append("e%s" % str(info_dict["episode"]).zfill(2))
        if info_dict.get("source"):
            keywords.append(info_dict["source"].replace("-", ""))
        if info_dict.get("release_group"):
            keywords.append(info_dict["release_group"])
        if info_dict.get("streaming_service"):
            service_name = info_dict["streaming_service"]
            short_names = cls.service_short_names.get(service_name.lower())
            if short_names:
                keywords.append(short_names)
        if info_dict.get("screen_size"):
            keywords.append(str(info_dict["screen_size"]))

        # 对关键字进行 URL 编码
        keywords = [quote(_keyword) for _keyword in keywords]
        return keywords 
开发者ID:gyh1621,项目名称:GetSubtitles,代码行数:40,代码来源:downloader.py

示例10: _search

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def _search(self, query, **kwargs):
        return self._prepare_request(quote('/'.join([self.version, 'search', query])), **kwargs) 
开发者ID:yeti-platform,项目名称:yeti,代码行数:4,代码来源:onyphe.py

示例11: parse_url

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def parse_url(self, url):
        url = quote(url).replace('%3A', ':')

        return url 
开发者ID:billythekids,项目名称:plugin.video.bimozie,代码行数:6,代码来源:channel.py

示例12: quote

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def quote(s):
    res = s
    if isinstance(res, six.text_type):
        res = s.encode('utf-8')
    return _quote(res) 
开发者ID:shichao-an,项目名称:115wangpan,代码行数:7,代码来源:utils.py

示例13: bulkconfig

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def bulkconfig(self, locations, attributes=None, **kwattrs):
        """Sets or modifies one or more object attributes or relations.

        Arguments can be supplied either as a dictionary or as keyword
        arguments.  Examples:
            stc.bulkconfig('emulateddevice[@name="mydev"]/bgprouterconfig/bgpipv4routeconfig[0]',  {'NextHopIncrement': '0.0.1.0'})
            stc.bulkconfig('emulateddevice[@name="mydev"]/bgprouterconfig/bgpipv4routeconfig[1]',  NextHopIncrement='0.0.1.0')

        Arguments:
        locations     -- the locations of object to modify.
        attributes -- Dictionary of attributes (name-value pairs).
        kwattrs    -- Optional keyword attributes (name=value pairs).

        """
        self._check_session()
        if kwattrs:
            if attributes:
                if isinstance(attributes, dict):
                    attributes.update(kwattrs)
                elif isinstance(attributes, list):
                    for attr in attributes:
                        attr.update(kwattrs)
            else:
                attributes = kwattrs
        
        attributes = json.dumps(attributes)
        status, data = self._rest.bulk_put_request('bulk/objects', quote(locations), attributes)
        return data 
开发者ID:Spirent,项目名称:py-stcrestclient,代码行数:30,代码来源:stchttp.py

示例14: decrypt_export

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def decrypt_export(url):
    decrypt_ed = decrypt((url).encode('utf-8'), KEY).decode('utf-8').lstrip(' ')
    escap_ed = quote(decrypt_ed, safe='~@#$&()*!+=:;,.?/\'')
    return escap_ed 
开发者ID:phanirithvij,项目名称:twist.moe,代码行数:6,代码来源:decrypt.py

示例15: fixurl

# 需要导入模块: from requests import utils [as 别名]
# 或者: from requests.utils import quote [as 别名]
def fixurl(url):
  # Inspired from https://stackoverflow.com/a/804380 but using requests
  from requests.utils import urlparse, urlunparse, quote, unquote

  # turn string into unicode
  if not isinstance(url, unicode):
    url = url.decode('utf8')

  # parse it
  parsed = urlparse(url)

  # divide the netloc further
  userpass, at, hostport = parsed.netloc.rpartition('@')
  user, colon1, pass_ = userpass.partition(':')
  host, colon2, port = hostport.partition(':')

  # encode each component
  scheme = parsed.scheme.encode('utf8')
  user = quote(user.encode('utf8'))
  colon1 = colon1.encode('utf8')
  pass_ = quote(pass_.encode('utf8'))
  at = at.encode('utf8')
  host = host.encode('idna')
  colon2 = colon2.encode('utf8')
  port = port.encode('utf8')
  path = '/'.join(  # could be encoded slashes!
    quote(unquote(pce).encode('utf8'), '')
    for pce in parsed.path.split('/')
  )
  query = quote(unquote(parsed.query).encode('utf8'), '=&?/')
  fragment = quote(unquote(parsed.fragment).encode('utf8'))

  # put it back together
  netloc = ''.join((user, colon1, pass_, at, host, colon2, port))
  #urlunparse((scheme, netloc, path, params, query, fragment))
  params = ''
  return urlunparse((scheme, netloc, path, params, query, fragment)) 
开发者ID:ColumbiaDVMM,项目名称:ColumbiaImageSearch,代码行数:39,代码来源:dl.py


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