예제 #1
0
    def get(self):
        user = users.get_current_user()
        if user and users.is_current_user_admin():
            self.response.headers['Content-Type'] = 'application/csv'
            self.response.headers[
                'Content-Disposition'] = 'attachment; filename=indicacoes.csv'
            writer = csv.writer(self.response.out,
                                delimiter=';',
                                quoting=csv.QUOTE_MINIMAL)
            writer.writerow([
                "Nome", "Telefone Celular", "Telefone Residencial", "Email",
                "Indicado por"
            ])

            for indicacao in Indicacao.all().filter('nomeIndicacao !=',
                                                    '').order('nomeIndicacao'):
                writer.writerow([
                    smart_str(indicacao.nomeIndicacao, encoding='ISO-8859-1'),
                    smart_str(indicacao.telCelularIndicacao,
                              encoding='ISO-8859-1'),
                    smart_str(indicacao.telResidencialIndicacao,
                              encoding='ISO-8859-1'),
                    smart_str(indicacao.emailIndicacao, encoding='ISO-8859-1'),
                    smart_str(indicacao.nome, encoding='ISO-8859-1')
                ])
예제 #2
0
 def resolve(self, path):
     tried = []
     match = self.regex.search(path)
     if match:
         new_path = path[match.end():]
         for pattern in self.url_patterns:
             try:
                 sub_match = pattern.resolve(new_path)
             except Resolver404 as e:
                 sub_tried = e.args[0].get('tried')
                 if sub_tried is not None:
                     tried.extend([(pattern.regex.pattern + '   ' + t)
                                   for t in sub_tried])
                 else:
                     tried.append(pattern.regex.pattern)
             else:
                 if sub_match:
                     sub_match_dict = dict([
                         (smart_str(k), v)
                         for k, v in list(match.groupdict().items())
                     ])
                     sub_match_dict.update(self.default_kwargs)
                     for k, v in six.iteritems(sub_match[2]):
                         sub_match_dict[smart_str(k)] = v
                     return sub_match[0], sub_match[1], sub_match_dict
                 tried.append(pattern.regex.pattern)
         raise Resolver404({'tried': tried, 'path': new_path})
     raise Resolver404({'path': path})
예제 #3
0
파일: http.py 프로젝트: 0xmilk/appscale
def urlencode(query, doseq=0):
    """
    A version of Python's urllib.urlencode() function that can operate on
    unicode strings. The parameters are first case to UTF-8 encoded strings and
    then encoded as per normal.
    """
    if hasattr(query, 'items'):
        query = query.items()
    return urllib.urlencode(
        [(smart_str(k),
         isinstance(v, (list,tuple)) and [smart_str(i) for i in v] or smart_str(v))
            for k, v in query],
        doseq)
예제 #4
0
def urlencode(query, doseq=0):
    """
    A version of Python's urllib.urlencode() function that can operate on
    unicode strings. The parameters are first case to UTF-8 encoded strings and
    then encoded as per normal.
    """
    if hasattr(query, 'items'):
        query = list(query.items())
    return urllib.parse.urlencode(
        [(smart_str(k),
          isinstance(v, (list, tuple)) and [smart_str(i)
                                            for i in v] or smart_str(v))
         for k, v in query], doseq)
예제 #5
0
 def get(self):
     user = users.get_current_user()
     if user and users.is_current_user_admin():
         self.response.headers['Content-Type'] = 'application/csv'
         self.response.headers['Content-Disposition'] = 'attachment; filename=indicacoes.csv'
         writer = csv.writer(self.response.out, delimiter=';', quoting=csv.QUOTE_MINIMAL)
         writer.writerow(["Nome", "Telefone Celular", "Telefone Residencial", "Email", "Indicado por"])
         
         for indicacao in Indicacao.all().filter('nomeIndicacao !=', '').order('nomeIndicacao'):
             writer.writerow([smart_str(indicacao.nomeIndicacao, encoding='ISO-8859-1'),
                              smart_str(indicacao.telCelularIndicacao, encoding='ISO-8859-1'),
                              smart_str(indicacao.telResidencialIndicacao, encoding='ISO-8859-1'),
                              smart_str(indicacao.emailIndicacao, encoding='ISO-8859-1'),
                              smart_str(indicacao.nome, encoding='ISO-8859-1')
                              ])
예제 #6
0
    def render(self, context):
        from google.appengine._internal.django.core.urlresolvers import reverse, NoReverseMatch
        args = [arg.resolve(context) for arg in self.args]
        kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
                       for k, v in list(self.kwargs.items())])

        # Try to look up the URL twice: once given the view name, and again
        # relative to what we guess is the "main" app. If they both fail,
        # re-raise the NoReverseMatch unless we're using the
        # {% url ... as var %} construct in which cause return nothing.
        url = ''
        try:
            url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app)
        except NoReverseMatch as e:
            if settings.SETTINGS_MODULE:
                project_name = settings.SETTINGS_MODULE.split('.')[0]
                try:
                    url = reverse(project_name + '.' + self.view_name,
                              args=args, kwargs=kwargs, current_app=context.current_app)
                except NoReverseMatch:
                    if self.asvar is None:
                        # Re-raise the original exception, not the one with
                        # the path relative to the project. This makes a
                        # better error message.
                        raise e
            else:
                if self.asvar is None:
                    raise e

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            return url
예제 #7
0
    def render(self, context):
        from google.appengine._internal.django.core.urlresolvers import reverse, NoReverseMatch
        args = [arg.resolve(context) for arg in self.args]
        kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
                       for k, v in self.kwargs.items()])

        # Try to look up the URL twice: once given the view name, and again
        # relative to what we guess is the "main" app. If they both fail,
        # re-raise the NoReverseMatch unless we're using the
        # {% url ... as var %} construct in which cause return nothing.
        url = ''
        try:
            url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app)
        except NoReverseMatch, e:
            if settings.SETTINGS_MODULE:
                project_name = settings.SETTINGS_MODULE.split('.')[0]
                try:
                    url = reverse(project_name + '.' + self.view_name,
                              args=args, kwargs=kwargs, current_app=context.current_app)
                except NoReverseMatch:
                    if self.asvar is None:
                        # Re-raise the original exception, not the one with
                        # the path relative to the project. This makes a
                        # better error message.
                        raise e
            else:
                if self.asvar is None:
                    raise e
예제 #8
0
 def set_many(self, data, timeout=0):
     safe_data = {}
     for key, value in list(data.items()):
         if isinstance(value, str):
             value = value.encode('utf-8')
         safe_data[smart_str(key)] = value
     self._cache.set_multi(safe_data, self._get_memcache_timeout(timeout))
예제 #9
0
 def __repr__(self):
     # Since this is called as part of error handling, we need to be very
     # robust against potentially malformed input.
     try:
         get = pformat(self.GET)
     except:
         get = '<could not parse>'
     if self._post_parse_error:
         post = '<could not parse>'
     else:
         try:
             post = pformat(self.POST)
         except:
             post = '<could not parse>'
     try:
         cookies = pformat(self.COOKIES)
     except:
         cookies = '<could not parse>'
     try:
         meta = pformat(self.META)
     except:
         meta = '<could not parse>'
     return smart_str(
         '<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>'
         % (self.path, six.text_type(get), six.text_type(post),
            six.text_type(cookies), six.text_type(meta)))
예제 #10
0
 def set_many(self, data, timeout=0):
     safe_data = {}
     for key, value in data.items():
         if isinstance(value, unicode):
             value = value.encode('utf-8')
         safe_data[smart_str(key)] = value
     self._cache.set_multi(safe_data, self._get_memcache_timeout(timeout))
예제 #11
0
 def __repr__(self):
     # Since this is called as part of error handling, we need to be very
     # robust against potentially malformed input.
     try:
         get = pformat(self.GET)
     except:
         get = '<could not parse>'
     if self._post_parse_error:
         post = '<could not parse>'
     else:
         try:
             post = pformat(self.POST)
         except:
             post = '<could not parse>'
     try:
         cookies = pformat(self.COOKIES)
     except:
         cookies = '<could not parse>'
     try:
         meta = pformat(self.META)
     except:
         meta = '<could not parse>'
     return smart_str(u'<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
                      (self.path, unicode(get), unicode(post),
                       unicode(cookies), unicode(meta)))
예제 #12
0
    def execute(self, *args, **options):
        """
        Try to execute this command, performing model validation if
        needed (as controlled by the attribute
        ``self.requires_model_validation``). If the command raises a
        ``CommandError``, intercept it and print it sensibly to
        stderr.

        """
        # Switch to English, because django-admin.py creates database content
        # like permissions, and those shouldn't contain any translations.
        # But only do this if we can assume we have a working settings file,
        # because django.utils.translation requires settings.
        if self.can_import_settings:
            try:
                from google.appengine._internal.django.utils import translation
                translation.activate('en-us')
            except ImportError as e:
                # If settings should be available, but aren't,
                # raise the error and quit.
                sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' %
                                                            e)))
                sys.exit(1)
        try:
            self.stdout = options.get('stdout', sys.stdout)
            self.stderr = options.get('stderr', sys.stderr)
            if self.requires_model_validation:
                self.validate()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    # This needs to be imported here, because it relies on
                    # settings.
                    from google.appengine._internal.django.db import connections, DEFAULT_DB_ALIAS
                    connection = connections[options.get(
                        'database', DEFAULT_DB_ALIAS)]
                    if connection.ops.start_transaction_sql():
                        self.stdout.write(
                            self.style.SQL_KEYWORD(
                                connection.ops.start_transaction_sql()) + '\n')
                self.stdout.write(output)
                if self.output_transaction:
                    self.stdout.write('\n' +
                                      self.style.SQL_KEYWORD("COMMIT;") + '\n')
        except CommandError as e:
            self.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
            sys.exit(1)
예제 #13
0
def urlquote_plus(url, safe=''):
    """
    A version of Python's urllib.quote_plus() function that can operate on
    unicode strings. The url is first UTF-8 encoded before quoting. The
    returned string can safely be used as part of an argument to a subsequent
    iri_to_uri() call without double-quoting occurring.
    """
    return force_unicode(urllib.parse.quote_plus(smart_str(url), safe))
예제 #14
0
파일: http.py 프로젝트: 0xmilk/appscale
def urlquote_plus(url, safe=''):
    """
    A version of Python's urllib.quote_plus() function that can operate on
    unicode strings. The url is first UTF-8 encoded before quoting. The
    returned string can safely be used as part of an argument to a subsequent
    iri_to_uri() call without double-quoting occurring.
    """
    return force_unicode(urllib.quote_plus(smart_str(url), safe))
예제 #15
0
def localize_input(value, default=None):
    """
    Checks if an input value is a localizable type and returns it
    formatted with the appropriate formatting string of the current locale.
    """
    if isinstance(value, (decimal.Decimal, float, int, long)):
        return number_format(value)
    if isinstance(value, datetime.datetime):
        value = datetime_safe.new_datetime(value)
        format = smart_str(default or get_format('DATETIME_INPUT_FORMATS')[0])
        return value.strftime(format)
    elif isinstance(value, datetime.date):
        value = datetime_safe.new_date(value)
        format = smart_str(default or get_format('DATE_INPUT_FORMATS')[0])
        return value.strftime(format)
    elif isinstance(value, datetime.time):
        format = smart_str(default or get_format('TIME_INPUT_FORMATS')[0])
        return value.strftime(format)
    return value
예제 #16
0
def localize_input(value, default=None):
    """
    Checks if an input value is a localizable type and returns it
    formatted with the appropriate formatting string of the current locale.
    """
    if isinstance(value, (decimal.Decimal, float, int, long)):
        return number_format(value)
    if isinstance(value, datetime.datetime):
        value = datetime_safe.new_datetime(value)
        format = smart_str(default or get_format("DATETIME_INPUT_FORMATS")[0])
        return value.strftime(format)
    elif isinstance(value, datetime.date):
        value = datetime_safe.new_date(value)
        format = smart_str(default or get_format("DATE_INPUT_FORMATS")[0])
        return value.strftime(format)
    elif isinstance(value, datetime.time):
        format = smart_str(default or get_format("TIME_INPUT_FORMATS")[0])
        return value.strftime(format)
    return value
예제 #17
0
파일: message.py 프로젝트: 0xmilk/appscale
 def _create_mime_attachment(self, content, mimetype):
     """
     Converts the content, mimetype pair into a MIME attachment object.
     """
     basetype, subtype = mimetype.split('/', 1)
     if basetype == 'text':
         encoding = self.encoding or settings.DEFAULT_CHARSET
         attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding)
     else:
         # Encode non-text attachments with base64.
         attachment = MIMEBase(basetype, subtype)
         attachment.set_payload(content)
         Encoders.encode_base64(attachment)
     return attachment
예제 #18
0
 def _create_mime_attachment(self, content, mimetype):
     """
     Converts the content, mimetype pair into a MIME attachment object.
     """
     basetype, subtype = mimetype.split('/', 1)
     if basetype == 'text':
         encoding = self.encoding or settings.DEFAULT_CHARSET
         attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding)
     else:
         # Encode non-text attachments with base64.
         attachment = MIMEBase(basetype, subtype)
         attachment.set_payload(content)
         Encoders.encode_base64(attachment)
     return attachment
예제 #19
0
 def resolve(self, path):
     tried = []
     match = self.regex.search(path)
     if match:
         new_path = path[match.end() :]
         for pattern in self.url_patterns:
             try:
                 sub_match = pattern.resolve(new_path)
             except Resolver404, e:
                 sub_tried = e.args[0].get("tried")
                 if sub_tried is not None:
                     tried.extend([(pattern.regex.pattern + "   " + t) for t in sub_tried])
                 else:
                     tried.append(pattern.regex.pattern)
             else:
                 if sub_match:
                     sub_match_dict = dict([(smart_str(k), v) for k, v in match.groupdict().items()])
                     sub_match_dict.update(self.default_kwargs)
                     for k, v in sub_match[2].iteritems():
                         sub_match_dict[smart_str(k)] = v
                     return sub_match[0], sub_match[1], sub_match_dict
                 tried.append(pattern.regex.pattern)
         raise Resolver404({"tried": tried, "path": new_path})
예제 #20
0
def get_format(format_type):
    """
    For a specific format type, returns the format for the current
    language (locale), defaults to the format in the settings.
    format_type is the name of the format, e.g. 'DATE_FORMAT'
    """
    format_type = smart_str(format_type)
    if settings.USE_L10N:
        cache_key = (format_type, get_language())
        try:
            return _format_cache[cache_key] or getattr(settings, format_type)
        except KeyError:
            for module in get_format_modules():
                try:
                    val = getattr(module, format_type)
                    _format_cache[cache_key] = val
                    return val
                except AttributeError:
                    pass
            _format_cache[cache_key] = None
    return getattr(settings, format_type)
예제 #21
0
    def message(self):
        encoding = self.encoding or settings.DEFAULT_CHARSET
        msg = SafeMIMEText(smart_str(self.body, encoding),
                           self.content_subtype, encoding)
        msg = self._create_message(msg)
        msg['Subject'] = self.subject
        msg['From'] = self.extra_headers.get('From', self.from_email)
        msg['To'] = ', '.join(self.to)

        # Email header names are case-insensitive (RFC 2045), so we have to
        # accommodate that when doing comparisons.
        header_names = [key.lower() for key in self.extra_headers]
        if 'date' not in header_names:
            msg['Date'] = formatdate()
        if 'message-id' not in header_names:
            msg['Message-ID'] = make_msgid()
        for name, value in list(self.extra_headers.items()):
            if name.lower() == 'from':  # From is already handled
                continue
            msg[name] = value
        return msg
예제 #22
0
def get_format(format_type):
    """
    For a specific format type, returns the format for the current
    language (locale), defaults to the format in the settings.
    format_type is the name of the format, e.g. 'DATE_FORMAT'
    """
    format_type = smart_str(format_type)
    if settings.USE_L10N:
        cache_key = (format_type, get_language())
        try:
            return _format_cache[cache_key] or getattr(settings, format_type)
        except KeyError:
            for module in get_format_modules():
                try:
                    val = getattr(module, format_type)
                    _format_cache[cache_key] = val
                    return val
                except AttributeError:
                    pass
            _format_cache[cache_key] = None
    return getattr(settings, format_type)
예제 #23
0
파일: message.py 프로젝트: 0xmilk/appscale
    def message(self):
        encoding = self.encoding or settings.DEFAULT_CHARSET
        msg = SafeMIMEText(smart_str(self.body, encoding),
                           self.content_subtype, encoding)
        msg = self._create_message(msg)
        msg['Subject'] = self.subject
        msg['From'] = self.extra_headers.get('From', self.from_email)
        msg['To'] = ', '.join(self.to)

        # Email header names are case-insensitive (RFC 2045), so we have to
        # accommodate that when doing comparisons.
        header_names = [key.lower() for key in self.extra_headers]
        if 'date' not in header_names:
            msg['Date'] = formatdate()
        if 'message-id' not in header_names:
            msg['Message-ID'] = make_msgid()
        for name, value in self.extra_headers.items():
            if name.lower() == 'from':  # From is already handled
                continue
            msg[name] = value
        return msg
예제 #24
0
파일: base.py 프로젝트: 0xmilk/appscale
    def execute(self, *args, **options):
        """
        Try to execute this command, performing model validation if
        needed (as controlled by the attribute
        ``self.requires_model_validation``). If the command raises a
        ``CommandError``, intercept it and print it sensibly to
        stderr.

        """
        # Switch to English, because django-admin.py creates database content
        # like permissions, and those shouldn't contain any translations.
        # But only do this if we can assume we have a working settings file,
        # because django.utils.translation requires settings.
        if self.can_import_settings:
            try:
                from google.appengine._internal.django.utils import translation
                translation.activate('en-us')
            except ImportError, e:
                # If settings should be available, but aren't,
                # raise the error and quit.
                sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
                sys.exit(1)
예제 #25
0
    def execute(self, *args, **options):
        """
        Try to execute this command, performing model validation if
        needed (as controlled by the attribute
        ``self.requires_model_validation``). If the command raises a
        ``CommandError``, intercept it and print it sensibly to
        stderr.

        """
        # Switch to English, because django-admin.py creates database content
        # like permissions, and those shouldn't contain any translations.
        # But only do this if we can assume we have a working settings file,
        # because django.utils.translation requires settings.
        if self.can_import_settings:
            try:
                from google.appengine._internal.django.utils import translation
                translation.activate('en-us')
            except ImportError, e:
                # If settings should be available, but aren't,
                # raise the error and quit.
                sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' %
                                                            e)))
                sys.exit(1)
예제 #26
0
 def add(self, key, value, timeout=0):
     if isinstance(value, unicode):
         value = value.encode('utf-8')
     return self._cache.add(smart_str(key), value, self._get_memcache_timeout(timeout))
예제 #27
0
 def delete(self, key):
     self._cache.delete(smart_str(key))
예제 #28
0
 def get(self):
     user = users.get_current_user()
     if user and users.is_current_user_admin():
         self.response.headers['Content-Type'] = 'application/csv'
         self.response.headers['Content-Disposition'] = 'attachment; filename=participantes.csv'
         writer = csv.writer(self.response.out, delimiter=';', quoting=csv.QUOTE_MINIMAL)
         writer.writerow(["Nome", "Data de Nascimento", "Sexo", "Identidade", "Familia",
                          "Logradouro", "Complemento", "Cidade", "UF", "Bairro", "Zona",
                          "Tel Celular1", "Tel Celular2", "Tel Residencial", "Email",
                          "Problema de Saude", "Restricao Atividade Fisica", "Tem Alguma Alergia", "Toma Algum Medicamento",
                          "Nome do Contato",
                          "Tel Celular1 Contato", "Tel Celular2 Contato", "Tel Residencial Contato", "Tel Comercial Contato",
                          "Familia", "Vai Levar Barraca"])
         
         for participante in Participante.all().order('nome'):
             writer.writerow([smart_str(participante.nome, encoding='ISO-8859-1'),
                              smart_str(participante.dataNascimento, encoding='ISO-8859-1'),
                              smart_str(participante.sexo, encoding='ISO-8859-1'),
                              smart_str(participante.identidade, encoding='ISO-8859-1'),
                              smart_str(participante.familia, encoding='ISO-8859-1'),
                              smart_str(participante.logradouro, encoding='ISO-8859-1'),
                              smart_str(participante.complemento, encoding='ISO-8859-1'),
                              smart_str(participante.cidade, encoding='ISO-8859-1'),
                              smart_str(participante.uf, encoding='ISO-8859-1'),
                              smart_str(participante.bairro, encoding='ISO-8859-1'),
                              smart_str(participante.zona, encoding='ISO-8859-1'),
                              smart_str(participante.telCelular1, encoding='ISO-8859-1'),
                              smart_str(participante.telCelular2, encoding='ISO-8859-1'),
                              smart_str(participante.telResidencial, encoding='ISO-8859-1'),
                              smart_str(participante.email, encoding='ISO-8859-1'),
                              smart_str(participante.problemaSaude, encoding='ISO-8859-1'),
                              smart_str(participante.restricaoAtividadeFisica, encoding='ISO-8859-1'),
                              smart_str(participante.temAlgumaAlergia, encoding='ISO-8859-1'),
                              smart_str(participante.tomaAlgumMedicamento, encoding='ISO-8859-1'),
                              smart_str(participante.nomeContato, encoding='ISO-8859-1'),
                              smart_str(participante.telCelular1Contato, encoding='ISO-8859-1'),
                              smart_str(participante.telCelular2Contato, encoding='ISO-8859-1'),
                              smart_str(participante.telResidencialContato, encoding='ISO-8859-1'),
                              smart_str(participante.telComercialContato, encoding='ISO-8859-1'),
                              smart_str(participante.familia, encoding='ISO-8859-1'),
                              smart_str(participante.barraca, encoding='ISO-8859-1')
                              ])
예제 #29
0
 def set(self, key, value, timeout=0):
     self._cache.set(smart_str(key), value,
                     self._get_memcache_timeout(timeout))
예제 #30
0
 def add(self, key, value, timeout=0):
     if isinstance(value, str):
         value = value.encode('utf-8')
     return self._cache.add(smart_str(key), value,
                            self._get_memcache_timeout(timeout))
예제 #31
0
    def get(self):
        user = users.get_current_user()
        if user and users.is_current_user_admin():
            self.response.headers['Content-Type'] = 'application/csv'
            self.response.headers[
                'Content-Disposition'] = 'attachment; filename=participantes.csv'
            writer = csv.writer(self.response.out,
                                delimiter=';',
                                quoting=csv.QUOTE_MINIMAL)
            writer.writerow([
                "Nome", "Data de Nascimento", "Sexo", "Identidade", "Familia",
                "Logradouro", "Complemento", "Cidade", "UF", "Bairro", "Zona",
                "Tel Celular1", "Tel Celular2", "Tel Residencial", "Email",
                "Problema de Saude", "Restricao Atividade Fisica",
                "Tem Alguma Alergia", "Toma Algum Medicamento",
                "Nome do Contato", "Tel Celular1 Contato",
                "Tel Celular2 Contato", "Tel Residencial Contato",
                "Tel Comercial Contato", "Familia", "Vai Levar Barraca"
            ])

            for participante in Participante.all().order('nome'):
                writer.writerow([
                    smart_str(participante.nome, encoding='ISO-8859-1'),
                    smart_str(participante.dataNascimento,
                              encoding='ISO-8859-1'),
                    smart_str(participante.sexo, encoding='ISO-8859-1'),
                    smart_str(participante.identidade, encoding='ISO-8859-1'),
                    smart_str(participante.familia, encoding='ISO-8859-1'),
                    smart_str(participante.logradouro, encoding='ISO-8859-1'),
                    smart_str(participante.complemento, encoding='ISO-8859-1'),
                    smart_str(participante.cidade, encoding='ISO-8859-1'),
                    smart_str(participante.uf, encoding='ISO-8859-1'),
                    smart_str(participante.bairro, encoding='ISO-8859-1'),
                    smart_str(participante.zona, encoding='ISO-8859-1'),
                    smart_str(participante.telCelular1, encoding='ISO-8859-1'),
                    smart_str(participante.telCelular2, encoding='ISO-8859-1'),
                    smart_str(participante.telResidencial,
                              encoding='ISO-8859-1'),
                    smart_str(participante.email, encoding='ISO-8859-1'),
                    smart_str(participante.problemaSaude,
                              encoding='ISO-8859-1'),
                    smart_str(participante.restricaoAtividadeFisica,
                              encoding='ISO-8859-1'),
                    smart_str(participante.temAlgumaAlergia,
                              encoding='ISO-8859-1'),
                    smart_str(participante.tomaAlgumMedicamento,
                              encoding='ISO-8859-1'),
                    smart_str(participante.nomeContato, encoding='ISO-8859-1'),
                    smart_str(participante.telCelular1Contato,
                              encoding='ISO-8859-1'),
                    smart_str(participante.telCelular2Contato,
                              encoding='ISO-8859-1'),
                    smart_str(participante.telResidencialContato,
                              encoding='ISO-8859-1'),
                    smart_str(participante.telComercialContato,
                              encoding='ISO-8859-1'),
                    smart_str(participante.familia, encoding='ISO-8859-1'),
                    smart_str(participante.barraca, encoding='ISO-8859-1')
                ])
예제 #32
0
 def get(self, key, default=None):
     val = self._cache.get(smart_str(key))
     if val is None:
         return default
     return val
예제 #33
0
 def __repr__(self):
     return smart_str(self._tzname)
예제 #34
0
class BaseCommand(object):
    """
    The base class from which all management commands ultimately
    derive.

    Use this class if you want access to all of the mechanisms which
    parse the command-line arguments and work out what code to call in
    response; if you don't need to change any of that behavior,
    consider using one of the subclasses defined in this file.

    If you are interested in overriding/customizing various aspects of
    the command-parsing and -execution behavior, the normal flow works
    as follows:

    1. ``django-admin.py`` or ``manage.py`` loads the command class
       and calls its ``run_from_argv()`` method.

    2. The ``run_from_argv()`` method calls ``create_parser()`` to get
       an ``OptionParser`` for the arguments, parses them, performs
       any environment changes requested by options like
       ``pythonpath``, and then calls the ``execute()`` method,
       passing the parsed arguments.

    3. The ``execute()`` method attempts to carry out the command by
       calling the ``handle()`` method with the parsed arguments; any
       output produced by ``handle()`` will be printed to standard
       output and, if the command is intended to produce a block of
       SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``.

    4. If ``handle()`` raised a ``CommandError``, ``execute()`` will
       instead print an error message to ``stderr``.

    Thus, the ``handle()`` method is typically the starting point for
    subclasses; many built-in commands and command types either place
    all of their logic in ``handle()``, or perform some additional
    parsing work in ``handle()`` and then delegate from it to more
    specialized methods as needed.

    Several attributes affect behavior at various steps along the way:

    ``args``
        A string listing the arguments accepted by the command,
        suitable for use in help messages; e.g., a command which takes
        a list of application names might set this to '<appname
        appname ...>'.

    ``can_import_settings``
        A boolean indicating whether the command needs to be able to
        import Django settings; if ``True``, ``execute()`` will verify
        that this is possible before proceeding. Default value is
        ``True``.

    ``help``
        A short description of the command, which will be printed in
        help messages.

    ``option_list``
        This is the list of ``optparse`` options which will be fed
        into the command's ``OptionParser`` for parsing arguments.

    ``output_transaction``
        A boolean indicating whether the command outputs SQL
        statements; if ``True``, the output will automatically be
        wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is
        ``False``.

    ``requires_model_validation``
        A boolean; if ``True``, validation of installed models will be
        performed prior to executing the command. Default value is
        ``True``. To validate an individual application's models
        rather than all applications' models, call
        ``self.validate(app)`` from ``handle()``, where ``app`` is the
        application's Python module.

    """
    # Metadata about this command.
    option_list = (
        make_option(
            '-v',
            '--verbosity',
            action='store',
            dest='verbosity',
            default='1',
            type='choice',
            choices=['0', '1', '2'],
            help=
            'Verbosity level; 0=minimal output, 1=normal output, 2=all output'
        ),
        make_option(
            '--settings',
            help=
            'The Python path to a settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'
        ),
        make_option(
            '--pythonpath',
            help=
            'A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'
        ),
        make_option('--traceback',
                    action='store_true',
                    help='Print traceback on exception'),
    )
    help = ''
    args = ''

    # Configuration shortcuts that alter various logic.
    can_import_settings = True
    requires_model_validation = True
    output_transaction = False  # Whether to wrap the output in a "BEGIN; COMMIT;"

    def __init__(self):
        self.style = color_style()

    def get_version(self):
        """
        Return the Django version, which should be correct for all
        built-in Django commands. User-supplied commands should
        override this method.

        """
        return django.get_version()

    def usage(self, subcommand):
        """
        Return a brief description of how to use this command, by
        default from the attribute ``self.help``.

        """
        usage = '%%prog %s [options] %s' % (subcommand, self.args)
        if self.help:
            return '%s\n\n%s' % (usage, self.help)
        else:
            return usage

    def create_parser(self, prog_name, subcommand):
        """
        Create and return the ``OptionParser`` which will be used to
        parse the arguments to this command.

        """
        return OptionParser(prog=prog_name,
                            usage=self.usage(subcommand),
                            version=self.get_version(),
                            option_list=self.option_list)

    def print_help(self, prog_name, subcommand):
        """
        Print the help message for this command, derived from
        ``self.usage()``.

        """
        parser = self.create_parser(prog_name, subcommand)
        parser.print_help()

    def run_from_argv(self, argv):
        """
        Set up any environment changes requested (e.g., Python path
        and Django settings), then run this command.

        """
        parser = self.create_parser(argv[0], argv[1])
        options, args = parser.parse_args(argv[2:])
        handle_default_options(options)
        self.execute(*args, **options.__dict__)

    def execute(self, *args, **options):
        """
        Try to execute this command, performing model validation if
        needed (as controlled by the attribute
        ``self.requires_model_validation``). If the command raises a
        ``CommandError``, intercept it and print it sensibly to
        stderr.

        """
        # Switch to English, because django-admin.py creates database content
        # like permissions, and those shouldn't contain any translations.
        # But only do this if we can assume we have a working settings file,
        # because django.utils.translation requires settings.
        if self.can_import_settings:
            try:
                from google.appengine._internal.django.utils import translation
                translation.activate('en-us')
            except ImportError, e:
                # If settings should be available, but aren't,
                # raise the error and quit.
                sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' %
                                                            e)))
                sys.exit(1)
        try:
            self.stdout = options.get('stdout', sys.stdout)
            self.stderr = options.get('stderr', sys.stderr)
            if self.requires_model_validation:
                self.validate()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    # This needs to be imported here, because it relies on
                    # settings.
                    from google.appengine._internal.django.db import connections, DEFAULT_DB_ALIAS
                    connection = connections[options.get(
                        'database', DEFAULT_DB_ALIAS)]
                    if connection.ops.start_transaction_sql():
                        self.stdout.write(
                            self.style.SQL_KEYWORD(
                                connection.ops.start_transaction_sql()) + '\n')
                self.stdout.write(output)
                if self.output_transaction:
                    self.stdout.write('\n' +
                                      self.style.SQL_KEYWORD("COMMIT;") + '\n')
        except CommandError, e:
            self.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
            sys.exit(1)
예제 #35
0
파일: __init__.py 프로젝트: 0xmilk/appscale
 def __repr__(self):
     return "<Text Node: '%s'>" % smart_str(self.s[:25], 'ascii',
             errors='replace')
예제 #36
0
파일: cache.py 프로젝트: 0xmilk/appscale
 def dictvalue(t):
     if t[1] is True:
         return t[0]
     else:
         return t[0] + '=' + smart_str(t[1])
예제 #37
0
 def __str__(self):
     return smart_str(self.name or '')
예제 #38
0
 def __repr__(self):
     return "<%s: %s (%s)>" % (
         self.__class__.__name__, smart_str(self.name), self.content_type)
예제 #39
0
 def get(self):
     user = users.get_current_user()
     if user and users.is_current_user_admin():
         self.response.headers['Content-Type'] = 'application/csv'
         self.response.headers['Content-Disposition'] = 'attachment; filename=servos.csv'
         writer = csv.writer(self.response.out, delimiter=';', quoting=csv.QUOTE_MINIMAL)
         writer.writerow(["Nome", "Data de Nascimento", "Sexo", "Equipe",
                          "Logradouro", "Complemento", "Cidade", "UF", "Bairro",
                          "Tel Celular1", "Tel Celular2", "Tel Residencial", "Email", "Rede Social",
                          "Problema de Saude", "Restricao Atividade Fisica", "Tem Alguma Alergia", "Toma Algum Medicamento",
                          "Nome do Contato",
                          "Tel Celular1 Contato", "Tel Celular2 Contato", "Tel Residencial Contato", "Tel Comercial Contato",
                          "Setor que Participa", "Nome Grupo de Oracao", "Nome do Pastor", "Tipo de Membro"])
         
         for servico in Servico.all().order('nome'):
             writer.writerow([smart_str(servico.nome, encoding='ISO-8859-1'),
                              smart_str(servico.dataNascimento, encoding='ISO-8859-1'),
                              smart_str(servico.sexo, encoding='ISO-8859-1'),
                              smart_str(servico.equipeServico, encoding='ISO-8859-1'),
                              smart_str(servico.logradouro, encoding='ISO-8859-1'),
                              smart_str(servico.complemento, encoding='ISO-8859-1'),
                              smart_str(servico.cidade, encoding='ISO-8859-1'),
                              smart_str(servico.uf, encoding='ISO-8859-1'),
                              smart_str(servico.bairro, encoding='ISO-8859-1'),
                              smart_str(servico.telCelular1, encoding='ISO-8859-1'),
                              smart_str(servico.telCelular2, encoding='ISO-8859-1'),
                              smart_str(servico.telResidencial, encoding='ISO-8859-1'),
                              smart_str(servico.email, encoding='ISO-8859-1'),
                              smart_str(servico.linkRedeSocial, encoding='ISO-8859-1'),
                              smart_str(servico.problemaSaude, encoding='ISO-8859-1'),
                              smart_str(servico.restricaoAtividadeFisica, encoding='ISO-8859-1'),
                              smart_str(servico.temAlgumaAlergia, encoding='ISO-8859-1'),
                              smart_str(servico.tomaAlgumMedicamento, encoding='ISO-8859-1'),
                              smart_str(servico.nomeContato, encoding='ISO-8859-1'),
                              smart_str(servico.telCelular1Contato, encoding='ISO-8859-1'),
                              smart_str(servico.telCelular2Contato, encoding='ISO-8859-1'),
                              smart_str(servico.telResidencialContato, encoding='ISO-8859-1'),
                              smart_str(servico.telComercialContato, encoding='ISO-8859-1'),
                              smart_str(servico.setorParticipa, encoding='ISO-8859-1'),
                              smart_str(servico.nomeGrupoOracao, encoding='ISO-8859-1'),
                              smart_str(servico.nomePastor, encoding='ISO-8859-1'),
                              smart_str(servico.tipoMembro, encoding='ISO-8859-1')
                              ])
예제 #40
0
 def __repr__(self):
     return smart_str(self._tzname)
예제 #41
0
 def get(self, key, default=None):
     val = self._cache.get(smart_str(key))
     if val is None:
         return default
     return val
예제 #42
0
 def __repr__(self):
     return "<Text Node: '%s'>" % smart_str(
         self.s[:25], 'ascii', errors='replace')
예제 #43
0
 def delete(self, key):
     self._cache.delete(smart_str(key))
예제 #44
0
 def __repr__(self):
     return "<%s: %s (%s)>" % (self.__class__.__name__, smart_str(
         self.name), self.content_type)
예제 #45
0
파일: base.py 프로젝트: 0xmilk/appscale
 def __str__(self):
     return smart_str(self.name or '')
예제 #46
0
 def set(self, key, value, timeout=0):
     self._cache.set(smart_str(key), value, self._get_memcache_timeout(timeout))
예제 #47
0
    def get(self):
        user = users.get_current_user()
        if user and users.is_current_user_admin():
            self.response.headers['Content-Type'] = 'application/csv'
            self.response.headers[
                'Content-Disposition'] = 'attachment; filename=servos.csv'
            writer = csv.writer(self.response.out,
                                delimiter=';',
                                quoting=csv.QUOTE_MINIMAL)
            writer.writerow([
                "Nome", "Data de Nascimento", "Sexo", "Equipe", "Logradouro",
                "Complemento", "Cidade", "UF", "Bairro", "Tel Celular1",
                "Tel Celular2", "Tel Residencial", "Email", "Rede Social",
                "Problema de Saude", "Restricao Atividade Fisica",
                "Tem Alguma Alergia", "Toma Algum Medicamento",
                "Nome do Contato", "Tel Celular1 Contato",
                "Tel Celular2 Contato", "Tel Residencial Contato",
                "Tel Comercial Contato", "Setor que Participa",
                "Nome Grupo de Oracao", "Nome do Pastor", "Tipo de Membro"
            ])

            for servico in Servico.all().order('nome'):
                writer.writerow([
                    smart_str(servico.nome, encoding='ISO-8859-1'),
                    smart_str(servico.dataNascimento, encoding='ISO-8859-1'),
                    smart_str(servico.sexo, encoding='ISO-8859-1'),
                    smart_str(servico.equipeServico, encoding='ISO-8859-1'),
                    smart_str(servico.logradouro, encoding='ISO-8859-1'),
                    smart_str(servico.complemento, encoding='ISO-8859-1'),
                    smart_str(servico.cidade, encoding='ISO-8859-1'),
                    smart_str(servico.uf, encoding='ISO-8859-1'),
                    smart_str(servico.bairro, encoding='ISO-8859-1'),
                    smart_str(servico.telCelular1, encoding='ISO-8859-1'),
                    smart_str(servico.telCelular2, encoding='ISO-8859-1'),
                    smart_str(servico.telResidencial, encoding='ISO-8859-1'),
                    smart_str(servico.email, encoding='ISO-8859-1'),
                    smart_str(servico.linkRedeSocial, encoding='ISO-8859-1'),
                    smart_str(servico.problemaSaude, encoding='ISO-8859-1'),
                    smart_str(servico.restricaoAtividadeFisica,
                              encoding='ISO-8859-1'),
                    smart_str(servico.temAlgumaAlergia, encoding='ISO-8859-1'),
                    smart_str(servico.tomaAlgumMedicamento,
                              encoding='ISO-8859-1'),
                    smart_str(servico.nomeContato, encoding='ISO-8859-1'),
                    smart_str(servico.telCelular1Contato,
                              encoding='ISO-8859-1'),
                    smart_str(servico.telCelular2Contato,
                              encoding='ISO-8859-1'),
                    smart_str(servico.telResidencialContato,
                              encoding='ISO-8859-1'),
                    smart_str(servico.telComercialContato,
                              encoding='ISO-8859-1'),
                    smart_str(servico.setorParticipa, encoding='ISO-8859-1'),
                    smart_str(servico.nomeGrupoOracao, encoding='ISO-8859-1'),
                    smart_str(servico.nomePastor, encoding='ISO-8859-1'),
                    smart_str(servico.tipoMembro, encoding='ISO-8859-1')
                ])
예제 #48
0
 def dictvalue(t):
     if t[1] is True:
         return t[0]
     else:
         return t[0] + '=' + smart_str(t[1])