Exemple #1
0
setup-app`) and provides the base testing objects.
"""
from unittest import TestCase

from paste import fixture
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp

import pylons.test

from pylons_common.lib.log import create_logger

logger = create_logger("tethr.tests")

from pylons_common.lib.utils import objectify
from pylons_common.lib.exceptions import ClientException, CompoundException
import simplejson as json

import formencode

from tethr.model.meta import Session
from tethr.lib.helpers import url_for, api_url

# Invoke websetup with the current config file
SetupCommand("setup-app").run([pylons.test.pylonsapp.config["__file__"]])

environ = {}
Exemple #2
0
This module initializes the application via ``websetup`` (`paster
setup-app`) and provides the base testing objects.
"""
from unittest import TestCase

from paste import fixture
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp

import pylons.test

from pylons_common.lib.log import create_logger
logger = create_logger('vanillons.tests')

from pylons_common.lib.utils import objectify
from pylons_common.lib.exceptions import ClientException, CompoundException
import simplejson as json

import formencode

from vanillons.model.meta import Session
from vanillons.lib.helpers import url_for, api_url

# Invoke websetup with the current config file
SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])

environ = {}
Exemple #3
0
from pylons import request, response

import simplejson
from sqlalchemy import sqlalchemy as sa

from pylons_common.lib.exceptions import *
from pylons_common.web.response import ajax, FORMAT_JSON
import time, sys, cgi

from pylons_common.lib.log import create_logger
logger = create_logger('pylons_common.controllers')

__all__ = ['ApiMixin']
# api modules can define ID_PARAM to connect the id request.param to a function
# parameter on the functions in the module. 
ID_CONNECTOR_PARAM = 'ID_PARAM'
REAL_USER_PARAM = 'real_user'

# Map HTTP methods to module functions.
# eg PUT /api/v1/campaign/abc123 calls campaign.create
http_to_functions = {
    'get':    'get',
    'put':    'create',
    'post':   'edit',
    'delete': 'deactivate'
}

class ApiMixin(object):
    """
    Will look for self.
      API_MODULE_BASE
Exemple #4
0
from pylons_common.lib.log import create_logger
logger = create_logger('pylons_common.web.validation')

from pylons_common.lib.utils import objectify

def validate(validation_class, fill_out_args=True, allow_extra_fields=True, **kwargs):
    
    args = kwargs
    if fill_out_args:
        
        def get_val(kw, f):
            if f in kwargs: return kwargs[f]
            return ''
        
        args = dict([(f, get_val(kwargs, f)) for f in validation_class.fields.keys()])
    
    params = validation_class(allow_extra_fields=allow_extra_fields).to_python(args)
    
    params = dict([(k, params[k]) for k in params.keys() if k in kwargs and validation_class.fields])
    
    return objectify(params)
Exemple #5
0
from pylons_common.lib.log import create_logger
from pylons_common.lib.utils import pluralize

logger = create_logger("pylons_common.lib.datetime")
from datetime import datetime, timedelta

DATE_FORMAT_ACCEPT = [
    u"%Y-%m-%d %H:%M:%S",
    u"%Y-%m-%d %H:%M:%SZ",
    u"%Y-%m-%d",
    u"%m-%d-%Y",
    u"%m/%d/%Y",
    u"%m.%d.%Y",
    u"%b %d, %Y",
]

popular_timezones = [
    u"US/Eastern",
    u"US/Central",
    u"US/Mountain",
    u"US/Pacific",
    u"US/Alaska",
    u"US/Hawaii",
    u"US/Samoa",
    u"Europe/London",
    u"Europe/Paris",
    u"Europe/Istanbul",
    u"Europe/Moscow",
    u"America/Puerto_Rico",
    u"America/Buenos_Aires",
    u"America/Sao_Paulo",
Exemple #6
0
"""
from unittest import TestCase
import tempfile
import os, shutil

from paste import fixture
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp

import pylons.test

from pylons_common.lib.log import create_logger
logger = create_logger('desio.tests')

from pylons_common.lib import exceptions as err
from pylons_common.lib.utils import objectify
from pylons_common.lib.exceptions import ClientException, CompoundException, AppException
import simplejson as json

from turbomail.control import interface

import formencode

from desio.model.meta import Session
from desio.lib.helpers import url_for, api_url

# Invoke websetup with the current config file
SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])
Exemple #7
0
from pylons_common.lib.exceptions import *

from pylons_common.lib.date import convert_date

from pylons_common.lib.log import create_logger
logger = create_logger('pylons_common.lib.decorators')

__all__ = ['zipargs', 'stackable', 'enforce']

def zipargs(decorated_fn):
    """
    This will zip up the positional args into kwargs. This makes handling them in
    decorators easier. Call on the inner deocrator function, and pass in the outer's
    arg. Outer function must be @stackable. Convolution. Apologies.
    """
    def decorator(fn):
        def new(*args, **kwargs):
            
            # Get the original func's param names. If this is the outer decorator, decorated_fn.func_code.co_varnames
            # will have the inner decorator's names ('args', 'kwargs'). The inner decorator should
            # attach original_varnames to the function
            varnames = hasattr(decorated_fn, 'original_varnames') and decorated_fn.original_varnames or decorated_fn.func_code.co_varnames
            
            dargs = dict(zip(varnames, args))
            dargs.update(kwargs)
            
            #if 'self' in dargs:
            #    del dargs['self']
            
            return fn(**dargs)
        
Exemple #8
0
import base64
import uuid as uuid_mod
from pylons_common.lib.log import create_logger
logger = create_logger('pylons_common.lib.utils')

class forgiving_dict_accessor(dict):
    """
    Allow accessing a dictionary with dot-notation, returning None if the attribute doesn't exist.
    """
    def __getattr__(self, attr):
        parent = super(self.__class__, self)
        if hasattr(parent, 'get') and callable(parent.get):
            return parent.get(attr)
        else:
            return super(self.__class__, self).__getitem__(attr)

    def __setattr__(self, attr, value):
        super(self.__class__, self).__setitem__(attr, value)

class dict_accessor(dict):
    """
    Allow accessing a dictionary content also using dot-notation.
    """
    def __getattr__(self, attr):
        return super(dict_accessor, self).__getitem__(attr)

    def __setattr__(self, attr, value):
        super(dict_accessor, self).__setitem__(attr, value)

def objectify(d, forgiving=False):
    """
Exemple #9
0
import turbomail, os, re
from turbomail import Message

from datetime import datetime
from collections import defaultdict
import pylons
from mako.lookup import TemplateLookup
from desio.lib.helpers import url_for
from desio.model import users

from pylons_common.lib.log import create_logger
logger = create_logger('desio.utils.email')

EMAIL_TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates', 'emails')
EMAIL_TEMPLATE_LOOKUP = TemplateLookup(directories=[EMAIL_TEMPLATES_DIR])

def absolute_url_for(*args, **kwargs):
    subdomain = kwargs.get('subdomain')
    if subdomain:
        url = pylons.config.get('subdomain_url') % (subdomain,)
        del kwargs['subdomain']
    else:
        url = pylons.config.get('pylons_url')
    return str(url) + url_for(*args, **kwargs)

def line_reduce(s):
    # this reduces any number of line breaks of 3 or more to a max of 2
    ws = re.compile("\s{3,}")
    return ws.sub("\n\n", s)

"""
Exemple #10
0
import formencode

from formencode import htmlfill
from paste.httpexceptions import HTTPException
import pylons, time
from pylons import tmpl_context as c, request, response
from pylons.templating import render_mako

# our junk
from pylons_common.lib.exceptions import *
from pylons_common.lib.log import create_logger
logger = create_logger('pylons_common.web.response')

from decorator import decorator

FORMAT_JSON = u'json'
FORMAT_CSV = u'csv'

STATUS_SUCCESS   = u'success'
STATUS_FAIL = u'fail'

ERROR_HTTP_STATUS = {
    FORBIDDEN: 403,
    NOT_FOUND: 404
}

MAX_DEBUG_REQUESTS = 200

def htmlfill_error_formatter(error):
    """
Exemple #11
0
from weberror.evalexception import EvalException, get_debug_count, DebugInfo
from weberror.errormiddleware import ErrorMiddleware, handle_exception
from pylons.middleware import head_html, footer_html, media_path, report_libs
from pylons.error import template_error_formatters
from webob import Request, Response
import simplejson as json
import traceback

import smtplib
from socket import sslerror #if desired

from paste import fileapp, registry

from pylons_common.lib import exceptions
from pylons_common.lib.log import create_logger
logger = create_logger('pylons_common.middleware.errors')

"""
Whats going here? This is Error middleware.

We have a VanillaErrorMiddleware, DebugErrorMiddleware and VariableErrorHandler.

- VanillaErrorMiddleware is a weberror.errormiddleware.ErrorMiddleware
  - Its __call__ method will be run on requests from non-admins or when not in production
  - It is extended so we can call handle_async_exception() on async requests.
  
- DebugErrorMiddleware is a weberror.evalexception.EvalException
  - It provides more information for debug purposes.
  - __call__ method (and in turn our overriden respond() method) called on requests from
    admins or when in dev.
  - Extended so we can handle errors properly on async requests.
Exemple #12
0
"""
from unittest import TestCase
import tempfile
import os, shutil

from paste import fixture
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp

import pylons.test

from pylons_common.lib.log import create_logger
logger = create_logger('desio.tests')

from pylons_common.lib import exceptions as err
from pylons_common.lib.utils import objectify
from pylons_common.lib.exceptions import ClientException, CompoundException, AppException
import simplejson as json

from turbomail.control import interface

import formencode

from desio.model.meta import Session
from desio.lib.helpers import url_for, api_url

# Invoke websetup with the current config file
SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])