Updating a Spreadsheet in Google Docs - python

I have a python script that takes a generated CSV and uploads it to Google Docs. It can upload it just fine, put I cannot seem to get it to replace the data, it returns an error I cannot find reference to.
Le Code:
import gdata.auth
import gdata.docs
import gdata.docs.service
import gdata.docs.data
import gdata.docs.client
email = 'admin#domain.com'
CONSUMER_KEY='domain.com'
CONSUMER_SECRET='blah54545blah'
ms_client = gdata.docs.client.DocsClient('Domain_Doc_Upload')
ms_client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(CONSUMER_KEY, CONSUMER_SECRET, email)
url = 'http://docs.google.com/feeds/documents/private/full/sd01blahgarbage'
ms = gdata.data.MediaSource(file_path="C:\\people.csv", content_type='text/csv')
csv_entry2 = ms_client.Update(url, ms)
It returns:
Traceback (most recent call last):
File "so_test.py", line 19, in <module>
csv_entry2 = ms_client.Update(ms, url)
File "build\bdist.win-amd64\egg\gdata\client.py", line 717, in update
AttributeError: 'MediaSource' object has no attribute 'to_string'
I cannot find anything about the 'to_string' attribute, so I am lost on the trace. ANy help, much appreciated.

I took a look at the docs and it looks like the Update method takes (entry, ms) where entry needs to be a gdata.docs.data.DocsEntry object. You should be able to get the DocsEntry object by getting a feed from your client.
feed = client.GetDocList()

Related

Error while updating Confluence page using Python

status = confluence.update_page(
parent_id=None,
page_id={con_pageid},
title={con_title},
body='Updated Page. You can use <strong>HTML tags</strong>!')
Using this code gives me the following error:
Traceback (most recent call last):
File "update2.py", line 24, in
status = confluence.update_page(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/atlassian/confluence.py", line 1513, in update_page
if not always_update and body is not None and self.is_page_content_is_already_updated(page_id, body, title):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/atlassian/confluence.py", line 1433, in is_page_content_is_already_updated
current_title = confluence_content.get("title", None)
AttributeError: 'str' object has no attribute 'get'
Does anyone have an idea on how to update a confluence page using python? I've tried various solutions provided even here, but none of them is working for me.
Finally tweaked a code that works. Providing whole code in case anyone would need it later.
import requests
from atlassian import Confluence
confluence = Confluence(
url='https://confluence.<your domain>.com',
token='CyberPunk EdgeRunners')
status = confluence.get_page_by_title(space='ABC', title='testPage')
print(status)
status = confluence.update_page(
parent_id=<a number sequence>,
page_id=<a number sequence>,
title='testpage',
body='<h1 id="WindowsSignatureSet2.4.131.3-2-HandoffinstructionstoOperations">A</h1>'
)
print(status)

Amazon Neptune on submitting query: AttributeError: 'str' object has no attribute 'source_instructions'

I have the following code running on AWS lambda, but getting the following error.
Error
[ERROR] AttributeError: 'str' object has no attribute 'source_instructions'
Traceback (most recent call last):
File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 56, in submit
    result_set = self._client.submit(bytecode, request_options=self._extract_request_options(bytecode))
  File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 81, in _extract_request_options
    options_strategy = next((x for x in bytecode.source_instructionsEND RequestId: 4ee8073c-e941-43b3-8014-8717893b3188
Source code
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
def test_neptune(host):
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
query = "g.V().groupCount().by(label).unfold().project('label','count').by(keys).by(values)"
response = remoteConn.submit(query)
print("response-> {}" .format(response))
# iterate repsonse
# go thru label
for set_item in response:
for item in set_item:
print("item-> item: {}".format(item))
remoteConn.close()
test_neptune()
Your DriverRemoteConnection call is wrong. You have:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
So you are sending {} as the hostname, and passing 'g' as a second parameter, which is probably where the error comes from. I don't know what you intended the 'g' for, but you probably want:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin'.format(host))
If you send the query as a text string you need to create the Client object differently or write the query as in-line Python. There are two examples at (1) and (2) that show each option. The error you are seeing is because the server is trying to find Gremlin bytecode in the packet sent but only found a string (which does not have a source_instructions method).
Using a DriverRemoteConnection you can use a Python line of code such as:
result = (g.V().groupCount().
by(label).
unfold().
project('label','count').
by(keys).
by(values).
next())
If you actually want/need to send the query as a string instead of bytecode, please see my answer to this question
https://github.com/krlawrence/graph/blob/master/sample-code/basic-client.py
https://github.com/krlawrence/graph/blob/master/sample-code/glv-client.py

How to use get_attachment call upon QueryResult (python cloudant) ?

I've been trying to get attachment image data from documents in Cloudant.
I can successfully do it once a document is selected (direct extract with _id, etc).
Now trying to do it in combination with "query" operation using selector, I run into trouble.
Here is my code.
targetName="chibika33"
targetfile="chibitest.png"
#--------------------------------------------------
# get all the documents with the specific nameField
#--------------------------------------------------
myDatabase.create_query_index(fields = ['nameField'])
selector = {'nameField': {'$eq': targetName}}
docs = myDatabase.get_query_result(selector)
#--------------------------------------------------
# get the attachment files to them, save it locally
#--------------------------------------------------
count = 0
for doc in docs:
count=count+1
result_filename="result%03d.png"%(count)
dataContent = doc.get_attachment(targetfile, attachment_type='binary')
dataContentb =base64.b64decode(dataContent)
with open(result_filename,'wb') as output:
output.write(dataContentb)
Causes error as;
Traceback (most recent call last):
File "view8.py", line 44, in <module>
dataContent = doc.get_attachment(targetfile, attachment_type='binary')
AttributeError: 'dict' object has no attribute 'get_attachment'
So far, I've been unable to find any API for converting dict to document object in the python-cloudant-document...[python-cloudant document]: http://python-cloudant.readthedocs.io/en/latest/index.html
Any advise would be highly appreciated.
The returned structure from get_query_result(...) isn't an array of documents.
Try:
resp = myDatabase.get_query_result(selector)
for doc in resp['docs']:
# your code here
See the docs at:
http://python-cloudant.readthedocs.io/en/latest/database.html#cloudant.database.CloudantDatabase.get_query_result

How to add members to a group using directory api and python?

I am trying to get my head around migrating to google admin sdk. I am trying to add members to a group (mailing list) using python. I have figured out how to create the group, but can't figure out how to add members. I have read this page: https://developers.google.com/admin-sdk/directory/v1/reference/members/insert but cannot figure out how to map it to python (I have little experience with REST or python, I'm trying to learn).
This is how I am trying to do it:
import httplib2
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
keyFile = file(p12File, 'rb')
key = keyFile.read()
keyFile.close()
credentials = SignedJwtAssertionCredentials(serviceAccount,
key,
scope,
prn=superAdmin)
http = httplib2.Http()
httplib2.debuglevel = False #change this to True if you want to see the output
http = credentials.authorize(http=http)
directoryService = build(serviceName='admin', version='directory_v1', http=http)
# THIS DOES NOT WORK
groupinfo = {'email': 'wibble#XXX.co.uk'}
directoryService.groups().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
When I run that I get:
Traceback (most recent call last):
File "add-member-to-group.py", line 58, in <module>
directoryService.groups().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 604, in method
raise TypeError('Got an unexpected keyword argument "%s"' % name)
TypeError: Got an unexpected keyword argument "groupKey"
I would be grateful if someone could help me to figure out how to do this.
After further hunting around I worked it out. That last line should have been:
directoryService.members().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
i.e. directoryService.members()... not directoryService.groups()...
The examples here helped me to work it out.

Tweepy follow Twitter users from text file using user_id (Python script)

I am trying to follow user_ids from a text file with 27 user_ids - one per line, e.g. :
217275660
234874181
27213931
230766319
83695362
234154065
68385750
I have some code that seems to work except it says user_id isn't defined (see pasted error at the bottom)... but user_id should be the correct variable in Tweepy... with or without [,follow] afterwards. My code is as follows:
# Script to follow Twitter users from text file containing user IDs (one per line)
# Header stuff I've just thrown in from another script to authenticate
import json
import time
import tweepy
import pprint
from tweepy.parsers import RawParser
from auth import TwitterAuth
from datetime import datetime
auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret)
auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret)
rawParser = RawParser()
api = tweepy.API(auth_handler = auth, parser = rawParser)
# Open to_follow.txt
to_follow = [line.strip() for line in open('to_follow.txt')]
print to_follow
# Follow everyone from list?!
for user_id in to_follow:
try:
api.create_friendship(user_id)
except tweepy.TweepError as e:
print e
continue
print "Done."
The error is:
$ python follow.py
['217275660', '234874181', '27213931', '230766319', '83695362', '234154065', '68385750', '94981006', '215003131', '30921943', '234526708', '229259895', '88973663', '108144701', '233419650', '70622223', '95445695', '21756719', '229243314', '18162009', '224705840', '49731754', '19352387', '80815034', '17493612', '23825654', '102493081']
Traceback (most recent call last):
File "follow.py", line 30, in <module>
api.create_friendship(user_id)
NameError: name 'user_id' is not defined
Indeed user_id isn't defined anywhere in your code.
I think you meant to do:
for user_id in to_follow:
The user_id's are in the list
And on a side note - the following code is better and more orthodox:
with open('to_follow.txt') as f:
for line in f:
user_id = line.strip()
api.create_friendship(user_id)

Categories

Resources