So i wanna use a for loop in a query and pull results if a record's field is equal to an object's property (in a list of objects) how do i do that? This is my code:
you = session.query(Users).filter_by(id=login_session['userid']).first()
friends = session.query(Friends).filter_by(user_id=login_session['userid']).all()
dashboard = session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()
but then i get this:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pearadox6/travellr/app.py", line 423, in feed
dashboard = session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()
File "<string>", line 1, in <lambda>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 51, in generate
fn(self, *args[1:], **kw)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 1216, in filter
criterion = expression._literal_as_text(criterion)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/expression.py", line 1521, in _literal_as_text
"SQL expression object or string expected."
ArgumentError: SQL expression object or string expected.
Why?
Why?
Because you can't pass a generator object as an argument for filter:
session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()
Use in_ with a list instead:
session.query(Markers).filter(Markers.owner.in_([f.friend_id for f in friends)]).all()
Related
from Bio.PDB import *
import nglview as nv
import ipywidgets
pdb_parser = PDBParser()
structure = pdb_parser.get_structure("PHA-L", "C:\\Users\\asus\\Downloads\\1FAT.pdb")
view = nv.show_biopython(structure)
I was Expecting a plot of the protein structure
Below are the tracebacks
Traceback (most recent call last):
File "C:\Python311\Lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\asus\Desktop\Rscripts\app.py", line 15, in view
pdbview(path_file)
File "C:\Users\asus\Desktop\Rscripts\mol.py", line 12, in pdbview
r.source(path+"NGLviewer.R")
^^^^^^^^
File "C:\Python311\Lib\site-packages\rpy2\robjects\__init__.py", line 434, in __getattribute__
return self.__getitem__(attr)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\rpy2\robjects\__init__.py", line 440, in __getitem__
res = conversion.get_conversion().rpy2py(res)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\functools.py", line 909, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\rpy2\robjects\conversion.py", line 252, in _rpy2py
raise NotImplementedError(
NotImplementedError: Conversion 'rpy2py' not defined for objects of type '<class 'rpy2.rinterface.SexpClosure'>'
127.0.0.1 - - [28/Nov/2022 13:39:11] "GET / HTTP/1.1" 500 -
Hey I've been trying to encrypt some inputted data into a SQLalchemy database. However I keep receiving this error when trying to retrieve the decyrpted data from the database. Any help would be much appreciated.
key = Fernet.generate_key()
fernet = Fernet(key)
Encryption part:
fnam = str(form.first_name.data.lower())
Cfname = bytes(fnam, 'utf-8')
Efname = str(fernet.encrypt(Cfname))
lnam = str(form.last_name.data.lower())
Clname = bytes(lnam,'utf-8')
Elname = str(fernet.encrypt(Clname))
print(Efname)
print(Elname)
appoint.first_name =Efname
appoint.last_name = Elname
Decryption part:
info = user.query.filter_by(id=user.id).first()
finam = info.first_name
lanam = info.last_name
first = str(fernet.decrypt(bytes(finam,'utf-8')))
last = str(fernet.decrypt(bytes(lanam,'utf-8')))
Error message
Traceback (most recent call last):
File "appsec2\venv\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "appsec2\venv\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "appsec2\venv\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "appsec2\venv\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\txzsp\OneDrive\Documents\Poly sch stuff\Y2, S1\appsec2\venv\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "appsec2\venv\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "appsec2\appsec\routes.py", line 908, in retrieveConsultation
first = str(fernet.decrypt(bytes(finam,'utf-8')))
File appsec2\venv\lib\site-packages\cryptography\fernet.py", line 83, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "appsec2\venv\lib\site-packages\cryptography\fernet.py", line 115, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken
I'm currently porting a web app to Google App Engine, Python 3, Standard Environment. (So I'm new to GAE and NDB).
I have a bug here that I don't understand. I obtain an entity like so, the adjust properties, then save.
sourceUsers = User.query().filter(User.email == request.form.get('sourceUserEmail')).fetch(1)
if sourceUsers:
sourceUser = sourceUsers[0]
# manipulation:
sourceUser.sentInvitationSubscriptionKeys.append(subscription.key)
# verify key:
assert sourceUser.key != None
sourceUser.put()
But the saving triggers the following traceback:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/yanone/Code/Google App Engine/typeworldappengine/main.py", line 500, in api
sourceUser.put()
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/_options.py", line 89, in wrapper
return wrapped(*pass_args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/utils.py", line 78, in wrapper
return wrapped(*args, **new_kwargs)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/utils.py", line 109, in positional_wrapper
return wrapped(*args, **kwds)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 4914, in _put
return self._put_async(_options=kwargs["_options"]).result()
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/tasklets.py", line 190, in result
self.check_success()
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/tasklets.py", line 137, in check_success
raise self._exception
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/tasklets.py", line 312, in _advance_tasklet
yielded = self.generator.send(send_value)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 4974, in put
ds_entity = _entity_to_ds_entity(self)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 722, in _entity_to_ds_entity
names = prop._to_datastore(entity, data)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 2063, in _to_datastore
value = self._get_base_value_unwrapped_as_list(entity)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 1551, in _get_base_value_unwrapped_as_list
wrapped = self._get_base_value(entity)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 1537, in _get_base_value
return self._apply_to_values(entity, self._opt_call_to_base_type)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 1834, in _apply_to_values
value[:] = map(function, value)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 1612, in _opt_call_to_base_type
value = _BaseValue(self._call_to_base_type(value))
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 1671, in _call_to_base_type
return call(value)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 1801, in call
new_value = method(self, value)
File "/usr/local/lib/python3.7/site-packages/google/cloud/ndb/model.py", line 3344, in _validate
"Expected Key, got {!r}".format(value)
google.cloud.ndb.exceptions.BadValueError: Expected Key, got None
In the debugging, I even made sure that the entity has a key (assert sourceUser.key != None). So I really don't get it. What am I doing wrong?
Mind you, all other entities save fine. Just this one doesn't.
Thank you.
I dont think this entity's primary key is the problem. It's probably another Key field on the object.
Whats the schema for the rest of you User object?
I want to insert multiple records into Mysql using python.
I have tried something like:
if request.method == 'POST':
req_json = request.get_json(force=True)
dir(req_json)
#sys.exit()
g.cursor.execute("INSERT INTO gmr (version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10})",
(req_json[0]['version'], req_json[0]['visitorId'], req_json[0]['dwellTime'], req_json[0]['poiId'], req_json[0]['srId'], req_json[0]['zoneId'], req_json[0]['poiProximityConfidence'], req_json[0]['zoneProximityConfidence'], req_json[0]['poiPresenceConfidence'], req_json[0]['zonePresenceConfidence'], req_json[0]['normalizedTime']))
Im passing json objects like:
[
{
"dwellTime":"2",
"normalizedTime":"1489574977000",
"poiId":"poi3",
"poiPresenceConfidence":"15",
"poiProximityConfidence":"1",
"srId":"sr3",
"version":"15",
"visitorId":"V123",
"zoneId":"Security",
"zonePresenceConfidence":"40",
"zoneProximityConfidence":"20"
},
{
"dwellTime":"234234",
"normalizedTime":"1489574977000",
"poiId":"poi3",
"poiPresenceConfidence":"15",
"poiProximityConfidence":"1",
"srId":"sr3",
"version":"16",
"visitorId":"V123",
"zoneId":"Security",
"zonePresenceConfidence":"40",
"zoneProximityConfidence":"20"
}
]
I get the error like:
ProgrammingError: not all arguments converted during string formatting
Traceback (most recent call last): File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1997, in call return self.wsgi_app(environ, start_response)
File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e)
File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb)
File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request()
File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e)
File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request()
File "/root/python-mysql/venv/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functionsrule.endpoint
File "/root/python-mysql/venv/py_gmr.py", line 56, in add (req_json[0]['version'], req_json[0]['visitorId'], req_json[0]['dwellTime'], req_json[0]['poiId'], req_json[0]['srId'], req_json[0]['zoneId'], req_json[0]['poiProximityConfidence'], req_json[0]['zoneProximityConfidence'], req_json[0]['poiPresenceConfidence'], req_json[0]['zonePresenceConfidence'], req_json[0]['normalizedTime']))
File "/root/python-mysql/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 283, in executemany self.rowcount = sum(self.execute(query, arg) for arg in args)
File "/root/python-mysql/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 283, in self.rowcount = sum(self.execute(query, arg) for arg in args)
File "/root/python-mysql/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 240, in execute self.errorhandler(self, ProgrammingError, str(m))
File "/root/python-mysql/venv/lib/python2.7/site-packages/MySQLdb/connections.py", line 52, in defaulterrorhandler raise errorclass(errorvalue) ProgrammingError: not all arguments converted during string formatting
If I replace {0}, {1} with %s, only a single value gets inserted
You cannot use {} as placeholders in an SQL statement. You must use %s.
Using {} wouldn't fix your "problem" with only inserting a single set of values. That is to be expected, because you are only accessing the first set of values in your JSON. If you want to insert them both, you need to iterate over the values with a for loop and insert one set each time - as you would when trying to do anything with any list.
I am writing SQLAlchemy code that takes a search bar's input and runs a query against my PostgreSQL database. To allow for misspellings and name fragments, I had this code that did the trick:
q = session.query(Detail).filter((Detail.sellers.ilike("%%%s%%" % (name_input)))).all()
Now I am trying to do the same thing, but to check against a list names that has multiple input values. I've accomplished that like so:
q = session.query(Detail).filter((Detail.sellers.in_(names))
That requires exact matches, however. I would like to combine the ilike operator and the in_ operator. Is this possible? I've tried:
q = session.query(Detail).filter((Detail.sellers.ilike.in_(names))
That gives the following traceback and error:
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Tom/projects/land-records/repo/scripts/app.py", line 162, in search
return query_db(names)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask_cache/__init__.py", line 537, in decorated_function
rv = f(*args, **kwargs)
File "/Users/Tom/projects/land-records/repo/scripts/app.py", line 106, in query_db
q = session.query(Detail).filter((Detail.sellers.ilike.in_(names))).all()
AttributeError: 'function' object has no attribute 'in_'
If it's just about the case insensitive 'in_' statement:
from sqlalchemy import func
q = session.query(Detail).filter(
func.lower(Detail.sellers).in_(map(str.lower, names))
)
Otherwise, if you wanted to have multiple 'ilike' statements,
from sqlalchemy import or_
conditions = []
for name in names:
conditions.append(Detail.sellers.ilike('%{}%'.format(name)))
q = session.query(Detail).filter(
or_(*conditions)
)
I haven't tested it, in case it didn't work, I can edit it.