Skip to content

Instantly share code, notes, and snippets.

@uralbash
Last active March 23, 2016 05:44
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 uralbash/019c0629e1448c9d4e71 to your computer and use it in GitHub Desktop.
Save uralbash/019c0629e1448c9d4e71 to your computer and use it in GitHub Desktop.
Funny application demonstrates the capabilities of SQLAlchemy and Pyramid.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2014 uralbash <root@uralbash.ru>
#
# Distributed under terms of the MIT license.
"""
Funny application demonstrates the capabilities of SQLAlchemy and Pyramid.
It is something between phpMyAdmin and django.contrib.admin. SQLAlchemy with
Pyramid mapped on existing Django generated database but not vice versa.
Requirements
------------
pip install pyramid, sqlalchemy
pip install git+https://github.com/ITCase/pyramid_sacrud.git@develop
Demonstration
-------------
python SQLAlchemyMyAdmin.py
goto http://localhost:8080/sacrud/
"""
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from sqlalchemy import engine_from_config, MetaData
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
def get_metadata(engine):
# produce our own MetaData object
metadata = MetaData()
metadata.reflect(engine)
# we can then produce a set of mappings from this MetaData.
Base = automap_base(metadata=metadata)
# calling prepare() just sets up mapped classes and relationships.
Base.prepare()
return metadata
def quick_mapper(table):
class GenericMapper(Base):
__table__ = table
__tablename__ = table.name
return GenericMapper
def get_app():
config = Configurator()
settings = config.registry.settings
settings['sqlalchemy.url'] = "postgresql://postgres:postgres@localhost/your_database_name"
# Database
engine = engine_from_config(settings)
DBSession.configure(bind=engine)
metadata = get_metadata(engine)
tables = [quick_mapper(table) for table in metadata.sorted_tables]
# SACRUD
settings['pyramid_sacrud.models'] = (
('tables', tables),
)
config.include('ps_alchemy') # for pyramid_sacrud >= 0.3.0 version
config.include('pyramid_sacrud')
return config.make_wsgi_app()
if __name__ == '__main__':
app = get_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment