I am trying to get account information, specifically my USDT balance to calculate the percentage (%) and I get the following error:
File "c:\Users\hecto\OneDrive\Escritorio\Bot Definitivo\bot.py", line 64, in
account_info = binance_client.futures_account()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hecto\OneDrive\Escritorio\Bot Definitivo\botdefinitivo\Lib\site-packages\binance\client.py", line 6063, in futures_account
return self._request_futures_api('get', 'account', True, data=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hecto\OneDrive\Escritorio\Bot Definitivo\botdefinitivo\Lib\site-packages\binance\client.py", line 339, in _request_futures_api
return self._request(method, uri, signed, True, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hecto\OneDrive\Escritorio\Bot Definitivo\botdefinitivo\Lib\site-packages\binance\client.py", line 315, in _request
return self._handle_response(self.response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hecto\OneDrive\Escritorio\Bot Definitivo\botdefinitivo\Lib\site-packages\binance\client.py", line 324, in _handle_response
raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-1021): Timestamp for this request is outside of the recvWindow.
I have made different modifications and nothing has worked for me yet so that my code runs normally.
Check:
account_info = binance_client.futures_account()
amount = percent_amount * account_info['balance']
With this I try to obtain the balance to calculate the amount with which it will enter the operation based on % of the account, I need help
Related
I'd like to request aggregated trade data beginning at a certain timestamp until now
client.get_aggregate_trades(symbol = 'EURBUSD', startTime = 165605516493)
but i only get an Error:
File "c:\Users\Pascal\Python Skripts\Binance\test.py", line 39, in
aggregate = client.get_aggregate_trades(symbol = ticker, startTime = 165605516493)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 743, in get_aggregate_trades
return self._get('aggTrades', data=params, version=self.PRIVATE_API_VERSION)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 371, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 334, in _request_api
return self._request(method, uri, signed, **kwargs)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 315, in _request
return self._handle_response(self.response)
File "C:\Users\Pascal\AppData\Local\Programs\Python\Python310\lib\site-packages\binance\client.py", line 324, in _handle_response
raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-1128): Combination of optional parameters invalid.
Even if i input all possible parameters (start and end time less than 1 hour), it still throws the same Error. What am i missing here?
Thank you a lot for helping.
I had the same problem.
I fixed it by adding an "endTime" parameter to the "get_aggregate_trades".
client.get_aggregate_trades(symbol='BTCUSDT', startTime='1534130155000', endTime='1534130169000')
I have a django view that causes FOREIGN KEY constraint failed. This is coming from a related question
def return_book(request,pk):
books = Books.objects.filter(school = request.user.school).get(id = pk)
book = Issue.objects.get(book_id_id=pk,book_id__school_id = request.user.school.id)
user = CustomUser.objects.get(id=request.user.id)
Return.objects.create(borrowed_item_id=book.id,returner=user)
Books.Addbook(books)
Issue.objects.get(book_id_id=pk).delete()
return redirect("view_books")
The erro is returned at Issue.objects.get(book_id_id=pk).delete()
I don't know the exact cause of this error. Could somebody explain to me what's going on hat causes the error>
The Traceback is below.
Traceback (most recent call last):
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\views.py", line 209, in return_book
Issue.objects.get(book_id_id=pk).delete()#Borrower_id is also required in the filter
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 947, in delete
return collector.delete()
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\deletion.py", line 396, in delete
count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 43, in delete_batch
num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 23, in do_query
cursor = self.get_compiler(using).execute_sql(CURSOR)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
class Issue(models.Model):
borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE)
book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
issue_date = models.DateField(default=datetime.date.today)
issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE)
class Return(models.Model):
return_date = models.DateField(default=datetime.date.today)
borrowed_item = models.ForeignKey(Issue,on_delete=models.DO_NOTHING)
returner = models.ForeignKey(CustomUser,on_delete=models.DO_NOTHING)
Do DO_NOTHING is typically not a good option since (most) databases will check referential integrity. This means that they guarantee that if a ForeignKey refers (in this case to an Issue), then that means that the table that stores the issues should have a record with the primary key the Return item refers to.
Often DO_NOTHING is used in combination with a certain trigger in the database system (that Django is not aware of).
Typically the most popular choices foron_delete are:
models.CASCADE: in that case it will remove all Returns related to the removed item;
models.PROTECT: in that case it will raise an error to prevent removing the Issue; and
models.SET_NULL: this is done on a NULLable field (so with null=Ture), in which case the impacted Return(s) will set the field to NULL/None.
Another option might be to "soft delete" records, for example with the django-soft-delete package [pypi]. In that case a boolean is added to the Issue that specifies if the item is removed. The package will also transparently filter the objects, such that you only retrieve records that are "alive".
This edge case is not directly relevant for the OP, but may help others that wind up here based on the title:
An IntegrityError: FOREIGN KEY constraint failed will also be raised when trying to delete some object x, if there is a table in your database that Django is unaware of, and this table has a reference to object x.
This can happen, for example, if you remove a model from your code without properly migrating the changes.
As a result, the table remains in the database, but Django does not know anything about it, so, when object x is deleted, Django does not know it should also delete the corresponding row from this "orphaned" table.
I am using django-pgcrypto package to work with encripted data. In documentation says that is possible to filter on encrypted fields as you would normal fields via exact, gt, gte, lt, and lte lookups this package for encryption.
Model:
class Profiles(BaseModel):
first_name = EncryptedCharField(max_length=255, null=True)
last_name = EncryptedCharField(max_length=255, null=True)
postal_code = models.CharField(max_length=32, null=True)
skype = EncryptedCharField(max_length=255, null=True)
email = EncryptedCharField(max_length=255, null=True)
...
Example of query:
email = Profiles.objects.filter(email__exact='example#email.com')
Error:
Traceback (most recent call last):
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedFunction: function dearmor(text) does not exist
LINE 1: ...irmed" FROM "profiles" WHERE convert_from(decrypt(dearmor("p...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/Projects/rab/rentautobus-site/uService2/traveler/views.py", line 206, in conversations
print(email)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 250, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__
self._fetch_all()
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1097, in execute_sql
cursor.execute(sql, params)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: function dearmor(text) does not exist
LINE 1: ...irmed" FROM "profiles" WHERE convert_from(decrypt(dearmor("p...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
If you read the documentation, it says here:
You must also make sure the pgcrypto extension is installed in your database. Django makes this easy with a CryptoExtension migration.
Your error log shows that you have yet to do this, and Django's documentation covers how to create a PostgreSQL extension in your database using a migration file CryptoExtension migration here.
The operation on your migration file looks like:
from django.contrib.postgres.operations import CryptoExtension
class Migration(migrations.Migration):
...
operations = [
CryptoExtension(),
...
]
Note that you have to set up the crypto extension in PostgreSQL before the first CreateModel or AddField operation that involves EncryptedCharField; So run this migration with the CryptoExtension operation before your you introduce EncryptedCharField.
If you rather not do it with a migration file, you can install the pgcrypto extension on your database directly. Assuming you're on PostgreSQL 9.1+, the [answer] here shows you how to install that extension on linux systems that use apt (or apt-get). Copying from Dustin's answer (linked to above),
sudo apt-get install postgresql-contrib
Once installation is completed, run this in your psql shell:
postgres#ztrustee:~$ psql test
psql (9.1.3)
Type "help" for help.
test=# CREATE EXTENSION pgcrypto;
CREATE EXTENSION
Once that is done, run your Django migrations again.
I'm an aws python newbie and trying to account for total bucket size shown via metrics tab on UI vs calculating sizes one folder at a time in a give bucket. I tried to fetch it by setting an inventory configuration but it doesn't show what I'm looking for.
I have an s3 bucket names my_bucket with versioning enabled.
It has 100 Objects and 26 subfolders (will 100000+ objects in each subfolder and atleast two versions for each of the object)
WHAT I AM TRYING TO DO:
Calculate and display total size including versions for each of the 180 subfolders.
A Size 1GB
B Size 10TB
.
.
.
Z Size 13TB
HOW I AM TRYING TO DO
Find a solution which combines
the profile based authentication from link one and use the bucket.object_versions
with the level one folder size calculation from link 2
while also taking into consideration the versions. (Link2 doesn't have versions)
Link1 https://stackoverflow.com/a/58125684/4590025
Link2 https://stackoverflow.com/a/49763268/4590025
import boto3
PROFILE = "my_profile"
BUCKET = "my_bucket"
session = boto3.Session(profile_name = PROFILE)
s3 = session.resource('s3')
bucket = s3.Bucket(BUCKET)
#bucket.object_versions.do_something_with_it
conn = boto3.client('s3')
top_level_folders = dict()
for key in conn.list_objects(Bucket='my_bucket')['Contents']:
folder = key['Key'].split('/')[0]
print("Key %s in folder %s. %d bytes" % (key['Key'], folder, key['Size']))
if folder in top_level_folders:
top_level_folders[folder] += key['Size']
else:
top_level_folders[folder] = key['Size']
for folder, size in top_level_folders.items():
print("Folder: %s, size: %d" % (folder, size))
I also referred to https://stackoverflow.com/a/48867829 and I'm not sure how to go about utilizing the two and Currently when I run it I get below error despite setting the session:
Traceback (most recent call last):
File ".\folder_size.py", line 17, in <module>
for key in conn.list_objects(Bucket='my_bucket')['Contents']:
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\client.py", line 316, in _api_call
return self._make_api_call(operation_name, kwargs)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\client.py", line 622, in _make_api_call
operation_model, request_dict, request_context)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\client.py", line 641, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\endpoint.py", line 132, in _send_request
request = self.create_request(request_dict, operation_model)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\endpoint.py", line 116, in create_request
operation_name=operation_model.name)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\hooks.py", line 356, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\hooks.py", line 228, in emit
return self._emit(event_name, kwargs)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\hooks.py", line 211, in _emit
response = handler(**kwargs)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\signers.py", line 90, in handler
return self.sign(operation_name, request)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\signers.py", line 160, in sign
auth.add_auth(request)
File "C:\Users\ginger\AppData\Local\Programs\Python\Python37\lib\site-packages\botocore\auth.py", line 357, in add_auth
raise NoCredentialsError
botocore.exceptions.NoCredentialsError: Unable to locate credentials
PS C:\Users\ginger\test>
The issue is that the program uses:
conn = boto3.client('s3')
This is ignoring the profile that was set earlier:
session = boto3.Session(profile_name = PROFILE)
Thus, if you want to create an S3 client with the profile, then it should use:
conn = session.client('s3')
To avoid the problem with pagination, you could use the resource method to retrieve all objects:
for object in bucket.objects.all():
folder = object.key.split('/')[0]
print("Key %s in folder %s. %d bytes" % (object.key, folder, object.size))
...
I’m creating a django based web app and I have used Auth > User model (without any customization except password hiding) and for user detail I have created another model ChangeShift. and model based form.
Case 1: When I am using alluser = ShiftChange.objects.all() I'm able to see all the data available in ShiftChange model.
Case 2: Now I want that when user is logging, he should be able to see data related to his name and I'm using this:
def retrieve_view(request):
# alluser = ShiftChange.objects.all()
alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username)
return render(request, 'apple/shift2.html', {'alluser': alluser})
For this code I am getting error:
cannot unpack non-iterable bool object
Error Traceback:
[21/Sep/2020 11:13:18] "GET /static/css/auth.css HTTP/1.1" 404 1662
Internal Server Error: /alldata/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/shaileshyadaav/djangoshaileshdurga/mapsIT/apple/views.py", line 53, in retrieve_view
alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1255, in build_filter
arg, value = filter_expr
TypeError: cannot unpack non-iterable bool object
The line:
alluser = ShiftChange.objects.filter(
ShiftChange.ldap_id == request.user.username)
is the error. The part ShiftChange.ldap_id == request.user.username is an expression that evaluates to True or False, and then your code becomes equivalent to
alluser = ShiftChange.objects.filter(True)
or
alluser = ShiftChange.objects.filter(False)
and that is probably not what you want.
Try using a single = sign and use a valid left side kwarg (because ShiftChange.ldap_id with the dot in the middle is not valid here).
So your code may end up similar to this:
alluser = ShiftChange.objects.filter(ldap_id=request.user.username)