Consider an ORM class describing a "Store":
class Store(Base, AbstractSchema):
__tablename__ = 'store'
id = Column(Integer, primary_key=True)
...
s2_cell_id = Column(BigInteger, unique=False, nullable=True)
s2_cell_id describes the location of a store as an id of S2 cell i.e Google S2 I am using s2sphere library in python for that.
Goal is to write a query that searches for stores in a certain range. I tried to use #hybrid_method as follows:
#hybrid_method
def lies_inside(self, cells : list[Cell]):
for c in cells:
is_inside = c.contains(Cell(CellId(self.s2_cell_id)))
if is_inside : return True
return False
#lies_inside.expression
def lies_inside(cls, cells: list[Cell]):
for c in cells:
is_inside = c.contains(Cell(CellId(cls.s2_cell_id)))
if is_inside : return True
return False
Usage is like this:
# Compute the set of cell that intersect the search area
candidates = router.location_manager.get_covering_cells(lat, lng, r, 13)
# Query the database for stores whose cell IDs are in the set of intersecting cells
query = db.query(Store).filter(Store.lies_inside(candidates)).all()
I get the following error unfortunately:
Traceback (most recent call last):
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 419, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\fastapi\applications.py", line 270, in __call__
await super().__call__(scope, receive, send)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
raise exc
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
raise exc
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
raise e
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\routing.py", line 706, in __call__
await route.handle(scope, receive, send)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\routing.py", line 276, in handle
await self.app(scope, receive, send)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\routing.py", line 66, in app
response = await func(request)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\fastapi\routing.py", line 235, in app
raw_response = await run_endpoint_function(
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\fastapi\routing.py", line 163, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\starlette\concurrency.py", line 41, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\anyio\to_thread.py", line 31, in run_sync
return await get_asynclib().run_sync_in_worker_thread(
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\anyio\_backends\_asyncio.py", line 937, in run_sync_in_worker_thread
return await future
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\anyio\_backends\_asyncio.py", line 867, in run
result = context.run(func, *args)
File "C:\Users\FARO-User\Desktop\personal\dev\repos\woher-backend\.\src\routers\search.py", line 33, in get_nearby_stores
query = db.query(Store).filter(Store.lies_inside(candidates)).all()
File "c:\users\faro-user\desktop\personal\dev\repos\woher-backend\src\sql\models\store.py", line 55, in lies_inside
is_inside = c.contains(Cell(CellId(cls.s2_cell_id)))
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\s2sphere\sphere.py", line 2354, in __init__
face, i, j, orientation = cell_id.to_face_ij_orientation()
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\s2sphere\sphere.py", line 1298, in to_face_ij_orientation
face = self.face()
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\s2sphere\sphere.py", line 1057, in face
return self.id() >> self.__class__.POS_BITS
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\sqlalchemy\sql\operators.py", line 458, in __rshift__
return self.operate(rshift, other)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\sqlalchemy\sql\elements.py", line 868, in operate
return op(self.comparator, *other, **kwargs)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\sqlalchemy\sql\operators.py", line 458, in __rshift__
return self.operate(rshift, other)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\sqlalchemy\sql\type_api.py", line 77, in operate
return o[0](self.expr, op, *(other + o[1:]), **kwargs)
File "C:\Users\FARO-User\Anaconda3\envs\woher-backend\lib\site-packages\sqlalchemy\sql\default_comparator.py", line 181, in _unsupported_impl
raise NotImplementedError(
NotImplementedError: Operator 'rshift' is not supported on this expression
Any idea how to design such query appropriately?
Some Analysis:
The issue occurs because internally in s2sphere, this line is computed somewhere which appears in the traceback as well: return self.id() >> self.__class__.POS_BITS which clashes with sqlalchemy
Related
I am new to python and fastapi, and was playing around it.
I wrote this code
from fastapi import FastAPI
app = FastAPI()
people = {
"1": {
"name": "abc",
"age": 27
},
"2": {
"name": "xyz",
"age": 60
}
}
#app.get("/")
def read_root():
return {"Hello": "World"}
#app.get("/people/")
def get_people(
min_age: int=0, max_age: int=100
):
results = [person for person in people.values() if person["age"] >= min_age and person["age"] <= max_age]
return results
#app.get("/people/{person_id}")
def get_person(person_id: int):
return people[person_id]
but on calling #app.get("/people/{person_id}") I am getting 500 error with this as traceback
Traceback (most recent call last):
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/applications.py", line 270, in __call__
await super().__call__(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
raise exc
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
raise e
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/routing.py", line 706, in __call__
await route.handle(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/routing.py", line 276, in handle
await self.app(scope, receive, send)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/routing.py", line 66, in app
response = await func(request)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/routing.py", line 235, in app
raw_response = await run_endpoint_function(
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/fastapi/routing.py", line 163, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/starlette/concurrency.py", line 41, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/anyio/to_thread.py", line 31, in run_sync
return await get_asynclib().run_sync_in_worker_thread(
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 937, in run_sync_in_worker_thread
return await future
File "/Users/abcB/Desktop/fastapi-tutorial/env/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 867, in run
result = context.run(func, *args)
File "/Users/abcB/Desktop/fastapi-tutorial/./main.py", line 31, in get_person
return people[person_id]
Can someone point me on what I am doing wrong here?
In your dictionary "people" you have declared the "id" (the keys) as strings.
However in the path operation of #app.get("/people/{person_id}") you have declared the person_id as an int. That's why the error occurs. Remember that pydantic uses these type declarations for data validation.
The correct thing would then be:
#app.get("/people/{person_id}")
def get_person(person_id: str):
return people[person_id]
I have the following sqlalchemy model:
class Person(Base):
__tablename__ = 'Person'
index = Column(BigInteger, index=True)
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
first_name = Column(String(50))
last_name = Column(String(50))
occupation = Column(String(50))
dob = Column(Date)
country = Column(String(30))
When I try to query Person based on first_name and last_name as follows:
session.query(Person).filter(and_(
Person.first_name == request.first_name,
Person.last_name == request.last_name,
)).first()
I got the following error:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: text = uuid
LINE 3: WHERE "Person".id = '7bcc3d89-0660-4d64-adca-620132fe88f8'::...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
[SQL: SELECT "Person".index, "Person".id, "Person".first_name, "Person".last_name, "Person".occupation, "Person".dob, "Person".country
FROM "Person"
WHERE "Person".id = %(pk_1)s]
[parameters: {'pk_1': UUID('7bcc3d89-0660-4d64-adca-620132fe88f8')}]
(Background on this error at: https://sqlalche.me/e/14/f405)
In a similar SA question the suggestion was to cast the datatype of both sides of the comparison in filter() to be the same. However, here I'm just trying to find a person info based on first_name and last_name and uuid is not a condition for filtering.
Could you show me a way to solve this? Thank you!
Edit
Below is my complete error traceback:
INFO: 127.0.0.1:53060 - "POST /person HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 404, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\uvicorn\middleware\debug.py", line 106, in __call__
raise exc from None
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\uvicorn\middleware\debug.py", line 103, in __call__
await self.app(scope, receive, inner_send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\fastapi\applications.py", line 270, in __call__
await super().__call__(scope, receive, send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
raise exc
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\middleware\cors.py", line 92, in __call__
await self.simple_response(scope, receive, send, request_headers=headers)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\middleware\cors.py", line 147, in simple_response
await self.app(scope, receive, send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\middleware\exceptions.py", line 75, in __call__
raise exc
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\middleware\exceptions.py", line 64, in __call__
await self.app(scope, receive, sender)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
raise e
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\routing.py", line 680, in __call__
await route.handle(scope, receive, send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\routing.py", line 275, in handle
await self.app(scope, receive, send)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\routing.py", line 65, in app
response = await func(request)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\fastapi\routing.py", line 231, in app
raw_response = await run_endpoint_function(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\fastapi\routing.py", line 162, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\starlette\concurrency.py", line 41, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\anyio\to_thread.py", line 31, in run_sync
return await get_asynclib().run_sync_in_worker_thread(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 937, in run_sync_in_worker_thread
return await future
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 867, in run
result = context.run(func, *args)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\project_name\service_name\routes.py", line 29, in create_data
new_data = services.create_data_in_db(session, request)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\project_name\service_name\services.py", line 29, in create_data_in_db
session.refresh(new_data)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2338, in refresh
loading.load_on_ident(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\orm\loading.py", line 407, in load_on_ident
return load_on_pk_identity(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\orm\loading.py", line 530, in load_on_pk_identity
session.execute(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1712, in execute
result = conn._execute_20(statement, params or {}, execution_options)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1705, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 333, in _execute_on_connection
return connection._execute_clauseelement(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1572, in _execute_clauseelement
ret = self._execute_context(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1943, in _execute_context
self._handle_dbapi_exception(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2124, in _handle_dbapi_exception
util.raise_(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1900, in _execute_context
self.dialect.do_execute(
File "D:\PythonProjects\FastAPI\Reusable\ProjectTemplate\venv\lib\site-packages\sqlalchemy\engine\default.py", line 736, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: text = uuid
LINE 3: WHERE "Person".index IS NULL AND "Person".id = '5076819f-2a8...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
[SQL: SELECT "Person".index, "Person".id, "Person".first_name, "Person".last_name, "Person".occupation, "Person".dob, "Person".country
FROM "Person"
WHERE "Person".index IS NULL AND "Person".id = %(pk_2)s]
[parameters: {'pk_2': UUID('5076819f-2a88-4d7e-b2bf-f9ab4734ab98')}]
(Background on this error at: https://sqlalche.me/e/14/f405)
In the update,and delete route,and now in Like and Dislike in the api (fastapi) it's giving the same error->mongoengine.errors.InvalidQueryError: Cannot resolve field "id",so to be simpler I'll just use Like as an example,the schema is
ps : if you're asking yourself,yes I already tried giving it id field and alias with _id and all possibilities that I could think
class Like(BaseModel):
user_id: str
post_id: str
The route is
#router.post("/like", status_code=201)
def like(like_data: schemas.Like, current_user: int = Depends(oauth2.get_current_user)):
new_like = Likes()
new_like.user_id = like_data.user_id
post_of_the_like = Post.objects(_id=like_data.post_id)
post_of_the_like.likes.append(new_like)
post_of_the_like.save()
return {"message": "successfully added like"}
and the model is
class Likes(mongoengine.EmbeddedDocument):
user_id = mongoengine.ObjectIdField(required=True)
class Post(mongoengine.Document):
_id = mongoengine.StringField(default=str(uuid.uuid4()),)
title = mongoengine.StringField(required=True)
content = mongoengine.StringField(required=True)
published = mongoengine.BooleanField(required=True, default=True)
created_at = mongoengine.DateTimeField(default=datetime.datetime.now)
likes = mongoengine.EmbeddedDocumentListField(Likes)
dislikes = mongoengine.EmbeddedDocumentListField(Dislikes)
comments = mongoengine.EmbeddedDocumentListField(Comment)
type = mongoengine.StringField(required=True, default="post")
about = mongoengine.StringField(default="The creater did not put an about")
tags = mongoengine.ListField(mongoengine.StringField())
banner = mongoengine.StringField(required=False)
meta = {
"db_alias": "jc",
"collection": "posts",
}
and the whole message error is
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\mongoengine\queryset\transform.py", line 91, in query
fields = _doc_cls._lookup_field(parts)
File "C:\Python39\lib\site-packages\mongoengine\base\document.py", line 1107, in _lookup_field
raise LookUpError('Cannot resolve field "%s"' % field_name)
mongoengine.errors.LookUpError: Cannot resolve field "id"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "C:\Python39\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "C:\Python39\lib\site-packages\fastapi\applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "C:\Python39\lib\site-packages\starlette\applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\Python39\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
raise exc
File "C:\Python39\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "C:\Python39\lib\site-packages\starlette\middleware\cors.py", line 84, in __call__
await self.app(scope, receive, send)
File "C:\Python39\lib\site-packages\starlette\exceptions.py", line 82, in __call__
raise exc
File "C:\Python39\lib\site-packages\starlette\exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "C:\Python39\lib\site-packages\starlette\routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "C:\Python39\lib\site-packages\starlette\routing.py", line 259, in handle
await self.app(scope, receive, send)
File "C:\Python39\lib\site-packages\starlette\routing.py", line 61, in app
response = await func(request)
File "C:\Python39\lib\site-packages\fastapi\routing.py", line 216, in app
solved_result = await solve_dependencies(
File "C:\Python39\lib\site-packages\fastapi\dependencies\utils.py", line 527, in solve_dependencies
solved = await run_in_threadpool(call, **sub_values)
File "C:\Python39\lib\site-packages\starlette\concurrency.py", line 39, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "C:\Python39\lib\site-packages\anyio\to_thread.py", line 28, in run_sync
return await get_asynclib().run_sync_in_worker_thread(func, *args, cancellable=cancellable,
File "C:\Python39\lib\site-packages\anyio\_backends\_asyncio.py", line 805, in run_sync_in_worker_thread
return await future
File "C:\Python39\lib\site-packages\anyio\_backends\_asyncio.py", line 743, in run
result = func(*args)
File "C:\Users\invis\OneDrive\Área de Trabalho\jc_api\.\app\oauth2.py", line 40, in get_current_user
user=User.objects(id=token_id).first()
File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 290, in first
result = queryset[0]
File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 200, in __getitem__
queryset._cursor[key],
File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 1645, in _cursor
self._cursor_obj = self._collection.find(self._query, **self._cursor_args)
File "C:\Python39\lib\site-packages\mongoengine\queryset\base.py", line 1694, in _query
self._mongo_query = self._query_obj.to_query(self._document)
File "C:\Python39\lib\site-packages\mongoengine\queryset\visitor.py", line 91, in to_query
query = query.accept(QueryCompilerVisitor(document))
File "C:\Python39\lib\site-packages\mongoengine\queryset\visitor.py", line 184, in accept
return visitor.visit_query(self)
File "C:\Python39\lib\site-packages\mongoengine\queryset\visitor.py", line 80, in visit_query
return transform.query(self.document, **query.query)
File "C:\Python39\lib\site-packages\mongoengine\queryset\transform.py", line 93, in query
raise InvalidQueryError(e)
mongoengine.errors.InvalidQueryError: Cannot resolve field "id"
If anyone could give a hint or opinion of what should help I would appreciate a lot,I searched through github but all examples are either flask or django and use methods that don't apply to this case,and even if you can't help,thanks for reading still here
Few things are wrong in your code snippet but hopefully you'll find the answer below:
class Post(mongoengine.Document):
_id = mongoengine.StringField(default=str(uuid.uuid4()),)
unrelated with your problem but default should be a callable, otherwise it gets evaluated once and will return the same value all the time
You should avoid using "_id" to name your field, "_id" is something used internally by mongoengine.
Set primary_key=True on the key that is supposed to be the primary key (i.e what gets saved in the document as "_id" when translating MongoENgine -> pymongo document)
Typically your primary key should be defined like (below is the default id that gets defined if you don't provide one)
id = ObjectIdField(default=ObjectId, primary_key=True)
I am new to FastAPI and I am stuck at fastapi's put method. I am following a certain tutorial.
Here is the code:
#app.put("/blog/{blog_id}", status_code=status.HTTP_202_ACCEPTED)
def update(blog_id: int, request: schemas.Blog,
db: Session = Depends(get_db)):
blog = db.query(models.Blog).filter(models.Blog.id == blog_id)
if blog.first() is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="Blog not found")
blog.update(request, synchronize_session=False)
db.commit()
return 'Blog updated'
#app.patch("/blog/{blog_id}", status_code=status.HTTP_202_ACCEPTED)
def partial_update(blog_id: int, request: schemas.Blog,
db: Session = Depends(get_db)):
blog = db.query(models.Blog).filter(models.Blog.id == blog_id)
if blog.first() is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="Blog not found")
blog.update(request, synchronize_session=False)
db.commit()
return 'Blog updated'
but the thing it is not updating the contents and is giving error 500 if I try to update it.
In console following error is shown:
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/routing.py", line 566, in __call__
await route.handle(scope, receive, send)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/fastapi/routing.py", line 201, in app
raw_response = await run_endpoint_function(
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/fastapi/routing.py", line 150, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
return await loop.run_in_executor(None, func, *args)
File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/satvir/Documents/dev/FastApi_Tutorial/./Blog/main.py", line 64, in update
blog.update(request, synchronize_session=False)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 3204, in update
upd = upd.values(values)
File "<string>", line 2, in values
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/sql/base.py", line 106, in _generative
x = fn(self, *args, **kw)
File "<string>", line 2, in values
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/sql/base.py", line 135, in check
return fn(self, *args, **kw)
File "/home/satvir/Documents/dev/FastApi_Tutorial/.env/lib/python3.9/site-packages/sqlalchemy/sql/dml.py", line 701, in values
for k, v in arg.items()
AttributeError: 'Blog' object has no attribute 'items'
schemas.Blog:
class Blog(BaseModel):
title: str
content: str
models.Blog:
class Blog(Base):
__tablename__ = "blogs"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
description = Column(String)
Everything else: creating, retrieving, deleting methods are working fine.
Please help me what to do??
The solution is to change blog.update(request, synchronize_session=False) in your update function to :
blog.update(request.__dict__, synchronize_session=False)
I'll explain why.
From the error message provided, sqlalchemy is attempting to loop over a dictionary, hence it gives that error message when it cannot find a dict type.
The request parameter in blog.update() method is of type Class. To confirm, add this line of code after your if statement:
print(type(request))
You should get an output similar to:
<class 'blog.schemas.Blog'>
Hence, the error. Now do this: print(type(request.__dict__)). Your output should be similar to this: <class 'dict'> which solves the problem.
I'm trying to run a simulation of a FWI(Full waveform inversion) with Devito, following this tutorial in a distributed system with Dask. Bellow a certain number of receivers(around 80) the program runs fine. Above this I get the following message:
File "fwi_v3.py", line 170, in <module>
d_obs = forward_modeling_multi_shots(geometry1, client, save=False)
File "fwi_v3.py", line 91, in forward_modeling_multi_shots
shots.append(futures[i].result()[0])
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/client.py", line 222, in result
result = self.client.sync(self._result, callback_timeout=timeout, raiseit=False)
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/client.py", line 832, in sync
return sync(
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/utils.py", line 340, in sync
raise exc.with_traceback(tb)
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/utils.py", line 324, in f
result[0] = yield future
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/tornado/gen.py", line 735, in run
value = future.result()
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/client.py", line 247, in _result
result = await self.client._gather([self])
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/client.py", line 1880, in _gather
response = await future
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/client.py", line 1931, in _gather_remote
response = await retry_operation(self.scheduler.gather, keys=keys)
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/utils_comm.py", line 385, in retry_operation
return await retry(
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/utils_comm.py", line 370, in retry
return await coro()
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/core.py", line 883, in send_recv_from_rpc
result = await send_recv(comm=comm, op=key, **kwargs)
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/core.py", line 682, in send_recv
raise exc.with_traceback(tb)
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/core.py", line 528, in handle_comm
result = await result
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/scheduler.py", line 2867, in gather
data, missing_keys, missing_workers = await gather_from_workers(
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/utils_comm.py", line 78, in gather_from_workers
r = await c
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/worker.py", line 3255, in get_data_from_worker
return await retry_operation(_get_data, operation="get_data_from_worker")
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/utils_comm.py", line 385, in retry_operation
return await retry(
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/utils_comm.py", line 370, in retry
return await coro()
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/worker.py", line 3235, in _get_data
response = await send_recv(
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/core.py", line 666, in send_recv
response = await comm.read(deserializers=deserializers)
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/distributed/comm/tcp.py", line 195, in read
n = await stream.read_into(frame)
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/tornado/iostream.py", line 490, in read_into
self._try_inline_read()
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/tornado/iostream.py", line 857, in _try_inline_read
pos = self._read_to_buffer_loop()
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/tornado/iostream.py", line 770, in _read_to_buffer_loop
if self._read_to_buffer() == 0:
File "/home/murilo/.conda/envs/devito/lib/python3.8/site-packages/tornado/iostream.py", line 911, in _read_to_buffer
raise StreamBufferFullError("Reached maximum read buffer size")
tornado.iostream.StreamBufferFullError: Reached maximum read buffer size
I am a little unsure messing directly with Tornado since I've only touched Dask until this point. Setting the memory limit when initializing a LocalCluster would help? I've currently set it to 0, to have no memory restrictions.
Cheers!