Esempio n. 1
0
 def __init__(self,
              hostname,
              port,
              username,
              password=None,
              use_manual_auth=False,
              callback=None,
              auto_close=True,
              logger=None,
              logPath=os.path.abspath(os.path.dirname(sys.argv[0]))):
     self.__hostname__ = hostname
     self.__port__ = port
     self.__username__ = username
     self.__password__ = password
     self.__transport__ = None
     self.__callback__ = callback
     self.__autoclose__ = auto_close
     self.__logPath__ = logPath
     self.__use_manual_auth__ = use_manual_auth
     self.logger = paramiko.util.get_logger(__name__)
     if (logger):
         self.logger = logger
     else:
         if (self.__logPath__) and (os.path.exists(
                 self.__logPath__)) and (os.path.isdir(self.__logPath__)):
             _utils._makeDirs(self.__logPath__)
             paramiko.util.log_to_file(
                 os.path.join(
                     self.__logPath__,
                     '%s.log' % (ObjectTypeName.objectSignature(self))))
     if self.hostname.find(':') >= 0:
         self.__hostname__, portstr = hostname.split(':')
         self.__port__ = int(portstr)
     self.__open__()
Esempio n. 2
0
def render_captcha_form(request,
                        form_name=None,
                        font_name=None,
                        font_size=18,
                        choices='QWERTYPASDFGHJKLZXCVBNM23456789',
                        fill=(255, 255, 255),
                        bgImage='bg.jpg'):
    try:
        imghash = ''
        tempname = ''
        imgtext = ''
        try:
            from random import choice
            import Image, ImageDraw, ImageFont, sha
            _settings = django_utils.get_from_session(
                request, 'settings', default=lists.HashedLists2())
            if (not _settings.has_key('SECRET_KEY')):
                from django.conf import settings as _settings
            SALT = _settings.SECRET_KEY[:20]
            imgtext = ''.join([choice(choices) for i in range(5)])
            imghash = sha.new(SALT + imgtext).hexdigest()
            image_fname = os.path.join(_settings.MEDIA_ROOT, bgImage)
            im = Image.open(image_fname)
            draw = ImageDraw.Draw(im)
            font_fname = os.path.join(_settings.MEDIA_ROOT, font_name)
            font = ImageFont.truetype(font_fname, font_size)
            draw.text((10, 10), imgtext, font=font, fill=fill)
            _captcha_symbol = 'captcha'
            image_name = '%s.jpg' % (imgtext)
            temp = os.path.join(_settings.MEDIA_ROOT, _captcha_symbol,
                                image_name)
            _utils._makeDirs(os.path.dirname(temp))
            tempname = '/'.join(
                [_settings.MEDIA_URL, _captcha_symbol, image_name])
            if (os.path.exists(tempname)):
                os.remove(tempname)
            im.save(temp, "JPEG")
        except:
            imghash = ''
            tempname = ''
            imgtext = ''
    except Exception as e:
        return _utils.formattedException(details=e)

    if (misc.isString(form_name)):
        c = {'hash': imghash, 'tempname': tempname}
        http_host = django_utils.get_http_host(request).split(':')[0]
        if (django_utils.isBeingDebugged(http_host)):
            c['imgtext'] = imgtext
        ctx = Context(c, autoescape=False)
        return render_to_string(form_name, context_instance=ctx)
    else:
        return render_to_string('405.html', {})
Esempio n. 3
0
class VyperDjangoMiddleware(object):
    def __adjust_apps__(self, apps, aSite):
        i_apps = apps
        o_apps = [
            app for app in i_apps if (not app.startswith('django.'))
        ]  # seek to determine which apps are from django and which are not...
        _apps = list(set(i_apps) - set(o_apps))
        o_apps = [
            '%s.%s' % (aSite.__name__, app.split('.')[-1]) for app in o_apps
        ]
        return tuple(_apps + o_apps)

    def process_request(self, request):
        url_toks = django_utils.parse_url_parms(request)

        http_host = request.META['HTTP_X_FORWARDED_SERVER'] if (
            request.META.has_key('HTTP_X_FORWARDED_SERVER')
        ) else request.META['HTTP_HOST']
        _host = http_host.split(':')[0]

        s = 'combined%s.settings' % ('.django' if (
            not django_utils.isProduction(django_utils._cname)) else '')
        m = LazyImport.LazyImport(s)
        m = m.__lazyimport_import
        settings._target = None
        settings.configure(**m.__dict__)

        d = lists.HashedLists2(
            dict([(k, v) for k, v in m.__dict__.iteritems()
                  if (not k.startswith('__')) and (not k.endswith('__')) and (
                      ObjectTypeName.typeClassName(v) != 'module')]))
        if (django_utils.isBeingDebugged) and (sys.platform != 'win32'):
            fout = open('/home/raychorn/debug.txt', 'w')
            try:
                print >> fout, '_host is "%s".' % (_host)
                print >> fout, '%s\n' % ('=' * 80)
                d.prettyPrint(title=s, fOut=fout)
            finally:
                fout.flush()
                fout.close()

        r_url = settings.ROOT_URLCONF

        isAdjustingInstalledApps = False
        if (settings.SITES.has_key(_host)):
            aSite = settings.SITES[_host]
            s = '%s.settings' % (aSite.__name__)
            m = LazyImport.LazyImport(s)
            m = m.__lazyimport_import

            d = dict([
                (k, v) for k, v in m.__dict__.iteritems()
                if (not k.startswith('__')) and (not k.endswith('__')) and (
                    ObjectTypeName.typeClassName(v) != 'module')
            ])
            if (d.has_key('INSTALLED_APPS')):
                d['INSTALLED_APPS'] = self.__adjust_apps__(
                    d['INSTALLED_APPS'], aSite)
                m.__dict__['INSTALLED_APPS'] = d['INSTALLED_APPS']
            request.session['settings'] = d

            settings._target = None
            settings.configure(**m.__dict__)

            d = lists.HashedLists2(
                dict([(k, v) for k, v in m.__dict__.iteritems()
                      if (not k.startswith('__')) and (not k.endswith('__'))
                      and (ObjectTypeName.typeClassName(v) != 'module')]))

            _path = aSite.__path__[0]

            x = ListWrapper.ListWrapper(sys.path)
            xi = x.findAllMatching(_path)
            if (len(xi) == 0):
                sys.path.insert(0, _path)

            isAdjustingInstalledApps = True
            settings.ROOT_URLCONF = '%s.%s' % (
                aSite.__name__, settings.ROOT_URLCONF.split('.')[-1])
        else:
            settings.ROOT_URLCONF = s.replace('.settings', '.urls')

        _app_loader_errors = []
        if (settings.INSTALLED_APPS):
            loading._loaded = False
            loading._app_list = []
            loading._app_models = {}
            for app in settings.INSTALLED_APPS:
                try:
                    aModule = loading.load_app(app)
                    app_name = app.split('.')[-1]
                    if (aModule is not None) and (
                            not loading._app_models.has_key(app_name)):
                        reload(aModule)
                except ImportError, e:
                    if (str(e).find('No module named') == -1):
                        _app_loader_errors.append(
                            _utils.formattedException(details=e))
            loading._loaded = True

        if (sys.platform != 'win32'):
            fname = '/home/raychorn/debug/%s/debug-apps.txt' % ('_'.join(
                _utils.timeStampForFileName().split('_')[0:-1]))
            _utils._makeDirs(os.path.dirname(fname))
            fout = open(fname, 'a')
            try:
                ts = ' '.join(_utils.timeStampLocalTime().split('T'))
                print >> fout, 'BEGIN: %s :: %s' % (ts, '=' * 80)
                print >> fout, '_host is "%s".' % (_host)
                print >> fout, '%s\n' % ('-' * 80)
                del d['SECRET_KEY']
                del d['DATABASE_PASSWORD']
                d.prettyPrint(title=s, fOut=fout)
                if (len(_app_loader_errors) > 0):
                    ReportTheList.reportTheList(_app_loader_errors,
                                                'App Loader Errors',
                                                fOut=fout)
                print >> fout, 'END!   %s :: %s\n\n' % (ts, '=' * 80)
            finally:
                fout.flush()
                fout.close()
Esempio n. 4
0
            d_ext['.pyc'] = f_new
        if (inRoot):
            d_ext['.pyc'] = [f for f in d_ext['.pyc'] if (f.find('compile-all.') == -1)]
            for k,v in d_ext.iteritems():
                if (k not in ['.pyc','.py']):
                    del d_ext[k]
        not_pyc = []
        for k,v in d_ext.iteritems():
            if (k.find('.py') == -1):
                not_pyc = not_pyc + d_ext[k]
        d[root] = (d_ext['.pyc'] if (d_ext['.pyc'] is not None) else [],not_pyc)

print 'Making dist folder...',

_dist_folder = os.path.join(os.path.join(fp,'dist'),'%s_dist' % (fp.split(os.sep)[-1]))
_utils._makeDirs(_dist_folder)
print 'Done !'

_utils.removeAllFilesUnder(os.path.dirname(_dist_folder))
_utils._makeDirs(_dist_folder)

for fname,tup in d.iteritems():
    for t in tup:
        for f in t:
            _fname = os.sep.join(fname.replace(fp,'').split(os.sep)[1:])
            f_new = os.path.join(_dist_folder,_fname)
            _utils.makeDirs(f_new)
            try:
                _f = os.path.join(f_new,f.replace(os.path.join(fp,fname)+os.sep,''))
                _utils.makeDirs(_f)
                if (os.path.splitext(f)[-1] == '.pyc'):
Esempio n. 5
0
        },
        'django.request': { # Stop SQL debug from logging to main logger
            'handlers': ['request_handler'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}
print '11.LOGGING=%s' % (LOGGING)
print '12.LOGGING["handlers"]["default"]["filename"]=%s' % (LOGGING["handlers"]["default"]["filename"])
print '13.LOGGING["handlers"]["request_handler"]["filename"]=%s' % (LOGGING["handlers"]["request_handler"]["filename"])

default_filepath = os.path.abspath(os.path.dirname(LOGGING["handlers"]["default"]["filename"]))
print '14.default_filepath=%s --> (%s)' % (default_filepath,os.path.exists(default_filepath))
if (not os.path.exists(default_filepath)):
    _utils._makeDirs(default_filepath)

request_filepath = os.path.abspath(os.path.dirname(LOGGING["handlers"]["request_handler"]["filename"]))
print '15.request_filepath=%s --> (%s)' % (request_filepath,os.path.exists(request_filepath))
if (not os.path.exists(request_filepath)):
    _utils._makeDirs(request_filepath)

#fpath = os.path.realpath('.')
#log_fpath = os.path.sep.join([fpath,'logs/blah.log'])
#_utils.makeDirs(log_fpath)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#    'django.template.loader.find_template',