Python urllib.urlencode() Examples

The following are 40 code examples for showing how to use urllib.urlencode(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module urllib , or try the search function .

Example 1
Project: wechatpy   Author: wechatpy   File: device.py    License: MIT License 6 votes vote down vote up
def get_qrcode_url(self, ticket, data=None):
        """
        通过 ticket 换取二维码地址
        详情请参考
        https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4

        :param ticket: 二维码 ticket
        :param data: 额外数据
        :return: 二维码地址
        """
        url = f"https://we.qq.com/d/{ticket}"
        if data:
            if isinstance(data, (dict, tuple, list)):
                data = urllib.urlencode(data)
            data = to_text(base64.b64encode(to_binary(data)))
            url = f"{url}#{data}"
        return url 
Example 2
Project: PiPark   Author: Humpheh   File: senddata.py    License: GNU General Public License v2.0 6 votes vote down vote up
def post_request(vals, url):
    """
    Build a post request.

    Args:
        vals: Dictionary of (field, values) for the POST
            request.
        url: URL to send the data to.

    Returns:
        Dictionary of JSON response or error info.
    """
    # Build the request and send to server
    data = urllib.urlencode(vals)
    
    try:
        request  = urllib2.Request(url, data)
        response = urllib2.urlopen(request)
    except urllib2.HTTPError, err:
        return {"error": err.reason, "error_code": err.code} 
Example 3
Project: google_streetview   Author: rrwen   File: api.py    License: MIT License 6 votes vote down vote up
def __init__(
    self,
    params,
    site_api='https://maps.googleapis.com/maps/api/streetview',
    site_metadata='https://maps.googleapis.com/maps/api/streetview/metadata'):
    
    # (params) Set default params
    defaults = {
      'size': '640x640'
    }
    for i in range(len(params)):
      for k in defaults:
        if k not in params[i]:
          params[i][k] = defaults[k]
    self.params = params
    
    # (image) Create image api links from parameters
    self.links = [site_api + '?' + urlencode(p) for p in params]
    
    # (metadata) Create metadata api links and data from parameters
    self.metadata_links = [site_metadata + '?' + urlencode(p) for p in params]
    self.metadata = [requests.get(url, stream=True).json() for url in self.metadata_links] 
Example 4
Project: sqliv   Author: the-robot   File: reverseip.py    License: GNU General Public License v3.0 6 votes vote down vote up
def reverseip(url):
    """return domains from given the same server"""

    # get only domain name
    url = urlparse(url).netloc if urlparse(url).netloc != '' else urlparse(url).path.split("/")[0]

    source = "http://domains.yougetsignal.com/domains.php"
    useragent = useragents.get()
    contenttype = "application/x-www-form-urlencoded; charset=UTF-8"

    # POST method
    opener = urllib2.build_opener(
        urllib2.HTTPHandler(), urllib2.HTTPSHandler())
    data = urllib.urlencode([('remoteAddress', url), ('key', '')])

    request = urllib2.Request(source, data)
    request.add_header("Content-type", contenttype)
    request.add_header("User-Agent", useragent)

    try:
        result = urllib2.urlopen(request).read()

    except urllib2.HTTPError, e:
        print >> sys.stderr, "[{}] HTTP error".format(e.code) 
Example 5
Project: sqliv   Author: the-robot   File: bing.py    License: GNU General Public License v3.0 6 votes vote down vote up
def search(self, query, stop=100):
        '''
        :type query : str
        :param query: Query for search
        
        :type stop  : int
        :param stop : Last result to retrieve.

        :rtype: list
        '''
 
        links = []
        start = 1

        for page in range(int(round(int(stop), -1)) / 10):
            URL = (self.bingsearch % (urllib.urlencode({'q': query}))) + '&first=' + str(start)

            html   = self.get_page(URL)
            result = self.parse_links(html)

            [links.append(_) for _ in result if _ not in links]

            start = start + 10

        return links 
Example 6
Project: Servo   Author: fpsw   File: note.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_sms_builtin(self, recipient, sender=None):
        """
        Sends SMS through built-in gateway
        """
        if not settings.SMS_HTTP_URL:
            raise ValueError(_('System is not configured for built-in SMS support.'))

        if sender is None:
            location = self.created_by.location
            sender = location.title

        data = urllib.urlencode({
            'username'  : settings.SMS_HTTP_USERNAME,
            'password'  : settings.SMS_HTTP_PASSWORD,
            'numberto'  : recipient.replace(' ', ''),
            'numberfrom': sender.encode(SMS_ENCODING),
            'message'   : self.body.encode(SMS_ENCODING),
        })

        from ssl import _create_unverified_context
        f = urllib.urlopen(settings.SMS_HTTP_URL, data, context=_create_unverified_context())
        return f.read() 
Example 7
Project: Servo   Author: fpsw   File: sms.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send(self):
        pwhash = md5(self.conf['sms_http_password']).hexdigest()

        params = {
            'username'  : self.conf['sms_http_user'],
            'password'  : pwhash,
            'message'   : self.body,
            'from'      : self.sender,
            'to'        : self.recipient,
        }

        if self.msg:
            dlruri = settings.SERVO_URL + '/api/messages/?id={0}'.format(self.msg.code)
            params['notify_url'] = dlruri

        params = urllib.urlencode(params)
        r = urllib.urlopen(self.URL, params, context=_create_unverified_context()).read()

        if 'ERROR:' in r:
            raise ValueError(self.ERRORS.get(r, _('Unknown error (%s)') % r)) 
Example 8
Project: Servo   Author: fpsw   File: sms.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send(self, note, number):
        conf = Configuration.conf()

        if not conf.get('sms_http_url'):
            raise ValueError(_("No SMS HTTP gateway defined"))

        params = urllib.urlencode({
            'username'  : conf['sms_http_user'],
            'password'  : conf['sms_http_password'],
            'text'      : note.body.encode('utf8'),
            'to'        : number
        })

        f = urllib.urlopen("%s?%s" % (conf['sms_http_url'], params),
                           context=_create_unverified_context())
        return f.read() 
Example 9
Project: Paradrop   Author: ParadropLabs   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def urlEncodeParams(data):
    """
    Return data URL-encoded.

    This function specifically handles None and boolean values
    to convert them to JSON-friendly strings (e.g. None -> 'null').
    """
    copy = dict()
    for key, value in six.iteritems(data):
        if value is None:
            copy[key] = 'null'
        elif isinstance(value, bool):
            copy[key] = json.dumps(value)
        else:
            copy[key] = value
    return urllib.urlencode(copy, doseq=True) 
Example 10
Project: httpninja   Author: irsdl   File: web_request_socket.py    License: Apache License 2.0 6 votes vote down vote up
def _setParams(self):
        parsedURL = urlparse.urlparse(self.url)
        # setting the path
        if self.useAbsolutePath == True:
            self._path = self.url
        else:
            self._path = parsedURL.path
            self.qs = parsedURL.query

        if self._path == '':
            self._path = '/'

        # fix the body if it is in dict format
        if isinstance(self.body,dict):
            self.body = urllib.urlencode(self.body)

        # set other necessary parameters
        self.targetName = parsedURL.netloc
        self.targetPort = parsedURL.port
        self.targetProtocol = (parsedURL.scheme).lower()
        if self.targetProtocol == 'https':
            self.isSSL = True
            if self.targetPort == None: self.targetPort = 443
        elif self.targetPort == None:
            self.targetPort = 80 
Example 11
Project: httpninja   Author: irsdl   File: web_request_socket.py    License: Apache License 2.0 6 votes vote down vote up
def _setParams(self):
        parsedURL = urlparse.urlparse(self.url)
        # setting the path
        if self.useAbsolutePath == True:
            self._path = self.url
        else:
            self._path = parsedURL.path
            self.qs = parsedURL.query

        if self._path == '':
            self._path = '/'

        # fix the body if it is in dict format
        if isinstance(self.body,dict):
            self.body = urllib.urlencode(self.body)

        # set other necessary parameters
        self.targetName = parsedURL.hostname
        self.targetPort = parsedURL.port
        self.targetProtocol = (parsedURL.scheme).lower()
        if self.targetProtocol == 'https':
            self.isSSL = True
            if self.targetPort == None: self.targetPort = 443
        elif self.targetPort == None:
            self.targetPort = 80 
Example 12
Project: tdw   Author: tdw1980   File: krasfs.py    License: GNU General Public License v3.0 6 votes vote down vote up
def upd(category, sort, str):
		post = urllib.urlencode({'checkbox_ftp':'on', 'checkbox_tor':'on','word':str}) 
		request = urllib2.Request('http://krasfs.ru/search.php?key=newkey')#url, post)

		request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)') 
		request.add_header('Host',    'www.krasfs.ru') 
		request.add_header('Accept', '*/*') 
		request.add_header('Accept-Language', 'ru-RU') 
		request.add_header('Referer',    'http://www.krasfs.ru') 

		try: 
			f = urllib2.urlopen(request) 
			html = f.read()
			html = html.replace(chr(10),"")
			n=html.find("<newkey>")
			k=html.find("</newkey>")
			key = html[n+8:k]
		except IOError, e: 
			if hasattr(e, 'reason'): 
				print 'We failed to reach a server. Reason: '+ e.reason
			elif hasattr(e, 'code'): 
				print 'The server couldn\'t fulfill the request. Error code: '+ e.code
			key = "59165b78-bf91-11e1-86bf-c6ab051766ba" 
Example 13
Project: jawfish   Author: war-and-code   File: jf-web.py    License: MIT License 6 votes vote down vote up
def run_simulation(self):
        global TARGET, ADDR, VULN_VAR, TIMEOUT, REQ_TOTAL,\
            METHOD, OTHER_VARIABLES
        tmp = OTHER_VARIABLES
        tmp[VULN_VAR] = self.genome
        try:
            if METHOD == 0:
                prep = urllib.urlencode(tmp)
                r = urllib.urlopen('http://%s/%s' % (TARGET, ADDR), data=prep, timeout=TIMEOUT)
            else:
                prep = urllib.urlencode(tmp)
                req = urllib.Request('http://%s/%s' % (TARGET, ADDR), data=prep)
                r = urllib.urlopen(req)
            REQ_TOTAL += 1
            self.m_text['text'] = r.get_data()
            self.m_text['url'] = r.get_full_url()
            self.m_text['status_code'] = r.getcode()
        except:
            pass
        return self.m_text 
Example 14
Project: hackernewsbot   Author: phil-r   File: bitly.py    License: MIT License 6 votes vote down vote up
def call_method(method, data):
  data.update({'access_token': TOKEN})
  data = urllib.urlencode(data)
  try:
    result = urlfetch.fetch(
        BASE_URL.format(method=method, qs=data),
        method=urlfetch.GET,
        deadline=10)
  except DeadlineExceededError as e:
    logging.exception(e)
    return None
  if result.status_code == 200:
    return json.loads(result.content).get('data')
  else:
    logging.error(result.content)
    return None 
Example 15
Project: plugin.video.kmediatorrent   Author: jmarth   File: magnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def from_torrent_url(url):
    import base64
    import bencode
    import hashlib
    import urllib
    from kmediatorrent.utils import url_get
    torrent_data = url_get(url)
    metadata = bencode.bdecode(torrent_data)
    hashcontents = bencode.bencode(metadata['info'])
    digest = hashlib.sha1(hashcontents).digest()
    b32hash = base64.b32encode(digest)
    params = {
        'dn': metadata['info']['name'],
        'tr': metadata['announce'],
    }
    plugin.log.info(params)
    paramstr = urllib.urlencode(params)
    return 'magnet:?%s&%s' % ('xt=urn:btih:%s' % b32hash, paramstr) 
Example 16
Project: polar-flow-export   Author: gabrielreid   File: polarflowexport.py    License: Apache License 2.0 6 votes vote down vote up
def _execute_request(self, path, post_params=None):

        url = "https://flow.polar.com%s" % path

        self._logger.debug("Requesting '%s'" % url)

        if post_params != None:
            postData = urllib.urlencode(post_params)
        else:
            postData = None

        try:
            response = self._url_opener.open(url, postData)
            data = response.read()
        except Exception, e:
            self._logger.error("Error fetching %s: %s" % (url, e))
            raise Exception(e) 
Example 17
Project: plugin.video.emby   Author: MediaBrowser   File: request.py    License: GNU General Public License v3.0 6 votes vote down vote up
def request_encode_url(self, method, url, fields=None, headers=None,
                           **urlopen_kw):
        """
        Make a request using :meth:`urlopen` with the ``fields`` encoded in
        the url. This is useful for request methods like GET, HEAD, DELETE, etc.
        """
        if headers is None:
            headers = self.headers

        extra_kw = {'headers': headers}
        extra_kw.update(urlopen_kw)

        if fields:
            url += '?' + urlencode(fields)

        return self.urlopen(method, url, **extra_kw) 
Example 18
Project: plugin.video.emby   Author: MediaBrowser   File: api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_backdrops(self, item_id, tags, query=None):

        ''' Get backdrops based of "BackdropImageTags" in the emby object.
        '''
        query = list(query) if query else []
        backdrops = []

        if item_id is None:
            return backdrops

        for index, tag in enumerate(tags):

            query.append(('Tag', tag))
            artwork = "%s/emby/Items/%s/Images/Backdrop/%s?%s" % (self.server, item_id, index, urllib.urlencode(query))

            if not self.verify_ssl:
                artwork += "|verifypeer=false"

            backdrops.append(artwork)

        return backdrops 
Example 19
Project: plugin.video.emby   Author: MediaBrowser   File: api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_artwork(self, item_id, image, tag=None, query=None):

        ''' Get any type of artwork: Primary, Art, Banner, Logo, Thumb, Disc
        '''
        query = list(query) if query else []

        if item_id is None:
            return ""

        if tag is not None:
            query.append(('Tag', tag))

        artwork = "%s/emby/Items/%s/Images/%s/0?%s" % (self.server, item_id, image, urllib.urlencode(query))

        if not self.verify_ssl:
            artwork += "|verifypeer=false"

        return artwork 
Example 20
Project: plugin.video.emby   Author: MediaBrowser   File: default.py    License: GNU General Public License v3.0 6 votes vote down vote up
def browse_subfolders(media, view_id, server_id=None):

    ''' Display submenus for emby views.
    '''
    from views import DYNNODES

    get_server(server_id)
    view = EMBY['api'].get_item(view_id)
    xbmcplugin.setPluginCategory(int(sys.argv[1]), view['Name'])
    nodes = DYNNODES[media]

    for node in nodes:

        params = {
            'id': view_id,
            'mode': "browse",
            'type': media,
            'folder': view_id if node[0] == 'all' else node[0],
            'server': server_id
        }
        path = "%s?%s" % ("plugin://plugin.video.emby/",  urllib.urlencode(params))
        directory(node[1] or view['Name'], path)

    xbmcplugin.setContent(int(sys.argv[1]), 'files')
    xbmcplugin.endOfDirectory(int(sys.argv[1])) 
Example 21
Project: plugin.video.emby   Author: MediaBrowser   File: default.py    License: GNU General Public License v3.0 6 votes vote down vote up
def browse_letters(media, view_id, server_id=None):

    ''' Display letters as options.
    '''
    letters = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    get_server(server_id)
    view = EMBY['api'].get_item(view_id)
    xbmcplugin.setPluginCategory(int(sys.argv[1]), view['Name'])

    for node in letters:

        params = {
            'id': view_id,
            'mode': "browse",
            'type': media,
            'folder': 'firstletter-%s' % node,
            'server': server_id
        }
        path = "%s?%s" % ("plugin://plugin.video.emby/",  urllib.urlencode(params))
        directory(node, path)

    xbmcplugin.setContent(int(sys.argv[1]), 'files')
    xbmcplugin.endOfDirectory(int(sys.argv[1])) 
Example 22
Project: baidufm-py   Author: tdoly   File: fm_api.py    License: MIT License 6 votes vote down vote up
def _request(self, url, method=None, extra_params=None):
        params = dict()
        if extra_params:
            params.update(extra_params)

        headers = consts.HEADERS
        if 'fm.baidu.com' in url:
            headers['Host'] = "fm.baidu.com"
        elif 'passport.baidu.com' in url:
            headers['Host'] = "passport.baidu.com"
        else:
            headers['Host'] = ".baidu.com"

        self._params_utf8(params)
        if method and method.lower() == 'post':
            response = self.session.post(url, data=params, verify=True, headers=headers)
        else:
            if '?' in url:
                url = url + urlencode(params)
            else:
                url = url + '?' + urlencode(params)
            response = self.session.get(url, verify=False, headers=headers)
        return response 
Example 23
Project: terraform-templates   Author: PaloAltoNetworks   File: wfapi.py    License: Apache License 2.0 6 votes vote down vote up
def report(self,
               hash=None,
               format=None):
        self.__clear_response()

        request_uri = '/publicapi/get/report'

        query = {}
        query['apikey'] = self.api_key
        if hash is not None:
            query['hash'] = hash
        if format is not None:
            query['format'] = format

        response = self.__api_request(request_uri=request_uri,
                                      body=urlencode(query))
        if not response:
            raise PanWFapiError(self._msg)

        if not self.__set_response(response):
            raise PanWFapiError(self._msg) 
Example 24
Project: terraform-templates   Author: PaloAltoNetworks   File: wfapi.py    License: Apache License 2.0 6 votes vote down vote up
def verdict(self,
                hash=None):
        self.__clear_response()

        request_uri = '/publicapi/get/verdict'

        query = {}
        query['apikey'] = self.api_key
        if hash is not None:
            query['hash'] = hash

        response = self.__api_request(request_uri=request_uri,
                                      body=urlencode(query))
        if not response:
            raise PanWFapiError(self._msg)

        if not self.__set_response(response):
            raise PanWFapiError(self._msg) 
Example 25
Project: terraform-templates   Author: PaloAltoNetworks   File: wfapi.py    License: Apache License 2.0 6 votes vote down vote up
def verdicts_changed(self,
                         date=None):
        self.__clear_response()

        request_uri = '/publicapi/get/verdicts/changed'

        query = {}
        query['apikey'] = self.api_key
        if date is not None:
            query['date'] = date

        response = self.__api_request(request_uri=request_uri,
                                      body=urlencode(query))
        if not response:
            raise PanWFapiError(self._msg)

        if not self.__set_response(response):
            raise PanWFapiError(self._msg) 
Example 26
Project: terraform-templates   Author: PaloAltoNetworks   File: wfapi.py    License: Apache License 2.0 6 votes vote down vote up
def sample(self,
               hash=None):
        self.__clear_response()

        request_uri = '/publicapi/get/sample'

        query = {}
        query['apikey'] = self.api_key
        if hash is not None:
            query['hash'] = hash

        response = self.__api_request(request_uri=request_uri,
                                      body=urlencode(query))
        if not response:
            raise PanWFapiError(self._msg)

        if not self.__set_response(response):
            raise PanWFapiError(self._msg) 
Example 27
Project: terraform-templates   Author: PaloAltoNetworks   File: wfapi.py    License: Apache License 2.0 6 votes vote down vote up
def pcap(self,
             hash=None,
             platform=None):
        self.__clear_response()

        request_uri = '/publicapi/get/pcap'

        query = {}
        query['apikey'] = self.api_key
        if hash is not None:
            query['hash'] = hash
        if platform is not None:
            query['platform'] = platform

        response = self.__api_request(request_uri=request_uri,
                                      body=urlencode(query))
        if not response:
            raise PanWFapiError(self._msg)

        if not self.__set_response(response):
            raise PanWFapiError(self._msg) 
Example 28
Project: qgis-cartodb   Author: gkudos   File: cartodbapi.py    License: GNU General Public License v2.0 6 votes vote down vote up
def getUserTables(self, page=1, per_page=20, shared='yes', returnDict=True):
        self.returnDict = returnDict
        payload = {
            'tag_name': '',
            'q': '',
            'page': page,
            'type': '',
            'exclude_shared': 'false',
            'per_page': per_page,
            'tags': '',
            'shared': shared,
            'locked': 'false',
            'only_liked': 'false',
            'order': 'name',
            'types': 'table'
        }
        url = QUrl(self.apiUrl + "viz?api_key={}&{}".format(self.apiKey, urllib.urlencode(payload)))
        request = self._getRequest(url)

        reply = self.manager.get(request)
        loop = QEventLoop()
        reply.downloadProgress.connect(self.progressCB)
        reply.error.connect(self._error)
        reply.finished.connect(loop.exit)
        loop.exec_() 
Example 29
Project: qgis-cartodb   Author: gkudos   File: cartodb.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, key, secret, email, password, cartodb_domain, host='carto.com', protocol='https', proxy_info=None, *args, **kwargs):
        super(CartoDBOAuth, self).__init__(cartodb_domain, host, protocol, *args, **kwargs)

        self.consumer_key = key
        self.consumer_secret = secret
        consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)

        client = oauth.Client(consumer, proxy_info=proxy_info)
        client.set_signature_method = oauth.SignatureMethod_HMAC_SHA1()

        params = {}
        params["x_auth_username"] = email
        params["x_auth_password"] = password
        params["x_auth_mode"] = 'client_auth'

        # Get Access Token
        access_token_url = ACCESS_TOKEN_URL % {'user': cartodb_domain, 'domain': host, 'protocol': protocol}
        resp, token = client.request(access_token_url, method="POST", body=urllib.urlencode(params))
        access_token = dict(urlparse.parse_qsl(token))
        token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret'])

        # prepare client
        self.client = oauth.Client(consumer, token) 
Example 30
Project: recruit   Author: Frank-qlu   File: request.py    License: Apache License 2.0 6 votes vote down vote up
def request_encode_url(self, method, url, fields=None, headers=None,
                           **urlopen_kw):
        """
        Make a request using :meth:`urlopen` with the ``fields`` encoded in
        the url. This is useful for request methods like GET, HEAD, DELETE, etc.
        """
        if headers is None:
            headers = self.headers

        extra_kw = {'headers': headers}
        extra_kw.update(urlopen_kw)

        if fields:
            url += '?' + urlencode(fields)

        return self.urlopen(method, url, **extra_kw) 
Example 31
Project: plugin.video.sosac.ph   Author: kodi-czsk   File: sutils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def getTVDB(self, name, id):
        if id:
            data = util.request('http://thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=tt' +
                                id + '&language=all')
            tvid = re.search('<id>(\d+)</id>', data)
            if tvid:
                return tvid.group(1)
        shortname = re.search('(.+) (\(\d{4}\))', name).group(1)
        urllang = [urllib.urlencode({'seriesname': shortname, 'language': 'cs'}),
                   urllib.urlencode({'seriesname': shortname, 'language': 'all'}),
                   urllib.urlencode({'seriesname': name, 'language': 'cs'}),
                   urllib.urlencode({'seriesname': name, 'language': 'all'})]
        for iter in urllang:
            data = util.request('http://thetvdb.com/api/GetSeries.php?' + iter)
            tvid = re.search('<id>(\d+)</id>', data)
            if tvid:
                return tvid.group(1)
        return None 
Example 32
Project: codepost-python   Author: codepost-io   File: assignments.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def list_submissions(self, id=None, student=None, grader=None):
        """
        Returns the list of submissions associated with an assignment, which
        optionally can be filtered according to a specific submitting `student`
        or a `grader`.
        """
        _class_type = type(self)

        id = self._get_id(id=id)

        endpoint = "{}/submissions".format(self.instance_endpoint_by_id(id=id))
        endpoint_params = {}

        if student != None:
            # Filter according to a specific student (will be URL-quoted later)
            endpoint_params["student"] = student

        if grader != None:
            # Filter according to a specific grader (will be URL-quoted later)
            endpoint_params["grader"] = grader

        if len(endpoint_params) > 0:
            endpoint += "?{}".format(_urlencode(endpoint_params))

        ret = self._requestor._request(
            endpoint=endpoint,
            method="GET",
        )
        if ret.status_code == 200:
            # Returns a list of all submissions
            return list(map(
                lambda kwargs: _submissions.Submissions(**kwargs),
                ret.json))

# ============================================================================= 
Example 33
Project: python-rest-api   Author: messagebird   File: signed_request.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _build_payload(self):
        checksum_body = hashlib.sha256(self._requestBody.encode('latin-1')).digest()
        str_checksum_body = checksum_body.decode('latin-1')
        parts = [self._requestTimestamp, urlencode(self._sort_dict(self._requestParameters), True), str_checksum_body]
        return "\n".join(parts) 
Example 34
Project: Servo   Author: fpsw   File: sms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send(self):
        """
        Sends SMS through SMS Jazz Gateway
        """
        conf = Configuration.conf()

        if not conf.get('sms_http_sender'):
            raise ValueError(_("SMS sender name not configured"))

        body = self.note.body.encode('utf-8')
        sender = conf.get('sms_http_sender')
        pwhash = md5(conf['sms_http_password']).hexdigest()
        checksum = md5(body + self.recipient.encode('ascii') + pwhash).hexdigest()

        params = {
            'username'  : conf['sms_http_user'],
            'password'  : pwhash,
            'message'   : body,
            'sender'    : sender.encode('ascii', 'replace'),
            'receiver'  : self.recipient,
            'charset'   : 'UTF8',
            'checksum'  : checksum,
        }

        if self.msg:
            dlruri = '/api/messages/?id={0}&status=%status%'.format(self.msg.code)
            dlruri = settings.SERVO_URL + dlruri
            params['dlruri'] = dlruri

        params = urllib.urlencode(params)
        r = urllib.urlopen(self.URL, params, context=_create_unverified_context()).read()

        if not '1:OK' in r:
            raise ValueError(_('Failed to send message to %s') % self.recipient) 
Example 35
Project: jawfish   Author: war-and-code   File: request.py    License: MIT License 5 votes vote down vote up
def request_encode_url(self, method, url, fields=None, **urlopen_kw):
        """
        Make a request using :meth:`urlopen` with the ``fields`` encoded in
        the url. This is useful for request methods like GET, HEAD, DELETE, etc.
        """
        if fields:
            url += '?' + urlencode(fields)
        return self.urlopen(method, url, **urlopen_kw) 
Example 36
Project: youku   Author: hanguokai   File: youku_oauth.py    License: Apache License 2.0 5 votes vote down vote up
def authorize_url(self, state=''):
        """ return user authorize url
        """
        url = 'https://openapi.youku.com/v2/oauth2/authorize?'
        params = {
            'client_id': self.client_id,
            'response_type': 'code',
            'state': state,
            'redirect_uri': self.redirect_uri
        }
        return url + urlencode(params) 
Example 37
Project: Alfred_ShadowsocksController   Author: yourtion   File: SSR.py    License: MIT License 5 votes vote down vote up
def _post(self, url, parma):
    try:
      params = urllib.urlencode(parma)
      headers = {'Content-type': 'application/x-www-form-urlencoded'
                     , 'Accept': 'text/plain'}
      self.httpClient.request('POST', url, params, headers)
      res = self.httpClient.getresponse()
      return res if res.status == 200 and res.reason == 'OK' else False
    except Exception, e:
      return False 
Example 38
Project: endpoints-tools   Author: cloudendpoints   File: generate-google-id-jwt.py    License: Apache License 2.0 5 votes vote down vote up
def main(args):
    """Request a Google ID token using a JWT."""
    params = urllib.urlencode({
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion': generate_jwt(args)})
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    conn = httplib.HTTPSConnection("www.googleapis.com")
    conn.request("POST", "/oauth2/v4/token", params, headers)
    res = json.loads(conn.getresponse().read())
    conn.close()
    return res['id_token'] 
Example 39
Project: sfdclib   Author: rbauction   File: rest.py    License: MIT License 5 votes vote down vote up
def soql_query(self, query):
        """ SOQL query """
        res = self.get(self._SOQL_QUERY_URI.format(**{'query': urlencode({'q': query})}))
        if not isinstance(res, dict):
            raise Exception("Request failed. Response: %s" % res)
        return res 
Example 40
Project: sfdclib   Author: rbauction   File: tooling.py    License: MIT License 5 votes vote down vote up
def anon_query(self, query):
        ''' Anonymous query '''
        res = self.get(self._ANON_QUERY_URI.format(**{'query': urlencode({'q': query})}))
        if not isinstance(res, dict):
            raise Exception("Request failed. Response: %s" % res)
        return res