Skip to main content

NextORM integration in Morepath

Project description

CI Status https://img.shields.io/pypi/v/more.next.svg https://img.shields.io/pypi/pyversions/more.next.svg

more.next: NextORM integration in Morepath

This package provides Morepath integration for the NextORM Object-Relational Mapper library.

This package binds the database session to the request so you can interact with the database in your App directly without using db_session.

Quick start

Install more.next:

$ pip install -U more.next

Extend your App class from NextApp:

from more.next import NextApp

class App(NextApp):
    pass

Create your model:

from nextorm import Database, Entity, Opt, PK

db = Database()


class Document(Entity):
    _table_ = 'document'

    id: PK[int]
    title: Opt[str]
    content: Opt[str]

    def update(self, payload={}):
        self.set(**payload)

    def remove(self):
        self.delete()

Setup the database in your start script:

import morepath

from .app import App
from .model import db


def run():
    db.bind("sqlite", "app.db")
    db.generate_mapping(create_tables=True)

    morepath.autoscan()
    morepath.run(App())

Now you can use the model in your path:

from .app import App
from .model import Document


@App.path(model=Document, path='documents/{id}')
def get_document(request, id=0):
    return Document[id]

And in your view:

from .app import App
from .model import Document


@App.json(model=Document)
def document_default(self, request):
    return {
        'id': self.id,
        'title': self.title,
        'content': self.content,
        'link': request.link(self)
    }


@App.json(model=Document, request_method='PUT')
def document_update(self, request):
    self.update(request.json)


@App.json(model=Document, request_method='DELETE')
def document_remove(self, request):
    self.remove()

Settings

You can set the arguments which are passed to db_session in the next section of your settings.

The default settings are:

@App.setting_section(section='next')
def get_next_settings():
    return {
        'allowed_exceptions': [],
        'immediate': False,
        'retry': 0,
        'retry_exceptions': [TransactionError],
        'serializable': False,
        'strict': False
    }

More information about the arguments you find in the NextORM API documentation.

You can also use the database settings section for your database setup, which allows you to use different setups for production, development and testing environments.

Just create create an App for each environment and load specific settings files:

class App(NextApp):
    pass

with open('settings/default.yml') as defaults:
  defaults_dict = yaml.load(defaults)

App.init_settings(defaults_dict)


class ProductionApp(App):
    pass


with open('settings/production.yml') as settings:
    settings_dict = yaml.load(settings)

ProductionApp.init_settings(settings_dict)


class TestApp(App):
    pass


with open('settings/test.yml') as settings:
    settings_dict = yaml.load(settings)

TestApp.init_settings(settings_dict)

The database configuration in the YAML settings files, depending on the database you use, could look something like:

database:
  provider: sqlite
  filename: app.db
  create_db: true

In your start script you setup the database and load the App according to the RUN_ENV environment variable:

import os
import morepath

from .app import App, ProductionApp, TestApp
from .model import db


def setup_db(app):
    db_params = app.settings.database.__dict__.copy()
    db.bind(**db_params)
    db.generate_mapping(create_tables=True)

def run():
  morepath.autoscan()

  if os.getenv('RUN_ENV') == 'production':
      ProductionApp.commit()
      app = ProductionApp()
  elif os.getenv('RUN_ENV') == 'test':
      TestApp.commit()
      app = TestApp()
  else:
      App.commit()
      app = App()

  setup_db(app)
  morepath.run(app)

Detail about the database configuration you find in the NextORM documentation.

Side effects

If you want to trigger side effects (like sending an email or writing to filesystem) on database commits you can emit a signal in the @request.after of the view which triggers the side effects.

Like this the side effects will be triggered just before the database session gets committed and only if it wasn’t rolled back.

This example uses more.emit:

@App.json(model=Document, request_method='PUT')
def document_update(self, request):
    self.update(request.json)

    @request.after
    def after(response):
        request.app.signal.emit('document_updated', self, request)

Altenatively you can use in your model the NextORM after_insert(), after_update() or after_delete() lifetime-hooks. This makes sure that the side effect is triggered after the database session has committed.

The drawback is that you don’t have easy access to the request or app in the model.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

more_next-0.1.1.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

more_next-0.1.1-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file more_next-0.1.1.tar.gz.

File metadata

  • Download URL: more_next-0.1.1.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for more_next-0.1.1.tar.gz
Algorithm Hash digest
SHA256 95efa1d3af6f3987490a0339c312c27f99182c527781ab6e7875d7b6671f0d2a
MD5 38e183e91ac91f8a48a61c070b78f679
BLAKE2b-256 5392099867cfebb1111df32165f5e9d6fc87f91821295bf770f2c6393fac4068

See more details on using hashes here.

File details

Details for the file more_next-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: more_next-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 6.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for more_next-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1e1bf0d714370fb1d030cff6172d8ca33d25691a283a2a96e5234018a3354497
MD5 c9ae03d7cfd0172ffe1aa55437f794a1
BLAKE2b-256 68736d92c363fce91d8a8f50429af35520757a3379998bdab04c72d103080be9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page