Skip to content

Commit

Permalink
Fixing read endpoint normalization and patch query
Browse files Browse the repository at this point in the history
  • Loading branch information
mzkrasner committed Nov 4, 2024
1 parent 98500bb commit 59820a1
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 36 deletions.
2 changes: 1 addition & 1 deletion ceramicsdk/ceramic_python/model_instance_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def patch(
self.content = patched_content
self.state = self.ceramic_client.get_stream_state(self.stream_id)

return self
return patched_content

def should_index(self, should_index: bool, opts: Optional[Dict[str, Any]] = None):
self.patch([], ModelInstanceDocumentMetadataArgs(None, None, shouldIndex=should_index), opts)
Expand Down
23 changes: 13 additions & 10 deletions ceramicsdk/orbis_python/orbis_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import Optional
from pathlib import Path
import json
from ceramic_python.model_instance_document import ModelInstanceDocument, ModelInstanceDocumentMetadataArgs

class OrbisDB:
"""A relational database stored on OrbisDB/Ceramic"""
Expand All @@ -21,7 +20,9 @@ def __init__(

if not table_stream and not controller_private_key:
raise ValueError("Either the table stream or the controller needs to be specified when instantiating an OrbisDB class")
self.o_endpoint = o_endpoint
# strip trailing slash
self.o_endpoint = o_endpoint.rstrip("/")
self.read_endpoint = self.o_endpoint + "/api/db/query/json"
self.context_stream = context_stream
self.table_stream = table_stream
self.controller = DID(private_key=controller_private_key)
Expand Down Expand Up @@ -84,20 +85,21 @@ def add_row(self, entry_data):
return doc.stream_id


def update_rows(self, filters, new_content: dict):
def update_rows(self, env_id: str, filters: dict, new_content: dict):
"""Update rows"""

if not self.controller:
raise ValueError("Read-only database. OrbisDB controller has not being specified. Cannot write to the database.")

document_ids = [row["stream_id"] for row in self.filter(filters)]
document_ids = [row["stream_id"] for row in self.filter(env_id, filters)]

metadata_args = ModelInstanceDocumentMetadataArgs(
controller=self.controller.public_key,
model=self.table_stream,
context=self.context_stream,
)

return_vals = []

for document_id in document_ids:
patch = []

Expand All @@ -112,9 +114,10 @@ def update_rows(self, filters, new_content: dict):
"value": value
})

modelInstance.patch(json_patch=patch, metadata_args=metadata_args, opts={'anchor': True, 'publish': True, 'sync': 0})

return len(document_ids)
item = modelInstance.patch(json_patch=patch, metadata_args=metadata_args, opts={'anchor': True, 'publish': True, 'sync': 0})
return_vals.append(item)

return return_vals


def query(self, env_id: str, query: str):
Expand All @@ -135,7 +138,7 @@ def query(self, env_id: str, query: str):
headers = {
"Content-Type": "application/json"
}
response = requests.post(url=self.o_endpoint, headers=headers, json=body)
response = requests.post(url=self.read_endpoint, headers=headers, json=body)
return response.json()["data"]


Expand All @@ -158,7 +161,7 @@ def filter(self, env_id: str, filters):
headers = {
"Content-Type": "application/json"
}
response = requests.post(url=self.o_endpoint, headers=headers, json=body)
response = requests.post(url=self.read_endpoint, headers=headers, json=body)
return response.json().get("data", [])


2 changes: 1 addition & 1 deletion ceramicsdk/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="ceramicsdk",
version="0.1.3",
version="0.1.4",
author='Ceramic Ecosystem Developers',
description="This Ceramic client implements the payload building, encoding, and signing needed to interact with the Ceramic Network. It currently supports ModelInstanceDocument and OrbisDB.",
long_description=long_description,
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
python-dotenv==1.0.1
ceramicsdk==0.1.3
ceramicsdk==0.1.4
flask
50 changes: 27 additions & 23 deletions server-example.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,32 +68,36 @@ def get_documents():
## Need to update below

# # GET http://127.0.0.1:5000/filter?customer_user_id=3&agent=agent_two
# @app.route('/filter')
# def get_filtered_documents():
# agent = request.args.get('agent')
# seed = switcher.get(agent)
# orbis = OrbisDB(c_endpoint=CERAMIC_ENDPOINT,
# o_endpoint=ORBIS_ENDPOINT,
# context_stream=CONTEXT_ID,
# table_stream=TABLE_ID,
# controller_private_key=seed)
@app.route('/filter')
def get_filtered_documents():
agent = request.args.get('agent')
seed = switcher.get(agent)
orbis = OrbisDB(c_endpoint=CERAMIC_ENDPOINT,
o_endpoint=ORBIS_ENDPOINT,
context_stream=CONTEXT_ID,
table_stream=TABLE_ID,
controller_private_key=seed)

# # Get the filter from the query string but remove the agent key
# filter = {k: v for k, v in request.args.items() if k != 'agent'}
# res = ceramic.get_with_filter(filter)
# return res
# Get the filter from the query string but remove the agent key
filter = {k: v for k, v in request.args.items() if k != 'agent'}
res = orbis.filter(ENV_ID, filter)
return res

# # PATCH http://127.0.0.1:5000/update_document?agent=agent_two
# # payload example: {"document_id": "kjzl6kcym7w8y9j9dxto4h933lir60ek5q2r82x3r0ky56fzzty83fovwu4pn6f", "content": {"customer_user_id": 8} }
# @app.route('/update_document', methods=['PATCH'])
# def update_document():
# agent = request.args.get('agent')
# ceramic = CeramicActions(agent)
# ceramic.initialize_ceramic()
# content = request.json.get('content')
# document_id = request.json.get('document_id')
# doc = ceramic.update_document(document_id, content)
# return json.dumps(doc)
# # payload example: { "filters": {"customer_user_id": 3 }, "content": {"customer_user_id": 4} }
@app.route('/update_document', methods=['PATCH'])
def update_document():
agent = request.args.get('agent')
seed = switcher.get(agent)
orbis = OrbisDB(c_endpoint=CERAMIC_ENDPOINT,
o_endpoint=ORBIS_ENDPOINT,
context_stream=CONTEXT_ID,
table_stream=TABLE_ID,
controller_private_key=seed)
content = request.json.get('content')
filters = request.json.get('filters')
doc = orbis.update_rows(ENV_ID, filters, content)
return doc

if __name__ == '__main__':
app.run(debug=True)

0 comments on commit 59820a1

Please sign in to comment.