Example #1
0
class FileForm(Form):
    title = fields.TextField(label=_('Title'),
                             description=_('The title of the file'),
                             validators=[validators.Required()])
    file_data = fields.FileField(label=_('File to upload'),
                                 description=_('Select file to upload'),
                                 validators=[validators.Required()])
Example #2
0
    def post(self, **kwargs):
        self.form = PasteForm(request.form)

        if self.form.validate():
            if self.current_user:
                user_key = str(self.current_user.key())
            else:
                user_key = None

            language_code = request.form.get('language')
            code_raw = request.form.get('code', u'')
            code = highlight(code_raw, language_code)

            values = {
                'area_key': str(self.area.key()),
                'user_key': user_key,
                'code_raw': code_raw,
                'code':     code,
                'language': language_code,
            }
            paste = Paste(**values)
            paste.put()
            self.set_message('success', _('The paste was saved.'), flash=True)

            return redirect_to('paste/view', paste_id=paste.id,
                area_name=self.area.name)
        else:
            self.set_form_error(_('Ooops, code is empty! Please post '
                'some lines.'))
            return self.get()
Example #3
0
class RegistrationForm(Form):
    username = fields.TextField(_('Username'), validators=[REQUIRED])
    password = fields.PasswordField(_('Password'), validators=[REQUIRED])
    password_confirm = fields.PasswordField(_('Confirm the password'),
                                            validators=[REQUIRED])
    email = fields.TextField(_('E-mail'), validators=[REQUIRED])
    email_confirm = fields.TextField(_('E-mail confirmation'),
                                     validators=[REQUIRED])
Example #4
0
    def post(self, **kwargs):
        if self.current_user is not None:
            # Don't allow existing users to access this page.
            return redirect(request.args.get('redirect', '/'))

        user = None
        error = None

        form, use_password = get_signup_form()
        username = form.data['username']
        email = form.data['email']

        kwargs = {'email': email}

        if use_password:
            kwargs['password'] = request.form.get('password')
            if kwargs['password'] != request.form.get('confirm_password'):
                error = True
                self.messages.add_form_error(_("Passwords didn't match."))

        if error is None:
            kwargs['is_admin'] = False
            if use_password:
                # Own authentication.
                auth_id = 'own|%s' % username
            else:
                current_user = users.get_current_user()
                if current_user is not None:
                    # App Engine authentication.
                    auth_id = 'gae|%s' % current_user.user_id()
                    kwargs['is_admin'] = users.is_current_user_admin()
                else:
                    # OpenId, Oauth, Facebook, Twitter or FriendFeed.
                    raise NotImplementedError()

            user = get_auth_system().create_user(username, auth_id, **kwargs)

            if user is None:
                self.messages.add_form_error(_('Username already exists. '
                    'Please try a different one.'))

        if user is not None:
            redirect_url = request.args.get('redirect', '/')
            if use_password:
                return redirect(create_login_url(redirect_url))
            else:
                return redirect(redirect_url)
        else:
            context = {
                'form': form,
                'messages': self.messages,
            }

            return self.render_response('users/signup.html', **context)
Example #5
0
    def get(self, exception=None, handler=None):
        logging.exception(exception)
        # Initial breadcrumbs for this app.
        self.request.context['breadcrumbs'] = [
            (url_for('home/index', area_name=self.area.name),
                i18n._('Home'))
        ]
        kwargs = {}
        code = 500
        template = 'base/error_500.html'

        if isinstance(exception, HTTPException):
            kwargs = {}
            code = exception.code
            if code in (404, 500):
                if exception.description != exception.__class__.description:
                    kwargs['message'] = exception.description

                template = 'base/error_%d.html' % code
            else:
                kwargs['message'] = exception.description

        response = self.render_response(template, **kwargs)
        response.status_code = code
        return response
Example #6
0
    def _build(self, mo, element_store, environ):
        heading_tag = self.tags[len(mo.group(1))-1]
        heading_text = mo.group(2)

        slug = _slugify(heading_text, default='heading')
        if environ is not None:
            headings = environ.setdefault('headings', [])
            i = 1
            original_slug = slug
            while True:
                if slug not in headings:
                    headings.append(slug)
                    break

                slug = '%s_%d' % (original_slug, i)
                i += 1

            toc = environ.setdefault('toc', [])
            toc.append((heading_tag, escape(heading_text), slug))

        # The heading itself.
        text = creoleparser.core.fragmentize(heading_text,
            self.child_elements, element_store, environ)
        # The anchor and link to the anchor.
        anchor = genshi.builder.tag.span(id=slug)
        anchor_link = genshi.builder.tag.a(genshi.core.Markup('¶'),
            class_='headerlink', href='#' + slug,
            title=escape(_('Permalink to this headline')))

        heading = genshi.builder.tag.__getattr__(heading_tag)
        return heading([text, anchor, anchor_link], class_='heading')
Example #7
0
    def set_form_error(self, body=None, title=None):
        """Adds a form error message.

        :param body:
            Message contents.
        :param title:
            Optional message title.
        :return:
            ``None``.
        """
        if body is None:
            body = i18n._("A problem occurred. Please correct the errors " "listed in the form.")

        if title is None:
            title = i18n._("Error")

        self.set_message("error", body, title=title, life=None)
Example #8
0
class PageForm(Form):
    title = fields.TextField(label=_('Title'),
                             description=_('The title of the page'),
                             validators=[validators.Required()])
    content = fields.TextAreaField(label=_('Content'),
                                   description=_('Content of the page'),
                                   validators=[validators.Required()])
    live = fields.BooleanField(
        label=_('Set live'),
        default=True,
        description=_('Live products will appear immediately'))
    language = fields.SelectField(
        label=_('Language'),
        description=_('The site language the page will appear'),
        choices=[('hu_HU', _('Magyar')), ('en_US', _('English'))],
        default='hu_HU',
        validators=[validators.Required()])
Example #9
0
class OrderForm(Form):
    comment = fields.TextAreaField(_('Comment'))
    delivery_method = fields.RadioField(_('Delivery Method'),
                                        choices=[('pickup', _('Pick up')),
                                                 ('box', _('Box delivery'))],
                                        validators=[REQUIRED])
    delivery_address = fields.TextField(_('Address'))
    delivery_city = fields.TextField(_('City'))
    delivery_zip = fields.TextField(_('Zip Code'))
    delivery_info = fields.TextAreaField(_('Other Information'))
Example #10
0
    def set_form_error(self, body=None, title=None):
        """Adds a form error message.

        :param body:
            Message contents.
        :param title:
            Optional message title.
        :return:
            ``None``.
        """
        if body is None:
            body = _('A problem occurred. Please correct the errors listed in '
                'the form.')

        if title is None:
            title = _('Error')

        self.set_message('error', body, title=title, life=None)
Example #11
0
File: models.py Project: ac001/moe
 def version(self):
     """Returns the current version id. Latest versions always have a key
     name, while older versions have a key id.
     """
     id = self.key().id()
     if id is None:
         return _('Latest')
     else:
         return str(id)
Example #12
0
 def post(self, subtitle_id):
     subtitles = Subtitles.get_by_id(subtitle_id);
     if subtitles:
         changeset = map(format_line, simplejson.loads(self.request.form.get('changeset')))
         changedLines = subtitles.set_changeset(changeset)
         logging.debug(changedLines)
         if changedLines:
             changeset = SubtitlesChangeSet(
                 text=[simplejson.dumps(x) for x in changedLines],
                 subtitles=subtitles,
                 user=self.auth_current_user.user
             )
             changeset.put()
             subtitles.put()
             return render_json_response({'status': 'ok'})
         else: 
             return render_json_response({'status': 'error', 'message': _('Error happened during the saving process')})
     else:
         return render_json_response({'status': 'error', 'message': _('Not valid Subtitles ID')})
Example #13
0
def get_files():
    files = File.get_latest_files(None, 100)
    '''
    [{ 'id': 1, 'title': 'title' }]
    '''
    
    
    default_list = {'id': '', 'title': unicode(_('Please choose an image'))}
    if files:
        file_list = [( { 'id': f.key().id(), 'title': unicode(f.title) }) for f in files]
        file_list.insert(0, default_list)
    else:
        file_list = default_list
    return file_list
Example #14
0
 def _validate(self):
     if self.delivery_method.data == "box":
         required = _("This field is required")
         logging.debug(self.delivery_area.data)
         if self.delivery_area.data == "":
             self.delivery_area.errors = ["%s" % required]
         if self.delivery_address.data == "":
             self.delivery_address.errors = ["%s" % required]
         if self.delivery_city.data == "":
             self.delivery_city.errors = ["%s" % required]
         if self.delivery_zip.data == "":
             self.delivery_zip.errors = ["%s" % required]
     if len(self.errors) > 0:
         return False
     else:
         return True
Example #15
0
 def post(self, **kwargs):
     redirect_url = self.redirect_path()
     if self.auth_current_user:
         return redirect(redirect_url)
     
     if self.form.validate():
         username = self.form.username.data
         password = self.form.password.data
         remember = self.form.remember.data
         
         res = self.auth_login_with_form(username, password, remember)
         if res:
             return redirect(redirect_url)
     
     self.set_message('error', _('Login failed. Please try again!'), life=None)
     return self.get(**kwargs)
Example #16
0
    def __call__(self, field, error=None, **kwargs):
        """Returns the recaptcha input HTML."""
        if get_config('tipfy.ext.wtforms', 'recaptcha_use_ssl'):
            server = RECAPTCHA_SSL_API_SERVER
        else:
            server = RECAPTCHA_API_SERVER

        query_options = dict(k=get_config('tipfy.ext.wtforms',
            'recaptcha_public_key'))

        if field.recaptcha_error is not None:
            query_options['error'] = unicode(field.recaptcha_error)

        query = url_encode(query_options)

        # Widget default options.
        options = {
            'theme': 'clean',
            'custom_translations': {
                'visual_challenge':    _('Get a visual challenge'),
                'audio_challenge':     _('Get an audio challenge'),
                'refresh_btn':         _('Get a new challenge'),
                'instructions_visual': _('Type the two words:'),
                'instructions_audio':  _('Type what you hear:'),
                'help_btn':            _('Help'),
                'play_again':          _('Play sound again'),
                'cant_hear_this':      _('Download sound as MP3'),
                'incorrect_try_again': _('Incorrect. Try again.'),
            }
        }
        custom_options = get_config('tipfy.ext.wtforms', 'recaptcha_options')
        if custom_options:
            options.update(custom_options)

        return RECAPTCHA_HTML % dict(
            script_url='%schallenge?%s' % (server, query),
            frame_url='%snoscript?%s' % (server, query),
            options=dumps(options)
        )
Example #17
0
    def get(self, **kwargs):
        paste_id = kwargs.pop('paste_id', None)
        if not paste_id:
            raise NotFound()

        paste = Paste.get_by_id(paste_id)
        if not paste:
            raise NotFound()

        self.add_breadcrumb('paste/view',
            _('Paste #%(paste_id)s', paste_id=paste.id),
            paste_id=paste.id)
        form = PasteForm(code=paste.code_raw, language=paste.language)

        context = {
            'paste': paste,
            'form': form,
        }
        return self.render_response('paste/view.html', **context)
Example #18
0
    def get(self, exception=None, handler=None):
        # Always log exceptions.
        logging.exception(exception)

        # Get the exception code and description, if it is an HTTPException,
        # or assume 500.
        code = getattr(exception, "code", 500)
        message = getattr(exception, "description", None)

        if self.app.dev and code not in (404,):
            # Raise the exception in dev except for NotFound.
            raise

        if code in (403, 404):
            # Render a special template for these codes.
            template = "base/error_%d.html" % code
        else:
            # Render a generic 500 template.
            template = "base/error_500.html"

        # Set breadcrumbs to follow rest of the site.
        self.request.context["breadcrumbs"] = [(url_for("home/index", area_name=self.area.name), i18n._("Home"))]

        # Render the template using the exception message, if any, and set
        # the status code.
        response = self.render_response(template, message=message)
        response.status_code = code
        return response
Example #19
0
    def render_response(self, filename, **values):
        self.request.context['breadcrumbs'] = [
            self.get_breadcrumb('home/index', _('Home')),
            self.get_breadcrumb('paste/index', _('Paste'))] + self.breadcrumbs

        return super(PasteBaseHandler, self).render_response(filename, **values)
Example #20
0
class SignupForm(Form):
    nickname = fields.TextField(_('Username'), validators=[REQUIRED])
Example #21
0
import csv
from pygments.util import ClassNotFound
from pygments.lexers import get_lexer_by_name, get_lexer_for_filename, \
     get_lexer_for_mimetype, PhpLexer, TextLexer
from pygments.styles import get_all_styles
from pygments.formatters import HtmlFormatter

from werkzeug import escape

from tipfy import Tipfy
from tipfy.ext.i18n import lazy_gettext as _

#: we use a hardcoded list here because we want to keep the interface
#: simple
LANGUAGES = {
    'text':             _('Text'),
    #'multi':            _('Multi-File'),
    'python':           _('Python'),
    'pycon':            _('Python Console Sessions'),
    'pytb':             _('Python Tracebacks'),
    'html+php':         _('PHP'),
    #'php':              _('PHP (inline)'),
    'html+django':      _('Django / Jinja Templates'),
    'html+mako':        _('Mako Templates'),
    'html+myghty':      _('Myghty Templates'),
    'apache':           _('Apache Config (.htaccess)'),
    'bash':             _('Bash'),
    'bat':              _('Batch (.bat)'),
    'brainfuck':        _('Brainfuck'),
    'c':                _('C'),
    #'gcc-messages':     _('GCC Messages'),
Example #22
0
class LoginForm(Form):
    username = fields.TextField(_('Username'), validators=[REQUIRED])
    password = fields.PasswordField(_('Password'), validators=[REQUIRED])
    remember = fields.BooleanField(_('Keep me signed in'))
Example #23
0
class ProductForm(Form):
    name = fields.TextField(label=_('Name'),
                            description=_('The name of the product'),
                            validators=[validators.Required()])
    description = fields.TextAreaField(
        label=_('Description'),
        description=_('A few words about the product'),
        validators=[validators.Required()])
    price = fields.FloatField(label=_('Price'),
                              description=_('The price of the product'),
                              validators=[validators.Required()])
    unit = fields.SelectField(label=_('Unit'),
                              description=_('The unit of the product'),
                              choices=[('piece', _('Piece')),
                                       ('gram', _('Gram')),
                                       ('pack', _('Pack'))],
                              validators=[validators.Required()])
    live = fields.BooleanField(
        label=_('Set live'),
        default=True,
        description=_('Live products will appear immediately'))
    tags = fields.TextField(
        label=_('Tags'), description=_('List of tags, separated by comma (,)'))
    language = fields.SelectField(
        label=_('Language'),
        description=_('The site language the product will appear'),
        choices=[('hu_HU', _('Magyar')), ('en_US', _('English'))],
        default='hu_HU',
        validators=[validators.Required()])
Example #24
0
# -*- coding: utf-8 -*-
"""
    urls
    ~~~~~~~~

    Mailer Constants

"""
from tipfy.ext.i18n import gettext as _


SHOP = "*****@*****.**"
SENDER = "*****@*****.**"
REPLY_TO = "*****@*****.**"
SUBJECT_ORDER = _("Order from Lumen Kave")
SUBJECT_REGISTRATION = _("Registration at Lumen Kave")

__all__ = ["SENDER", "REPLY_TO", "SUBJECT_ORDER", "SUBJECT_REGISTRATION", "SHOP"]
Example #25
0
def get_language_name(code):
    """Language name, based on the language code."""
    return str(LANGUAGES.get(code, _('Undefined language')))
Example #26
0
class BlogPostForm(Form):
    """Form class for Blog post validation"""
    title = fields.TextField(label=_('Title'),
                             description=_('The title of your blog post'),
                             validators=[validators.Required()])
    lead = fields.TextAreaField(
        label=_('Lead'),
        description=_('A limited length lead text for your post'),
        validators=[validators.Required()])
    content = fields.TextAreaField(
        label=_('Content'),
        description=_('The main text for your blog post'),
        validators=[validators.Required()])
    live = fields.BooleanField(
        label=_('Set live'),
        description=_('Live posts will appear immediately'))
    tags = fields.TextField(
        label=_('Tags'), description=_('List of tags, separated by comma (,)'))
    language = fields.SelectField(
        label=_('Language'),
        description=_('The site language the product will appear'),
        choices=[('hu_HU', _('Magyar')), ('en_US', _('English'))],
        default='hu_HU',
        validators=[validators.Required()])