Initial checkin.
This commit is contained in:
commit
616f220cfc
183
.gitignore
vendored
Normal file
183
.gitignore
vendored
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
# -*- mode: gitignore; -*-
|
||||||
|
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
pip-wheel-metadata/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# PyInstaller
|
||||||
|
# Usually these files are written by a python script from a template
|
||||||
|
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||||
|
*.manifest
|
||||||
|
*.spec
|
||||||
|
|
||||||
|
# Installer logs
|
||||||
|
pip-log.txt
|
||||||
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.nox/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
.cache
|
||||||
|
nosetests.xml
|
||||||
|
coverage.xml
|
||||||
|
*.cover
|
||||||
|
*.py,cover
|
||||||
|
.hypothesis/
|
||||||
|
.pytest_cache/
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
*.pot
|
||||||
|
|
||||||
|
# Django stuff:
|
||||||
|
*.log
|
||||||
|
local_settings.py
|
||||||
|
db.sqlite3
|
||||||
|
db.sqlite3-journal
|
||||||
|
|
||||||
|
# Flask stuff:
|
||||||
|
instance/
|
||||||
|
.webassets-cache
|
||||||
|
|
||||||
|
# Scrapy stuff:
|
||||||
|
.scrapy
|
||||||
|
|
||||||
|
# Sphinx documentation
|
||||||
|
docs/_build/
|
||||||
|
|
||||||
|
# PyBuilder
|
||||||
|
target/
|
||||||
|
|
||||||
|
# Jupyter Notebook
|
||||||
|
.ipynb_checkpoints
|
||||||
|
|
||||||
|
# IPython
|
||||||
|
profile_default/
|
||||||
|
ipython_config.py
|
||||||
|
|
||||||
|
# pyenv
|
||||||
|
.python-version
|
||||||
|
|
||||||
|
# pipenv
|
||||||
|
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||||
|
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||||
|
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||||
|
# install all needed dependencies.
|
||||||
|
#Pipfile.lock
|
||||||
|
|
||||||
|
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||||
|
__pypackages__/
|
||||||
|
|
||||||
|
# Celery stuff
|
||||||
|
celerybeat-schedule
|
||||||
|
celerybeat.pid
|
||||||
|
|
||||||
|
# SageMath parsed files
|
||||||
|
*.sage.py
|
||||||
|
|
||||||
|
# Environments
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
|
||||||
|
# Spyder project settings
|
||||||
|
.spyderproject
|
||||||
|
.spyproject
|
||||||
|
|
||||||
|
# Rope project settings
|
||||||
|
.ropeproject
|
||||||
|
|
||||||
|
# mkdocs documentation
|
||||||
|
/site
|
||||||
|
|
||||||
|
# mypy
|
||||||
|
.mypy_cache/
|
||||||
|
.dmypy.json
|
||||||
|
dmypy.json
|
||||||
|
|
||||||
|
# pytype
|
||||||
|
.pytype/
|
||||||
|
|
||||||
|
# Pyre type checker
|
||||||
|
.pyre/
|
||||||
|
|
||||||
|
# emacs things
|
||||||
|
*~
|
||||||
|
\#*\#
|
||||||
|
/.emacs.desktop
|
||||||
|
/.emacs.desktop.lock
|
||||||
|
*.elc
|
||||||
|
auto-save-list
|
||||||
|
tramp
|
||||||
|
.\#*
|
||||||
|
|
||||||
|
# Org-mode
|
||||||
|
.org-id-locations
|
||||||
|
*_archive
|
||||||
|
|
||||||
|
# flymake-mode
|
||||||
|
*_flymake.*
|
||||||
|
|
||||||
|
# eshell files
|
||||||
|
/eshell/history
|
||||||
|
/eshell/lastdir
|
||||||
|
|
||||||
|
# elpa packages
|
||||||
|
/elpa/
|
||||||
|
|
||||||
|
# reftex files
|
||||||
|
*.rel
|
||||||
|
|
||||||
|
# AUCTeX auto folder
|
||||||
|
/auto/
|
||||||
|
|
||||||
|
# cask packages
|
||||||
|
.cask/
|
||||||
|
dist/
|
||||||
|
|
||||||
|
# Flycheck
|
||||||
|
flycheck_*.el
|
||||||
|
|
||||||
|
# server auth directory
|
||||||
|
/server/
|
||||||
|
|
||||||
|
# projectiles files
|
||||||
|
.projectile
|
||||||
|
|
||||||
|
# directory configuration
|
||||||
|
.dir-locals.el
|
||||||
|
|
||||||
|
# network security
|
||||||
|
/network-security.data
|
22
LICENSE
Normal file
22
LICENSE
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
Copyright © 2021 Cassowary Rusnov
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of this software and associated documentation files (the
|
||||||
|
“Software”), to deal in the Software without restriction, including
|
||||||
|
without limitation the rights to use, copy, modify, merge, publish,
|
||||||
|
distribute, sublicense, and/or sell copies of the Software, and to
|
||||||
|
permit persons to whom the Software is furnished to do so, subject to
|
||||||
|
the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be
|
||||||
|
included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||||
|
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
|
7
README.md
Normal file
7
README.md
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# CiviCRM APIv4 #
|
||||||
|
|
||||||
|
**alpha state**
|
||||||
|
|
||||||
|
This is an extremely thin layer which supports basic operations against CiviCRM's APIv4. It does little processing,
|
||||||
|
and mostly encodes some knowledge about how to interact with the API so that this code need not be repeated in projects.
|
||||||
|
|
3
pyproject.toml
Normal file
3
pyproject.toml
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools", "wheel"]
|
||||||
|
build-backend = "setuptools-build_meta"
|
2
requirements.txt
Normal file
2
requirements.txt
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
requests
|
||||||
|
beautifulsoup4
|
36
setup.cfg
Normal file
36
setup.cfg
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
[metadata]
|
||||||
|
name = civicrmapi4
|
||||||
|
version = 0.0.1
|
||||||
|
description = A simple layer to interact with the CiviCRM APIv4
|
||||||
|
author = Cassowary Rusnov
|
||||||
|
author_email = rusnovc@gmail.com
|
||||||
|
keywords = api, civicrm
|
||||||
|
long_description = file: README.md
|
||||||
|
long_description_content_type = text/markdown
|
||||||
|
license_file = LICENSE
|
||||||
|
url =
|
||||||
|
license = MIT
|
||||||
|
platform = any
|
||||||
|
classifiers =
|
||||||
|
Development Status :: 3 - Alpha
|
||||||
|
Intended Audience :: Developers
|
||||||
|
License :: OSI Approved :: MIT License
|
||||||
|
Operating System :: OS Independent
|
||||||
|
Programming Language :: Python
|
||||||
|
Programming Language :: Python :: 3.6
|
||||||
|
Programming Language :: Python :: 3.7
|
||||||
|
Programming Language :: Python :: 3.8
|
||||||
|
Programming Language :: Python :: 3.9
|
||||||
|
Topic :: Internet
|
||||||
|
Topic :: Internet :: WWW/HTTP
|
||||||
|
|
||||||
|
[options]
|
||||||
|
packages =
|
||||||
|
civicrmapi4
|
||||||
|
|
||||||
|
zip_safe = true
|
||||||
|
install_requires =
|
||||||
|
python_version >= "3.6"
|
||||||
|
requests
|
||||||
|
beautifulsoup4
|
||||||
|
|
5
src/civicrmapi4/__init__.py
Normal file
5
src/civicrmapi4/__init__.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
"""Top-level package for civicrmapi4."""
|
||||||
|
|
||||||
|
__author__ = """Cassowary Rusnov"""
|
||||||
|
__email__ = "rusnovc@gmail.com"
|
||||||
|
__version__ = "0.0.1"
|
132
src/civicrmapi4/civicrmapi4.py
Normal file
132
src/civicrmapi4/civicrmapi4.py
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
"""Main module."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from typing import List, Optional, Dict, Union
|
||||||
|
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class APIError (BaseException):
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class CallFailed(APIError):
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class APIv4:
|
||||||
|
def __init__(self, base_url: str):
|
||||||
|
self.base_url = base_url
|
||||||
|
self.api_url = self.base_url + "/civicrm/ajax/api4"
|
||||||
|
self.session = None
|
||||||
|
|
||||||
|
def login(self, user: str, password: str):
|
||||||
|
self.session = requests.Session()
|
||||||
|
|
||||||
|
### Perform login post
|
||||||
|
self.session.cookies.update({"has_js": "1"})
|
||||||
|
postdata = {
|
||||||
|
"name": user,
|
||||||
|
"pass": password,
|
||||||
|
"form_id": "user_login_block",
|
||||||
|
}
|
||||||
|
res = self.session.post(self.base_url, data=postdata)
|
||||||
|
if (not res.ok):
|
||||||
|
log.error("Login failed. Code: {}. Result: {}".format(res.status_code, res.text))
|
||||||
|
# we should raise an error here.
|
||||||
|
self.session = None
|
||||||
|
return
|
||||||
|
# session now has the correct session cookie to do authenticated requests
|
||||||
|
# these headers seem to be required to pass CSRF
|
||||||
|
self.session.headers.update({
|
||||||
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
|
"Content-Type": "application/json;charset=utf-8",
|
||||||
|
})
|
||||||
|
log.info("Successfully logged into CRM.")
|
||||||
|
|
||||||
|
def _call(self, objName: str, action: str, params: Optional[Dict] = None) -> requests.Response:
|
||||||
|
"""
|
||||||
|
Low level, minimal processing call to the API.
|
||||||
|
"""
|
||||||
|
if (self.session is None):
|
||||||
|
log.error("Need to login first.")
|
||||||
|
raise APIError("Need to login first.")
|
||||||
|
|
||||||
|
url = self.api_url+'/'+objName+'/'+action
|
||||||
|
if params:
|
||||||
|
result = self.session.post(url, params={'params':json.dumps(params)}, data="")
|
||||||
|
else:
|
||||||
|
result = self.session.post(url, data="")
|
||||||
|
if (not result.ok):
|
||||||
|
raise CallFailed("Call returned non-2xx: {} {}".format(result.status_code, result.text))
|
||||||
|
|
||||||
|
return result.json()
|
||||||
|
|
||||||
|
def call_values(self, objName: str, action: str, params: Optional[Dict] = None) -> Optional[List]:
|
||||||
|
"""A quick wrapper to just return the values of an API call"""
|
||||||
|
result = self._call(objName, action, params)
|
||||||
|
if result and ("values" in result):
|
||||||
|
return result["values"]
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_fields(self, objName: str) -> List:
|
||||||
|
"""
|
||||||
|
Return a list of fields on the target object type.
|
||||||
|
"""
|
||||||
|
return self.call_values(objName, "getFields")
|
||||||
|
|
||||||
|
def get_actions(self, objName: str) -> List:
|
||||||
|
"""
|
||||||
|
Return a list of possible actions for a given object type.
|
||||||
|
"""
|
||||||
|
return self.call_values(objName, "getActions")
|
||||||
|
|
||||||
|
def get_entities(self, detailed: bool = False) -> Union[List[str], List[Dict]]:
|
||||||
|
"""Return a list of possible entities."""
|
||||||
|
ent = self.call_values("Entity", "get")
|
||||||
|
if detailed:
|
||||||
|
return ent
|
||||||
|
|
||||||
|
return [x["name"] for x in ent]
|
||||||
|
|
||||||
|
def get(self, objName: str, where: Optional[List]=None, limit: Optional[int]=None, select=Optional[List[str]]) -> List:
|
||||||
|
"""Get objects based on a where clause, optional limit and optional field list."""
|
||||||
|
params = {}
|
||||||
|
if limit is not None:
|
||||||
|
params["limit"] = limit
|
||||||
|
if where is not None:
|
||||||
|
params["where"] = where
|
||||||
|
if columns is not None and columns:
|
||||||
|
params["select"] = select
|
||||||
|
|
||||||
|
return self.call_values(objName, "get", params=params)
|
||||||
|
|
||||||
|
def create(self, objName: str, values: Dict) -> Dict:
|
||||||
|
"""Create an object using the values specified, and return the newly created object."""
|
||||||
|
result = self.call_values(objName, "create", params={"values": values})
|
||||||
|
if result:
|
||||||
|
return result[0]
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def delete(self, objName: str, where: List) -> int:
|
||||||
|
"""Delete objects with the specified where clauses and return the count.."""
|
||||||
|
result = self._call(objName, "delete", params={"where": where})
|
||||||
|
|
||||||
|
if "count" in result:
|
||||||
|
return result["count"]
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def replace(self, objName: str, records: List[Dict], where: List) -> List:
|
||||||
|
...
|
||||||
|
|
||||||
|
def update(self, objName: str, fields: Dict, where: List) -> List:
|
||||||
|
"""Update is an upsert operation."""
|
||||||
|
...
|
Loading…
Reference in New Issue
Block a user