Python Business Transactions Library - ContractsPY

Overview

Python Business Transactions Library - ContractsPY

Declare and define business transactions in Python. Use the contracts library to validate business transactions with Railway-oriented approach.

Compatibility

Tested on Python 3.8+

Installation

There is no additional dependencies. Library's footprint is small.

>>> pip install contractsPY

Contract functions

Contract functions are simple python functions that return True or False. They are used to define business rules for transactions. They accept only one argument, which is the current state of the transaction.

def my_contract(state):
    return state.a > state.b

if_fails decorator

You can use the if_fails decorator to define a message if the contract fails. This decorator is optional. If you don't use it, the message will be the name of the contract function.

Example (Create User):

Let's assume we have a user service that creates a new user. There are multiple steps to create a new user.

  1. First, we need to validate the user's data.
  2. Then, we need to make sure that the user doesn't already exist.
  3. We need to save the user to the database.
  4. We need to send an email to the user.

There are many ways to do this. We can use the contracts library to make it easier and more readable. All you need to do is to define a contract for each step. I can hear you saying "Why do I need to make things like this?". Well, I'm glad you asked.

  • Railway-oriented approach:

As we mentioned before, the contractsPY library uses the Railway-oriented approach. This approach helps you to handle every possible scenario on the way to the final step. That's why they called it "Railway-oriented".

Whenever you call a function, there are two possible returns (success and failure). Your business logic is executed in the success case. If the business logic fails, you can handle the failure case.

from contractspy import if_fails, Usecase


@if_fails(message="Not validated.")
def validate_inputs(state):
    if state.password and state.username:
        return True
    return False

@if_fails(message="User not generated.")
def generate_user(state):
    state.user = User(state.username, state.password)
    return True if state.user else False

@if_fails(message="User exists.")
def validate_user_exists(state):
    for user in users:
        if user.username == state.user.username:
            return False
    return True

@if_fails(message="User not saved.")
def persist_user(state):
    users.append(state.user)
    return True if state.user else False

register_user = Usecase()
register_user.contract = [
    validate_inputs,
    generate_user,
    validate_user_exists,
    persist_user
]

if  __name__ == '__main__':
    result = register_user.apply(username='johndoe', password='foobar')
    print(result)

Result:

As you can see from the Result, user was not created. The reason is that the user already exists. Now, we can handle the failure case, and send proper error messages to the user.

>>> Result(state={'username': 'johndoe', 'password': 'foobar', 'user': User(username=johndoe, password=foobar)}, case=error, message='User exists.')

The result object contains three fields. State, case, message. You can check the case and message to see what went wrong. If everything went well, you can pick a value from the state dictionary.

result.state = {'username': 'johndoe', 'password': 'foobar', 'user': User(username=johndoe, password=foobar)}

result.case = error

result.message = 'User exists.'

If there was no failure, the result should have been like this:

>>> Result(state={'username': 'johndoe', 'password': 'foobar', 'user': User(username=johndoe, password=foobar)}, case=success, message='Ok')

(C) Arzu Hussein

Owner
Arzu Huseynov
Python, JS Developer, Full-stack Instructor, Pasta lover, Coffee addict.
Arzu Huseynov
Temperature Monitoring and Prediction Using a Modified Lambda Architecture

Temperature Monitoring and Prediction Using a Modified Lambda Architecture A more detailed write up can be seen in this paper. Original Lambda Archite

Parsa Yousefi 2 Jun 27, 2022
An attendance bot that joins google meet automatically according to schedule and marks present in the google meet.

Google-meet-self-attendance-bot An attendance bot which joins google meet automatically according to schedule and marks present in the google meet. I

Sarvesh Wadi 12 Sep 20, 2022
twitter bot tha uses tweepy library class to connect to TWITTER API

TWITTER-BOT-tweepy- twitter bot that uses tweepy library class to connect to TWITTER API replies to mentions automatically and follows the tweet.autho

Muziwandile Nkomo 2 Jan 08, 2022
Simple, yet effective moderator bot for telegram. With reports, logs, profanity filter and more :3

👹 Samurai Telegram Bot Simple, yet effective moderator bot for telegram. With reports, logs, profanity filter and more :3 Description Personal bot, m

Abraham Tugalov 106 Dec 13, 2022
Telegram bot for making Heroku app.json by @AbirHasan2005

Heroku-app.json A Telegram bot for making Heroku app.json by @AbirHasan2005. Demo Bot Host Bot Deploy to Heroku Click Below Button to Deploy to Heroku

Abir Hasan 46 Nov 13, 2022
A Telegram Most Powerful Media Info Bot.

Media Info Bot Support 🚑 Demo For The Bot -Test Our Bot By Clicking The Button Below Deploy To Heroku 🗳 Press the Deploy Button to Get Your Own Bot.

Anonymous 5 May 16, 2022
Deezer client for python

Deezer Python Client A friendly Python wrapper around the Deezer API. Installation The package is published on PyPI and can be installed by running: p

Bruno Alla 103 Dec 19, 2022
Quadrirrotor UFABC - ROS/Gazebo

QuadROS_UFABC - Repositório utilizado durante minha dissertação de mestrado para simular sistemas de controle e estimação para navegação de um quadrirrotor utilizando visão computacional.

Mateus Ribeiro 1 Dec 13, 2022
Example of Telegram local API and aiogram 3.x

Telegram Local Full example of Telegram local application. Contains Telegram Bot API Local Telegram Bot API server based on aiogram Bot API Server ima

Oleg A. 9 Sep 16, 2022
Pydf: A modular Telegram Bot which provides Pdf Tools using PyPdf2

pyDF-Bot 🌍 Pydf - Pyrogram Document File Bot, a modular Telegram Bot which prov

HyDrix 2 Feb 18, 2022
Python Script to download hundreds of images from 'Google Images'. It is a ready-to-run code!

Google Images Download Python Script for 'searching' and 'downloading' hundreds of Google images to the local hard disk! Documentation Documentation H

Hardik Vasa 8.2k Jan 05, 2023
Python wrappers for INHECO ODTC and SCILA libraries by INHECO GmbH.

Python wrappers for INHECO ODTC and SCILA libraries by INHECO GmbH.

1 Feb 09, 2022
Discord bot developed by Delhi University Student Community!

DUSC-Bot Discord bot developed by Delhi University Student Community! Libraries Used Pycord - Documentation Features Can purge messages in bulk Drop-D

professor 1 Jan 29, 2022
trackbranch is a tool for developers that can be used to store collections of branches in the form of profiles.

trackbranch trackbranch is a tool for developers that can be used to store collections of branches in the form of profiles. This can be useful for sit

Kevin Morris 1 Oct 21, 2021
Basic query to access Traindex API

traindex-api-query Basic query to access Traindex API Please make sure to provide your Traindex API key to the line 8 in the script file. There are tw

Foretheta 1 Nov 11, 2021
POC de uma AWS lambda que executa a consulta de preços de criptomoedas, e é implantada na AWS usando Github actions.

Cryptocurrency Prices Overview Instalação Repositório Configuração CI/CD Roadmap Testes Overview A ideia deste projeto é aplicar o conteúdo estudado s

Gustavo Santos 3 Aug 31, 2022
The EscapePod Python SDK for Cyb3rVector's EscapePod Extension Proxy

EscapePod Extension SDK for Python by cyb3rdog This is the EscapePod Python SDK for Cyb3rVector's EscapePod Extension Proxy. With this SDK, you can: m

cyb3rdog 3 Mar 07, 2022
Python package for agilex robotics mobile base platform

This is Python API for Agilex Robotics Mobile base This is a python API for Can communication with Agilex Robotics Mobile base and controlling it. Sup

7 Sep 06, 2022
Python SDK for interacting with the Frame.io API.

python-frameio-client Frame.io Frame.io is a cloud-based collaboration hub that allows video professionals to share files, comment on clips real-time,

Frame.io 37 Dec 21, 2022
DB-Drive-CSV - This is app is can be used to access CSV file as JSON from Google Drive.

DB Drive CSV This is app is can be used to access CSV file as JSON from Google Drive. How To Use Create file/ upload file to Google Drive There's 2 fi

Hartawan Bahari M. 5 Oct 20, 2022