Metadata-Version: 2.1
Name: petisco
Version: 0.21.2
Summary: Petisco is a framework for helping Python developers to build clean Applications
Home-page: https://github.com/alice-biometrics/petisco
Author: ALiCE Biometrics
Author-email: support@alicebiometrics.com
License: MIT
Keywords: DDD,Use Case,Clean Architecture,REST,Applications
Platform: UNKNOWN
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Description-Content-Type: text/markdown
Requires-Dist: meiga (>=1.2.7)
Requires-Dist: dataclasses-json (==0.3.8)
Requires-Dist: pyjwt (>=1.7.1)
Requires-Dist: cryptography (>=2.1.4)
Requires-Dist: py-healthcheck (==1.7.2)
Requires-Dist: pyyaml
Requires-Dist: deprecation
Requires-Dist: dotmap
Requires-Dist: dataclasses (==0.7) ; python_version < "3.7"
Requires-Dist: backports-datetime-fromisoformat (>=1.0.0) ; python_version < "3.7"
Provides-Extra: fixtures
Requires-Dist: pytest ; extra == 'fixtures'
Provides-Extra: flask
Requires-Dist: connexion (==2.6.0) ; extra == 'flask'
Requires-Dist: connexion[swagger-ui] ; extra == 'flask'
Requires-Dist: Flask-Cors (==3.0.7) ; extra == 'flask'
Provides-Extra: gunicorn
Requires-Dist: gunicorn ; extra == 'gunicorn'
Requires-Dist: json-logging-py (==0.2) ; extra == 'gunicorn'
Provides-Extra: rabbitmq
Requires-Dist: pika (==1.1.0) ; extra == 'rabbitmq'
Provides-Extra: redis
Requires-Dist: redis (>=3.3.11) ; extra == 'redis'
Requires-Dist: fakeredis (>=1.0.5) ; extra == 'redis'
Provides-Extra: sqlalchemy
Requires-Dist: sqlalchemy (>=1.3.11) ; extra == 'sqlalchemy'
Requires-Dist: sqlalchemy-utils ; extra == 'sqlalchemy'
Requires-Dist: PyMySQL (==0.9.2) ; extra == 'sqlalchemy'

# petisco :cookie:  [![version](https://img.shields.io/github/release/alice-biometrics/petisco/all.svg)](https://github.com/alice-biometrics/petisco/releases) [![ci](https://github.com/alice-biometrics/petisco/workflows/ci/badge.svg)](https://github.com/alice-biometrics/petisco/actions) [![pypi](https://img.shields.io/pypi/dm/petisco)](https://pypi.org/project/petisco/)

<img src="https://github.com/alice-biometrics/custom-emojis/blob/master/images/alice_header.png" width=auto>

Petisco is a framework for helping Python developers to build clean Applications in Python.

:warning: disclaimer: not stable yet


## Table of Contents
- [Installation :computer:](#installation-computer)
- [Getting Started :chart_with_upwards_trend:](#getting-started-chart_with_upwards_trend)
    * [Flask Application (by petisco :cookie:)](#flask-application-by-petisco-cookie)
    * [Configure your Application :rocket:](#configure-your-application-rocket)
    * [Handlers](#handlers)
      - [Controller Handler](#controller-handler)
    * [Model your Domain](#model-your-domain)
      - [Value Objects](#value-objects)
      - [Events](#events)
      - [Aggregate Root](#aggregate-root)
- [Testing :white_check_mark:](#testing-white_check_mark)
- [Extras](#extras)
- [Contact :mailbox_with_mail:](#contact-mailbox_with_mail)


## Installation :computer:

```console
pip install petisco
```

Installation with Extras 

```console
pip install petisco[flask]
pip install petisco[sqlalchemy]
pip install petisco[redis]
pip install petisco[rabbitmq]
pip install petisco[fixtures]
pip install petisco[flask,sqlalchemy,redis,rabbitmq,fixtures]
```

## Getting Started :chart_with_upwards_trend:	

### Flask Application (by Petisco :cookie:)

Check the following repo to learn how to use petisco with flask: [petisco-task-manager](https://github.com/alice-biometrics/petisco-task-manager)

### Configure your Application :rocket:

Configure your app using the `petisco.yml`

```yaml
app:
  name: taskmanager
  version:
    from_file: VERSION
framework:
    selected_framework: flask
    config_file: swagger.yaml
    port: 8080
    port_env: PETISCO_PORT
logger:
    selected_logger: logging
    name: petisco
    format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    config_func: taskmanager.src.config.logging_config_func.logging_config_func
persistence:
  config_func: taskmanager.src.config.config_persistence.config_persistence
  models:
    task: taskmanager.src.modules.tasks.infrastructure.persistence.models.task_model.TaskModel
infrastructure:
   services_provider_func: taskmanager.src.config.services_provider.services_provider
   repositories_provider_func: taskmanager.src.config.repositories_provider.repositories_provider
   event_manager_provider_func: taskmanager.src.config.event_manager_provider.event_manager_provider
   publish_deploy_event_func: True
   event_topic: taskmanager
```

If your app don't need persistence and repositories, you can remove it from the `petisco.yml`:

```yaml
app:
  name: taskmanager-nopersistence
  version:
    from_file: VERSION
framework:
    selected_framework: flask
    config_file: swagger.yaml
    port: 8080
    port_env: PETISCO_PORT
logger:
    selected_logger: logging
    name: petisco
    format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    config_func: taskmanager.src.config.logging_config_func.logging_config_func
infrastructure:
   services_provider_func: taskmanager.src.config.services_provider.services_provider
   event_manager_provider_func: taskmanager.src.config.event_manager_provider.event_manager_provider
   publish_deploy_event_func: True
   event_topic: taskmanager
```

### Handlers

**petisco** implement a sort of decorator to handle common behaviour of application elements.

#### Controller Handler

Add it to your entry point controller and manage the behaviour:

```python
    from petisco import controller_handler
    from meiga import Success

    @controller_handler()
    def my_controller(headers=None):
        return Success("Hello Petisco")
```
*controller_handler parameters:*

    Parameters
    ----------
    app_name
        Application Name
    app_version
        Application Version
    logger
        A ILogger implementation. Default NotImplementedLogger
    event_config
        EventConfig object. Here, you can define event management.
    token_manager
        TokenManager object. Here, you can define how to deal with JWT Tokens
    success_handler
        Handler to deal with Success Results
    error_handler
        Handler to deal with Failure Results
    correlation_id_provider
        Injectable function to provide correlation_id. By default is used flask_correlation_id_provider
    headers_provider
        Injectable function to provide headers. By default is used headers_provider
    logging_types_blacklist
        Logging Blacklist. Object of defined Type will not be logged. By default ( [bytes] ) bytes object won't be logged.
    petisco
        Use Petisco to set params as: app_name, app_version, logger, or event_manager (EventConfig)

### Model your Domain


#### Value Objects

Extend `ValueObject` to model your Value Objects.

Find some examples in [petisco/domain/value_objects](petisco/domain/value_objects)

#### Events

Extend `Event` to model your domain events.

```python
from petisco import Event, UserId, Name

class UserCreated(Event):
    user_id: UserId
    name: Name

    def __init__(self, user_id: UserId, name: Name):
        self.user_id = user_id
        self.name = name
        super().__init__()
```

To prevent the propagation of Id parameters throughout your domain, you can compose your Event with a [`InfoId`](petisco/domain/aggregate_roots/info_id.py)

```python
user_created = UserCreated(user_id, name).add_info_id(info_id)
```

#### Aggregate Root

Extend `AggregateRoot` to model your Aggregate Roots

```python
from petisco import AggregateRoot, UserId, Name
from my_code import UserCreated

class User(AggregateRoot):

    def __init__(self, name: Name, user_id: UserId):
        self.name = name
        self.user_id = user_id
        super().__init__()

    @staticmethod
    def create(name: Name):
        user = User(name, UserId.generate())
        user.record(UserCreated(user.user_id, user.name))
        return user
```

Use semantic constructors and `record` domain `Event`s very easy.

```python 
user = User.create(Name("Petisco"))
events = user.pull_domain_events() # Events ready to be published
```
### Testing :white_check_mark:

###### Petisco Fixtures

Import useful petisco fixtures with :

```python
from petisco.fixtures import *
```

We can use [petisco_client](petisco/fixtures/client.py) to simulate our client in acceptance tests

```python
import pytest

@pytest.mark.acceptance
def test_should_return_200_when_call_healthcheck(
    petisco_client
):
    response = petisco_client.get("/petisco/environment")
    assert response.status_code == 200
```

Included in *petisco_client* we can find [petisco_sql_database](petisco/fixtures/persistence.py).
This fixture will create and connect a database and after the test this will be deleted.


#### Extras

###### RabbitMQ

To test RabbitEventManager you need to run locally a RabbitMQ application, otherwise related test will be skipped.
Please, check the official doc here: https://www.rabbitmq.com/download.html

With docker

```console
docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
```

How to use the RabbitMQEventManager:

```python
from time import sleep

from pika import ConnectionParameters
from petisco import Event, RabbitMQEventManager, UserId


class UserCreated(Event):
    user_id: UserId

    def __init__(self, user_id: UserId):
        self.user_id = user_id
        super().__init__()


def callback(ch, method, properties, body):
    event = Event.from_json(body)
    print(f" [x] Received {event}")
    # do your stuff here
    ok = True
    if ok:
        ch.basic_ack(delivery_tag=method.delivery_tag)
    else:
        ch.basic_nack(delivery_tag=method.delivery_tag)


topic = "petisco"
event_manager = RabbitMQEventManager(
    connection_parameters=ConnectionParameters(host="localhost"),
    subscribers={topic: callback},
)

event_manager.publish(
    topic, UserCreated(user_id=UserId.generate())
)

sleep(0.5)  # wait for the callback

event_manager.unsubscribe_all()
```

## Development

### Using lume

```console
pip install lume
```

Then:

```console 
lume -install -all
```


## Contact :mailbox_with_mail:

support@alicebiometrics.com


