Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'gspread' in functional components in Python. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
def test_add_csv_data_00(self, mocker):
"""Ensure the data is appended to the worksheet."""
fake_fields = self.fake.pylist(10, True, str)
fake_data = []
for _ in range(self.fake.random_digit()):
fake_entry = {}
for field in fake_fields:
fake_entry[field] = self.fake.word()
fake_data.append(fake_entry)
g = GSheets(self.fake.file_path(depth=1, category=None, extension='json'), [])
g.spreadsheet = Spreadsheet(None, None)
g.worksheet = mocker.MagicMock()
g.worksheet.append_row = mocker.MagicMock()
g.add_csv_data(fake_fields, fake_data)
assert not g.worksheet.append_row.call_count == len(fake_data)
def setUpClass(cls):
super(WorksheetTest, cls).setUpClass()
ss_id = cls.config.get('Spreadsheet', 'id')
cls.spreadsheet = cls.gc.open_by_key(ss_id)
try:
test_sheet = cls.spreadsheet.worksheet('wksht_int_test')
if test_sheet:
# somehow left over from interrupted test, remove.
cls.spreadsheet.del_worksheet(test_sheet)
except gspread.exceptions.WorksheetNotFound:
pass # expected
def test_share_00(self, mocker):
"""Ensure the document is shared with valid contributors."""
contributors = ['alice@gmail.com:user:writer', 'alice@gmail.com:user:reader']
g = GSheets(self.fake.file_path(depth=1, category=None, extension='json'), contributors)
g.spreadsheet = Spreadsheet(None, None)
g.spreadsheet.share = mocker.MagicMock()
g.share()
assert g.spreadsheet.share.call_count == len(contributors)
def test_share_01(self, mocker):
"""Ensure the document is not shared with invalid contributors."""
contributors = ['alice@gmail.com']
g = GSheets(self.fake.file_path(depth=1, category=None, extension='json'), contributors)
g.spreadsheet = Spreadsheet(None, None)
g.spreadsheet.share = mocker.MagicMock()
g.share()
assert not g.spreadsheet.share.called
import os.path
import json
from gspread.models import Cell
from gspread_dataframe import _cellrepr
def contents_of_file(filename, et_parse=True):
with open(os.path.join(os.path.dirname(__file__), filename), 'r') as f:
return json.load(f)
SHEET_CONTENTS_FORMULAS = contents_of_file('sheet_contents_formulas.json')
SHEET_CONTENTS_EVALUATED = contents_of_file('sheet_contents_evaluated.json')
CELL_LIST = [
Cell(row=i+1, col=j+1, value=value)
for i, row in enumerate(contents_of_file('cell_list.json'))
for j, value in enumerate(row)
]
CELL_LIST_STRINGIFIED = [
Cell(row=i+1, col=j+1, value=_cellrepr(value, allow_formulas=True))
for i, row in enumerate(contents_of_file('cell_list.json'))
for j, value in enumerate(row)
]
_without_index = contents_of_file('cell_list.json')
for _r in _without_index:
del _r[0]
CELL_LIST_STRINGIFIED_NO_THINGY = [
Cell(row=i+1, col=j+1, value=_cellrepr(value, allow_formulas=True))
for i, row in enumerate(_without_index)
def sheet_copy(file_id, dist_id, title=None, copy_permissions=False):
"""
REF: https://github.com/burnash/gspread
I reuse the gspread function to make this request.
"""
self = G_ACCESS
url = "{0}/{1}/copy".format(DRIVE_FILES_API_V2_URL, file_id)
payload = {
"title": title,
"mimeType": "application/vnd.google-apps.spreadsheet",
"parents": [{"kind": "drive#childList", "id": dist_id}],
}
r = self.request("post", url, json=payload)
spreadsheet_id = r.json()["id"]
new_spreadsheet = self.open_by_key(spreadsheet_id)
if copy_permissions:
original = self.open_by_key(file_id)
permissions = original.list_permissions()
for p in permissions:
def create_sheet_container(file_id, dir_name):
"""
REF: https://github.com/burnash/gspread
I reuse the gspread function to make this API request.
"""
self = G_ACCESS
payload = {
"title": dir_name,
"mimeType": "application/vnd.google-apps.folder",
"parents": [{"kind": "drive#childList", "id": file_id}],
}
r = self.request("post", DRIVE_FILES_API_V2_URL, json=payload)
return r.json()["id"]
def setUp(self):
if self.__class__.gc is None:
self.__class__.setUpClass()
self.assertTrue(isinstance(self.gc, gspread.client.Client))
def setUpClass(cls):
try:
cls.config = ConfigParser.RawConfigParser()
cls.gc = gspread.client.Client(auth={})
except IOError as e:
msg = "Can't find %s for reading test configuration. "
raise Exception(msg % e.filename)
parameters_path = os.path.join(os.path.dirname(__file__), '..', 'default_parameters.txt')
lines = open(parameters_path, 'r').readlines()
parameters = {}
for line in lines:
key, value = line.split(':')
parameters[key] = value[:-1]
spreadsheet_name = "Sign up form for INF3331/INF43331 (2016) (Responses)"
# or use
# spreadsheet_name = parameters["course"]
# Log on to disk
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file, scope)
gc = gspread.authorize(credentials)
try:
wks = gc.open(spreadsheet_name).sheet1
except gspread.SpreadsheetNotFound:
json_key = json.load(open(json_file))
print "The spreadsheet document '{}' not found. Maybe it does not exist?".format(spreadsheet_name)
print "Otherwise, make sure that you shared the spreadsheet with {} and try again.".format(json_key['client_email'])
sys.exit(1)
# Store file in ../Attendance/
attendance_location = os.path.join(os.path.dirname(__file__), '..',
*parameters["filepath"].split(os.path.sep)[:-1])
# Create ../Attendance/ if it does not exist
if not os.path.exists(attendance_location):
os.makedirs(attendance_location)
filename = os.path.join(attendance_location, "%s-students_base.txt" % parameters['course'])