def _proxy( self, allow, data=None ): api = self._getApiFromUrl() test = api.startswith( 'test/' ) if test: api = api.replace( 'test/', '', 1 ) debug = api.startswith( 'debug/' ) if debug: api = api.replace( 'debug/', '', 1 ) if not re.match( allow, api ): self.abort( 403 ) if test: response = Response( api ) response.headers['Content-Type'] = 'text/plain' return response result = EarthEngine( self ).post( api, data ) if debug: json = json_encode( result, indent=4 ) else: json = json_encode( result ) response = Response( json ) if debug: response.headers['Content-Type'] = 'text/plain' else: response.headers['Content-Type'] = 'application/json' return response
def _proxy(self, allow, data=None): api = self._getApiFromUrl() test = api.startswith('test/') if test: api = api.replace('test/', '', 1) debug = api.startswith('debug/') if debug: api = api.replace('debug/', '', 1) if not re.match(allow, api): self.abort(403) if test: response = Response(api) response.headers['Content-Type'] = 'text/plain' return response result = EarthEngine(self).post(api, data) if debug: json = json_encode(result, indent=4) else: json = json_encode(result) response = Response(json) if debug: response.headers['Content-Type'] = 'text/plain' else: response.headers['Content-Type'] = 'application/json' return response
def test_json(self): class JsonHandler(RequestHandler): def get(self, **kwargs): return Response(self.request.json['foo']) app = Tipfy(rules=[ Rule('/', name='home', handler=JsonHandler), ], debug=True) data = json_encode({'foo': 'bar'}) client = app.get_test_client() response = client.get('/', content_type='application/json', data=data) self.assertEqual(response.data, 'bar')
def render_response(self, filename, **kwargs): auth_session = None if self.auth.session: auth_session = self.auth.session kwargs.update({ 'auth_session': auth_session, 'current_user': self.auth.user, 'login_url': self.auth.login_url(), 'logout_url': self.auth.logout_url(), 'current_url': self.request.url, }) if self.messages: kwargs['messages'] = json_encode([dict(body=body, level=level) for body, level in self.messages]) return super(BaseHandler, self).render_response(filename, **kwargs)
def render_response(self, filename, **kwargs): auth_session = None if self.auth.session: auth_session = self.auth.session kwargs.update({ 'auth_session': auth_session, 'current_user': self.auth.user, 'login_url': self.auth.login_url(), 'logout_url': self.auth.logout_url(), 'current_url': self.request.url, }) if self.messages: kwargs['messages'] = json_encode([ dict(body=body, level=level) for body, level in self.messages ]) return super(BaseHandler, self).render_response(filename, **kwargs)
def post(self): ''' Upload shape/kml file ''' file = self.request.files['shape_file'] if not file: return self.render_json({'error': 'No file uploaded'}) name = file.filename base, ext = os.path.splitext(name) if ext.lower() != '.kml': return self.render_json({'error': 'Not a KML file'}) g = geo.Kml(file).toGeo() #return self.render_json( g ) name = g['features'][0]['properties']['name'] geojson = json_encode(g) key = result = self.save_place(name, geojson)['key'] return self.render_json({ 'name': name, 'key': key, 'geo': g, })
def __call__(self, field, error=None, **kwargs): """Returns the recaptcha input HTML.""" config = current_handler.get_config('tipfyext.wtforms') if config.get('recaptcha_use_ssl'): server = RECAPTCHA_SSL_API_SERVER else: server = RECAPTCHA_API_SERVER query_options = dict(k=config.get('recaptcha_public_key')) if field.recaptcha_error is not None: query_options['error'] = unicode(field.recaptcha_error) query = url_encode(query_options) # Widget default options. options = { 'theme': 'clean', 'custom_translations': { 'visual_challenge': _('Get a visual challenge'), 'audio_challenge': _('Get an audio challenge'), 'refresh_btn': _('Get a new challenge'), 'instructions_visual': _('Type the two words:'), 'instructions_audio': _('Type what you hear:'), 'help_btn': _('Help'), 'play_again': _('Play sound again'), 'cant_hear_this': _('Download sound as MP3'), 'incorrect_try_again': _('Incorrect. Try again.'), } } custom_options = config.get('recaptcha_options') if custom_options: options.update(custom_options) return RECAPTCHA_HTML % dict(script_url='%schallenge?%s' % (server, query), frame_url='%snoscript?%s' % (server, query), options=json_encode(options))
def __call__(self, field, error=None, **kwargs): """Returns the recaptcha input HTML.""" config = current_handler.app.config['tipfyext.wtforms'] if config.get('recaptcha_use_ssl'): server = RECAPTCHA_SSL_API_SERVER else: server = RECAPTCHA_API_SERVER query_options = dict(k=config.get('recaptcha_public_key')) if field.recaptcha_error is not None: query_options['error'] = unicode(field.recaptcha_error) query = url_encode(query_options) # Widget default options. options = { 'theme': 'clean', 'custom_translations': { 'visual_challenge': _('Get a visual challenge'), 'audio_challenge': _('Get an audio challenge'), 'refresh_btn': _('Get a new challenge'), 'instructions_visual': _('Type the two words:'), 'instructions_audio': _('Type what you hear:'), 'help_btn': _('Help'), 'play_again': _('Play sound again'), 'cant_hear_this': _('Download sound as MP3'), 'incorrect_try_again': _('Incorrect. Try again.'), } } custom_options = config.get('recaptcha_options') if custom_options: options.update(custom_options) return RECAPTCHA_HTML % dict( script_url='%schallenge?%s' % (server, query), frame_url='%snoscript?%s' % (server, query), options=json_encode(options) )
def post( self ): ''' Upload shape/kml file ''' file = self.request.files['shape_file'] if not file: return self.render_json({ 'error': 'No file uploaded' }) name = file.filename base, ext = os.path.splitext( name ) if ext.lower() != '.kml': return self.render_json({ 'error': 'Not a KML file' }) g = geo.Kml( file ).toGeo() #return self.render_json( g ) name = g['features'][0]['properties']['name'] geojson = json_encode( g ) key = result = self.save_place( name, geojson )['key'] return self.render_json({ 'name': name, 'key': key, 'geo': g, })
def get_value_for_datastore(self, model_instance): """Encodes the value to JSON.""" value = super(JsonProperty, self).get_value_for_datastore(model_instance) if value is not None: return db.Text(json_encode(value, separators=(',', ':')))
def old_earthengine_map( self, action, opt ): ''' Create an Earth Engine map as tiles or as a download image, or requests statistics. action = 'click', 'download', 'stats', or 'tiles' opt = { 'sat': [ satname, sensor ], 'mode': 'fractcover' or 'forestcover' or 'forestchange', 'times': [ { 'starttime': n, 'endtime': n }, /* ... */ ], # for tiles or download: 'bbox': [ west, south, east, north ], 'crs': 'EPSG:nnnn', # for click: 'points': [ lng, lat ], # for fractcover: 'bias': n, 'gain': n, 'gamma': n, # for forestcover: # (nothing extra) # for forestchange: 'type': 'deforestation' or 'disturbance', # for forestcover or forestchange: 'palette': [ rrggbb, ..., rrggbb ], } ''' polygon = [ polyBbox( opt['bbox'] ) ] palette = opt.get('palette') mode = opt['mode'] final = None bandsDown = None if mode == 'fractcover': bands = 'sub,pv,npv' bandsDown = 'sub,pv,npv,sdev_sub,sdev_pv,sdev_npv,rms' visual = 'bias=%f&gain=%f&gamma=%f' %( float(opt['bias']), float(opt['gain']), float(opt['gamma']) ) elif mode == 'forestcover': final = 'ForestCoverMap' bands = 'Forest_NonForest' visual = 'min=0&max=2&palette=%s' %( str( ','.join(palette) ) ) statFields = 'count' elif mode == 'forestchange': final = 'ForestCoverChange' bands = ( 'disturb', 'deforest' )[ opt['type'] == 'deforestation' ] visual = 'min=1&max=%d&palette=%s' %( len(palette), str( ','.join(palette) ) ) statFields = 'DEFORESTATION_PIX_CNT,DISTURBANCE_PIX_CNT,TOTAL_PIX_CNT' if action == 'download': ( w, s, e, n ) = opt['bbox'] coords = [ [ w, s ], [ w, n ], [ e, n ], [ e, s ], ] region = json_encode({ "type": "LinearRing", "coordinates": coords, }) bands = map( lambda band: { 'id': band, 'scale': 30 }, ( bandsDown or bands ).split(',') ) bands = '%s&crs=%s®ion=%s' %( json_encode(bands), opt['crs'], region ) ee = EarthEngine( current_handler ) ei = EarthImage() modImage = ei.obj( 'Image', 'MOD44B_C4_TREE_2000' ) tempImage = ei.obj( 'Image', 'LANDSAT/L7_L1T/LE72290682008245EDC00' ) collection = ei.obj( 'ImageCollection', opt['sat'][1] ) sensor = opt['sat'][0] image = [] for time in opt['times']: image.append( ei.step( CLASLITE+'MosaicScene', collection, modImage, sensor, time['starttime'], time['endtime'], [ polygon ] ) ) if len(image) == 1: image = image[0] if final: image = ei.step( CLASLITE+final, image ) #image = ei.clip( image ) if action == 'stats': image = ei.step( CLASLITE+final+'Stat', image, { "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": polygon } } ] }) params = 'image=%s' % json_encode(image) if action == 'click': params += '&points=[[%s,%s]]' %( opt['lng'], opt['lat'] ) elif action == 'stats': params += '&fields=%s' % statFields else: params += '&bands=%s' %( bands ) def vp( p ): return visual + '&' + p if action == 'click': value = ee.get( 'value', params ) return value elif action == 'download': download = ee.post( 'download', vp(params) ) return download elif action == 'tiles': tiles = ee.post( 'mapid', vp(params) ) if 'error' in tiles: return tiles else: return { 'tiles': tiles['data'] } elif action == 'stats': stats = ee.post( 'value', params ) if 'error' in stats: return stats else: return { 'stats': stats['data']['properties'] }
def render_json(self, dict): ''' Using this code instead of tipfy.utils.render_json_response because the mimetype='application/json' triggers a file download in Firefox. ''' return self.app.response_class(json_encode(dict))
def render_json( self, dict ): ''' Using this code instead of tipfy.utils.render_json_response because the mimetype='application/json' triggers a file download in Firefox. ''' return self.app.response_class( json_encode(dict) )
def get_value_for_datastore(self, model_instance): """Encodes the value to JSON.""" value = super(JsonProperty, self).get_value_for_datastore( model_instance) if value is not None: return db.Text(json_encode(value, separators=(',', ':')))
def test_json_encode(self): self.assertEqual(json_encode('<script>alert("hello")</script>'), '"<script>alert(\\"hello\\")<\\/script>"')