Getting error 500 for read requests to google spreadsheet using gspread - google-sheets-api

I have a script python script trying to access a google spreadsheet, but I am getting a 500 error from trying to get the list of worksheets with gc.worksheets()
APIError: {'code': 500, 'message': 'Internal error encountered.', 'status': 'INTERNAL'}
---------------------------------------------------------------------------
APIError Traceback (most recent call last)
/tmp/ipykernel_14907/1619355115.py in <module>
----> 1 gc.worksheets()
~/anaconda3/lib/python3.8/site-packages/gspread/models.py in worksheets(self)
351 in a spreadsheet.
352 """
--> 353 sheet_data = self.fetch_sheet_metadata()
354 return [Worksheet(self, x['properties']) for x in sheet_data['sheets']]
355
~/anaconda3/lib/python3.8/site-packages/gspread/models.py in fetch_sheet_metadata(self, params)
293 url = SPREADSHEET_URL % self.id
294
--> 295 r = self.client.request('get', url, params=params)
296
297 return r.json()
~/anaconda3/lib/python3.8/site-packages/gspread/client.py in request(self, method, endpoint, params, data, json, files, headers)
74 return response
75 else:
---> 76 raise APIError(response)
77
78 def list_spreadsheet_files(self, title=None):
APIError: {'code': 500, 'message': 'Internal error encountered.', 'status': 'INTERNAL'}
The Code I am using is the following:
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
CREDENTIALS_JSON = 'credentials.json'
SCOPES = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIALS_JSON, SCOPES)
client = gspread.authorize(creds)
gc = client.open_by_url('<I use the url of the file here>')
worksheets = gc.worksheets() # This like is returning an error
sheet1 = gc.get_worksheet_by_id(<sheet id>) # This line is also returning an error
Everything was working just fine a day before, and I haven't made any changes to the script.

Related

I am unable to retrieve data from pndas_datareader. how will it work for yahoo data

PG = wb.DataReader('PG',data_source = 'yahoo',start = '2000-1-1', end = '2001-1-1')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[34], line 2
1 # !pip install pandas_datareader
----> 2 PG = wb.DataReader('PG',data_source = 'yahoo',start = '2000-1-1', end = '2001-1-1')
File c:\Users\intiz\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_decorators.py:211, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper(*args, **kwargs)
209 else:
210 kwargs[new_arg_name] = new_arg_value
--> 211 return func(*args, **kwargs)
File c:\Users\intiz\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas_datareader\data.py:379, in DataReader(name, data_source, start, end, retry_count, pause, session, api_key)
367 raise NotImplementedError(msg)
369 if data_source == "yahoo":
370 return YahooDailyReader(
371 symbols=name,
372 start=start,
373 end=end,
374 adjust_price=False,
375 chunksize=25,
376 retry_count=retry_count,
377 pause=pause,
378 session=session,
--> 379 ).read()
381 elif data_source == "iex":
...
--> 153 data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
154 except KeyError:
155 msg = "No data fetched for symbol {} using {}"
TypeError: string indices must be integers
I need PG stock index information datewise

Translate Tweets using googletrans - AttributeError: 'NoneType' object has no attribute 'group'

I have a pandas dataframe with some German tweets. I want to translate these tweets to English and use googletrans for this task and try to apply it via a lambda function to my dataframe.
I use this code:
from googletrans import Translator
df1['translated_tweet'] = df1['tweet'].apply(lambda x: Translator().translate(x, dest='en').text)
And get this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-16-ed0b3a6e6dd8> in <module>
----> 1 df1['translated_tweet'] = df1['tweet'].apply(lambda x: Translator().translate(x, dest='en').text)
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4136 else:
4137 values = self.astype(object)._values
-> 4138 mapped = lib.map_infer(values, f, convert=convert_dtype)
4139
4140 if len(mapped) and isinstance(mapped[0], Series):
pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-16-ed0b3a6e6dd8> in <lambda>(x)
----> 1 df1['translated_tweet'] = df1['tweet'].apply(lambda x: Translator().translate(x, dest='en').text)
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\googletrans\client.py in translate(self, text, dest, src, **kwargs)
180
181 origin = text
--> 182 data = self._translate(text, dest, src, kwargs)
183
184 # this code will be updated when the format is changed.
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\googletrans\client.py in _translate(self, text, dest, src, override)
76
77 def _translate(self, text, dest, src, override):
---> 78 token = self.token_acquirer.do(text)
79 params = utils.build_params(query=text, src=src, dest=dest,
80 token=token, override=override)
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\googletrans\gtoken.py in do(self, text)
192
193 def do(self, text):
--> 194 self._update()
195 tk = self.acquire(text)
196 return tk
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\googletrans\gtoken.py in _update(self)
60
61 # this will be the same as python code after stripping out a reserved word 'var'
---> 62 code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
63 # unescape special ascii characters such like a \x3d(=)
64 code = code.encode().decode('unicode-escape')
AttributeError: 'NoneType' object has no attribute 'group'
What do I have to change here?

Pandas can't read in excel file

Something is wrong with my pandas module. I tried to read in an excel file using the following code, which works on my classmate's computer, but it's giving me an error on my computer:
FFT1=pd.read_excel('FFT1.xlsx', sheet_name='sheet1')
The file named 'FFT1.xlsx' is in the same directory as my jupyter notebook. The error message says:
XLRDError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7436/2793485739.py in <module>
----> 1 FFT1=pd.read_excel('FFT1.xlsx', sheet_name='sheet1')
D:\Softwares\Anaconda\lib\site-packages\pandas\io\excel\_base.py in read_excel(io, sheet_name, header, names, index_col, usecols, squeeze, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, verbose, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols, **kwds)
302
303 if not isinstance(io, ExcelFile):
--> 304 io = ExcelFile(io, engine=engine)
305 elif engine and engine != io.engine:
306 raise ValueError(
D:\Softwares\Anaconda\lib\site-packages\pandas\io\excel\_base.py in __init__(self, io, engine)
819 self._io = stringify_path(io)
820
--> 821 self._reader = self._engines[engine](self._io)
822
823 def __fspath__(self):
D:\Softwares\Anaconda\lib\site-packages\pandas\io\excel\_xlrd.py in __init__(self, filepath_or_buffer)
19 err_msg = "Install xlrd >= 1.0.0 for Excel support"
20 import_optional_dependency("xlrd", extra=err_msg)
---> 21 super().__init__(filepath_or_buffer)
22
23 #property
D:\Softwares\Anaconda\lib\site-packages\pandas\io\excel\_base.py in __init__(self, filepath_or_buffer)
351 self.book = self.load_workbook(filepath_or_buffer)
352 elif isinstance(filepath_or_buffer, str):
--> 353 self.book = self.load_workbook(filepath_or_buffer)
354 elif isinstance(filepath_or_buffer, bytes):
355 self.book = self.load_workbook(BytesIO(filepath_or_buffer))
D:\Softwares\Anaconda\lib\site-packages\pandas\io\excel\_xlrd.py in load_workbook(self, filepath_or_buffer)
34 return open_workbook(file_contents=data)
35 else:
---> 36 return open_workbook(filepath_or_buffer)
37
38 #property
D:\Softwares\Anaconda\lib\site-packages\xlrd\__init__.py in open_workbook(filename, logfile, verbosity, use_mmap, file_contents, encoding_override, formatting_info, on_demand, ragged_rows, ignore_workbook_corruption)
168 # files that xlrd can parse don't start with the expected signature.
169 if file_format and file_format != 'xls':
--> 170 raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')
171
172 bk = open_workbook_xls(
XLRDError: Excel xlsx file; not supported
How should I fix this?
Make sure that you already install openpyxl, if you don't try
pip install openpyxl
Change your code to
FFT1=pd.read_excel('FFT1.xlsx', sheet_name='sheet1',engine='openpyxl')

Trying to place a binance futures trailing stop order using python?

I have got so far,
#changing the margin
client.futures_change_margin_type(symbol = symbol_buy, marginType = 'ISOLATED')
#changing the leverage
client.futures_change_leverage(symbol = symbol_buy, leverage = 1)
shared.client.futures_create_order( symbol=symbol_buy, side = 'SELL', type='TRAILING_STOP_LOSS', quantity = 100)
and i'm thus getting this error below
BinanceAPIException Traceback (most recent call last)
in
3
4 #orderdetails_buy = shared.client_future.futures_create_order( symbol=symbol_buy, side = 'BUY', type='MARKET', quantity = 100)
----> 5 orderdetails_sell = shared.client_future.futures_create_order( symbol=symbol_buy, side = 'SELL', type='TRAILING_STOP_LOSS', quantity = 100)
6
C:\ProgramData\Anaconda3\lib\site-packages\binance\client.py in futures_create_order(self, **params)
5289
5290 """
-> 5291 return self._request_futures_api('post', 'order', True, data=params)
5292
5293 def futures_place_batch_order(self, **params):
C:\ProgramData\Anaconda3\lib\site-packages\binance\client.py in _request_futures_api(self, method, path, signed, **kwargs)
331 uri = self._create_futures_api_uri(path)
332
--> 333 return self._request(method, uri, signed, True, **kwargs)
334
335 def _request_futures_data_api(self, method, path, signed=False, **kwargs) -> Dict:
C:\ProgramData\Anaconda3\lib\site-packages\binance\client.py in _request(self, method, uri, signed, force_params, **kwargs)
307
308 self.response = getattr(self.session, method)(uri, **kwargs)
--> 309 return self._handle_response(self.response)
310
311 #staticmethod
C:\ProgramData\Anaconda3\lib\site-packages\binance\client.py in _handle_response(response)
316 """
317 if not (200 <= response.status_code < 300):
--> 318 raise BinanceAPIException(response, response.status_code, response.text)
319 try:
320 return response.json()
BinanceAPIException: APIError(code=-1116): Invalid orderType.
you've probably solved this by now but with binance futures, I don't think there is a TRAILING_STOP_LOSS trade type via API just yet, available order types are (from the docs):
Order types (orderTypes, type):
LIMIT
MARKET
STOP
STOP_MARKET
TAKE_PROFIT
TAKE_PROFIT_MARKET
TRAILING_STOP_MARKET
[https://binance-docs.github.io/apidocs/futures/en/#public-endpoints-info][1]

Selenium returning error: element not clickable

trying to scrape a website using selenium. the following code works fine.
import selenium
import numpy as np
from tqdm import tqdm
import time
import pandas as pd
from selenium import webdriver as wb
time.sleep(2)
driver=wb.Chrome('chromedriver.exe')
driver.maximize_window()
driver.get('https://www.jumia.co.ke/')
button = driver.find_element_by_xpath('//*[#id="jm"]/div[4]/section/button').click();
move=driver.find_element_by_xpath('//*[#id="jm"]/div[3]/button').click();
time.sleep(3)
clickObj=driver.find_element_by_xpath('//*
[#id="jm"]/main/div[1]/div[1]/div[1]/div/a[5]/span')
clickObj.click()
however am getting an error running code below, although the chrome driver clicks on the page: when I rerun again, the error disappears.
gash=driver.find_element_by_xpath('//*[#id="ctlg"]/div/div[2]/div/div/a[2]/p')
gash.click()
the error:
ElementClickInterceptedException Traceback (most recent call last)
<ipython-input-3-79a9b5b24451> in <module>
1 gash=driver.find_element_by_xpath('//*[#id="ctlg"]/div/div[2]/div/div/a[2]/p')
----> 2 gash.click()
~\anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py in click(self)
78 def click(self):
79 """Clicks the element."""
---> 80 self._execute(Command.CLICK_ELEMENT)
81
82 def submit(self):
~\anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py in _execute(self,
command, params)
631 params = {}
632 params['id'] = self._id
--> 633 return self._parent.execute(command, params)
634
635 def find_element(self, by=By.ID, value=None):
~\anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute(self,
driver_command, params)
319 response = self.command_executor.execute(driver_command, params)
320 if response:
--> 321 self.error_handler.check_response(response)
322 response['value'] = self._unwrap_value(
323 response.get('value', None))
~\anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py in
check_response(self, response)
240 alert_text = value['alert'].get('text')
241 raise exception_class(message, screen, stacktrace, alert_text)
--> 242 raise exception_class(message, screen, stacktrace)
243
244 def _value_or_default(self, obj, key, default):
ElementClickInterceptedException: Message: element click intercepted: Element is not
clickable at point (313, 748)
(Session info: chrome=87.0.4280.88)
how can I solve this error?
Kindly include an example
Use the following code to resolve this issue
browser.execute_script("arguments[0].click();", "name of button ")