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
Web app for spotify playlist management with last.fm integration

Music Tools Set of utility tools for Spotify and Last.fm. Built on my other libraries for Spotify (spotframework), Last.fm (fmframework) and interfaci

andy 3 Dec 14, 2022
Source code for "Efficient Training of BERT by Progressively Stacking"

Introduction This repository is the code to reproduce the result of Efficient Training of BERT by Progressively Stacking. The code is based on Fairseq

Gong Linyuan 101 Dec 02, 2022
Simple Bot With Python 3.8+ For Converstaion Your Media

Media-Conversation Simple Bot With Python 3.8+ For Converstaion Your Media

Farzin 2 Dec 06, 2021
CoWIN Vaccination slot booking telegram bot with auto captcha resolver & alerting feature.Now, never miss a slot.

COWIN VACCINATION SLOT AUTO BOOKING (Bot with captcha solving & alerting capabilities. Never miss the vaccine slot.) June-10-2021/ 0030 hrs: 23 succes

Shashank Bafna 17 Nov 12, 2022
Integrating Amazon API Gateway private endpoints with on-premises networks

Integrating Amazon API Gateway private endpoints with on-premises networks Read the blog about this application: Integrating Amazon API Gateway privat

AWS Samples 12 Sep 09, 2022
Python wrapper for eBay API

python-ebay - Python Wrapper for eBay API This project intends to create a simple python wrapper around eBay APIs. Development and Download Sites The

Roopesh 99 Nov 16, 2022
For Help/Questions Join in discord

Simple-Nitro-Generator-Source Must have installed python! Discord: $MartoBossX#7777 Server: https://discord.gg/ErynDxTV5Y DONATE: (Crypto) BTC: bc1qg8

1 Jan 08, 2022
OliviaV2: danger bot with python

🎶 OLIVIA V2 🎵 Requirements 📝 FFmpeg NodeJS nodesource.com Python 3.7 or higher PyTgCalls 🧪 Get SESSION_NAME from below: Pyrogram 🎖 History Featur

Alvaro Einstein 2 Nov 04, 2021
A bot which provides online/offline and player status for Thicc SMP, using Replit.

AlynaaStatus A bot which provides online/offline and player status for Thicc SMP. Currently being hosted on Replit. How to use? Create a repl on Repli

QuanTrieuPCYT 8 Dec 15, 2022
Python wrapper for Revolt API

defectio is a direct implementation of the entire Revolt API and provides a way to authenticate and start communicating with Revolt servers. Similar interface to discord.py

Leon Bowie 26 Sep 18, 2022
A Simple Telegram Bot That Can Generate Strong Password With Many Features Written In Python Using Pyrogram

Password-Generator-Bot A Simple Telegram Bot That Can Generate Strong Password With Many Features Written In Python Using Pyrogram Features Random Pas

Muhammed Fazin 17 Dec 23, 2022
Github Workflows üzerinde Çalışan A101 Aktüel Telegam Bot

A101AktuelRobot Github Workflows üzerinde Çalışan A101 Aktüel Telegam Bot @A101AktuelRobot 💸 Bağış Yap ☕️ Kahve Ismarla 🌐 Telif Hakkı ve Lisans Copy

Ömer Faruk Sancak 10 Nov 02, 2022
Python based Discord Bot with a simple music player

C32 Discord Bot Discord bot that plays music Table Of Contents About the Project Built With Acknowledgements About The Project Play music using the !p

Christopher Burwell 2 Oct 17, 2021
A Telegram Filter Bot, Support Unlimited Filter. Also, The Bot can auto-filter telegram File | video

A Telegram Filter Bot, Support Unlimited Filter. Also, The Bot can auto-filter telegram File | video

Hash Minner 3 Nov 27, 2021
Python library for RetroMMO related stuff, including API wrapper

python library for RetroMMO related stuff, including API wrapper.

1 Nov 25, 2021
Creates Spotify playlists from Spinitron playlists.

spin2spot Creates Spotify playlists from Spinitron playlists. Quick Start You can use spin2spot as a command-line tool: Erik Didriksen 1 Aug 28, 2021

Program that automates the bump of the Disboard Bot. Done 100% in Python with PyAutoGUI library

Auto-Discord-Bump Program that automates the bump of the Disboard Bot done 100% in python with PyAutoGUI How to configue You will need 3 things before

Mateus 1 Dec 19, 2021
This Is A Python Program To Showcase Two Modules (Gratient And Fade)

Hellooo, It's PndaBoi Here! This Is A Python Program To Showcase Two Modules (Gratient And Fade). I Really Like Both Of These Modules So I Decided To

PndaBoi! 6 May 31, 2022
This repository contains modules that extend / modify parts of Odoo ERP

Odoo Custom Addons This repository contains addons that extend / modify parts of Odoo ERP. Addons list account_cancel_permission Only shows the button

Daniel Luque 3 Dec 28, 2022
A maintained fork of Danny's discord.py

Nextcord A modern, easy-to-use, feature-rich, and async-ready API wrapper for Discord written in Python. Fork notice This is a fork of discord.py, whi

977 Jan 05, 2023