def token(self): """ GET: /arc2box/token Checks to see if access token for Box API is up to date and usable. Returns JSON: {"valid": true} or {"valid": false, "url": <box_login_url>} """ box = find_box(self.context) client = BoxClient(box, self.request.registry.settings) if client.check_token(): return {'valid': True} if not box.state: box.state = str(uuid.uuid4()) query = { 'response_type': 'code', 'client_id': client.client_id, 'state': box.state, 'redirect_uri': self.request.resource_url(box, '@@box_auth'), } url = client.authorize_url + '?' + urlencode(query) logger.info('arc2box: Got token') return {'valid': False, 'url': url}
def url_for(request, name, **kwargs): if name in paths: if kwargs: params = dict((k, v) for k, v in kwargs.iteritems() if v != None) return '%s?%s' % (name, urlencode(params)) return name else: raise UnresolvedRoute('Can\'t resolved %s route' % name)
def render_image(self, extent, size): query = dict( service="WMS", request="GetMap", version=self.connection.version, layers=self.wmslayers, styles="", format=self.imgformat, bbox=",".join(map(str, extent)), width=size[0], height=size[1], transparent="true", ) # Vendor-specific parameters for p in self.vendor_params: query[p.key] = p.value # In the GetMap operation the srs parameter is called crs in 1.3.0. srs = 'crs' if self.connection.version == '1.3.0' else 'srs' query[srs] = "EPSG:%d" % self.srs.id auth = None username = self.connection.username password = self.connection.password if username and password: auth = (username, password) sep = "&" if "?" in self.connection.url else "?" # ArcGIS server requires that space is url-encoded as "%20" # but it does not accept space encoded as "+". # It is always safe to replace spaces with "%20". url = (self.connection.url + sep + urlencode(query).replace("+", "%20")) try: response = requests.get( url, auth=auth, headers=env.wmsclient.headers, timeout=env.wmsclient.options['timeout'].total_seconds()) except RequestException: raise ExternalServiceError() if response.status_code == 200: data = BytesIO(response.content) try: return PIL.Image.open(data) except IOError: raise ExternalServiceError("Image processing error.") elif response.status_code in (204, 404): return None else: raise ExternalServiceError()
def sign_request(path, params, client_id, private_key_str): '''Returns signature field as a hex string''' if isinstance(params, dict): params = params.items() params.append( ('client_id', client_id) ) params.sort() to_sign = path + '?' + urlencode(params) print 'Signing', to_sign hash = SHA256.new(to_sign) key = RSA.importKey(private_key_str) signer = PKCS1_PSS.new(key) signature = signer.sign(hash).encode('base64').strip() return params + [ ('signature', signature) ]
def _send_mail_sendgrid(sender, to, subject, body, replyto=None, cc=None, bcc=None, html=None): from worker.tasks import requests_post registry = get_current_registry() settings = registry.settings or {} base_url = 'https://sendgrid.com/api/mail.send.json' params = { 'api_user': settings.get('giza.sendgrid_user', ''), 'api_key': settings.get('giza.sendgrid_key', ''), 'subject': subject, 'text': body, 'fromname': sender[0], 'from': sender[1] } if html: params['html'] = html # Encode the simple stuff encoded_params = urlencode(params) # List of 'to' addresses encoded_params += '&' + urlencode([('toname[]', toname) for toname,_ in to]) encoded_params += '&' + urlencode([('to[]', toaddr) for _,toaddr in to]) if replyto: encoded_params += '&' + urlencode([('replyto', replyto[0][1])]) if cc: encoded_params += '&' + urlencode([('ccname[]', ccname) for ccname,_ in cc]) encoded_params += '&' + urlencode([('cc[]', ccaddr) for _,ccaddr in cc]) if bcc: encoded_params += '&' + urlencode([('bccname[]', bccname) for bccname,_ in bcc]) encoded_params += '&' + urlencode([('bcc[]', bccaddr) for _,bccaddr in bcc]) headers = {'Content-Type': 'application/x-www-form-urlencoded'} requests_post(base_url, data=encoded_params, headers=headers, verify=False, timeout=10) """
def render_image(self, extent, size): query = dict( service="WMS", request="GetMap", version=self.connection.version, layers=self.wmslayers, styles="", format=self.imgformat, bbox=",".join(map(str, extent)), width=size[0], height=size[1], transparent="true", ) # Vendor-specific parameters for p in self.vendor_params: query[p.key] = p.value # In the GetMap operation the srs parameter is called crs in 1.3.0. srs = 'crs' if self.connection.version == '1.3.0' else 'srs' query[srs] = "EPSG:%d" % self.srs.id auth = None username = self.connection.username password = self.connection.password if username and password: auth = (username, password) sep = "&" if "?" in self.connection.url else "?" # ArcGIS server requires that space is url-encoded as "%20" # but it does not accept space encoded as "+". # It is always safe to replace spaces with "%20". url = ( self.connection.url + sep + urlencode(query).replace("+", "%20") ) return PIL.Image.open(BytesIO(requests.get( url, auth=auth, headers=env.wmsclient.headers).content))
def validate_request(request): '''Either returns (client, params) or raises a 403''' from . import model as M params = dict(request.params) try: signature_str = params.pop('signature') client_id = params['client_id'] client = M.client.m.get(_id=client_id) if not client: raise exc.HTTPNotFound() to_sign = request.path + '?' + urlencode(sorted(params.items())) print 'Validate', to_sign if not signature_is_valid(to_sign, signature_str, client.public_key): raise exc.HTTPForbidden() if client.ip_addrs and request.remote_addr not in client.ip_addrs: raise exc.HTTPForbidden() return client except exc.HTTPError: raise except KeyError, ke: raise exc.HTTPBadRequest, repr(ke)
def pagemaker(page): batch_start = str((page - 1) * batch['batch_size']) url = '?%s' % urlencode([('batch_start', batch_start)] + query_terms) return dict(page=page, url=url)
def model_url(model, query=None): for urlkey, cfg in AutoHQResource.children.iteritems(): if cfg['model'] is model: queries = ('?' + urlencode(query)) if query else '' return ROOT_URL + urlkey + '/' + queries raise KeyError('Model %s has not been registered in AutoHQ' % model)