Я изучаю FastAPI на YouTube, и когда мы соединяем таблицы с помощью sqlalchemy, я не получаю тот же результат, что и на видео. Видео выпущено 2 года назад, и я пытался найти решение, но ничего не добился.
Поэтому я пытаюсь присоединиться к POST таблица с таблицей голосов и подсчетом голосов для каждого POST, но я получаю общее количество голосов, но не объект сообщения, он просто показывает объект запроса.
Спасибо за заранее. Модель
INFO: 127.0.0.1:50202 - "GET /posts HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 322, in jsonable_encoder
data = dict(obj)
^^^^^^^^^
TypeError: cannot convert dictionary update sequence element #0 to a sequence
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 327, in jsonable_encoder
data = vars(obj)
^^^^^^^^^
TypeError: vars() argument must have __dict__ attribute
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 426, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/applications.py", line 1106, in __call__
await super().__call__(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/applications.py", line 122, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
raise exc
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__
raise e
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__
await self.app(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 718, in __call__
await route.handle(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 276, in handle
await self.app(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 66, in app
response = await func(request)
^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/routing.py", line 292, in app
content = await serialize_response(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/routing.py", line 180, in serialize_response
return jsonable_encoder(response_content)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 301, in jsonable_encoder
jsonable_encoder(
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 330, in jsonable_encoder
raise ValueError(errors) from e
ValueError: [TypeError('cannot convert dictionary update sequence element #0 to a sequence'), TypeError('vars() argument must have __dict__ attribute')]
Я изучаю FastAPI на YouTube, и когда мы соединяем таблицы с помощью sqlalchemy, я не получаю тот же результат, что и на видео. Видео выпущено 2 года назад, и я пытался найти решение, но ничего не добился. Поэтому я пытаюсь присоединиться к POST таблица с таблицей голосов и подсчетом голосов для каждого POST, но я получаю общее количество голосов, но не объект сообщения, он просто показывает объект запроса. Спасибо за заранее. [b]Модель[/b] [code]class Post(Base): __tablename__ = "posts"
id = Column(Integer, primary_key=True, nullable=False) title = Column(String, nullable=False) content = Column(String, nullable=False) published = Column(Boolean, server_default="TRUE") created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()')) owner_id = Column(Integer, ForeignKey( "users.id", ondelete="CASCADE"), nullable=False)
owner = relationship("User")
class Vote(Base): __tablename__ = "votes"
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), primary_key=True) post_id = Column(Integer, ForeignKey("posts.id", ondelete="CASCADE"), primary_key=True) created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()')) [/code] Это моя функция маршрутизации POST. Запрос, который возвращает объект запроса, является результатом [code]@router.get("/posts") async def get_posts( db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user), search: Optional[str] = '', ):
[/code] Я хочу, чтобы это было в реальном объекте POST, а не в объекте запроса. [b]Это ошибка, когда я возвращаю результаты.[/b]< /p> [code]INFO: 127.0.0.1:50202 - "GET /posts HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 322, in jsonable_encoder data = dict(obj) ^^^^^^^^^ TypeError: cannot convert dictionary update sequence element #0 to a sequence
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 327, in jsonable_encoder data = vars(obj) ^^^^^^^^^ TypeError: vars() argument must have __dict__ attribute
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 426, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/applications.py", line 1106, in __call__ await super().__call__(scope, receive, send) File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/applications.py", line 122, in __call__ await self.middleware_stack(scope, receive, send) File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 79, in __call__ raise exc File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 68, in __call__ await self.app(scope, receive, sender) File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__ raise e File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__ await self.app(scope, receive, send) File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 718, in __call__ await route.handle(scope, receive, send) File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 276, in handle await self.app(scope, receive, send) File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 66, in app response = await func(request) ^^^^^^^^^^^^^^^^^^^ File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/routing.py", line 292, in app content = await serialize_response( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/routing.py", line 180, in serialize_response return jsonable_encoder(response_content) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 301, in jsonable_encoder jsonable_encoder( File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 330, in jsonable_encoder raise ValueError(errors) from e ValueError: [TypeError('cannot convert dictionary update sequence element #0 to a sequence'), TypeError('vars() argument must have __dict__ attribute')]
Я изучаю FastAPI на YouTube, и когда мы соединяем таблицы с помощью sqlalchemy, я не получаю тот же результат, что и на видео. Видео выпущено 2 года назад, и я пытался найти решение, но ничего не добился.
Поэтому я пытаюсь присоединиться к POST...
Я использую платформу NPoco (и Umbraco) и получаю с ее помощью много данных из отдельных таблиц. Теперь я хочу объединить таблицы вместе, но кажется, что это вообще не работает.
Две таблицы выглядят следующим образом: Game является основной...
У меня есть две таблицы, и я хочу объединить их.
но я не могу сделать это без rawQueryset и необработанного SQL.
как мне объединить две модели без внешнего ключа? Столбцы для JOIN не уникальны, поэтому это не могут быть PK и внешний ключ.
Я хочу...
У меня возникла проблема при попытке объединить два массива в PHP.
Я использую laravel, поэтому мои запросы выглядят так:
$users = DB::table('users')
->select('name', 'user_id')
->get();
и
$speech = DB::table('users')
->select('user_id',...
У меня есть таблица, в которой мне требуется последнее значение свойства для каждого идентификатора механизма на каждом идентификаторе устройства (может быть 3 механизма на устройство). Последний измеряется по идентификатору ImportId (чем выше, тем...