I'm using freebase library to get the article. But it is not working. I'm using this example. http://tinyurl.com/6ynwrbk Can any one fix this error? thanks
import freebase
query = {
"id": "/en/jimi_hendrix",
"/common/topic/article": [{
"text": {
"maxlength": 400,
"chars": None
}
}]
}
result = freebase.mqlread(query)
print (result)
##################################
Edit : Code Updated
The error you are getting is MQL complaining that there is no such property "chars". It works in the queryeditor because you are using MQL Extensions, a feature that is not currently supported.
Freebase doesn't store topic descriptions along with the other data due to size issues, but you can use the new Text API to retrieve them by id:
https://www.googleapis.com/freebase/v1-sandbox/text/en/jimi_hendrix
The python library you are using does not support this new API, but you can find more details and documentation, including library support here:
http://wiki.freebase.com/wiki/ApiText
python has no null keyword, instead it has None which is an object that represents a null-like value.
Also, the request in the link you posted appears to be json. Python's None will be encoded as null in json.
To solve your first problem, switch null with None.
To solve your second problem (in the comments), try (in your import/feature list):
import logging
logging.basicConfig()
Or, you can try a variant of the solution found here.
It might work. I hope this helped.
Related
After the deprecation of my discovery url, I had to make some change on my code and now I get this error.
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://mybusinessbusinessinformation.googleapis.com/v1/accounts/{*accountid*}/locations?filter=locationKey.placeId%3{*placeid*}&readMask=paths%3A+%22locations%28name%29%22%0A&alt=json returned "Request contains an invalid argument.". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'read_mask', 'description': 'Invalid field mask provided'}]}]">
I am trying to use this end point accounts.locations.list
I'm using :
python 3.8
google-api-python-client 2.29.0
My current code look likes :
from google.protobuf.field_mask_pb2 import FieldMask
googleAPI = GoogleAPI.auth_with_credentials(client_id=config.GMB_CLIENT_ID,
client_secret=config.GMB_CLIENT_SECRET,
client_refresh_token=config.GMB_REFRESH_TOKEN,
api_name='mybusinessbusinessinformation',
api_version='v1',
discovery_service_url="https://mybusinessbusinessinformation.googleapis.com/$discovery/rest")
field_mask = FieldMask(paths=["locations(name)"])
outputLocation = googleAPI.service.accounts().locations().list(parent="accounts/{*id*}",
filter="locationKey.placeId=" + google_place_id,
readMask=field_mask
).execute()
From the error, i tried a lot of fieldmask path and still don't know what they want.
I've tried things like location.name, name, locations.name, locations.location.name and it did'nt work.
I also try to pass the readMask params without use the FieldMask class with passing a string and same problem.
So if someone know what is the format of the readMask they want it will be great for me !
.
Can help:
https://www.youtube.com/watch?v=T1FUDXRB7Ns
https://developers.google.com/google-ads/api/docs/client-libs/python/field-masks
You have not set the readMask correctly. I have done a similar task in Java and Google returns the results. readMask is a String type, and what I am going to provide you in the following line includes all fields. You can omit anyone which does not serve you. I am also writing the request code in Java, maybe it can help you better to convert into Python.
String readMask="storeCode,regularHours,name,languageCode,title,phoneNumbers,categories,storefrontAddress,websiteUri,regularHours,specialHours,serviceArea,labels,adWordsLocationExtensions,latlng,openInfo,metadata,profile,relationshipData,moreHours";
MyBusinessBusinessInformation.Accounts.Locations.List request= mybusinessaccountLocations.accounts().locations().list(accountName).setReadMask(readMask);
ListLocationsResponse Response = request.execute();
List<Location>= Response.getLocations();
while (Response.getNextPageToken() != null) {
locationsList.setPageToken(Response.getNextPageToken());
Response=request.execute();
locations.addAll(Response.getLocations());
}
-- about the question in the comment you have asked this is what I have for placeId:
As other people said you before, the readmask is not set correctly.
Here Google My Business Information api v1 you can see:
"This is a comma-separated list of fully qualified names of fields"
and here Google Json representation you can see the field.
With this, I tried this
read_mask = "name,title"
and it worked for me, hope this work for you too.
I'm using Facebook's Python SDK to extract Ads Insights, but I can't find the right way to retrieve ALL fields without having to declare them, which is pretty cumbersome.
My current code looks like this:
ads = tempaccount.get_insights(
params={'date_preset': 'yesterday',
'level': 'ad'},
fields=[AdsInsights.Field.account_id,
AdsInsights.Field.account_name,
AdsInsights.Field.ad_id,
AdsInsights.Field.ad_name,
AdsInsights.Field.adset_id,
AdsInsights.Field.adset_name,
AdsInsights.Field.campaign_id,
AdsInsights.Field.campaign_name,
AdsInsights.Field.cost_per_outbound_click,
AdsInsights.Field.outbound_clicks,
AdsInsights.Field.spend])
Is there a way to force the "fields" attribute to bring all possible fields without declaring them?
Unfortunately, you will need to specify all the required fields. It's not possible to get all fields without explicitly specifying them.
My code also looks similar to yours when querying the insights endpoint.
This worked for me:
from facebookads.adobjects.adsinsights import AdsInsights
for property, value in vars(AdsInsights.Field).items():
print(property, ":", value)
Got from this post: How to enumerate an object's properties in Python?
I have been using the ElasticSearch DSL python package to query my elastic search database. The querying method is very intuitive but I'm having issues retrieving the documents. This is what I have tried:
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
es = Elasticsearch(hosts=[{"host":'xyz', "port":9200}],timeout=400)
s = Search(using=es,index ="xyz-*").query("match_all")
response = s.execute()
for hit in response:
print hit.title
The error I get :
AttributeError: 'Hit' object has no attribute 'title'
I googled the error and found another SO : How to access the response object using elasticsearch DSL for python
The solution mentions:
for hit in response:
print hit.doc.firstColumnName
Unfortunately, I had the same issue again with 'doc'. I was wondering what the correct way to access my document was?
Any help would really be appreciated!
I'm running into the same issues as I've found different versions of this, but it seems to depend on the version of the elasticsearch-dsl library you're using. You might explore the response object, and it's sub-objects. For instance, using version 5.3.0, I see the expected data using the below loop.
for hit in RESPONSE.hits._l_:
print(hit)
or
for hit in RESPONSE.hits.hits:
print(hit)
NOTE these are limited to 10 data elements for some strange reason.
print(len(RESPONSE.hits.hits))
10
print(len(RESPONSE.hits._l_))
10
This doesn't match the amount of overall hits if I print the number of hits using print('Total {} hits found.\n'.format(RESPONSE.hits.total))
Good luck!
From version 6 onwards the response does not return your populated Document class anymore, meaning that your fields are just an AttrDict which is basically a dictionary.
To solve this you need to have a Document class representing the document you want to parse. Then you need to parse the hit dictionary with your document class using the .from_es() method.
Like I answered here.
https://stackoverflow.com/a/64169419/5144029
Also have a look at the Document class here
https://elasticsearch-dsl.readthedocs.io/en/7.3.0/persistence.html
I'm trying to duplicate a sheet using the Google Sheets API. I've been successful reading and writing variables, but I'm stuck on the DuplicateSheetRequest with batchUpdate() code. My code looks like this:
requests = []
requests.append({
"DuplicateSheetRequest": {
"sourceSheetId": sheet_id_source,
"insertSheetIndex": target_index,
"newSheetId": 123456,
"newSheetName": destination_sheet_name
}
})
body = {
'requests': requests
}
response = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId,
body=body).execute()
When I execute the code, I get an error:
https://sheets.googleapis.com/v4/spreadsheets/[sheet ID redacted]:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "duplicate_sheet_request" at 'requests[0]': Cannot find field.">
What's really odd is that the error says "duplicate_sheet_request" whereas my code says DuplicateSheetRequest. (I also tested something I knew was wrong, e.g. "DuplicateSheetRequestsss", which became "duplicate_sheet_requestsss"). I don't know why the variable name is chasing, though I'm inclined to believe this is a red herring.
The closest thing I could find is this Google Groups issue that suggests that perhaps the method I'm trying to use isn't allowed with a service account, but I may be misreading that thread.
The problem was that the batch update method I was looking for should have been duplicateSheet, not DuplicateSheetRequest:
requests.append({
"duplicateSheet": {
"sourceSheetId": sheet_id_source,
"insertSheetIndex": target_index,
#"newSheetId": 123456,
"newSheetName": destination_sheet_name
}
})
Quack quack.
i'm getting the following error every time that i try to send an issue to Jira:
suds.WebFault: Server raised fault: 'org.xml.sax.SAXException:
Found character data inside an array element while deserializing'
I search on stackoverflow and the web for the answer and some people say that is suds 0.3 < fault. But i'm using the 0.4.1.1 version.
Here is my issue dict:
issue = {"assignee": "user_test",
"components": "17311",
"project": "TES",
"description" : "This is a test",
"priority" : "Major",
"summary" : "Just a test title",
"type":"Incident"
}
Class Jira made by me:
def create_issue(self,issue):
if(not isinstance(issue,dict)):
raise Exception("Issue must be a dict")
new_issue = self.jira.service.createIssue(in0 = self.auth,in1 = issue)
return new_issue["key"]
Using jira-python I was able to add components with like:
jira.create_issue(project={'key': project_id}, summary=ticket_summary,
description=ticket_description, issuetype={'name': ticket_issue_type},
components=[{'name': 'Application Slow'},], parent={'id': new_issue_key}, customfield_10101=termination_change_date,
)
I kept trying to send a component as "components={'name': 'Application Slow'}", but I was getting a "data was not an array" (or something similar). I took a look at the REST API and how some of their array examples were composed which is how I came to my example above.
https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue#JIRARESTAPIExample-CreateIssue-Request
Labels
"customfield_10006": ["examplelabelnumber1", "examplelabelnumber2"]
Labels are arrays of strings
I know this is a bit off topic, but when I searched for my issue I found myself coming back here often so I hope this is a bit helpful for your case and to anyone else. The concept is the same as the components field will only accept an array of objects.
components is not right. It has to be an array of things because it is multivalued. Some hints at https://developer.atlassian.com/display/JIRADEV/Creating+a+JIRA+SOAP+Client or look at how the JIRA Python CLI does it
'components': [17311]