Back

Cannot create collection in Python Function

  • 1
  • Functions
retr122
24 Nov, 2023, 18:19

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

TypeScript
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!")

TypeScript
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]}}
)
TypeScript
TL;DR
The user is unable to create a collection in a Python function. They are receiving an error message stating "Object of type function is not JSON serializable." They are also requesting help on generating an ID from the server. There is a suggestion to catch the error and include a stack trace for more information. The user is also experiencing issues with the syntax for updating a document in Appwrite. Solution: 1. To generate an ID from the server, the user can use `ID.unique()`. 2. To fix the JSON serializable error, the user needs to change `ID.custom` to `ID.custom('my-custom-id
Drake
24 Nov, 2023, 18:30

btw, adding the language after the first 3 backticks will enable syntax highlighting

Drake
24 Nov, 2023, 18:32

this error seems to suggest you're trying to call json.dumps() on a function 🧐

Drake
24 Nov, 2023, 18:34

btw, this doesn't work:

TypeScript
data={'chats': {'$add': [new_collection_id]}}
retr122
25 Nov, 2023, 09:26

what i should do instead?

retr122
25 Nov, 2023, 09:26

why?

Drake
25 Nov, 2023, 15:44

Because that syntax doesn't exist in Appwrite

Drake
25 Nov, 2023, 15:44

{'chats': updatedArray}

retr122
25 Nov, 2023, 15:47

I don't catch it. Why I had error in line where I trying to create new collection?

Drake
25 Nov, 2023, 15:51

I don't know why you're getting that error. Maybe you can get a stack trace to get more info?

retr122
25 Nov, 2023, 15:53

Full error message?

Drake
25 Nov, 2023, 15:54
retr122
25 Nov, 2023, 16:07
TypeScript
  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
retr122
25 Nov, 2023, 16:07
TypeScript
  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
Drake
25 Nov, 2023, 16:10

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')

retr122
25 Nov, 2023, 16:23

what I should write this to generate ID from server? What means ID.unique and ID.mro?

Drake
25 Nov, 2023, 16:29

To let Appwrite generate the id, you would do ID.unique()

retr122
25 Nov, 2023, 17:22

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?

Drake
25 Nov, 2023, 17:29

One of the parameters is an array of permissions

Drake
25 Nov, 2023, 17:29
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more