Traceback error while uploading file to dropbox in python - python

I am building a test upload api to check dropbox to build final project but I am getting this error when i run python file in cmd:
Traceback (most recent call last):
File "C:\Users\sufiy\Desktop\test.py", line 7, in <module>
dbx.files_upload(file_contents, '/testdropbox.txt', mode=dropbox.files.WriteMode.overwrite)
File "C:\Users\sufiy\AppData\Local\Programs\Python\Python311\Lib\site-packages\dropbox\base.py", line 3210, in files_upload
r = self.request(
^^^^^^^^^^^^^
File "C:\Users\sufiy\AppData\Local\Programs\Python\Python311\Lib\site-packages\dropbox\dropbox_client.py", line 326, in request
res = self.request_json_string_with_retry(host,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\sufiy\AppData\Local\Programs\Python\Python311\Lib\site-packages\dropbox\dropbox_client.py", line 476, in request_json_string_with_retry
return self.request_json_string(host,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\sufiy\AppData\Local\Programs\Python\Python311\Lib\site-packages\dropbox\dropbox_client.py", line 538, in request_json_string
raise TypeError('expected request_binary as binary type, got %s' %
TypeError: expected request_binary as binary type, got <class 'str'>
here is my code:
import dropbox
dbx = dropbox.Dropbox('my api key')
with open('testdropbox.txt', 'r') as f:
file_contents = f.read()
dbx.files_upload(file_contents, '/testdropbox.txt', mode=dropbox.files.WriteMode('overwrite'))
I tried to build a program that overwrite txt file every minute and I want it to work so I can schedule this by using windows task schedule

Related

Simple Python pytube code not working anymore

This is just simple Python code that worked when I first ran it, but didn't work the next day, even though I didn't change anything:
from pytube import YouTube
link = "https://www.youtube.com/watch?v=6_ardA6TuX0"
video = YouTube(link)
yt = video.streams.get_highest_resolution()
yt.download("Lieder")
I get this Error:
Traceback (most recent call last):
File "C:\Users\edonj\OneDrive\Desktop\Spot\main.py", line 9, in <module>
yt.download("Lieder")
File "C:\Users\edonj\OneDrive\Desktop\Spot\venv\lib\site-packages\pytube\streams.py", line 252, in download
for chunk in request.stream(
File "C:\Users\edonj\OneDrive\Desktop\Spot\venv\lib\site-packages\pytube\request.py", line 185, in stream
chunk = response.read()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 476, in read
s = self._safe_read(self.length)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 628, in _safe_read
raise IncompleteRead(b''.join(s), amt)
http.client.IncompleteRead: IncompleteRead(66612 bytes read, 9370572 more expected)
VideoUnavailable.
Proxy will help you.

How to save SHA256 object to a file?

(I'm doing all this in python 3.10.4 using pycryptodome)
I'm trying to do this process:
Get a hash of a file
Save that hash somewhere
Load that hash and perform RSA signing using a private key
I'm having a problem in step 3 where to save the hash, I have to save it as a string which doesn't work in Step 3.
I've tried using pickle but I'm getting
"ctypes objects containing pointers cannot be pickled"
Code generating the hash:
sha256 = SHA256.new()
with open(fileDir, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha256.update(data)
Code to perform the signing:
get_file(fileName + '.hash', directory)
with open(currentDir + '/client_files/downloaded/' + fileName + '.hash', 'r') as f:
hash_data = f.read()
with open(currentDir + '/client_files/private_key.pem', 'rb') as f:
private_key = RSA.importKey(f.read())
print(private_key)
signer = PKCS1_v1_5.new(private_key)
signature = signer.sign(hash_data)
The error I'm getting:
Traceback (most recent call last):
File "c:\Users\User\Documents\Coding\VSCode Projects\practiceGround\sec_cloud_project\client\client.py", line 168, in <module>
main()
File "c:\Users\User\Documents\Coding\VSCode Projects\practiceGround\sec_cloud_project\client\client.py", line 163, in main
sign(fileName, 'worker_test_files')
File "c:\Users\User\Documents\Coding\VSCode Projects\practiceGround\sec_cloud_project\client\client.py", line 120, in sign
signature = signer.sign(hash_data)
File "C:\Users\User\anaconda3\envs\nscc_project\lib\site-packages\Crypto\Signature\pkcs1_15.py", line 77, in sign
em = _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k)
File "C:\Users\User\anaconda3\envs\nscc_project\lib\site-packages\Crypto\Signature\pkcs1_15.py", line 191, in _EMSA_PKCS1_V1_5_ENCODE
digestAlgo = DerSequence([ DerObjectId(msg_hash.oid).encode() ])
AttributeError: 'str' object has no attribute 'oid'
Note that I'm currently saving the original hash as a string to a text file. If I try to use pickle to save the object as a whole I get this error
with open(currentDir + '/worker_files/sha256.pickle', 'wb') as f:
pickle.dump(sha256, f)
Traceback (most recent call last):
File "c:\Users\User\Documents\Coding\VSCode Projects\practiceGround\sec_cloud_project\worker\worker.py", line 188, in <module>
main()
File "c:\Users\User\Documents\Coding\VSCode Projects\practiceGround\sec_cloud_project\worker\worker.py", line 179, in main
hash_file(fileName, 'worker_test_files')
File "c:\Users\User\Documents\Coding\VSCode Projects\practiceGround\sec_cloud_project\worker\worker.py", line 55, in hash_file
pickle.dump(sha256, f)
ValueError: ctypes objects containing pointers cannot be pickled
Thanks to #Topaco. Changing to using Cyptography for both hashing and signing seemed to work.
Hashing with Cryptography, dumping to a file with pickle, then load and sign with Cryptography again.

Parsing GFF files throws TypeError

I am trying to parse a gif file with Biopython, and am using the sample code from their website. This is the code:
from BCBio import GFF
in_file = "infile.gff"
in_handle = open(in_file)
for rec in GFF.parse(in_handle):
print(rec)
in_handle.close()
When I run the code I get the following error:
Traceback (most recent call last):
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/Bio/SeqIO/Interfaces.py", line 47, in __init__
self.stream = open(source, "r" + mode)
TypeError: expected str, bytes or os.PathLike object, not FakeHandle
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "get_genes_dpt.py", line 37, in <module>
for rec in GFF.parse(in_handle):
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/BCBio/GFF/GFFParser.py", line 746, in parse
target_lines):
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/BCBio/GFF/GFFParser.py", line 322, in parse_in_parts
for results in self.parse_simple(gff_files, limit_info, target_lines):
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/BCBio/GFF/GFFParser.py", line 343, in parse_simple
for results in self._gff_process(gff_files, limit_info, target_lines):
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/BCBio/GFF/GFFParser.py", line 637, in _gff_process
for out in self._lines_to_out_info(line_gen, limit_info, target_lines):
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/BCBio/GFF/GFFParser.py", line 699, in _lines_to_out_info
fasta_recs = self._parse_fasta(FakeHandle(line_iter))
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/BCBio/GFF/GFFParser.py", line 560, in _parse_fasta
return list(SeqIO.parse(in_handle, "fasta"))
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/Bio/SeqIO/__init__.py", line 607, in parse
return iterator_generator(handle)
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/Bio/SeqIO/FastaIO.py", line 183, in __init__
super().__init__(source, mode="t", fmt="Fasta")
File "/Users/juliofdiaz/anaconda2/envs/python37/lib/python3.7/site-packages/Bio/SeqIO/Interfaces.py", line 51, in __init__
if source.read(0) != "":
TypeError: read() takes 1 positional argument but 2 were given
I am not sure how to fix the error as it seems I am passing a str and not a FakeHandle. I am running biopython 1.78 with conda.

TypeError when using remote_create using Facebook Python Business SDK

I am currently getting this error (along with most recent calls) when trying to run the remote_create method in the Facebook Python Business SDK:
Traceback (most recent call last):
File "ad_creator.py", line 41, in <module>
campaign.remote_create()
File "/usr/local/lib/python3.6/site-packages/facebook_business/adobjects/abstractcrudobject.py", line 296, in remote_create
response = request.execute()
File "/usr/local/lib/python3.6/site-packages/facebook_business/api.py", line 667, in execute
api_version=self._api_version,
File "/usr/local/lib/python3.6/site-packages/facebook_business/api.py", line 329, in call
if fb_response.is_failure():
File "/usr/local/lib/python3.6/site-packages/facebook_business/api.py", line 117, in is_failure
return not self.is_success()
File "/usr/local/lib/python3.6/site-packages/facebook_business/api.py", line 102, in is_success
return json_body['success']
TypeError: string indices must be integers
It appears the error is being thrown from the api.py file in the API:
https://github.com/facebook/facebook-python-business-sdk/blob/master/facebook_business/api.py
My code (after creating a Facebook session), is the following:
if __name__ == '__main__':
FacebookAdsApi.set_default_api(api)
account = AdAccount(config['act_id'])
print('**** Creating ad...')
campaign = Campaign(parent_id=account)
campaign.update({
Campaign.Field.name: 'My First Campaign',
Campaign.Field.objective: 'REACH',
})
campaign.remote_create()
print(campaign)
Please help me figure out what's causing the TypeError.

Error serving large files when using Flask and Tornado

I am serving large static files ~70 MB, I am able to download the files when working in flask alone, but I am getting the error below when using Tornado and flask.
Exception ignored in: <bound method Future.__del__ of <tornado.concurrent.Future object at 0x32c61acc>>
Traceback (most recent call last):
File "/home/user/virtual/lib/python3.4/site-packages/tornado/concurrent.py", line 333, in __del__
File "/usr/local/lib/python3.4/traceback.py", line 181, in format_exception
File "/usr/local/lib/python3.4/traceback.py", line 153, in _format_exception_iter
File "/usr/local/lib/python3.4/traceback.py", line 18, in _format_list_iter
File "/usr/local/lib/python3.4/traceback.py", line 65, in _extract_tb_or_stack_iter
File "/usr/local/lib/python3.4/linecache.py", line 15, in getline
File "/usr/local/lib/python3.4/linecache.py", line 41, in getlines
File "/usr/local/lib/python3.4/linecache.py", line 126, in updatecache
File "/usr/local/lib/python3.4/tokenize.py", line 437, in open
AttributeError: 'module' object has no attribute 'open'
Here is the code that I am using to serve files
def download(path):
def generate():
with open(path, 'rb') as file_handler:
while True:
chunk = file_handler.read(1024)
if not chunk:
break
yield chunk
return Response(generate(), direct_passthrough=True, mimetype='application/octet-stream',
headers={'Content-Disposition': 'attachment;filename={}'.format(os.path.basename(path))})
http_server = HTTPServer(WSGIContainer(APP))
http_server.listen(PORT, address='0.0.0.0')
IOLoop.instance().start()

Categories