Python client for FlexBase HTTP API
Project description
Sphere FlexBase Client
Python-клиент для взаимодействия с FlexBase HTTP API. Предоставляет удобный интерфейс для работы с документами и коллекциями.
Установка
pip install sphere-flexbase
Быстрый старт
from flexbase_client import FlexBaseClient
# Инициализация клиента
client = FlexBaseClient(api_key="your_super_secret_key")
# Или через переменную окружения FLEXBASE_API_KEY
# export FLEXBASE_API_KEY=your_super_secret_key
# client = FlexBaseClient()
# Создание коллекции
response = client.create_collection("users")
print("Коллекция создана:", response)
# Вставка документа
doc = {
"name": "Alice",
"age": 30,
"active": True
}
result = client.insert_document("users", doc)
print("Документ добавлен:", result)
# Получение всех документов
documents = client.get_documents("users")
for doc in documents:
print(doc)
# Получение документа по ID
doc = client.get_document_by_id("users", "document_id")
print("Документ:", doc)
# Обновление документа
update = {
"age": 31,
"name": "Alice Updated"
}
result = client.update_document("users", "document_id", update)
print("Документ обновлен:", result)
# Поиск по фильтру
result = client.search_documents("users", filters={"name:~": "Alice"})
print("Найдено документов:", result["total"])
for doc in result["data"]:
print(doc)
# Удаление документа
client.delete_document("users", "document_id")
API Методы
Коллекции
create_collection(name: str) -> Dict- Создание новой коллекцииget_documents(collection: str) -> List[Dict]- Получение всех документов коллекции
Документы
insert_document(collection: str, data: Dict) -> Dict- Вставка нового документаget_document_by_id(collection: str, doc_id: str) -> Dict- Получение документа по IDupdate_document(collection: str, doc_id: str, changes: Dict) -> Dict- Обновление документаdelete_document(collection: str, doc_id: str) -> None- Удаление документаsearch_documents(collection: str, filters: Dict) -> Dict- Поиск документов по фильтру
Обработка ошибок
Клиент предоставляет следующие типы исключений:
from flexbase_client.exceptions import (
FlexBaseError, # Базовое исключение
UnauthorizedError, # Ошибка авторизации (401)
BadRequestError, # Неверный запрос (400)
NotFoundError, # Ресурс не найден (404)
ConnectionError, # Ошибка соединения
TimeoutError # Таймаут запроса
)
Пример обработки ошибок:
try:
client.create_collection("users")
except UnauthorizedError:
print("Ошибка авторизации. Проверьте API ключ")
except BadRequestError as e:
print(f"Ошибка в запросе: {e}")
except NotFoundError:
print("Ресурс не найден")
except Exception as e:
print(f"Неизвестная ошибка: {e}")
Примеры использования с Flask
from flask import Flask, jsonify, request
from flexbase_client import FlexBaseClient
app = Flask(__name__)
db = FlexBaseClient()
@app.route("/users", methods=["GET"])
def get_users():
try:
users = db.get_documents("users")
return jsonify(users)
except Exception as e:
return {"error": str(e)}, 400
@app.route("/users", methods=["POST"])
def create_user():
try:
user = db.insert_document("users", request.json)
return jsonify(user), 201
except Exception as e:
return {"error": str(e)}, 400
@app.route("/users/<user_id>", methods=["GET"])
def get_user(user_id):
try:
user = db.get_document_by_id("users", user_id)
return jsonify(user)
except NotFoundError:
return {"error": "User not found"}, 404
except Exception as e:
return {"error": str(e)}, 400
if __name__ == "__main__":
app.run(debug=True)
Поиск документов
Поддерживаются следующие операторы фильтрации:
# Точное совпадение
filters = {"name": "Alice"}
# Частичное совпадение (like)
filters = {"name:~": "Ali"}
# Сравнение
filters = {
"age:>": 25, # больше
"age:>=": 25, # больше или равно
"age:<": 30, # меньше
"age:<=": 30 # меньше или равно
}
# Комбинация фильтров
filters = {
"name:~": "Ali",
"age:>=": 25,
"active": True
}
Лицензия
MIT # python-sphere-flexbase
python-sphere-flexbase
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sphere_flexbase-0.1.0.tar.gz.
File metadata
- Download URL: sphere_flexbase-0.1.0.tar.gz
- Upload date:
- Size: 6.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c9ce746790e0910f83f502d7aa42939e506e3a86322e2952f962f63568faf940
|
|
| MD5 |
101a8a4ecb09286dc561b1777e4853c3
|
|
| BLAKE2b-256 |
a4771fe7c238eb43cbb295c36743c4b21d032458022e8261d5e14108bab55718
|
File details
Details for the file sphere_flexbase-0.1.0-py3-none-any.whl.
File metadata
- Download URL: sphere_flexbase-0.1.0-py3-none-any.whl
- Upload date:
- Size: 6.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ee87a8d8ce55d1528e2bc63bf7ef7d7d06af5b4202e2c9cf2fe24314efaf3593
|
|
| MD5 |
b93e54b160fb9a73d9ed3a5df313057b
|
|
| BLAKE2b-256 |
d6be734bcf284d01436d9f5b6e9c44c3d895a16ab4f0df9a154ce64fe85024a5
|