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

Py2transactions #61

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
*.egg-info
*.bak
*.pyc
.*.sw?
build
Expand Down
79 changes: 59 additions & 20 deletions baph/__init__.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,67 @@
from importlib import import_module
import os
import sys
from types import ModuleType

import six
from six.moves import html_parser


try:
from collections import MutableMapping
except ImportError:
import collections
import collections.abc
collections.MutableMapping = collections.abc.MutableMapping
collections.Mapping = collections.abc.Mapping

try:
HTMLParseError = html_parser.HTMLParseError
except AttributeError:
# create a dummy class for Python 3.5+ where it's been removed
class HTMLParseError(Exception):
pass

html_parser.HTMLParseError = HTMLParseError


if six.PY3:
# coffin/template/__init__.py uses 'import library' for a relative import,
# which doesn't work in python3. To get around this we create an actual
# 'library' module so the import works
pass


def setup():
from baph.apps import apps
from baph.conf import settings
from baph.utils.log import configure_logging
from baph.apps import AppConfig, apps
from baph.conf import settings
from baph.utils.log import configure_logging

configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)

module = ModuleType('django.apps')
setattr(module, 'AppConfig', AppConfig)
sys.modules['django.apps'] = module

apps.populate(settings.INSTALLED_APPS)

configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
apps.populate(settings.INSTALLED_APPS)

def replace_settings_class():
from django import conf
from baph.conf import settings
conf.settings = settings
from django import conf
from baph.conf import settings
conf.settings = settings


def apply_patches():
import os
from importlib import import_module

patch_dir = os.path.join(os.path.dirname(__file__), 'patches')
for mod_name in os.listdir(patch_dir):
filename = os.path.join(patch_dir, mod_name)
with open(filename, 'rt') as fp:
src = fp.read()
code = compile(src, filename, 'exec')
mod = import_module(mod_name)
exec(code, mod.__dict__)
patch_dir = os.path.join(os.path.dirname(__file__), 'patches')
for mod_name in os.listdir(patch_dir):
filename = os.path.join(patch_dir, mod_name)
with open(filename, 'rt') as fp:
src = fp.read()
code = compile(src, filename, 'exec')
mod = import_module(mod_name)
exec(code, mod.__dict__)


replace_settings_class()
apply_patches()
apply_patches()
2 changes: 1 addition & 1 deletion baph/apps/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .config import AppConfig
from .registry import apps

__all__ = ['AppConfig', 'apps']
__all__ = ['AppConfig', 'apps']
5 changes: 4 additions & 1 deletion baph/apps/registry.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import threading
from collections import Counter, OrderedDict, defaultdict

from functools32 import lru_cache
try:
from functools32 import lru_cache
except ImportError:
from functools import lru_cache

from .config import AppConfig

Expand Down
4 changes: 0 additions & 4 deletions baph/auth/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
from .permission import Permission
print 'Permission imported'
from .organization import Organization
print 'Organization imported'
from .group import Group
print 'Group imported'
from .user import AnonymousUser, User
print 'User imported'
from .usergroup import UserGroup
from .permissionassociation import PermissionAssociation
from .oauth_ import OAuthConsumer, OAuthNonce
4 changes: 2 additions & 2 deletions baph/auth/models/oauth_/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.conf import settings
from oauth import oauth
import oauth2 as oauth
from sqlalchemy import (Column, DateTime, ForeignKey, Integer, String,
UniqueConstraint)
from sqlalchemy.orm import relationship
Expand Down Expand Up @@ -30,7 +30,7 @@ def as_consumer(self):
'''Creates an oauth.OAuthConsumer object from the DB data.
:rtype: oauth.OAuthConsumer
'''
return oauth.OAuthConsumer(self.key, self.secret)
return oauth.Consumer(self.key, self.secret)


class OAuthNonce(Base):
Expand Down
5 changes: 3 additions & 2 deletions baph/auth/registration/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from django import forms
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
import six
from sqlalchemy.orm import joinedload

from baph.auth.models import User, Organization
Expand Down Expand Up @@ -188,7 +189,7 @@ def save(self):
""" Generate a random username before falling back to parent signup form """
session = orm.sessionmaker()
while True:
username = unicode(sha_constructor(str(random.random())).hexdigest()[:5])
username = six.text_type(sha_constructor(str(random.random()).encode('utf8')).hexdigest()[:5])
user = session.query(User).filter(User.username==username).first()
if not user:
break
Expand All @@ -211,7 +212,7 @@ def __init__(self, user, *args, **kwargs):
"""
super(ChangeEmailForm, self).__init__(*args, **kwargs)
if not isinstance(user, User):
raise TypeError, "user must be an instance of %s" % User._meta.model_name
raise TypeError("user must be an instance of %s" % User._meta.model_name)
else: self.user = user

def clean_email(self):
Expand Down
3 changes: 2 additions & 1 deletion baph/auth/registration/managers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime
import re

import six
from sqlalchemy.orm import joinedload

from baph.auth.models import User, Organization
Expand All @@ -19,7 +20,7 @@ class SignupManager(object):
@staticmethod
def create_user(username, email, password, active=False, send_email=True,
**kwargs):
uname = username.encode('utf-8') if isinstance(username, unicode) else username
uname = username.encode('utf-8') if isinstance(username, six.text_type) else username
salt, activation_key = generate_sha1(uname)

#org_key = Organization._meta.verbose_name
Expand Down
2 changes: 1 addition & 1 deletion baph/auth/registration/tests/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test_secure_required(self):
# Test if the redirected url contains 'https'. Couldn't use
# ``assertRedirects`` here because the redirected to page is
# non-existant.
self.assertTrue('https' in str(response))
self.assertTrue('https' in response['location'])

# Set back to the old settings
auth_settings.BAPH_USE_HTTPS = False
2 changes: 1 addition & 1 deletion baph/auth/registration/tests/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class ChangeEmailFormTests(TestCase):
def test_change_email_form(self):
session = orm.sessionmaker()
user = session.query(User).get(1)
session.close()
#session.close()
invalid_data_dicts = [
# No change in e-mail address
{'data': {'email': '[email protected]'},
Expand Down
1 change: 1 addition & 0 deletions baph/auth/registration/tests/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ def test_delete_expired_users(self):
expired_user = SignupManager.create_user(**self.user_info)
expired_user.date_joined -= datetime.timedelta(days=auth_settings.BAPH_ACTIVATION_DAYS + 1)
expired_user.save()
self.session.expunge_all()

deleted_users = SignupManager.delete_expired_users()

Expand Down
16 changes: 10 additions & 6 deletions baph/auth/registration/tests/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def test_valid_activation(self):
# reverse('baph_profile_detail', kwargs={'username': user.username}))

user = session.query(User).filter_by(email='[email protected]').first()
session.close()
#session.close()
self.failUnless(user.is_active)

def test_activation_expired_retry(self):
Expand All @@ -61,7 +61,7 @@ def test_activation_expired_retry(self):
self.assertContains(response, "Request a new activation link")

user = session.query(User).filter_by(email='[email protected]').first()
session.close()
#session.close()
self.failUnless(not user.is_active)
auth_settings.BAPH_ACTIVATION_RETRY = False

Expand All @@ -86,12 +86,12 @@ def test_retry_activation_ask(self):
# We must reload the object from database to get the new key
user = session.query(User).filter_by(email='[email protected]').first()
new_key = user.signup.activation_key
session.close()
#session.close()
self.assertContains(response, "Account re-activation succeded")

self.failIfEqual(old_key, new_key)
user = session.query(User).filter_by(email='[email protected]').first()
session.close()
#session.close()
self.failUnless(not user.is_active)

self.failUnlessEqual(len(mail.outbox), 2)
Expand All @@ -103,7 +103,7 @@ def test_retry_activation_ask(self):

session = orm.sessionmaker()
user = session.query(User).filter_by(email='[email protected]').first()
session.close()
#session.close()
self.failUnless(user.is_active)
auth_settings.BAPH_ACTIVATION_RETRY = False

Expand Down Expand Up @@ -332,6 +332,7 @@ def test_signout_view(self):

def test_change_email_view(self):
""" A ``GET`` to the change e-mail view. """
auth_settings.BAPH_AUTH_WITHOUT_USERNAMES = False
response = self.client.get(reverse('baph_email_change'))

# Anonymous user should not be able to view the profile page
Expand All @@ -349,6 +350,7 @@ def test_change_email_view(self):

self.assertTemplateUsed(response,
'registration/email_form.html')
auth_settings.BAPH_AUTH_WITHOUT_USERNAMES = True

def test_change_valid_email_view(self):
""" A ``POST`` with a valid e-mail address """
Expand All @@ -369,8 +371,10 @@ def test_change_password_view(self):
self.failUnless(response.context['form'],
PasswordChangeForm)

#@override_settings(BAPH_AUTH_WITHOUT_USERNAMES=False)
def test_change_password_view_success(self):
""" A valid ``POST`` to the password change view """
auth_settings.BAPH_AUTH_WITHOUT_USERNAMES = False
self.client.login(identification='john', password='blowfish')

new_password = 'suckfish'
Expand All @@ -384,7 +388,7 @@ def test_change_password_view_success(self):
# Check that the new password is set.
session = orm.sessionmaker()
john = session.query(User).filter_by(username='john').first()
session.close()
#session.close()
self.failUnless(john.check_password(new_password))

'''
Expand Down
4 changes: 2 additions & 2 deletions baph/auth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def generate_sha1(string, salt=None):

"""
if not salt:
salt = sha1(str(random.random())).hexdigest()[:5]
hash = sha1(salt+str(string)).hexdigest()
salt = sha1(str(random.random()).encode('utf8')).hexdigest()[:5]
hash = sha1(salt.encode('utf8') + str(string).encode('utf8')).hexdigest()

return (salt, hash)
19 changes: 14 additions & 5 deletions baph/conf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@
import pkgutil
import sys

from chainmap import ChainMap
try:
from collections import ChainMap
except ImportError:
from chainmap import ChainMap
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import LazyObject, empty
import six

from baph.core.preconfig.loader import PreconfigLoader

Expand Down Expand Up @@ -47,8 +51,7 @@ def __new__(cls, name, bases, attrs):
attrs['__module__'] = 'django.conf'
return super(SettingsMeta, cls).__new__(cls, name, bases, attrs)

class LazySettings(LazyObject):
__metaclass__ = SettingsMeta
class LazySettings(six.with_metaclass(SettingsMeta, LazyObject)):

def _setup(self, name=None):
settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
Expand Down Expand Up @@ -164,6 +167,10 @@ def load_settings_module(self, module, explicit=True):
if setting.isupper():
setting_value = getattr(module, setting)
self.apply_setting(setting, setting_value, explicit)
if hasattr(module, 'apply'):
# call the apply func, passing the current settings dict
module.apply(self.__dict__)

self.actions = self.actions.parents
logger.info(msg.ljust(64) + 'SUCCESS')

Expand Down Expand Up @@ -201,7 +208,9 @@ def get_package_path(self, package):
return None
if not loader.is_package(package):
raise ValueError('%r is not a package' % package)
self.package_paths[package] = loader.filename
fullpath = loader.get_filename()
path, filename = fullpath.rsplit('/', 1)
self.package_paths[package] = path
return self.package_paths[package]

@staticmethod
Expand All @@ -222,7 +231,7 @@ def compile_module(module):
content = fp.read()
node = ast.parse(content, path)
code = compile(node, path, 'exec')
exec code in module.__dict__
exec(code, module.__dict__)

def load_module_settings(self, module_name):
msg = ' %s' % module_name
Expand Down
18 changes: 0 additions & 18 deletions baph/context_processors/__init__.py

This file was deleted.

Loading