Skip to content

Instantly share code, notes, and snippets.

@christabor
Last active December 2, 2016 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christabor/ca318ab4994af78d17d1cca7c85ba80e to your computer and use it in GitHub Desktop.
Save christabor/ca318ab4994af78d17d1cca7c85ba80e to your computer and use it in GitHub Desktop.
PostgreSQL introspection to API - some automation experiments
# Make this folder import-able.
"""A RESTFUL API for {{ cookiecutter.app }}."""
from flask import Flask
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
import flask_restless
from flask_restful import Api
# First-party
import models
from sessions import SESSION, ENGINE
app = Flask('{{ cookiecutter.app }}')
app.debug = bool({{ cookiecutter.app }})
api = Api(app)
manager = flask_restless.APIManager(app, session=SESSION)
# Setup Migrations
migrate = Migrate(app, ENGINE)
# Setup script Manager
script_manager = Manager(app)
script_manager.add_command('db', MigrateCommand)
api_options = dict(
methods=['GET', 'POST', 'PATCH', 'DELETE', 'PUT'],
results_per_page=100,
)
# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
# Create the Flask-Restless API manager.
{% for model in cookiecutter.models %}
manager.create_api(models.{{ model }}, **api_options)
{% endfor %}
if __name__ == '__main__':
script_manager.run()
import json
from sqlalchemy.ext.declarative.api import DeclarativeMeta
import models
invalid = ['Base']
jsonconfig = dict(
app='myapp',
db='postgresql://user:pass@0.0.0.0:5432/mydb',
debug=True,
models=list(set([obj.__name__ for k, obj in globals().items() if isinstance(obj, DeclarativeMeta) and obj.__name__ not in invalid]))
)
with open('cookiecutter.json', 'wb') as config:
config.write(json.dumps(jsonconfig, indent=4))
{
"app": "myapp",
"debug": true,
"db_uri": "postgresql://user:pass@0.0.0.0:5432/mydb"
}
pip install sqlacodegen
pip install cookiecutter
pip install flask-restless
sqlacodegen postgresql://user:pass@0.0.0.0:5432/mydb > models.py
# Generate the cookiecutter json
python config_maker.py
# Assuming this is the folder where the actual python files/cookiecutter code lives.
cookiecutter myflask-app
"""Session setup for accessing models for {{ cookiecutter.app }}"""
from __future__ import absolute_import
from contextlib import contextmanager
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
DB_URI = '{{ cookiecutter.db_uri }}'
ENGINE = create_engine(DB_URI, echo=bool('{{ cookiecutter.debug }}'))
SESSION = scoped_session(sessionmaker(bind=ENGINE))
@contextmanager
def session_scope():
"""Provide a transactional scope around a series of db operations."""
_session = SESSION()
try:
yield _session
_session.commit()
except:
_session.rollback()
raise
finally:
_session.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment