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')
Related
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
I'm trying to export data from Google Search Console to Big Query using Python. However it keeps timing out and I keep getting the following error:
Traceback (most recent call last):
File "/Users/markleach/Python/GSC_BQ/gsc_bq.py", line 147, in <module>
y = get_sc_df(p,"2021-12-01","2022-12-01",x)
File "/Users/markleach/Python/GSC_BQ/gsc_bq.py", line 71, in get_sc_df
response = service.searchanalytics().query(siteUrl=site_url, body=request).execute()
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/googleapiclient/http.py", line 923, in execute
resp, content = _retry_request(
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/googleapiclient/http.py", line 222, in _retry_request
raise exception
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/googleapiclient/http.py", line 191, in _retry_request
resp, content = http.request(uri, method, *args, **kwargs)
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/google_auth_httplib2.py", line 218, in request
response, content = self.http.request(
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/httplib2/__init__.py", line 1720, in request
(response, content) = self._request(
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/httplib2/__init__.py", line 1440, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/site-packages/httplib2/__init__.py", line 1392, in _conn_request
response = conn.getresponse()
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/http/client.py", line 1377, in getresponse
response.begin()
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/http/client.py", line 320, in begin
version, status, reason = self._read_status()
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/http/client.py", line 281, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/socket.py", line 704, in readinto
return self._sock.recv_into(b)
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/ssl.py", line 1242, in recv_into
return self.read(nbytes, buffer)
File "/Users/markleach/opt/anaconda3/envs/Sandpit/lib/python3.9/ssl.py", line 1100, in read
return self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out
This is the code around the mentioned lines:
for p in PROPERTIES:
for x in range(0,100000,25000):
y = get_sc_df(p,"2021-12-01","2022-12-01",x)
if len(y) < 25000:
break
else:
continue
I'd be grateful for any advice on how to correct this. Thanks in advance.
Mark
ps whole code in picture format below as i'm not allowed to have more code than text
Script was timing out because of the size of the dataset required.
I need to fetch data from google cloud datastore using python, when fetching all the collection it succeed, but when try to fetch specific value according to the key it failed, I provide the store data method and fetch data method:
def store_data(name, value):
entity = datastore.Entity(key=datastore_client.key('visit', name))
entity.update({
'name': name,
'value': value
})
datastore_client.put(entity)
def fetch_name(name):
query = datastore_client.query(kind='visit')
print("name is: " + name)
# query.add_filter("name", "=", name)
results = list(query.fetch())
# print("GET - param is results: " + results)
return jsonify(results)
which mean, if I uncommit the line:
# query.add_filter("name", "=", name)
will get this error:
Traceback (most recent call last):
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/srv/main.py", line 107, in getVariable
times = fetch_times(name)
File "/srv/main.py", line 40, in fetch_times
results = list(query.fetch())
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/page_iterator.py", line 208, in _items_iter
for page in self._page_iter(increment=False):
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/page_iterator.py", line 244, in _page_iter
page = self._next_page()
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/cloud/datastore/query.py", line 610, in _next_page
response_pb = self.client._datastore_api.run_query(
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/cloud/datastore_v1/services/datastore/client.py", line 579, in run_query
response = rpc(
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/gapic_v1/method.py", line 154, in __call__
return wrapped_func(*args, **kwargs)
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/retry.py", line 283, in retry_wrapped_func
return retry_target(
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/retry.py", line 190, in retry_target
return target()
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 74, in error_remapped_callable
raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.FailedPrecondition: 400 no matching index found.
and the response return: Internal server error. How can fix that ?
I tried to add indexing from the UI of google cloud page - add index to name property.
You'll want to check the mode of your database (https://cloud.google.com/sdk/gcloud/reference/alpha/firestore/databases/describe). It's likely your database is in Firestore native mode instead of Firestore in Datastore mode. If so, you'll want to use the Firestore client libraries instead of the Datastore client libraries, or switch your database type to Datastore mode.
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.
First of all I know what the problem is, But I dont know why or how to fix it, I know that the function needs to pass a string to the database, I have a view function for create and edit, in the create part I have added "str" to the function to over come the problem but I dont know how to do this for the edit part. The form has a querySelectField which is correctly populated for the create part, and when I submit the "str" transforms the query result correctly.
So to over come the problem I have added "str" to the create part of the function, but I cannot see how to add this to the edit part with the 'populate.obj', also I expect the field to be populated with the data stored in the db when I created the form, but it is not. It is only this QuerySelectfield which is causing the problems. Here is some of my code.
#bp.route('/control/addheatingcircuit', methods=['GET', 'POST'])
#bp.route('/control/addheatingcircuit/<int:id>', methods=('GET',
'POST'))
#login_required
def addheatingcircuit(id=None):
if id is not None:
obj = Heatingcircuit.query.get(id) or Heatingcircuit()
form = AddHeatingcircuitForm(request.form, obj=obj)
if form.validate_on_submit():
form.populate_obj(obj)
db.session.add(obj)
db.session.commit()
return redirect(url_for('index.index'))
else:
form = AddHeatingcircuitForm()
if form.validate_on_submit():
heatingcircuit = Heatingcircuit(name=form.name.data,
sensor_ID1=str(form.sensor_ID1.data),\ #here i have added 'str'
pin_ID1=str(form.pin_ID1.data))
db.session.add(heatingcircuit)
db.session.commit()
flash('Congratulations, you are now a registered a new
device!')
return redirect(url_for('index.index'))
return render_template('control/addheatingcircuit.html', title=
'add edit heating circuit',
form=form)
forms.py
from wtforms_alchemy.fields import QuerySelectField
class AddHeatingcircuitForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
sensor_ID1 = QuerySelectField('sensor_ID1',
query_factory=lambda: Sensors.query.all(),
allow_blank=True, get_label='sensorID')
sensor_ID2 = QuerySelectField('sensor_ID2',
query_factory=lambda: Sensors.query.all(),
allow_blank=True, get_label='sensorID')
.....
models.py
class Heatingcircuit(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
sensor_ID1 = db.Column(db.String(30))
sensor_ID2 = db.Column(db.String(30))
sensor_ID3 = db.Column(db.String(30))
pin_ID1 = db.Column(db.Integer)
pin_ID2 = db.Column(db.Integer)
pin_ID3 = db.Column(db.Integer)
temp = db.Column(db.Float)
state = db.Column(db.String(9))
timer = db.relationship('Timers', backref='time')
def __repr__(self):
return '{}'.format(self.id)
I have looked at many questions on the forums but this is the closest match Flask WTF 'StringField' object has no attribute 'translate'
So as explained I expect the function on the edit an existing entry part to populate the form with the information already enregistered, and that when I change this and submit the populated form is excepted, instead I get this error message;
AttributeError: 'Heatingcircuit' object has no attribute 'translate'
(full error log possible if needed)
many thanks Paul
EDIT, I am looking at theis tutorial https://www.rithmschool.com/courses/flask-fundamentals/forms-with-wtforms
Here it talks about CSRF and a how to disable tokens for iterating over the form, Could my problem be this.
This problem affects SelectField as well.
Edit2
I tried the idea mentioned in the link http://wtforms.simplecodes.com/docs/0.6.1/ext.html#module-wtforms.ext.sqlalchemy.fields this code through an error "sqlalchemy.exc.InvalidRequestError: Entity '' has no property 'enabled'"
This is my code
def enabled_sensors():
return Sensors.query.filter_by(enabled=True)
But this failed to
EDIT ERROR
Traceback (most recent call last):
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pi/heating/venv/lib/python3.7/site-packages/flask_login/utils.py", line 261, in decorated_view
return func(*args, **kwargs)
File "/home/pi/heating/homeHeating/control/control.py", line 154, in addheatingcircuit
db.session.commit()
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1026, in commit
self.transaction.commit()
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 493, in commit
self._prepare_impl()
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 472, in _prepare_impl
self.session.flush()
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2451, in flush
self._flush(objects)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2589, in _flush
transaction.rollback(_capture_exception=True)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 129, in reraise
raise value
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2549, in _flush
flush_context.execute()
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute
rec.execute(self)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 589, in execute
uow,
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 236, in save_obj
update,
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 978, in _emit_update_statements
statement, multiparams
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
return meth(self, multiparams, params)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
distilled_params,
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
e, statement, parameters, cursor, context
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1468, in _handle_dbapi_exception
util.reraise(*exc_info)
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 129, in reraise
raise value
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1244, in _execute_context
cursor, statement, parameters, context
File "/home/pi/heating/venv/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 552, in do_execute
cursor.execute(statement, parameters)
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 168, in execute
query = self.mogrify(query, args)
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 147, in mogrify
query = query % self._escape_args(args, conn)
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 127, in _escape_args
return {key: conn.literal(val) for (key, val) in args.items()}
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 127, in <dictcomp>
return {key: conn.literal(val) for (key, val) in args.items()}
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/connections.py", line 467, in literal
return self.escape(obj, self.encoders)
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/connections.py", line 460, in escape
return converters.escape_item(obj, self.charset, mapping=mapping)
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/converters.py", line 27, in escape_item
val = encoder(val, mapping)
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/converters.py", line 118, in escape_unicode
return u"'%s'" % _escape_unicode(value)
File "/home/pi/heating/venv/lib/python3.7/site-packages/pymysql/converters.py", line 73, in _escape_unicode
return value.translate(_escape_table)
AttributeError: 'Sensors' object has no attribute 'translate'
I had this same error message for the second half of the "def addpin():" function, I resaerched and found that I needed to return a string so I added str(form.sensor_ID1.data) "str" and this solved the problem there But the first half of the function is the edit part and and I now have the problem there but dont know how to solve it.
the error is here I believe;
if id is not None:
obj = Heatingcircuit.query.get(id) or Heatingcircuit()
form = AddHeatingcircuitForm(request.form, obj=obj)
if form.validate_on_submit():
form.populate_obj(obj)
db.session.add(obj)
db.session.commit()
Thanks for the help
Warm regards
Paul
Two problems. First, QuerySelectField's query_factory argument takes a query, not a list of results. So take off the .all():
sensor_ID1 = QuerySelectField('sensor_ID1',
query_factory=lambda: Sensors.query,
allow_blank=True, get_label='sensorID')
Secondly, the data for the given form field is going to give you a Sensors object. So you can't just cast it, you need to ask it for its id. The same goes for the pin_ID1 field. How you do this will depend on how the Sensors class is declared:
heatingcircuit = Heatingcircuit(
name=form.name.data,
sensor_ID1=form.sensor_ID1.data.sensorID,
pin_ID1=form.pin_ID1.data.pinID
)