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)
Related
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
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)
I am working on a project that has a FastAPI back end with a React Frontend. When calling the back end via fetch I sometimes get the following:
Access to fetch at 'http://localhost:8000/get-main-query-data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This happens every so often, I can call one endpoint then the error gets thrown. Sometimes the error gets thrown for all endpoints
I have set up Middleware in my main.py like so: (also at this line)
# allows cross-origin requests from React
origins = [
"http://localhost",
"http://localhost:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Could this be an issue with fetch it's self? I am worried at when I get to host this ill be getting CORS errors and my prototype won't be working :(
The whole main.py is like so:
Backend
""" API to allow for data retrieval and manipulation. """
from typing import Optional
from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import models
from db import Session
app = FastAPI()
""" Pydantic BaseModels for the API. """
class SignalJourneyAudiences(BaseModel):
"""SignalJourneyAudiences BaseModel."""
audienceId: Optional[int] # PK
segment: str
enabled: bool
class SignalJourneyAudienceConstraints(BaseModel):
"""SignalJourneyAudienceConstraints BaseModel."""
uid: Optional[int] # PK
constraintId: int
audienceId: int # FK - SignalJourneyAudiences -> audienceId
sourceId: int # FK - SignalJourneySources -> sourceId
constraintTypeId: int # FK - SignalJourneyConstraintType -> constraintTypeId
constraintValue: str
targeting: bool
frequency: int
period: int
class SignalJourneyAudienceConstraintRelations(BaseModel):
"""SignalJourneyAudienceConstraintRelations BaseModel."""
uid: Optional[int] # PK
audienceId: int
relation: str
constraintIds: str
class SignalJourneyConstraintType(BaseModel):
"""SignalJourneyConstraintType BaseModel."""
constraintTypeId: Optional[int] # PK
constraintType: str
class SingalJourneySources(BaseModel):
"""SignalJourneySources BaseModel."""
sourceId: Optional[int] # PK
source: str
# allows cross-origin requests from React
origins = [
"http://localhost",
"http://localhost:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# database instance
db = Session()
#app.get("/")
def index():
"""Root endpoint."""
return {
"messagee": "Welcome to Signal Journey API. Please use the API documentation to learn more."
}
#app.get("/audiences", status_code=status.HTTP_200_OK)
def get_audiences():
"""Get all audience data from the database."""
return db.query(models.SignalJourneyAudiences).all()
#app.get("/audience-constraints", status_code=status.HTTP_200_OK)
def get_audience_constraints():
"""Get all audience constraint data from the database."""
return db.query(models.SignalJourneyAudienceConstraints).all()
#app.get("/audience-constraints-relations", status_code=status.HTTP_200_OK)
def get_audience_constraints_relations():
"""Get all audience constraint data from the database."""
return db.query(models.SignalJourneyAudienceConstraintRelations).all()
#app.get("/get-constraint-types", status_code=status.HTTP_200_OK)
def get_constraints_type():
"""Get all audience constraint data from the database."""
return db.query(models.SignalJourneyConstraintType).all()
#app.post("/add-constraint-type", status_code=status.HTTP_200_OK)
def add_constraint_type(sjct: SignalJourneyConstraintType):
"""Add a constraint type to the database."""
constraint_type_query = (
db.query(models.SignalJourneyConstraintType)
.filter(
models.SignalJourneyConstraintType.constraintType
== sjct.constraintType.upper()
and models.SignalJourneyConstraintType.constraintTypeId
== sjct.constraintTypeId
)
.first()
)
if constraint_type_query is not None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Constaint type already exists.",
)
constraint_type = models.SignalJourneyConstraintType(
constraintType=sjct.constraintType.upper(),
)
db.add(constraint_type)
db.commit()
return {
"message": f"Constraint type {sjct.constraintType.upper()} added successfully."
}
#app.get("/get-sources", status_code=status.HTTP_200_OK)
def get_sources():
"""Get all sources data from the database."""
return db.query(models.SingalJourneySources).all()
#app.post("/add-source", status_code=status.HTTP_200_OK)
def add_source_type(sjs: SingalJourneySources):
"""Add a new source type to the database."""
source_type_query = (
db.query(models.SingalJourneySources)
.filter(models.SingalJourneySources.source == sjs.source.upper())
.first()
)
if source_type_query is not None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Source already exists.",
)
source_type = models.SingalJourneySources(source=sjs.source.upper())
db.add(source_type)
db.commit()
return {"message": f"Source {sjs.source.upper()} added successfully."}
"""
Endpoints for populating the UI with data. These need to consist of some joins.
Query to be used in SQL
SELECT
constraintid,
sja.segment,
sjs.source,
sjct.constrainttype,
constraintvalue,
targeting,
frequency,
period
FROM signaljourneyaudienceconstraints
JOIN signaljourneyaudiences sja ON sja.audienceid = signaljourneyaudienceconstraints.audienceid;
JOIN signaljourneysources sjs ON sjs.sourceid = signaljourneyaudienceconstraints.sourceid
JOIN signaljourneyconstrainttype sjct ON sjct.constrainttypeid = signaljourneyaudienceconstraints.constrainttypeid
"""
#app.get("/get-main-query-data", status_code=status.HTTP_200_OK)
def get_main_query_data():
"""Returns data for the main query."""
return (
db.query(
models.SignalJourneyAudienceConstraints.constraintId,
models.SignalJourneyAudiences.segment,
models.SingalJourneySources.source,
models.SignalJourneyConstraintType.constraintType,
models.SignalJourneyAudienceConstraints.constraintValue,
models.SignalJourneyAudienceConstraints.targeting,
models.SignalJourneyAudienceConstraints.frequency,
models.SignalJourneyAudienceConstraints.period,
)
.join(
models.SignalJourneyAudiences,
models.SignalJourneyAudiences.audienceId
== models.SignalJourneyAudienceConstraints.audienceId,
)
.join(
models.SingalJourneySources,
models.SingalJourneySources.sourceId
== models.SignalJourneyAudienceConstraints.sourceId,
)
.join(
models.SignalJourneyConstraintType,
models.SignalJourneyConstraintType.constraintTypeId
== models.SignalJourneyAudienceConstraints.constraintTypeId,
)
.all()
)
Frontend
I am calling my API endpoints like so:
//form.jsx
// pulls segments name from signaljourneyaudiences
useEffect(() => {
fetch('http://localhost:8000/audiences')
.then((res) => res.json())
.then((data) => setSegmentNames(data))
.catch((err) => console.log(err));
}, []);
// pulls field names from signaljourneyaudiences
useEffect(() => {
fetch('http://localhost:8000/get-constraint-types')
.then((res) => res.json())
.then((data) => setConstraints(data))
.catch((err) => console.log(err));
}, []);
// table.jsx
useEffect(() => {
fetch('http://localhost:8000/get-main-query-data')
.then((res) => res.json())
.then((data) => {
setTableData(data);
})
.catch((err) => console.log(err));
}, []);
As you can see here the table has been populated by the endpoints but on the other hand, one of the dropdowns have not.
HTTP 500 error description
INFO: 127.0.0.1:62301 - "GET /get-constraint-types HTTP/1.1" 500 Internal Server Error
2022-02-24 09:26:44,234 INFO sqlalchemy.engine.Engine [cached since 2972s ago] ()
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1702, in _execute_context
context = constructor(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 6191820800 and this is thread id 6174994432.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 372, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/applications.py", line 259, in __call__
await super().__call__(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/cors.py", line 92, in __call__
await self.simple_response(scope, receive, send, request_headers=headers)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/middleware/cors.py", line 147, in simple_response
await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
raise e
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/routing.py", line 227, in app
raw_response = await run_endpoint_function(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/fastapi/routing.py", line 162, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/starlette/concurrency.py", line 39, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/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 "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 818, in run_sync_in_worker_thread
return await future
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 754, in run
result = context.run(func, *args)
File "/Users/paul/Developer/signal_journey/backend/./main.py", line 109, in get_constraints_type
return db.query(models.SignalJourneyConstraintType).all()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 2759, in all
return self._iter().all()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 2894, in _iter
result = self.session.execute(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 1692, in execute
result = conn._execute_20(statement, params or {}, execution_options)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1614, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection
return connection._execute_clauseelement(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1481, in _execute_clauseelement
ret = self._execute_context(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1708, in _execute_context
self._handle_dbapi_exception(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1702, in _execute_context
context = constructor(
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "/Users/paul/.local/share/virtualenvs/backend-CF5omcRU/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 6191820800 and this is thread id 6174994432.
[SQL: SELECT "SignalJourneyConstraintType"."constraintTypeId" AS "SignalJourneyConstraintType_constraintTypeId", "SignalJourneyConstraintType"."constraintType" AS "SignalJourneyConstraintType_constraintType"
FROM "SignalJourneyConstraintType"]
[parameters: [{}]]
(Background on this error at: https://sqlalche.me/e/14/f405)
When a server side error occurs (a response code of 5xx), the CORS middleware doesn't get to add their headers since the request is effectively terminated, making it impossible for the browser to read the response.
For your second problem, you should use a separate session for each invocation of your API. The reference guide has an example of how to do this:
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
...
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
...
#app.post("/users/{user_id}/items/", response_model=schemas.Item)
def create_item_for_user(..., db: Session = Depends(get_db)):
return crud.create_user_item(db=db, item=item, user_id=user_id)
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.