Python requests.utils.quote() Examples

The following are 22 code examples of requests.utils.quote(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests.utils , or try the search function .
Example #1
Source File: translate.py    From ieighteen with MIT License 6 votes vote down vote up
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 
Example #2
Source File: client.py    From Tenable.io-SDK-for-Python with MIT License 6 votes vote down vote up
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. 
Example #3
Source File: stchttp.py    From py-stcrestclient with MIT License 6 votes vote down vote up
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 
Example #4
Source File: articledownloader.py    From article-downloader with MIT License 6 votes vote down vote up
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 
Example #5
Source File: decorators.py    From modern-paste with MIT License 6 votes vote down vote up
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 
Example #6
Source File: onyphe.py    From yeti with Apache License 2.0 5 votes vote down vote up
def _search(self, query, **kwargs):
        return self._prepare_request(quote('/'.join([self.version, 'search', query])), **kwargs) 
Example #7
Source File: ShinetoLogin.py    From Anti_teNelgniS with GNU General Public License v2.0 5 votes vote down vote up
def request_vpn(self):
        if not self.user:
            raise RequestVpnFailed('Not Login yet.')
        lb64 = LongBase64()
        vpnparams = 'username=%s&password=%s&flashInfo=%s' % (
            self.user['stcode'], self.user['userpassword'], self.user['sxcode'])
        postdata = quote(vpnparams)

        vpn_resp = self.s.post(self._vpn_uri, params={'st': postdata})
        return lb64.decodestring(vpn_resp.content) 
Example #8
Source File: ShinetoLogin.py    From Anti_teNelgniS with GNU General Public License v2.0 5 votes vote down vote up
def do_login(self, password):
        lb64 = LongBase64()
        logininfo = '%s|%s|122.227.254.206|8988|1|4.0.1.2' % (self.username, password)
        logininfo = lb64.encodestring(logininfo)
        postdata = quote(logininfo)

        login_resp = self.s.post(self._login_uri, data={'logininfo': postdata})
        login_res = json.loads(login_resp.content)
        if login_res['r'] != 1:
            raise LoginFailed('Login Failed: %s' % login_res['err_msg'])
        self.user = login_res
        return True, login_res 
Example #9
Source File: dl.py    From ColumbiaImageSearch with Apache License 2.0 5 votes vote down vote up
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)) 
Example #10
Source File: decrypt.py    From twist.moe with The Unlicense 5 votes vote down vote up
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 
Example #11
Source File: stchttp.py    From py-stcrestclient with MIT License 5 votes vote down vote up
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 
Example #12
Source File: utils.py    From 115wangpan with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def quote(s):
    res = s
    if isinstance(res, six.text_type):
        res = s.encode('utf-8')
    return _quote(res) 
Example #13
Source File: channel.py    From plugin.video.bimozie with GNU General Public License v3.0 5 votes vote down vote up
def parse_url(self, url):
        url = quote(url).replace('%3A', ':')

        return url 
Example #14
Source File: _manager.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
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) 
Example #15
Source File: downloader.py    From GetSubtitles with MIT License 5 votes vote down vote up
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 
Example #16
Source File: commit.py    From marge-bot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #17
Source File: users_api.py    From seqr with GNU Affero General Public License v3.0 5 votes vote down vote up
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}) 
Example #18
Source File: endpoint.py    From zenpy with GNU General Public License v3.0 4 votes vote down vote up
def __call__(self, query=None, **kwargs):

        renamed_kwargs = dict()
        modifiers = list()
        params = dict()
        for key, value in kwargs.items():
            if isinstance(value, date):
                kwargs[key] = value.strftime(self.ZENDESK_DATE_FORMAT)
            elif isinstance(key, datetime):
                kwargs[key] = value.strftime(self.ISO_8601_FORMAT)
            elif is_iterable_but_not_string(value) and key == 'ids':
                kwargs[key] = ", ".join(map(str, value))
            if key.endswith('_between'):
                modifiers.append(self.format_between(key, value))
            elif key in ('sort_by', 'sort_order'):
                params[key] = value
            elif key.endswith('_after'):
                renamed_kwargs[key.replace('_after', '>')] = kwargs[key]
            elif key.endswith('_before'):
                renamed_kwargs[key.replace('_before', '<')] = kwargs[key]
            elif key.endswith('_greater_than'):
                renamed_kwargs[key.replace('_greater_than', '>')] = kwargs[key]
            elif key.endswith('_less_than'):
                renamed_kwargs[key.replace('_less_than', '<')] = kwargs[key]
            elif key == 'minus':
                if is_iterable_but_not_string(value):
                    [modifiers.append("-%s" % v) for v in value]
                else:
                    modifiers.append("-%s" % value)
            elif is_iterable_but_not_string(value):
                modifiers.append(self.format_or(key, value))
            else:
                if isinstance(value, str) and value.count(' ') > 0:
                    value = '"{}"'.format(value)
                renamed_kwargs.update({key + ':': '%s' % value})

        search_query = [
            '%s%s' % (key, value) for (key, value) in renamed_kwargs.items()
        ]
        search_query.extend(modifiers)
        if query is not None:
            search_query.insert(0, query)
        params['query'] = quote(' '.join(search_query))
        return Url(self.endpoint, params) 
Example #19
Source File: articledownloader.py    From article-downloader with MIT License 4 votes vote down vote up
def get_dois_from_journal_issn(self, issn, rows=500, pub_after=2000, mailto="null@null.com"):
    '''
    Grabs a set of unique DOIs based on a journal ISSN using the CrossRef API

    :param issn: The ISSN of the journal
    :type issn: str

    :param rows: the maximum number of DOIs to find
    :type rows: int

    :param pub_after: the minimum publication year for DOIs returned
    :type pub_after: int

    :param mailto: mailto address for API
    :type rows: str

    :returns: the unique set of DOIs as a list
    :rtype: list
    '''

    dois = []
    base_url = 'https://api.crossref.org/journals/' + issn + '/works?filter=from-pub-date:' + str(pub_after)
    max_rows = 1000 #Defined by CrossRef API

    headers = {
      'Accept': 'application/json',
      'User-agent': 'mailto:' + mailto
    }

    if rows <= max_rows: #No multi-query needed
      search_url = str(base_url) + '&rows=' + str(rows)
      response = requests.get(search_url, headers=headers, timeout=self.timeout_sec).json()

      for item in response["message"]["items"]:
        dois.append(item["DOI"])

    else: #Need to split queries
      cursor = "*"
      keep_paging = True
      while (keep_paging):
        sleep(self.sleep_sec)
        r = requests.get(base_url + "&rows=" + str(max_rows) + "&cursor=" + cursor,
                         headers=headers, timeout=self.timeout_sec)
        cursor = quote(r.json()['message']['next-cursor'], safe='')
        if len(r.json()['message']['items']) == 0:
          keep_paging = False

        for item in r.json()['message']['items']:
          dois.append(item['DOI'])

    return list(set(dois)) 
Example #20
Source File: articledownloader.py    From article-downloader with MIT License 4 votes vote down vote up
def get_dois_from_search(self, query, rows=500, mailto="null@null.com"):
    '''
    Grabs a set of unique DOIs based on a search query using the CrossRef API

    :param query: the search string
    :type query: str

    :param rows: the maximum number of DOIs to find
    :type rows: int

    :param mailto: mailto address for API
    :type rows: str

    :returns: the unique set of DOIs as a list
    :rtype: list
    '''

    dois = []
    base_url = 'https://api.crossref.org/works?query='
    max_rows = 1000 #Defined by CrossRef API

    headers = {
      'Accept': 'application/json',
      'User-agent': 'mailto:' + mailto
    }

    if rows <= max_rows: #No multi-query needed
      search_url = base_url + query + '&rows=' + str(rows)
      response = requests.get(search_url, headers=headers, timeout=self.timeout_sec).json()

      for item in response["message"]["items"]:
        dois.append(item["DOI"])

    else: #Need to split queries
      cursor = "*"
      keep_paging = True
      while (keep_paging):
        sleep(self.sleep_sec)
        r = requests.get(base_url + query + "&rows=" + str(max_rows) + "&cursor=" + cursor,
                         headers=headers, timeout=self.timeout_sec)
        cursor = quote(r.json()['message']['next-cursor'], safe='')
        if len(r.json()['message']['items']) == 0:
          keep_paging = False

        for item in r.json()['message']['items']:
          dois.append(item['DOI'])

    return list(set(dois)) 
Example #21
Source File: decorators.py    From edx-enterprise with GNU Affero General Public License v3.0 4 votes vote down vote up
def force_fresh_session(view):
    """
    View decorator which terminates stale TPA sessions.

    This decorator forces the user to obtain a new session
    the first time they access the decorated view. This prevents
    TPA-authenticated users from hijacking the session of another
    user who may have been previously logged in using the same
    browser window.

    This decorator should be used in conjunction with the
    enterprise_login_required decorator.

    Usage::
        @enterprise_login_required
        @force_fresh_session()
        def my_view(request, enterprise_uuid):
            # Some functionality ...

        OR

        class MyView(View):
            ...
            @method_decorator(enterprise_login_required)
            @method_decorator(force_fresh_session)
            def get(self, request, enterprise_uuid):
                # Some functionality ...
    """
    @wraps(view)
    def wrapper(request, *args, **kwargs):
        """
        Wrap the function.
        """
        if not request.GET.get(FRESH_LOGIN_PARAMETER):
            # The enterprise_login_required decorator promises to set the fresh login URL
            # parameter for this URL when it was the agent that initiated the login process;
            # if that parameter isn't set, we can safely assume that the session is "stale";
            # that isn't necessarily an issue, though. Redirect the user to
            # log out and then come back here - the enterprise_login_required decorator will
            # then take effect prior to us arriving back here again.
            enterprise_customer = get_enterprise_customer_or_404(kwargs.get('enterprise_uuid'))
            provider_id = enterprise_customer.identity_provider or ''
            sso_provider = get_identity_provider(provider_id)
            if sso_provider:
                # Parse the current request full path, quote just the path portion,
                # then reconstruct the full path string.
                # The path and query portions should be the only non-empty strings here.
                scheme, netloc, path, params, query, fragment = urlparse(request.get_full_path())
                redirect_url = urlunparse((scheme, netloc, quote(path), params, query, fragment))

                return redirect(
                    '{logout_url}?{params}'.format(
                        logout_url='/logout',
                        params=urlencode(
                            {'redirect_url': redirect_url}
                        )
                    )
                )
        return view(request, *args, **kwargs)

    return wrapper 
Example #22
Source File: _partition.py    From python-zhmcclient with Apache License 2.0 4 votes vote down vote up
def mount_iso_image(self, image, image_name, ins_file_name):
        """
        Upload an ISO image and associate it to this Partition
        using the HMC operation 'Mount ISO Image'.

        When the partition already has an ISO image associated,
        the newly uploaded image replaces the current one.

        Authorization requirements:

        * Object-access permission to this Partition.
        * Task permission to the "Partition Details" task.

        Parameters:

          image (:term:`byte string` or file-like object):
            The content of the ISO image.

            Images larger than 2GB cannot be specified as a Byte string; they
            must be specified as a file-like object.

            File-like objects must have opened the file in binary mode.

          image_name (:term:`string`): The displayable name of the image.

            This value must be a valid Linux file name without directories,
            must not contain blanks, and must end with '.iso' in lower case.

            This value will be shown in the 'boot-iso-image-name' property of
            this partition.

          ins_file_name (:term:`string`): The path name of the INS file within
            the file system of the ISO image.

            This value will be shown in the 'boot-iso-ins-file' property of
            this partition.

        Raises:

          :exc:`~zhmcclient.HTTPError`
          :exc:`~zhmcclient.ParseError`
          :exc:`~zhmcclient.AuthError`
          :exc:`~zhmcclient.ConnectionError`
        """
        query_parms_str = '?image-name={}&ins-file-name={}'. \
            format(quote(image_name, safe=''), quote(ins_file_name, safe=''))
        self.manager.session.post(
            self.uri + '/operations/mount-iso-image' + query_parms_str,
            body=image)