I'm trying to get the webContentLink and the webViewLink of a Google Document. For the moment, my code looks like this :
http = decorator.http()
service = discovery.build("drive", "v2", http=http)
fields = "items(id,title,mimeType,webViewLink,webContentLink),nextLink,nextPageToken"
list = service.files().list(fields=fields).execute(http)
docs = [docs for docs in list["items"]
if docs["mimeType"] == DOCS_MIMETYPE]
template_values = {
'docs': docs,
}
The id and the title of the document are here but the webViewLink and webContentLink are both empty.
How can I get them properly?
Be noted that the webViewLink property is only returned for public folders, and not the single files inside such folders. You can use that as the base url to construct links to your files.
To retrieve the WebViewLink property, your request should look like this:
results = service.files().list(
pageSize=10,fields="nextPageToken, files(id, name, webViewLink)").execute()
Check these related SO questions:
Not receiving "webViewLink" in response?
Getting WebViewLinks with Google Drive
Related
I have a list of dictionaries that contain album information which I'm trying to use to search within Spotify and then add to users' saved albums. I tried following the examples given in the spotipy documentation, however, I'm getting an issue when using the search function via spotipy.
SCOPE = 'user-library-modify'
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, scope=SCOPE))
for album in newMusic:
albumName = album["Title"]
artistName = f"{album['Last Name']}+{album[' First Name']}"
getRecord = sp.search(q = f"artist:{artistName}&album:{albumName}", type='album')
print(getRecord)
I provided the redirect url when prompted after running, but this results in a 401 response for each album result as such:
{
"error": {
"status": 401,
"message": "No token provided"
}
}
I have the .cache file with the access and refresh tokens but it still says no token is provided. I thought maybe I was entering the query incorrectly, but I don't see anything wrong. This is how an example end url looks:
https://api.spotify.com/v1/search?query=artist:band+name&album:album+name&type=album&offset=0&limit=10
What am I doing wrong here? How can I get my access code recognized?
Found the issue; the query entry format was wrong. I found this answer to a past question that explains my problem: Using python to get a track from the spotify API by using search Endpoint
The artist, album, etc. do not need to be declared separately (e.g. "artist: _", "album: _"). They should just be combined together like:
https://api.spotify.com/v1/search?query=first+name+last+name+album+title&type=album&offset=0&limit=10
Weirdly, this contradicts what is in the Spotify API documentation where an example query value is given as such:
Example value:
"remaster%20track:Doxy+artist:Miles%20Davis"
https://developer.spotify.com/documentation/web-api/reference/#/operations/search
I have a trial account with Azure and have uploaded some JSON files into CosmosDB. I am creating a python program to review the data but I am having trouble doing so. This is the code I have so far:
import pydocumentdb.documents as documents
import pydocumentdb.document_client as document_client
import pydocumentdb.errors as errors
url = 'https://ronyazrak.documents.azure.com:443/'
key = '' # primary key
# Initialize the Python DocumentDB client
client = document_client.DocumentClient(url, {'masterKey': key})
collection_link = '/dbs/test1/colls/test1'
collection = client.ReadCollection(collection_link)
result_iterable = client.QueryDocuments(collection)
query = { 'query': 'SELECT * FROM server s' }
I read somewhere that the key would be my primary key that I can find in my Azure account Keys. I have filled the key string with my primary key shown in the image but key here is empty just for privacy purposes.
I also read somewhere that the collection_link should be '/dbs/test1/colls/test1' if my data is in collection 'test1' Collections.
My code gets an error at the function client.ReadCollection().
That's the error I have "pydocumentdb.errors.HTTPFailure: Status code: 401
{"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get\ncolls\ndbs/test1/colls/test1\nmon, 29 may 2017 19:47:28 gmt\n\n'\r\nActivityId: 03e13e74-8db4-4661-837a-f8d81a2804cc"}"
Once this error is fixed, what is there left to do? I want to get the JSON files as a big dictionary so that I can review the data.
Am I in the right path? Am I approaching this the wrong way? How can I read documents that are in my database? Thanks.
According to your error information, it seems to be caused by the authentication failed with your key as the offical explaination said below from here.
So please check your key, but I think the key point is using pydocumentdb incorrectly. These id of Database, Collection & Document are different from their links. These APIs ReadCollection, QueryDocuments need to be pass related link. You need to retrieve all resource in Azure CosmosDB via resource link, not resource id.
According to your description, I think you want to list all documents under the collection id path /dbs/test1/colls/test1. As reference, here is my sample code as below.
from pydocumentdb import document_client
uri = 'https://ronyazrak.documents.azure.com:443/'
key = '<your-primary-key>'
client = document_client.DocumentClient(uri, {'masterKey': key})
db_id = 'test1'
db_query = "select * from r where r.id = '{0}'".format(db_id)
db = list(client.QueryDatabases(db_query))[0]
db_link = db['_self']
coll_id = 'test1'
coll_query = "select * from r where r.id = '{0}'".format(coll_id)
coll = list(client.QueryCollections(db_link, coll_query))[0]
coll_link = coll['_self']
docs = client.ReadDocuments(coll_link)
print list(docs)
Please see the details of DocumentDB Python SDK from here.
For those using azure-cosmos, the current library (2019) I opened a doc bug and provided a sample in GitHub
Sample
from azure.cosmos import cosmos_client
import json
CONFIG = {
"ENDPOINT": "ENDPOINT_FROM_YOUR_COSMOS_ACCOUNT",
"PRIMARYKEY": "KEY_FROM_YOUR_COSMOS_ACCOUNT",
"DATABASE": "DATABASE_ID", # Prolly looks more like a name to you
"CONTAINER": "YOUR_CONTAINER_ID" # Prolly looks more like a name to you
}
CONTAINER_LINK = f"dbs/{CONFIG['DATABASE']}/colls/{CONFIG['CONTAINER']}"
FEEDOPTIONS = {}
FEEDOPTIONS["enableCrossPartitionQuery"] = True
# There is also a partitionKey Feed Option, but I was unable to figure out how to us it.
QUERY = {
"query": f"SELECT * from c"
}
# Initialize the Cosmos client
client = cosmos_client.CosmosClient(
url_connection=CONFIG["ENDPOINT"], auth={"masterKey": CONFIG["PRIMARYKEY"]}
)
# Query for some data
results = client.QueryItems(CONTAINER_LINK, QUERY, FEEDOPTIONS)
# Look at your data
print(list(results))
# You can also use the list as JSON
json.dumps(list(results), indent=4)
I am trying to update a file that I created with some new data. Essentially, i am trying to append contents to an already created file. I have tried different ways using different attributes but nothing seems to work so far. The migration from v2 to v3 seems to have made things harder to develop in python.
This is my code so far
def updateFile(fileID, contents):
credentials = get_credentials() #this function gets the credentials for oauth
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
# First retrieve the file from the API.
#fileCreated = service.files().get(fileId=fileID).execute()
#print(dir(fileCreated.update()))
# File's new content.
file_metadata = { 'name' : 'notes.txt', 'description' : 'this is a test' }
fh = BytesIO(contents.encode())
media = MediaIoBaseUpload(fh,
mimetype='text/plain')
# Send the request to the API.
#print(BytesIO(contents.encode()).read())
print(fileID)
updated_file = service.files().update(
body=file_metadata,
#uploadType = 'media',
fileId=fileID,
#fields = fileID,
media_body=media).execute()
I have tried using MediaFileUpload (it works only for uploading a file) but I am appending a 'string' that is real time generated using a voice interface and is not stored in any file. So I ended up using MediaIoBaseUpload.
The code runs without any error, but the file is not updated. Any help is appreciated.
okay, so i figured out what was wrong with my code. Apparently, nothing is wrong with this chunk of code that I posted. I realized that I have not converted the document I created to a "google document" hence the code didnt update the document. I changed the mime type of the document i create to be a google document, and now the code works fine :)
You can also use service.files().get_media(fileId=fileID).execute() to get the file content and append new content to it.
Shopify Python API on Github
I am able to get this far and pull in a list of all of the assets, but can't figure out how to actually pull them down from here. Any ideas?
SHOP_NAME = "SHOP-NAME"
API_PASSWORD = "API-PASSWORD"
session = shopify.Session(SHOP_NAME)
session.token = API_PASSWORD
shopify.ShopifyResource.activate_session(session)
assets = shopify.Asset.find()
shopify.Asset.find() is using the list endpoint which doesn't include the asset value, and it sounds like that is what you are after.
If you use the receive a single Asset endpoint, then you can also get the assets value.
asset = shopify.Asset.find(assets[0].key, theme_id=assets[0].theme_id)
print asset.value
(For clarity, this post relates to the difference between the Google Documents List API and Google Drive API on Google App Engine with Python)
With the [now deprecated] Documents list API I was able to edit Google Documents by exporting as HTML, modifying the HTML and then re-uploading, either as a new document or as a modification to the original. This was useful for things like generating PDF documents from a template. I have been trying to replicate this functionality with the new Drive API (V2), however seem unable to.
Have come up with this ...
http = # authenticated http client
drive_service = build('drive', 'v2', http=http)
# get the file ...
file = drive_service.files().get(fileId=FILE_ID).execute()
# download the html ...
url = file['exportLinks']['text/html']
response, content = http.request(url)
# edit html
html = content.replace('foo', 'bar')
# create new file with modified html ...
body = {'title':'Modified Doc',
'description':'Some description',
'mimeType':'text/html'}
media_body = MediaIoBaseUpload(StringIO.StringIO(html), 'text/html', resumable=False)
drive_service.files().insert(body=body, media_body=media_body)
The above code uploads an html file as a file into Google Drive, rather then rendering the HTML into a Google Document. Fair enough, this makes sense. But how to I get it render as a Google Doc, as I was able to do with the Documents List API?
One other thing - if I set resumable=True it throws the following error on App Engine - '_StreamSlice' has no len(). Couldn't figure out how to get resumable=True to work?
And one last thing - the sample code in the docs uses a MediaInMemoryUpload object, however if you look at the source it is now deprecated, in favour of MediaIoBaseUpload. Should the sample code be updated?!
i suspect the issue is that the default for conversion has changed from true to false. You must explicitly set convert=true on the upload. See https://developers.google.com/drive/v2/reference/files/insert