Skip to main content

Adds SQLAlchemy support to your Flask application for handle apis.

Project description

SQLAlchemy-Api-Handler is an extension that adds support for handling apis with sqlalchemy. It helps to handle models with humanized ids once it is jsonified, throws api errors for some casting of value during the save time, and dictifies model objects into jsonified ones.

[![CircleCI](https://circleci.com/gh/betagouv/sqlalchemy-api-handler/tree/master.svg?style=svg)](https://circleci.com/gh/betagouv/sqlalchemy-api-handler/tree/master) [![Coverage Status](https://coveralls.io/repos/github/betagouv/sqlalchemy-api-handler/badge.svg)](https://coveralls.io/github/betagouv/sqlalchemy-api-handler)

Installing

Install and update using pip:

$ pip install -U SQLAlchemy-Api-Handler

A Simple Example

Suppose a request POST /users {“email”: “marx.foo@plop.fr”, name: “Marx Foo”} :

from flask import Flask, jsonify, request
from sqlalchemy_api_handler import ApiHandler

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///example.sqlite"
db = SQLAlchemy(app)
ApiHandler.set_db(db)

class User(ApiHandler, db.Model):
    email = db.Column(db.String, unique=True, nullable=False)
    name = db.Column(db.String, unique=True, nullable=False)

@app.route('/users', methods=['POST'])
def post_user():
  user = User(**request.form)
  ApiHandler.save(user)
  return jsonify(as_dict(user))

The success result will have stored a user object at, let’s say id = 32, and so will fetch an object at humanized id = humanize(32), ie

{"id": "EA", "email": "marx.foo@plop.fr", name: "Marx Foo"}

Playing with nesting data

Suppose a request GET /offers

from flask import Flask, jsonify, request
from sqlalchemy.orm import relationship
from sqlalchemy_api_handler import ApiHandler

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///example.sqlite"
db = SQLAlchemy(app)
ApiHandler.set_db(db)

class Venue(ApiHandler, db.Model):
    address = db.Column(db.String, unique=True, nullable=False)
    name = db.Column(db.String, unique=True, nullable=False)

class Offer(ApiHandler, db.Model):
    name = db.Column(db.String, unique=True, nullable=False)
    venueId = db.Column(db.BigInteger,
                 db.ForeignKey("venue.id"),
                 nullable=False,
                 index=True)
    venue = relationship('Venue',
                         foreign_keys=[venueId],
                         backref='offers')

class Stock(ApiHandler, db.Model):
    available = db.Column(db.Integer, nullable=False)
    offerId = db.Column(db.BigInteger,
                     db.ForeignKey('offer.id'),
                     index=True,
                     nullable=False)
    offer = relationship('Offer',
                         foreign_keys=[offerId],
                         backref='stocks')

venue = Venue(address="Somewhere I belong", name="MyVenue")
offer = Offer(name="MyOffer")
stock = Stock(available=10)
stock.offer = offer
offer.venue = venue
ApiHandler.save(stock)

offer_includes = [
  'stocks',
  {
    "key": 'venue',
    "includes": [
      '-address'
    ]
  }
]

@app.route('/offers', methods=['GET'])
def get_offers():
  offers = Offer.query.all()
  return jsonify(as_dict(offers, includes=offer_includes))

The success will return

[
  {
    "id": "AE",
    "name": "MyOffer",
    "stocks": [
      {
        "available": 10,
        "id": "AE"
      }
    ],
    "venue": {
      "name": "MyVenue"
    }
  }
]

Deploy

First, make sure that the deploy environment is started:

./sqlaah start

In a second tab, then:

  1. Change the __version__ into sqlalchemy_api_handler/__init__.py

  2. Pre publish:

./sqlaah prepublish
  1. Publish:

./sqlaah publish

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

SQLAlchemy-Api-Handler-0.2.15.tar.gz (26.7 kB view details)

Uploaded Source

Built Distribution

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

SQLAlchemy_Api_Handler-0.2.15-py2.py3-none-any.whl (24.2 kB view details)

Uploaded Python 2Python 3

File details

Details for the file SQLAlchemy-Api-Handler-0.2.15.tar.gz.

File metadata

  • Download URL: SQLAlchemy-Api-Handler-0.2.15.tar.gz
  • Upload date:
  • Size: 26.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.5

File hashes

Hashes for SQLAlchemy-Api-Handler-0.2.15.tar.gz
Algorithm Hash digest
SHA256 444f6c1a03500966c4a699bb9959dc86718475f9dc1e6bdb9bae1ced20ac8bee
MD5 3b6abc018938d43d06eba2d69f4403c9
BLAKE2b-256 dad4610fa7ff4de8b6081dfcb194d31580276476959dd3914eb50d6cb84fc602

See more details on using hashes here.

File details

Details for the file SQLAlchemy_Api_Handler-0.2.15-py2.py3-none-any.whl.

File metadata

  • Download URL: SQLAlchemy_Api_Handler-0.2.15-py2.py3-none-any.whl
  • Upload date:
  • Size: 24.2 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.5

File hashes

Hashes for SQLAlchemy_Api_Handler-0.2.15-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 8f79b1ff47ded512760963e18b5dfb72923a9879e625dae6037059f72e786a7b
MD5 40a4047c2772a7204e5472b8d796ca49
BLAKE2b-256 b6ed6221277ac76353bae4c488a1568654c6d3a89ffefac25cda2b010d1ff44b

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