Hello. I trying to make a function that creates collection in Database, but it don't works properly. When this python code starts in server, it returns ```appwrite.exception.AppwriteException: Object of type function is not JSON serializable TypeError: Object of type function is not JSON serializable
Python code
from appwrite.client import Client import os import json from appwrite.services.databases import Databases from appwrite.id import ID
def main(context): # You can log messages to the console context.log("Hello, Logs!")
context.log(json.dumps(context.req.headers))
headers_json = json.dumps(context.req.headers)
# Преобразование строки JSON обратно в словарь Python
headers_dict = json.loads(headers_json)
chatId1 = str(headers_dict.get("chatid1"))
chatId2 = str(headers_dict.get("chatid2"))
context.log(chatId1)
context.log(chatId2)
client = Client()
client.set_endpoint('https://cloud.appwrite.io/v1') # Замените на адрес вашего Appwrite сервера
client.set_project('MY_PROJECT_ID') # Замените на ID вашего проекта
client.set_key('MY_API_KEY') # Замените на ваш API ключ
database = Databases(client)
new_collection_name = str('Chat ' + chatId1 + " " + chatId2)
new_collection = database.create_collection('655b677272e7fcdaf20b', ID.custom, new_collection_name)
new_collection_id = new_collection['$id']
context.log(new_collection)
# Обновление документа для участника чата 1
document_1 = database.update_document("652b64a5791875d98083",
'65328bfb067b6087e4fb',
document_id=chatId1,
data={'chats': {'$add': [new_collection_id]}}
)
# Обновление документа для участника чата 2
document_2 = database.update_document("652b64a5791875d98083",
'65328bfb067b6087e4fb',
document_id=chatId2,
data={'chats': {'$add': [new_collection_id]}}
)
btw, adding the language after the first 3 backticks will enable syntax highlighting
this error seems to suggest you're trying to call json.dumps()
on a function 🧐
btw, this doesn't work:
data={'chats': {'$add': [new_collection_id]}}
what i should do instead?
why?
Because that syntax doesn't exist in Appwrite
{'chats': updatedArray}
I don't catch it. Why I had error in line where I trying to create new collection?
I don't know why you're getting that error. Maybe you can get a stack trace to get more info?
Full error message?
No, stack trace. Wrap your code in a try/except and include this: https://stackoverflow.com/questions/4564559/get-exception-description-and-stack-trace-which-caused-an-exception-all-as-a-st
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/appwrite/client.py", line 89, in call
response = requests.request( # call method dynamically https://stackoverflow.com/a/4246075/2299554
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/requests/api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/requests/sessions.py", line 575, in request
prep = self.prepare_request(req)
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/requests/sessions.py", line 486, in prepare_request
p.prepare(
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/requests/models.py", line 371, in prepare
self.prepare_body(data, files, json)
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/requests/models.py", line 511, in prepare_body
body = complexjson.dumps(json, allow_nan=False)
File "/usr/local/lib/python3.9/json/__init__.py", line 234, in dumps
return cls(
File "/usr/local/lib/python3.9/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/lib/python3.9/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/local/lib/python3.9/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable
File "/usr/local/server/src/server.py", line 165, in handler
output = await asyncio.wait_for(execute(context), timeout=safeTimeout)
File "/usr/local/lib/python3.9/asyncio/tasks.py", line 479, in wait_for
return fut.result()
File "/usr/local/server/src/server.py", line 158, in execute
output = userModule.main(context)
File "/usr/local/server/src/function/src/main.py", line 45, in main
result = update_collection(chatId1, chatId2) # Выполняем операции и получаем результат
File "/usr/local/server/src/function/src/main.py", line 64, in update_collection
new_collection = database.create_collection('655b677272e7fcdaf20b', ID.custom, new_collection_name)
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/appwrite/services/databases.py", line 138, in create_collection
return self.client.call('post', api_path, {
File "/usr/local/server/src/function/runtime-env/lib/python3.9/site-packages/appwrite/client.py", line 116, in call
raise AppwriteException(e)
appwrite.exception.AppwriteException: Object of type function is not JSON serializable
Ohhhh you passed in ID.custom
. that's supposed to be a function where you pass in the id like: ID.custom('my-custom-id')
what I should write this to generate ID from server? What means ID.unique and ID.mro?
To let Appwrite generate the id, you would do ID.unique()
Thanks you very much! Bug was so simple and I shock about IT. One more question - how to add Any Permission when I create new collection?
One of the parameters is an array of permissions
For info on permissions see https://appwrite.io/docs/advanced/platform/permissions
Recommended threads
- HTTP POST to function returning "No Appw...
Hi everyone, I’m running into an issue with my self-hosted Appwrite instance. I’ve set up my environment variables (APPWRITE_FUNCTION_PROJECT_ID, APPWRITE_FUNC...
- Can't add dart 3.5 runtime
Modified the `.env` to enable dart 3.5 runtime on my self-hosted instance but still can't find the runtime when creating a new function. I manually pulled the i...
- How to verify an user using AppWrite Fun...
I have seen similar questions but none whose solutions serve me. I have a function to verify a user with their secret and their id: https://blahblah.appwrite.gl...