Getting error while Formatting request query in Python - python

I am trying to request a Graphql API through python. I have written the script which is trying to pull audit log from Github for each organisation.
This is the Python script I have written.
Query = """
query {
organization(login: '{}') {
auditLog(first: 100, '{}') {
edges {
node {
... on RepositoryAuditEntryData {
repository {
name
}
}
... on OrganizationAuditEntryData {
organizationResourcePath
organizationName
organizationUrl
}
... on TeamAuditEntryData {
teamName
}
... on TopicAuditEntryData {
topicName
}
... on OauthApplicationAuditEntryData {
oauthApplicationName
}
... on EnterpriseAuditEntryData {
enterpriseResourcePath
enterpriseUrl
enterpriseSlug
}
... on AuditEntry {
actorResourcePath
action
actorIp
actorLogin
operationType
createdAt
actorLocation {
countryCode
country
regionCode
region
city
}
#User 'Action' was performed on
userLogin
userResourcePath
userUrl
}
}
cursor
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
}
}
}
}
"""
l = []
l.append("CoreDevOpsTools")
l.append("JIRA-Cloud")
res = []
for i in range(len(l)):
org = str(l[i])
after = ''
while True:
result = requests.post('https://api.github.com/graphql',
json={'query': Query.format(org,after)},
headers=headers)
json_data = json.loads(result.text)
if 'errors' in json_data:
print(json_data['errors'])
break
res_list = json_data['data']['organization']['auditLog']
for items in res_list['edges']:
res.append(items)
if not res_list['pageInfo']['hasNextPage']:
break
after = 'after: "%s"' % res_list['edges'][-1]['cursor']
time.sleep(1)
File "../AuditLog.py", line 98, in <module>
json={'query': Query.format(org,after)},
KeyError: '\n organization(login'
This is the structure of query in Insomnia/Postman.
query {
organization(login: "CoreDevOpsTools") {
auditLog(first: 100, after: "XYZ") {
edges {
node {
... on RepositoryAuditEntryData {
repository {
name
}
}
... on OrganizationAuditEntryData {
organizationResourcePath
organizationName
organizationUrl
}
... on TeamAuditEntryData {
teamName
}
... on TopicAuditEntryData {
topicName
}
... on OauthApplicationAuditEntryData {
oauthApplicationName
}
... on EnterpriseAuditEntryData {
enterpriseResourcePath
enterpriseUrl
enterpriseSlug
}
... on AuditEntry {
actorResourcePath
action
actorIp
actorLogin
operationType
createdAt
actorLocation {
countryCode
country
regionCode
region
city
}
#User 'Action' was performed on
userLogin
userResourcePath
userUrl
}
}
cursor
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
}
}
}
}
This is error I am getting, I am not able to figure out what is wrong. I looked at other same type of questions here but that didn't work either.

The issue with your code is that the string you're trying to format itself has curly brackets in places where you don't want to replace things. e.g the first line "query {"
You can fix this by doubling the curly brackets. So "{" becomes "{{" etc.
More on this here: stackoverflow.com

Related

How to use conditionals on Uniswap GraphQL API pool method?

So I'm new to graphQL and I've been figuring out the Uniswap API, through the sandbox browser, but I'm running this program which just gets metadata on the top 100 tokens and their relative pools, but the pool one isn't working at all. I'm trying to put two conditions of if token0's hash is this and token1's hash is this, it should output the pool of those two, however if only outputs pools with the token0 hash, and just ignores the second one. I've tried using and, _and, or two where's seperated by {} or , so on so forth. This is an example I have (python btw):
class ExchangePools:
def QueryPoolDB(self, hash1, hash2):
query = """
{
pools(where: {token0: "%s"}, where: {token1:"%s"}, first: 1, orderBy:volumeUSD, orderDirection:desc) {
id
token0 {
id
symbol
}
token1 {
id
symbol
}
token1Price
}
}""" % (hash1, hash2)
return query
or in the sandbox explorer this:
{
pools(where: {token0: "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"} and: {token1:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"}, first: 1, orderBy:volumeUSD, orderDirection:desc) {
id
token0 {
id
symbol
}
token1 {
id
symbol
}
token1Price
}
}
with this output:
{
"data": {
"pools": [
{
"id": "0x4585fe77225b41b697c938b018e2ac67ac5a20c0",
"token0": {
"id": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
"symbol": "WBTC"
},
"token1": {
"id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"symbol": "WETH"
},
"token1Price": "14.8094450357546760737720184457113"
}
]
}
}
How can I get the API to register both statements?

Is there any way to insert data in parent and child model in one graphql mutation

I have a model named Project and a CustomProject model that inherits from it. Currently, I have two mutations one to add a project and one to add a custom project
class Project(models.Model):
url = models.URLField(blank=True)
description = models.TextField()
class CustomProject(Project):
role = models.CharField(max_length=15, null=True, blank=True)
mutation InsertProjects(
$projects: [graph_project_insert_input!]! = [
{
url: "https://github.com/smsajjadzaidi/FixedRouteSuggestion"
description: "_test_desc_"
}
]
) {
projects: insert_graph_project(
objects: $projects
on_conflict: {
constraint: graph_project_pkey
update_columns: [url, description]
}
) {
returning {
id
}
affected_rows
}
}
mutation InsertCustomProject(
$projects: [custom_project_insert_input!]! = [
{
project_ptr_id: 2
role:"author"
}
]
) {
customprojects: insert_custom_project(
objects: $projects
on_conflict: {
constraint: custom_project_pkey
update_columns: [role]
}
) {
returning {
graph_project{
id
}
}
affected_rows
}
}
Need a way to do the above in one mutation
mutation InsertCustomProject(
$url: String = "_____test______"
$description: String = "___test____"
$role: String = "author"
$title: String = "__test__"
) {
repositories: insert_customproject_one(
object: {
role: $role
project: {
data: {
url: $url
description: $description
}
on_conflict: {
constraint: project_pkey
update_columns: [url, description]
}
}
}
on_conflict: {
constraint: customproject_pkey
update_columns: [role]
}
) {
project_id: project_ptr_id
}
}

Unhandled Rejection (TypeError): Cannot read property 'find' of undefined for react-redux

Please help me fix this error : Unhandled Rejection (TypeError): Cannot read property 'find' of undefined.
All code as below ;
import { CART_ADD_ITEM } from '../constants/cartConstants'
export const cartReducer = (state = {cartItems: []}, action) => {
switch (action.type) {
case CART_ADD_ITEM:
const item = action.payload
const existItem = state.cartItems.find(x => x.product === item.product)
if (existItem) {
return {
...state,
cartItems: state.cartItems.map(x =>
x.product === existItem.product ? item : x)
}
} else {
return {
...state,
cartItems: [...state.cartItems, item]
}
}
default:
return state
}
}
this is CartAction
import axios from 'axios'
import { CART_ADD_ITEM } from '../constants/cartConstants'
export const addToCart = (id, qty) => async (dispatch, getState) => {
const {data} = await axios.get(`/api/products/${id}`)
dispatch({
type: CART_ADD_ITEM,
payload: {
product: data._id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
qty
}
})
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import { listProducts, listProductDetails } from './reducers/productReducers'
import { cartReducer } from './reducers/cartReducers'
const cartFromLocalStorage = localStorage.getItem('cartITems') ? JSON.parse(localStorage.getItem('cartItems')) : []
**const initialState = {
cart: { cartITems: cartFromLocalStorage }
}**
const reducer = combineReducers({
productsList: listProducts,
productDetails: listProductDetails,
cart: cartReducer,
})
const middleware = [thunk]
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
)
export default store
if found the same error while I was giving "cartFromLocalStorage" in the initialState, and I made mistake in declaring cart: { cartITems: cartFromLocalStorage }instead of cart: { cartItems: cartFromLocalStorage }, i used Capital T in cartItems, so i corrected it, now add to cart is working fine enter image description here

Graphql query in Python

Here is a graphql query with its result : OK.
I try to get the same result with Python, but I get nothing : response.text is empty. (API key is not needed).
q = """
{
node(id: "UXVlc3Rpb25uYWlyZTo5NTNjYjdjYS0xY2E0LTExZTktOTRkMi1mYTE2M2VlYjExZTE=") {
... on Questionnaire {
replies(first: 10, after: null) {
totalCount
pageInfo {
hasNextPage
endCursor
}
edges {
node {
id
createdAt
publishedAt
updatedAt
author {
id
}
responses {
question {
title
}
... on ValueResponse {
value
}
}
}
}
}
}
}
}
"""
response = requests.post(url = "https://granddebat.fr/graphql" , json = {'query': q})
print(response.text)
Please, any idea ?
It's all good with the query itself. In request you need to pass headers with {'Accept':
'application/vnd.cap-collectif.preview+json'}
response = requests.post(
url = "https://granddebat.fr/graphql",
json = {'query': q,},
headers= {'Accept': 'application/vnd.cap-collectif.preview+json'}
)

How to get only a subset of data using graphql?

I have a lengthy query of the github API:
query = """
{
repository(name: "fifteen5", owner: "15five") {
commit: object(expression: "c63a83caf81ef21616392fe5acb84f9655f94d92") {
... on Commit {
associatedPullRequests(first:5){
edges{
node{
title
number
body
}
}
}
}
}
}
}
The returned value is a deepnly nested dictionary - to get the values I want (title, number, and body) I have to do something like this:
# barf!
prs = areplStore['data']['repository']['commit']['associatedPullRequests']['edges']
for pr in prs:
print(pr['node'])
The length of that dictionary access makes my eyes bleed. Is there something I can specify in my graphql query to return only the edges result?
One method that looks slightly cleaner is to use py-jsonq. Unfortuantely this still has a lengthy access.
from pyjsonq import JsonQ
j = JsonQ(data={'data':
{'repository':
{'commit':
{'associatedPullRequests':
{'edges':
[
{'node':
{
'title': 'Add more foobar',
'number': 14253,
'body': 'More foo for the win'
}
}
]
}
}
}
}
}
)
prs = [
edge['node'] for edge in j.at('data.repository.commit.associatedPullRequests.edges').get()
]
print(prs)
https://repl.it/#almenon/json-q-test

Categories

Resources