Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binding DB sessions based on SQLAlchemy 1, changing how to declare Base Model classes, and other code modernization #50

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,18 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
codebase
- Use host 0.0.0.0 for test servers
- Fix bug with example-flask-peewee import
- Fix bug with example-cherrypy import (Specify parent package name when importing setting, local_setting modules)
- Changed the DB session creation, DB connection closing, and DB model creation to align with SQLAlchemy 2. (for example-flask program)
- Removed flask-script package from requirements.txt as it doesn't work with recent flasks (programs: example-flask, example-flask-mongoengine, example-flask-peewee)
- Configured the manage.py file to use the CLI environment built into flask (programs: example-flask, example-flask-mongoengine, example-flask-peewee) as the flask-script package has been removed
- Changed the part that binds the DB session to comply with SQLAlchemy 2 (for example-pyramid program)
- Changed the part that fetches authenticated users from DB to be SQLAlchemy 2 based (for example-pyramid program)
- Removed all entries in the SOCIAL_AUTH_KEYS dictionary in local_settings.py.template into a single variable (tests showed that adding provider-supplied key information in SOCIAL_AUTH_KEYS caused errors on social login) (for example-pyramid program)
- Changed the DB model creation part. (for example-pyramid program)
- Error occurred when social login integration was completed because it was supposed to find google plus ID in the redirected URL. google plus is discontinued, so delete the part that gets plus ID. (for example-pyramid program)
- Changed the part that binds the DB session and creates the Base Model class to comply with SQLAlchemy 2 (for example-tornado, example-webpy program)
- Added local_settings.py.template file to reference other programs to easily generate local_settings.py (for example-tornado, example-webpy program)
- Fixed an error importing the local_settings module from settings.py (for the example-tornado program)
- Change the declaration of the Model class based on SQLAlchemy 2 (corresponds to the example-tornado, example-webpy program)
- Fix bug with example-webpy import
- Separated AUTHENTICATION_BACKENDS and PIPELINE entries into separate settings.py entries as web.config entries in app.py (for example-webpy program)
6 changes: 3 additions & 3 deletions example-cherrypy/example/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import sys

import cherrypy
import settings
from common import filters
from common.utils import common_context, url_for
from example import settings
from jinja2 import Environment, FileSystemLoader
from social_cherrypy.utils import backends, load_strategy
from social_cherrypy.views import CherryPyPSAViews
Expand Down Expand Up @@ -66,7 +66,7 @@ def get_settings(module):
SOCIAL_SETTINGS = get_settings(settings)

try:
import local_settings
from example import local_settings

SOCIAL_SETTINGS.update(get_settings(local_settings))
except ImportError:
Expand All @@ -82,7 +82,7 @@ def run_app(listen_address="0.0.0.0:8001"):
"server.socket_port": int(port),
"server.socket_host": host,
"tools.sessions.on": True,
"tools.sessions.storage_type": "ram",
"tools.sessions.storage_class": cherrypy.lib.sessions.RamSession,
"tools.db.on": True,
"tools.authenticate.on": True,
"SOCIAL_AUTH_USER_MODEL": "example.db.user.User",
Expand Down
6 changes: 4 additions & 2 deletions example-cherrypy/example/db/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import DeclarativeBase

Base = declarative_base()

class Base(DeclarativeBase):
pass
8 changes: 4 additions & 4 deletions example-cherrypy/example/db/saplugin.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from cherrypy.process import plugins
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm import Session


class SAEnginePlugin(plugins.SimplePlugin):
def __init__(self, bus, connection_string=None):
self.sa_engine = None
self.connection_string = connection_string
self.session = scoped_session(sessionmaker(autoflush=True, autocommit=False))
self.session = Session(autoflush=True, autocommit=False)
super().__init__(bus)

def start(self):
Expand All @@ -23,7 +23,7 @@ def stop(self):
self.sa_engine = None

def bind(self):
self.session.configure(bind=self.sa_engine)
self.session.bind = self.sa_engine
return self.session

def commit(self):
Expand All @@ -33,4 +33,4 @@ def commit(self):
self.session.rollback()
raise
finally:
self.session.remove()
self.session.close()
17 changes: 10 additions & 7 deletions example-cherrypy/example/db/user.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
from sqlalchemy import Boolean, Column, Integer, String
from typing import Optional

from sqlalchemy import Boolean, String
from sqlalchemy.orm import Mapped, mapped_column

from . import Base


class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String(200))
password = Column(String(200), default="")
name = Column(String(100))
email = Column(String(200))
active = Column(Boolean, default=True)
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(200))
password: Mapped[str] = mapped_column(String(200), default="")
name: Mapped[Optional[str]] = mapped_column(String(100))
email: Mapped[Optional[str]] = mapped_column(String(200))
active: Mapped[bool] = mapped_column(default=True)

def is_active(self):
return self.active
Expand Down
16 changes: 11 additions & 5 deletions example-flask-mongoengine/manage.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
#!/usr/bin/env python
import click
from example import app, db
from flask_script import Manager, Server, Shell
from flask.cli import FlaskGroup

manager = Manager(app)
manager.add_command("runserver", Server())
manager.add_command("shell", Shell(make_context=lambda: {"app": app, "db": db}))

@click.group(cls=FlaskGroup, create_app=lambda: app)
def cli():
"""Management script for the Example Flask Social Login application."""

@app.shell_context_processor
def make_shell_context():
return dict(db=db)


if __name__ == "__main__":
manager.run()
cli()
1 change: 0 additions & 1 deletion example-flask-mongoengine/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
-r ../requirements.txt
flask-script
flask-mongoengine
social-auth-app-flask-mongoengine
14 changes: 8 additions & 6 deletions example-flask-peewee/manage.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#!/usr/bin/env python
import click
from example import app, database
from flask_script import Manager, Server, Shell
from flask.cli import FlaskGroup

manager = Manager(app)
manager.add_command("runserver", Server())
manager.add_command("shell", Shell(make_context=lambda: {"app": app}))

@click.group(cls=FlaskGroup, create_app=lambda: app)
def cli():
"""Management script for the Example Flask Social Login application."""

@manager.command

@app.cli.command()
def syncdb():
from example.models.user import User
from social_flask_peewee.models import FlaskStorage
Expand All @@ -25,4 +27,4 @@ def syncdb():


if __name__ == "__main__":
manager.run()
cli()
1 change: 0 additions & 1 deletion example-flask-peewee/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
-r ../requirements.txt
flask-script
social-auth-app-flask-peewee
9 changes: 4 additions & 5 deletions example-flask/example/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from social_flask.utils import load_strategy
from social_flask_sqlalchemy.models import init_social
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm import Session

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Expand All @@ -25,8 +25,7 @@

# DB
engine = create_engine(app.config["SQLALCHEMY_DATABASE_URI"])
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db_session = scoped_session(Session)
db_session = Session(engine, autocommit=False, autoflush=False)

app.register_blueprint(social_auth)
init_social(app, db_session)
Expand All @@ -42,7 +41,7 @@
@login_manager.user_loader
def load_user(userid):
try:
return models.user.User.query.get(int(userid))
return db_session.get(models.user.User, int(userid))
except (TypeError, ValueError):
pass

Expand All @@ -60,7 +59,7 @@ def commit_on_success(error=None):
else:
db_session.rollback()

db_session.remove()
db_session.close()


@app.context_processor
Expand Down
23 changes: 13 additions & 10 deletions example-flask/example/models/user.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
from typing import Optional

from example import db_session
from flask_login import UserMixin
from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


Base = declarative_base()
Base.query = db_session.query_property()
class Base(DeclarativeBase):
pass


class User(Base, UserMixin):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String(200))
password = Column(String(200), default="")
name = Column(String(100))
email = Column(String(200))
active = Column(Boolean, default=True)
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(200))
password: Mapped[str] = mapped_column(String(200), default="")
name: Mapped[Optional[str]] = mapped_column(String(100))
email: Mapped[Optional[str]] = mapped_column(String(200))
active: Mapped[bool] = mapped_column(default=True)

def is_active(self):
return self.active
21 changes: 12 additions & 9 deletions example-flask/manage.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
#!/usr/bin/env python
import click
from example import app, db_session, engine
from flask_script import Manager, Server, Shell
from flask.cli import FlaskGroup

manager = Manager(app)
manager.add_command("runserver", Server())
manager.add_command(
"shell", Shell(make_context=lambda: {"app": app, "db_session": db_session})
)

@click.group(cls=FlaskGroup, create_app=lambda: app)
def cli():
"""Management script for the Example Flask Social Login application."""

@manager.command
@app.shell_context_processor
def make_shell_context():
return dict(db_session=db_session)


@app.cli.command()
def syncdb():
from example.models import user
from social_flask_sqlalchemy import models
Expand All @@ -19,4 +22,4 @@ def syncdb():


if __name__ == "__main__":
manager.run()
cli()
1 change: 0 additions & 1 deletion example-flask/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
-r ../requirements.txt
Flask
Flask-Login
Flask-Script
Werkzeug
Jinja2
social-auth-app-flask
Expand Down
2 changes: 1 addition & 1 deletion example-pyramid/example/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def get_settings(module):
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
DBSession.bind = engine
Base.metadata.bind = engine
session_factory = SignedCookieSessionFactory("thisisasecret")
settings["jinja2.globals"] = {"url": utils.url_for}
Expand Down
3 changes: 2 additions & 1 deletion example-pyramid/example/auth.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from example.models import DBSession, User
from pyramid.events import BeforeRender, subscriber
from social_pyramid.utils import backends
from sqlalchemy import select


def login_user(backend, user, user_social_auth):
Expand All @@ -14,7 +15,7 @@ def login_required(request):
def get_user(request):
user_id = request.session.get("user_id")
if user_id:
user = DBSession.query(User).filter(User.id == user_id).first()
user = DBSession.scalar(select(User).where(User.id == user_id))
else:
user = None
return user
Expand Down
Loading