def websocket_receive(self, message): request = json.loads(message['text']) id = request.get('id') if request['type'] == 'connection_init': return elif request['type'] == 'start': payload = request['payload'] context = AttrDict(self.scope) context.subscribe = functools.partial(self._subscribe, id) stream = StreamObservable() result = schema.execute( payload['query'], operation_name=payload['operationName'], variable_values=payload['variables'], context_value=context, root_value=Observable.create(stream).share(), allow_subscriptions=True, ) if hasattr(result, 'subscribe'): result.subscribe(functools.partial(self._send_result, id)) self.subscriptions[id] = stream else: self._send_result(id, result) elif request['type'] == 'stop': self._unsubscribe(id) if id in self.subscriptions: del self.subscriptions[id]
def query(): payload = request.get_json(silent=True) if payload.get('query') is None: return 'Not good' query = payload['query'] data = schema.execute(query) return json.dumps({'data': data.data, 'error': data.errors})
def _process(self, query): result = schema.execute(query) if len(result.errors) > 0: self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps([error.message for error in result.errors])) else: self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(result.data))
def graphql(): query = request.json.get('query') return jsonify({ 'data': schema.execute(query, context_value={ 'user': g.user, 'session': db }).data })
def race(): query = ''' query getRace{ race { traits } } ''' result = schema.execute(query) return json.dumps(result.data, indent=4)
def bagofwords(text): schema = graphene.Schema(BagOfWords) result = schema.execute('{ txt }', context={'txt': text}) data = result.data['txt'].replace("\'", "\"") res = json.dumps(json.loads(data)["result"], ensure_ascii=False).encode('utf8') res = res.decode() res = res.replace("\"", "") res = res.replace("[", "") res = res.replace("]", "") return {'result': res}
def update_graph_live(n): #arguments correspond to the input values #get username from cookies username = request.cookies.get('username') query = '{ \ dataByTenantName(tenantName: "%s", last: 50) {\ id\ value\ time\ tenant {\ id\ name\ }\ sensor {\ id\ name\ }\ }\ }' % (username) result = schema.execute(query) if result and result.data: data = result.data['dataByTenantName'] #add data to pandas table df = pd.DataFrame( [[i['tenant']['name'], i['sensor']['name'], i['value'], i['time']] for i in data]) df.rename(columns={ 0: 'tenant_id', 1: 'sid', 2: 'value', 3: 'time' }, inplace=True) #Group by sid and get keys keys = df.groupby('sid').groups.keys() #Return data grouped by sid return { 'data': [ { 'y': df[(df.sid == sid)]['value'], #'x': df_tenant[(df_tenant.sid==sid)]['time'], 'x': range(len(df[(df.sid == sid)])), #'mode': 'markers', #'marker': {'size': 12}, 'type': 'line', 'name': sid } for sid in keys ], 'layout': { 'title': "{}'s data".format(username) } }
def setUp(self): self.expected_titles = [ 'My Sweet Lord', 'Hark! The Herald Angels Sing', 'Silent Night', 'O Come All Ye Faithful (Album Version)' ] query_string = '''{ filterSongByArtist(artistId: "ARXJJSN1187B98CB37") { msdTrackId title } }''' self.queried_titles = [] for f in schema.execute(query_string).data['filterSongByArtist']: self.queried_titles.append(f['title']) self.expected_msd_track_id = [ 'TRPYNNL12903CAF506', 'TRFMJLM12903CAF4FB', 'TRSKGOU12903CAF4FD', 'TRQSEJD12903CAF4F9' ] self.queried_msd_track_id = [] for f in schema.execute(query_string).data['filterSongByArtist']: self.queried_msd_track_id.append(f['msdTrackId'])
def index(): global data query = ''' query songQuery { songs { edges { node { id title url primaryartist { edges { node { id name } } } sampledsongs { edges { node { id title } } } samplingsongs { edges { node { id title } } } } } } } ''' result = schema.execute(query) errors = result.errors pprint(errors) edges = list(result.data.values())[0]['edges'] return render_template( 'start.html', title='Rapgraph - Index', data=edges, result=json.dumps(result.data).replace("'", "'"))
def postag(text): schema = graphene.Schema(PosTagging) result = schema.execute('{ txt }', context={'txt': text}) da = result.data['txt'].replace("\'", "\"") dat = da.replace("(", "[") data = dat.replace(")", "]") res = json.dumps(json.loads(data)["result"], ensure_ascii=False).encode('utf8') res = res.decode() res = res.replace("\"", "") res = res.replace("[", "") res = res.replace("]", "") return {'result': res}
def graphQL(): try: try: user = user_actions.get_logged_user() except messages.user_not_logged_in: user = None query = flask.request.data.decode("utf-8") query = json.loads(query) query = query.get('query', None) if query is None: return "Please provide a query" result = schema.execute(query, context={"user": user}) if result.errors is not None or result.data is None: errors = [str(error) for error in result.errors] errors = json.dumps(errors) return errors result = json.dumps(dict(result.data)) return result except Exception as err: raise err return messages.jsonify_message(message=err)
def graphql_subscription(message): model = message.content['model'] pk = message.content['pk'] instance = apps.get_model(model).objects.get(pk=pk) subscription_id = message.content['subscription_id'] payload = message.content['payload'] result = schema.execute( payload['query'], operation_name=payload['operationName'], variable_values=payload['variables'], root_value=instance, context_value=message, # message.user is the same as request.user allow_subscriptions=True, ) observer = GraphQLObserver(message.reply_channel, subscription_id) if hasattr(result, 'subscribe'): result.subscribe(observer)
def test_container_request(self): result = schema.execute(""" { container(id: 1) { id, name, items { id, name, current_container { id, name } } current_items { id, name } } } """) self.assertDictEqual( result.data, { 'container': { 'id': 1, 'name': 'container_0', 'items': [ { 'id': 1, 'name': 'item_0', 'current_container': { 'id': 1, 'name': 'container_0' } }, { 'id': 2, 'name': 'item_1', 'current_container': { 'id': 1, 'name': 'container_0' } }, { 'id': 3, 'name': 'item_2', 'current_container': { 'id': 1, 'name': 'container_0' } }, { 'id': 4, 'name': 'item_3', 'current_container': { 'id': 1, 'name': 'container_0' } }, { 'id': 5, 'name': 'item_4', 'current_container': { 'id': 2, 'name': 'container_1' } } ], 'current_items': [ { 'id': 1, 'name': 'item_0' }, { 'id': 2, 'name': 'item_1' }, { 'id': 3, 'name': 'item_2' }, { 'id': 4, 'name': 'item_3' } ] } })
def parse(query, source, page): execution = schema.execute(query, args={'page': page, 'source': source}) if execution.errors: raise Exception(execution.errors[0]) return execution.data
def test_item_request(self): result = schema.execute(""" { item(name: "item_4") { id name containers { id name items { id name } } } } """) self.assertEqual(result.errors, []) self.assertDictEqual( result.data, { 'item': { 'id': 5, 'name': 'item_4', 'containers': [ { 'id': 1, 'name': 'container_0', 'items': [ { 'id': 1, 'name': 'item_0' }, { 'id': 2, 'name': 'item_1' }, { 'id': 3, 'name': 'item_2' }, { 'id': 4, 'name': 'item_3' }, { 'id': 5, 'name': 'item_4' } ] }, { 'id': 2, 'name': 'container_1', 'items': [ { 'id': 5, 'name': 'item_4' } ] } ] } })
def post(self): query = self.request.body self.response.write(json.dumps(schema.execute(query).data)) print schema.execute(query).errors
def post(self): query = self.request.body self.response.headers.add_header("Access-Control-Allow-Origin", "*") self.response.write(json.dumps(schema.execute(query).data)) print schema.execute(query).errors
def get_emails(): result = schema.execute(default_query) return srsly.json_dumps(result.data)
def get(self): query = self.request.get("query") self.response.write(json.dumps(schema.execute(query).data))
def test_photos_query(app): response = { 'feature': 'popular', 'filters': { 'category': False, 'exclude': False }, 'current_page': 1, 'total_pages': 250, 'total_items': 5000, 'photos': [ { 'id': 4910421, 'name': 'Orange or lemon', 'description': '', 'times_viewed': 709, 'rating': 97.4, 'created_at': '2012-02-09T02:27:16-05:00', 'category': 0, 'privacy': False, 'width': 472, 'height': 709, 'votes_count': 88, 'comments_count': 58, 'nsfw': False, 'image_url': 'http://pcdn.500px.net/4910421/c4a10b46e857e33ed2df35749858a7e45690dae7/2.jpg', 'images': [ { 'url': 'http://pcdn.500px.net/4910421/' \ 'c4a10b46e857e33ed2df35749858a7e45690dae7/2.jpg' } ], 'user': { 'id': 386047, 'username': '******', 'firstname': 'Lluis ', 'lastname': 'de Haro Sanchez', 'city': 'Sabadell', 'country': 'Catalunya', 'fullname': 'Lluis de Haro Sanchez', 'userpic_url': 'http://acdn.500px.net/386047/' \ 'f76ed05530afec6d1d0bd985b98a91ce0ce49049/1.jpg?0', 'upgrade_status': 0 } }, { 'id': 4905955, 'name': 'R E S I G N E D', 'description': 'From the past of Tagus River, we have History' \ 'and memories, some of them abandoned and disclaimed in their margins ...', 'times_viewed': 842, 'rating': 97.4, 'created_at': '2012-02-08T19:00:13-05:00', 'category': 0, 'privacy': False, 'width': 750, 'height': 500, 'votes_count': 69, 'comments_count': 29, 'nsfw': False, 'image_url': 'http://pcdn.500px.net/4905955/' \ '7e1a6be3d8319b3b7357c6390289b20c16a26111/2.jpg', 'images': [ { 'url': 'http://pcdn.500px.net/4905955/' \ '7e1a6be3d8319b3b7357c6390289b20c16a26111/2.jpg' } ], 'user': { 'id': 350662, 'username': '******', 'firstname': 'Carlos', 'lastname': 'Resende', 'city': 'Forte da Casa', 'country': 'Portugal', 'fullname': 'Carlos Resende', 'userpic_url': 'http://acdn.500px.net/350662.jpg', 'upgrade_status': 0 } } ] } responses.add( responses.GET, PHOTOS_ENDPOINT, json=response ) query = '''{ photos { currentPage totalPages photos { url aspectRatio name description artist } } }''' result = schema.execute(query) assert not result.errors assert result.data == OrderedDict({ 'photos': OrderedDict({ 'currentPage': response['current_page'], 'totalPages': response['total_pages'], 'photos': [ OrderedDict({ 'url': response['photos'][0]['images'][0]['url'], 'aspectRatio': response['photos'][0]['width'] / response['photos'][0]['height'], 'name': response['photos'][0]['name'], 'description': response['photos'][0]['description'], 'artist': response['photos'][0]['user']['username'], }), OrderedDict({ 'url': response['photos'][1]['images'][0]['url'], 'aspectRatio': response['photos'][1]['width'] / response['photos'][1]['height'], 'name': response['photos'][1]['name'], 'description': response['photos'][1]['description'], 'artist': response['photos'][1]['user']['username'], }) ] }) })
def get_result(query): result = schema.execute(query) return result
from schema import schema if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description="Find songs that have been played by an artist") parser.add_argument('-a', metavar='Artist ID', help='Artist ID from the Second Hands Dataset', dest='artist_id') args = parser.parse_args() query_string = '''{ filterSongByArtist(artistId: "%s") { msdTrackId title } }''' % args.artist_id result = schema.execute(query_string) print('Artist %s has played the following songs' % args.artist_id) for f in result.data['filterSongByArtist']: print('\t%s (MSD Track ID: %s)' % (f['title'], f['msdTrackId']))
def parse(query, source, page): execution = schema.execute(query, args={'page': page, 'source': source}) if execution.errors: raise Exception(execution.errors[0]) return execution.data
if __name__ == '__main__': # print('schema is {0}'.format(s)) query1 = """ query { time(dataSet:"MO_201708_PR_PF_6903279",lt:24705.21747685185) { values indexes}} """ query2 = """ query getPres($time: String){ pres(dataSet:"MO_201708_PR_PF_6903279",time:$time,) { name values}} """ result = s.execute(query2, variables={"time": query1}) print(result.data) print(result.errors) q = """ SELECT $pres = query { pres(dataSet:"MO_201708_PR_PF_6903279", time:$time) { name values units } } WHERE $time = query { time(dataSet:"MO_201708_PR_PF_6903279",eq:24705.21747685185) { values indexes
from schema import schema if __name__ == '__main__': result = schema.execute('{ hello }') print(result.data['hello']) # "Hello World"
from schema import schema print( schema.execute( ''' { encoded(at_id: "/experiments/ENCSR688AWP/") { at_id } } ''' ) ) print( schema.execute( ''' { encoded(at_id: "/experiments/ENCSR688AWP/") { embedded { ... on Experiment { status uuid at_id files { at_id embedded { ... on File { status award { at_id
#!/usr/bin/env python3 '''isort:skip_file''' import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cindy.settings") import json import django django.setup() from schema import schema query = ''' { __schema { types { kind name possibleTypes { name } } } } ''' result = schema.execute(query) print(json.dumps(result.data, indent=2))
def get_json(): # If you return a dict from a view, it will be converted to a JSON response. Or use jsonify() return jsonify(schema.execute(request.args["query"]).data)