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 am in the process of building several example APIs to and ran into this 'is not mapped' sqlalchemy.orm.exe.UnmappedInstance Error issue. I believe this error would possible be generated if I was trying to pass an object instance that wasn't a model, however, I am passing a pydanic model within the db.add() method which is mapped (or at least I think it is.) So, I'm not sure why I'm getting this error when the object being passed to db.Add (new_inventory) is a prudence model that is aligned to the base schema. What am I missing? Or educate me on why I'm getting a Unmapped Instance Error when I can clearly see that the type received is a mapped pedantic model. I've raved existing Stack Overflow post which was centered around using marshmallows, which I prefer to make that an 'if all else fails' solution. Any solution to get the code I have in place massaged would be highly appreciated.
Using Python 3.10.4 / Pydantic / SqlAlchemy / FastAPI
file name c:\app\main.py
'''python
from msilib import schema
mport psycopg2
from psycopg2.extras import RealDictCursor
from os import stat
from fastapi import Depends, FastAPI, Response, status, HTTPException
from pydantic import BaseModel
from typing import Optional
import pdb
from db.conn import Postgre
from db.sql_alchemy import db_engine, fetch_db, Base
from db.models.Inventory import InventorySchema, InventoryModel
from sqlalchemy.orm import Session
from pydantic import BaseModel
Base.metadata.create_all(bind=db_engine)
app = FastAPI()
#app.get("/fetch/vehicles", status_code=status.HTTP_200_OK)
def fetch_vehiles(db: Session = Depends(fetch_db)):
vehicles = db.query(InventorySchema).all()
print(vehicles)
return {"all vehicles": vehicles}
#app.post("/post/vehicles",status_code=status.HTTP_201_CREATED)
def insert_vechiles(inventory: InventoryModel, db: Session = Depends(fetch_db)):
new_inventory = InventoryModel(
name = inventory.name,
price = inventory.price,
color = inventory.color,
manufactured_by = inventory.manufactured_by,
model = inventory.model,
size = inventory.size,
quantity = inventory.quantity,
active = inventory.active)
pdb.set_trace()
db.add(new_inventory) # <---generates error
# db.commit()
# db.refresh(new_intentory)
return {"Posted": new_inventory}
# file name: c:\db\models\Inventory.py
from email.policy import default
from msilib import schema
from xmlrpc.client import Boolean, boolean
from psycopg2 import Timestamp
from pydantic import BaseModel
from db.sql_alchemy import Base
from sqlalchemy import TIMESTAMP, Column, Integer, String, Boolean
from sqlalchemy.sql.expression import text
from sqlalchemy.sql.sqltypes import TIMESTAMP
class InventoryModel(BaseModel):
name: str = 'Yshmael'
price: str = '3.00'
color: str = 'blue'
manufactured_by: str = 'ford'
model: str = 'branch'
size: str = '4 door'
quantity: str = '10'
active: str = 'False'
class InventorySchema(Base):
__tablename__ = "vehicles"
id = Column(Integer, primary_key=True, nullable=False)
name = Column(String, nullable=False)
price = Column(String, nullable=False)
color = Column(String, nullable=False)
manufactured_by = Column(String, nullable=False)
model = Column(String, nullable=False)
size = Column(String, nullable=False)
quantity = Column(String, nullable=False)
active = Column(String, nullable=False)
created_on = Column(TIMESTAMP(timezone=True), nullable=False,
server_default=text('now()'))
'''
StackTrace
Traceback (most recent call last):
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 366, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\fastapi\applications.py", line 269, in __call__
await super().__call__(scope, receive, send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
raise exc
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\exceptions.py", line 93, in __call__
raise exc
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__
await self.app(scope, receive, sender)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
raise e
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\routing.py", line 670, in __call__
await route.handle(scope, receive, send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\routing.py", line 266, in handle
await self.app(scope, receive, send)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\routing.py", line 65, in app
response = await func(request)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\fastapi\routing.py", line 227, in app
raw_response = await run_endpoint_function(
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\fastapi\routing.py", line 162, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\starlette\concurrency.py", line 41, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\anyio\to_thread.py", line 31, in run_sync
return await get_asynclib().run_sync_in_worker_thread(
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 937, in run_sync_in_worker_thread
return await future
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 867, in run
result = context.run(func, *args)
File "C:\QA\Dev\projects\testdriven.io\posting_system\.\app\main.py", line 40, in insert_vechiles
db.add(new_inventory)
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2605, in add
util.raise_(
File "C:\QA\Dev\projects\testdriven.io\posting_system\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
**sqlalchemy.orm.exc.UnmappedInstanceError: Class 'db.models.Inventory.InventoryModel' is not mapped**
It seems that you are confused with the inheritance of model and schema, BaseModel is for schemas and Base is for models.
Try to change the classes of:
class InventoryModel(BaseModel):
class InventorySchema(Base):
__tablename__ = "vehicles"
to:
class InventoryModel(Base):
__tablename__ = "vehicles"
class InventorySchema(BaseModel):
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.
So I'm developing discord bot with discord.py for my server. I'm using replit's database system. When I try to add instance of my class Player to key of that database it says:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 36, in jointothefun
db[f"{context.message.author.id}"] = p
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 486, in __setitem__
self.set(key, value)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 495, in set
self.set_raw(key, _dumps(value))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 56, in dumps
return json.dumps(val, separators=(",", ":"), cls=DBJSONEncoder)
File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
return cls(
File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Circular reference detected
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: Circular reference detected
I have no idea why it's not working at all. Some one could help?
Oh and source code (yes i know i'm making spaghetti code)
Main file for bot
from discord.ext import commands
from replit import db
from alive import startup
from playerclass import Player
print(db.keys())
class PlayerClient(discord.Client):
async def on_member_join(self,member):
print(f"{member} joined")
async def on_ready(self):
print("Bot ready to work!")
def __init__(self):
self.intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
self.bot = commands.Bot(command_prefix = '~rpg ', intents = intents)
intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
client = bot = commands.Bot(command_prefix = '~rpg ', intents = intents)
#client.command(name='join')
async def jointothefun(context):
keys = db.keys()
rpgc = client.get_channel(811518285634863124)
if context.message.channel == rpgc:
if not f"{context.message.author.id}" in keys:
await context.message.channel.send("Hi "+str(context.message.author.mention))
#not working code
db[f"{context.message.author.id}"] = Player(100,0,0,0,0,1)
else:
await context.message.channel.send("Bruh you've joined already")
else:
await context.message.channel.send('Yo wrong channel!')
#client.command(name='stats')
async def stats(context):
rpgc = client.get_channel(811518285634863124)
if context.message.channel==rpgc:
keys = db.keys()
if str(context.message.author.id) in keys:
embed=db[str(context.message.author.id)].displayEquipment
await context.send(embed=embed)
else:
await context.message.channel.send("Join first to access stats!")
else:
await context.message.channel.send(f"XD {context.message.author.mention} to nie ten kanał! Pisz na #rpg")
#client.command()
async def ping(ctx):
await ctx.send("Pong!")
startup()
#yes i know that will not work but it's private i guess it's obvious
client.run("my bot token")
Player class
from item_class import Weapon
import discord
class Player:
def __init__(self,h,m,de,c,t,dm):
self.hp=h
self.mana=m
self.defense=de
self.coins=c
self.truecoins=t
self.weapon=Weapon("Stick",10,1,1,100,1,0)
self.dmg=dm+self.weapon.dmg
self.itlist=[]
def addItemToEq(self,it):
self.itlist.append(it)
def displayEquipment(self,client,context):
embed = discord.Embed(
title="Inventory",colour=discord.Colour.Green)
for i in self.itlist:
if type(i)==Weapon:
embed.add_field(i.self.name,"Weapon",False)
else:
embed.add_field(i.self.name,"Item",False)
return embed
Item class
import random
class Item:
def __init__(self,name):
self.name = name
def use(self):
print("its normal item bruh")
class Food(Item):
def __init__(self,name,nutrition):
self.name=name
self.hpboost=nutrition
class Weapon(Item):
def __init__(self,name,durablity,dmgboost,critchcmin,critchcmax,crit,boost):
self.name=name
self.durablity=durablity
self.dmg=dmgboost
self.critmin=critchcmin
self.critmax=critchcmax
self.critdmg=crit
self.fnc=boost
def attack(self):
print(self.dmg)
print(str(self.calcCrit()))
self.durablity-=1
def calcCrit(self):
if random.randint(self.critmin,self.critmax)<=self.critmax/2:
return True
else:
return False
def useBoost(self):
self.boost()
I would be so grateful if someone would help me :)
as answered here, the values of replit's database must be JSON-serializable. This means, you'd have to pass (most likely) a dict instead of a class object, but then you won't be able to use the object's functions.
Anything in Replit's database has to be JSON serializable. (Str, int, float, list, etc)
You could save the important properties as a json to the database. (e.g "name": "stick", "durablity": 10, "dmg": 1)