def confirmation(self):  # redirect_url
        context = {}
        transaction_param = self.config.get(
            'transaction_param',
            self.pg.config.get('TRANSACTION_PARAM', 'transaction_id')
        )
        transaction_code = request.args.get(transaction_param)
        if transaction_code:
            context['transaction_code'] = transaction_code
            response = self.pg.check_transaction(transaction_code)
            logger.debug(response.xml)
            reference = getattr(response, 'reference', None)
            if not reference:
                logger.error("no reference found")
                return render_template('cart/simple_confirmation.html',
                                       **context)
            prefix = self.pg.config.get('REFERENCE_PREFIX', '') or ''
            prefix = prefix.replace('%s', '')

            status = getattr(response, 'status', None)

            # get grossAmount to populate a payment with methods
            try:
                # self.cart = Cart.objects.get(
                #     reference_code=reference.replace(PREFIX, '')
                # )
                ref = reference.replace(prefix, '')
                qs = Cart.objects.filter(
                    reference_code=ref
                ) or Cart.objects.filter(id=ref)

                if not qs:
                    return "Cart not found"

                self.cart = qs[0]

                self.cart.set_status(
                    self.STATUS_MAP.get(str(status), self.cart.status)
                )

                self.cart.transaction_code = transaction_code
                msg = "Status changed to: %s" % self.cart.status
                self.cart.addlog(msg)
                context['cart'] = self.cart
                logger.info("Cart updated")

                fee_amount = getattr(response, 'feeAmount', None)
                if fee_amount:
                    self.cart.set_tax(fee_amount)
                    msg = "Tax set to: %s" % fee_amount
                    self.cart.addlog(msg)

                # send response to reference and products
                self.cart.send_response(response, 'pagseguro')

                return render_template('cart/confirmation.html', **context)
            except Exception as e:
                msg = "Error in confirmation: {} - {}".format(reference, e)
                logger.error(msg)
        return render_template('cart/simple_confirmation.html', **context)
示例#2
0
    def confirmation(self):  # redirect_url
        context = {}
        transaction_param = self.config.get(
            'transaction_param',
            self.pg.config.get('TRANSACTION_PARAM', 'transaction_id'))
        transaction_code = request.args.get(transaction_param)
        if transaction_code:
            context['transaction_code'] = transaction_code
            response = self.pg.check_transaction(transaction_code)
            logger.debug(response.xml)
            reference = getattr(response, 'reference', None)
            if not reference:
                logger.error("no reference found")
                return render_template('cart/simple_confirmation.html',
                                       **context)
            prefix = self.pg.config.get('REFERENCE_PREFIX', '') or ''
            prefix = prefix.replace('%s', '')

            status = getattr(response, 'status', None)

            # get grossAmount to populate a payment with methods
            try:
                # self.cart = Cart.objects.get(
                #     reference_code=reference.replace(PREFIX, '')
                # )
                ref = reference.replace(prefix, '')
                qs = Cart.objects.filter(
                    reference_code=ref) or Cart.objects.filter(id=ref)

                if not qs:
                    return "Cart not found"

                self.cart = qs[0]

                self.cart.set_status(
                    self.STATUS_MAP.get(str(status), self.cart.status))

                self.cart.transaction_code = transaction_code
                msg = "Status changed to: %s" % self.cart.status
                self.cart.addlog(msg)
                context['cart'] = self.cart
                logger.info("Cart updated")

                fee_amount = getattr(response, 'feeAmount', None)
                if fee_amount:
                    self.cart.set_tax(fee_amount)
                    msg = "Tax set to: %s" % fee_amount
                    self.cart.addlog(msg)

                # send response to reference and products
                self.cart.send_response(response, 'pagseguro')

                return render_template('cart/confirmation.html', **context)
            except Exception as e:
                msg = "Error in confirmation: {} - {}".format(reference, e)
                logger.error(msg)
        return render_template('cart/simple_confirmation.html', **context)
示例#3
0
    def post(self):
        form = self.form(request.form)
        if form.validate():
            user = get_current_user()
            avatar_file_path = user.avatar_file_path
            avatar = request.files.get('avatar')
            if avatar:
                filename = secure_filename(avatar.filename)
                avatar_file_path = os.path.join(
                    'avatars', str(user.id), filename
                )
                path = os.path.join(lazy_media_path(), avatar_file_path)
                if not os.path.exists(os.path.dirname(path)):
                    os.makedirs(os.path.dirname(path), 0o777)
                avatar.save(path)
            form.populate_obj(user)
            user.avatar_file_path = avatar_file_path
            if avatar:
                user.use_avatar_from = 'upload'
            user.username = User.generate_username(
                user.username or user.name, user=user
            )

            self.update_user_links(request.form, user)

            user.save()
            flash('Profile saved!', 'alert')
            return redirect(
                request.args.get('next') or
                url_for('quokka.modules.accounts.profile_edit')
            )
        else:
            flash('Error ocurred!', 'alert error')  # form errors
            return render_template('accounts/profile_edit.html', form=form)
示例#4
0
    def get(self, long_slug):
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath)

        if channel.render_content:
            return ContentDetail().get(
                channel.render_content.content.long_slug, True)

        self.channel = channel

        base_filters = {}

        filters = {
            'published': True,
            'available_at__lte': now,
            'show_on_channel': True
        }

        if not channel.is_homepage:
            base_filters['__raw__'] = {
                'mpath': {'$regex': "^{0}".format(mpath)}}

        filters.update(channel.get_content_filters())
        contents = Content.objects(**base_filters).filter(**filters)

        themes = channel.get_themes()
        return render_template(self.get_template_names(),
                               theme=themes,
                               contents=contents,
                               channel=channel)
示例#5
0
 def get(self, long_slug, render_content=False):
     context = self.get_context(long_slug, render_content)
     if not render_content and isinstance(context, collections.Callable):
         return context
     return render_template(self.get_template_names(),
                            theme=self.content.get_themes(),
                            **context)
示例#6
0
文件: views.py 项目: munum/quokka
    def post(self, long_slug):
        context = self.get_context_by_long_slug(long_slug)
        form = context.get('form')

        #if form.validate():
        #    comment = Comment()
        #    form.populate_obj(comment)
        #
        #    content = context.get('content')
        #    content.comments.append(comment)
        #    content.save()
        #
        #    return redirect(url_for('.detail', long_slug=long_slug))

        if form.validate():
            answer = Answer()
            form.populate_obj(answer)

            question = context.get('question')
            question.tries.append(answer)
            question.save()

            #candidate = context.get('candidate')
            #candidate.answers.append(answer)
            #candidate.save()

            return redirect(url_for('.detail', long_slug=long_slug))

        return render_template(
            self.get_template_names(),
            theme=self.question.get_themes(),
            **context
        )
示例#7
0
文件: views.py 项目: jstacoder/quokka
 def get(self):
     user = get_current_user()
     context = {}
     for link in user.links:
         context[link.icon] = link.link
     return self.needs_login(user) or render_template(
         'accounts/profile_edit.html', form=self.form(obj=user), **context)
示例#8
0
    def post(self):
        form = self.form(request.form)
        if form.validate():
            user = get_current_user()
            avatar_file_path = user.avatar_file_path
            avatar = request.files.get('avatar')
            if avatar:
                filename = secure_filename(avatar.filename)
                avatar_file_path = os.path.join('avatars', str(user.id),
                                                filename)
                path = os.path.join(lazy_media_path(), avatar_file_path)
                if not os.path.exists(os.path.dirname(path)):
                    os.makedirs(os.path.dirname(path), 0o777)
                avatar.save(path)
            form.populate_obj(user)
            user.avatar_file_path = avatar_file_path
            if avatar:
                user.use_avatar_from = 'upload'
            user.username = User.generate_username(user.username or user.name,
                                                   user=user)

            self.update_user_links(request.form, user)

            user.save()
            flash('Profile saved!', 'alert')
            return redirect(
                request.args.get('next')
                or url_for('quokka.modules.accounts.profile_edit'))
        else:
            flash('Error ocurred!', 'alert error')  # form errors
            return render_template('accounts/profile_edit.html', form=form)
 def process(self, *args, **kwargs):
     kwargs.update(self._record.config)
     kwargs.update(self.cart.config)
     response = self.pg.checkout(**kwargs)
     self.cart.addlog(
         (
             "lib checkout data:{pg.data}\n"
             " code:{r.code} url:{r.payment_url}\n"
             " errors: {r.errors}\n"
             " xml: {r.xml}\n"
         ).format(
             pg=self.pg, r=response
         )
     )
     if not response.errors:
         self.cart.checkout_code = response.code
         #self.cart.status = 'checked_out'  # should set on redirect url
         self.cart.addlog("PagSeguro processed! {}".format(response.code))
         return redirect(response.payment_url)
     else:
         self.cart.addlog(
             'PagSeguro error processing {}'.format(
                 response.errors
             )
         )
         return render_template("cart/checkout_error.html",
                                response=response, cart=self.cart)
示例#10
0
 def get(self):
     """
     Fixme: Should include extra paths, fixed paths
     config based paths, static paths
     """
     return render_template('sitemap.xml',
                            contents=self.get_contents(),
                            channels=self.get_channels())
def dispatch_aliases():
    """
    When ALIASES_ENABLED == True

    This method handle 3 QuokkaCMS features:
    1. Fixed aliases
      Alias is defined in ALIASES_MAP setting as a dictionary
    2. Managed Redirects
      Alias defined in database
    3. Channel and Content aliases
      Alias defined in specific channel or content

    ALIASES_MAP
    keys are long_slug
        keys should always start with /
        & end with / or extension.
    {
        "/team/": {
            "alias_type": "endpoint|long_slug|url|string|template",
            "action": "redirect|render",
            "to": "authors|/articles/science.html|http://t.co|'<b>Hello</b>'",
            "published": True,
            "available_at": "",
            "available_until: "",
        }
    }

    - 'endpoint' and 'long_slug' by default are rendered
    - 'url' is always redirect
    - 'string' and 'template' are always rendered
    """

    app = current_app
    aliases_map = app.config.get('ALIASES_MAP')
    if aliases_map and request.path in aliases_map:
        alias = aliases_map[request.path]
        status = alias.get('status', 200)
        if alias['alias_type'] == 'endpoint':
            endpoint = alias['to']
            if alias.get('action') == 'redirect':
                return redirect(url_for(endpoint, **request.args))
            else:  # render
                return app.process_response(
                    app.make_response(app.view_functions[endpoint]()))
        elif alias['alias_type'] == 'long_slug':
            long_slug = alias['to']
            if alias.get('action') == 'redirect':
                return redirect(long_slug)  # pass request.args ?
            else:  # render
                endpoint = route_from(long_slug)[0]
                return app.process_response(
                    app.make_response(app.view_functions[endpoint]()))
        elif alias['alias_type'] == 'url':
            return redirect(alias['to'])
        elif alias['alias_type'] == 'string':
            return render_template_string(alias['to']), status
        elif alias['alias_type'] == 'template':
            return render_template(alias['to']), status
示例#12
0
文件: views.py 项目: nleite/quokka
 def get(self, long_slug):
     context = self.get_context(long_slug)
     if isinstance(context, collections.Callable):
         return context
     return render_template(
         self.get_template_names(),
         theme=self.content.get_themes(),
         **context
     )
示例#13
0
文件: views.py 项目: munum/quokka
 def get(self, pretty_slug, render_content=False):
     context = self.get_context_by_pretty_slug(pretty_slug, render_content)
     if not render_content and isinstance(context, collections.Callable):
         return context
     return render_template(
         self.get_template_names(),
         theme=self.question.get_themes(),
         **context
     )
示例#14
0
文件: views.py 项目: alyoung/quokka
    def get(self, long_slug):
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath, published=True)

        # if channel.is_homepage and request.path != "/":
        #     return redirect("/")

        if channel.redirect_url:
            return redirect(channel.redirect_url)

        if channel.render_content:
            return ContentDetail().get(
                channel.render_content.content.long_slug, True)

        self.channel = channel

        base_filters = {}

        filters = {
            'published': True,
            'available_at__lte': now,
            'show_on_channel': True
        }

        if not channel.is_homepage:
            base_filters['__raw__'] = {
                'mpath': {'$regex': "^{0}".format(mpath)}}

        filters.update(channel.get_content_filters())
        contents = Content.objects(**base_filters).filter(**filters)

        if current_app.config.get("PAGINATION_ENABLED", True):
            pagination_arg = current_app.config.get("PAGINATION_ARG", "page")
            page = request.args.get(pagination_arg, 1)
            per_page = (
                request.args.get('per_page') or
                channel.per_page or
                current_app.config.get("PAGINATION_PER_PAGE", 10)
            )
            contents = contents.paginate(page=int(page),
                                         per_page=int(per_page))

        # this can be overkill! try another solution
        # to filter out content in unpublished channels
        # when homepage and also in blocks
        # contents = [content for content in contents
        #             if content.channel.published]

        themes = channel.get_themes()
        return render_template(self.get_template_names(),
                               theme=themes,
                               contents=contents,
                               channel=channel)
示例#15
0
    def process_pipeline(self):
        if not self.items:
            return render_template('cart/empty_cart.html',
                                   url=self.continue_shopping_url)

        pipelines = self.build_pipeline()
        index = session.get('cart_pipeline_index', 0)
        pipeline = import_string(pipelines[index])
        return pipeline(self, pipelines, index)._preprocess()
示例#16
0
 def method_not_allowed_page(error):
     """
     The method specified in the Request-Line is not allowed for the
     resource
     identified by the Request-URI. The response MUST include an
     Allow header
     containing a list of valid methods for the requested resource.
     """
     return render_template("errors/method_not_allowed.html"), 405
示例#17
0
    def process_pipeline(self):
        if not self.items:
            return render_template('cart/empty_cart.html',
                                   url=self.continue_shopping_url)

        pipelines = self.build_pipeline()
        index = session.get('cart_pipeline_index', 0)
        pipeline = import_string(pipelines[index])
        return pipeline(self, pipelines, index)._preprocess()
示例#18
0
def dispatch_aliases():
    """
    When ALIASES_ENABLED == True

    This method handle 3 QuokkaCMS features:
    1. Fixed aliases
      Alias is defined in ALIASES_MAP setting as a dictionary
    2. Managed Redirects
      Alias defined in database
    3. Channel and Content aliases
      Alias defined in specific channel or content

    ALIASES_MAP
    keys are long_slug
        keys should always start with /
        & end with / or extension.
    {
        "/team/": {
            "alias_type": "endpoint|long_slug|url|string|template",
            "action": "redirect|render",
            "to": "authors|/articles/science.html|http://t.co|'<b>Hello</b>'",
            "published": True,
            "available_at": "",
            "available_until: "",
        }
    }

    - 'endpoint' and 'long_slug' by default are rendered
    - 'url' is always redirect
    - 'string' and 'template' are always rendered
    """

    app = current_app
    aliases_map = app.config.get("ALIASES_MAP")
    if aliases_map and request.path in aliases_map:
        alias = aliases_map[request.path]
        status = alias.get("status", 200)
        if alias["alias_type"] == "endpoint":
            endpoint = alias["to"]
            if alias.get("action") == "redirect":
                return redirect(url_for(endpoint, **request.args))
            else:  # render
                return app.process_response(app.make_response(app.view_functions[endpoint]()))
        elif alias["alias_type"] == "long_slug":
            long_slug = alias["to"]
            if alias.get("action") == "redirect":
                return redirect(long_slug)  # pass request.args ?
            else:  # render
                endpoint = route_from(long_slug)[0]
                return app.process_response(app.make_response(app.view_functions[endpoint]()))
        elif alias["alias_type"] == "url":
            return redirect(alias["to"])
        elif alias["alias_type"] == "string":
            return render_template_string(alias["to"]), status
        elif alias["alias_type"] == "template":
            return render_template(alias["to"]), status
示例#19
0
 def __call__(self, *args, **kwargs):
     html = super(PrepopulatedText, self).__call__(*args, **kwargs)
     slave = args[0].id
     if self.master:
         html += render_template('admin/custom/prepopulated.html',
                                 theme=current_app.config.get(
                                     'ADMIN_THEME', 'admin'),
                                 master=self.master,
                                 slave=slave)
     return html
示例#20
0
 def get(self):
     user = get_current_user()
     context = {}
     for link in user.links:
         context[link.icon] = link.link
     return self.needs_login() or render_template(
         'accounts/profile_edit.html',
         form=self.form(instance=user),
         **context
     )
示例#21
0
文件: views.py 项目: Cetids/quokka
 def get(self):
     """
     Fixme: Should include extra paths, fixed paths
     config based paths, static paths
     """
     return render_template(
         'sitemap.xml',
         contents=self.get_contents(),
         channels=self.get_channels()
     )
示例#22
0
 def __call__(self, *args, **kwargs):
     html = super(PrepopulatedText, self).__call__(*args, **kwargs)
     slave = args[0].id
     if self.master:
         html += render_template(
             'admin/custom/prepopulated.html',
             theme=current_app.config.get('ADMIN_THEME', 'cosmo'),
             master=self.master,
             slave=slave
         )
     return html
示例#23
0
文件: models.py 项目: sant0sh/quokka
 def render(self, template, **kwargs):
     # Store self as admin_view
     kwargs['admin_view'] = self
     kwargs['admin_base_template'] = self.admin.base_template
     # Provide i18n support even if flask-babel is not installed or enabled.
     kwargs['_gettext'] = gettext
     kwargs['_ngettext'] = ngettext
     kwargs['h'] = h
     # Contribute extra arguments
     kwargs.update(self._template_args)
     return render_template(template, **kwargs)
示例#24
0
 def __call__(self, *args, **kwargs):
     html = super(PrepopulatedText, self).__call__(*args, **kwargs)
     slave = args[0].id
     if self.master:
         html += render_template(
             "admin/custom/prepopulated.html",
             theme=current_app.config.get("ADMIN_TEHME", "admin"),
             master=self.master,
             slave=slave,
         )
     return html
示例#25
0
 def render(self, template, **kwargs):
     # Store self as admin_view
     kwargs['admin_view'] = self
     kwargs['admin_base_template'] = self.admin.base_template
     # Provide i18n support even if flask-babel is not installed or enabled.
     kwargs['_gettext'] = gettext
     kwargs['_ngettext'] = ngettext
     kwargs['h'] = h
     # Contribute extra arguments
     kwargs.update(self._template_args)
     return render_template(template, **kwargs)
示例#26
0
    def confirmation(self):  # redirect_url
        context = {}
        transaction_param = self.config.get(
            'transaction_param',
            self.pg.config.get('TRANSACTION_PARAM', 'transaction_id')
        )
        transaction_code = request.args.get(transaction_param)
        if transaction_code:
            context['transaction_code'] = transaction_code
            response = self.pg.check_transaction(transaction_code)
            logger.debug(response.xml)
            reference = getattr(response, 'reference', None)
            if not reference:
                logger.error("no reference found")
                return render_template('cart/simple_confirmation.html',
                                       **context)
            PREFIX = self.pg.config.get('REFERENCE_PREFIX', '') or ''
            PREFIX = PREFIX.replace('%s', '')

            status = getattr(response, 'status', None)

            # TODO: get grossAmount to populate a payment with methods
            try:
                self.cart = Cart.objects.get(
                    reference_code=reference.replace(PREFIX, '')
                )

                self.cart.set_status(
                    self.STATUS_MAP.get(str(status), self.cart.status)
                )

                self.cart.transaction_code = transaction_code
                msg = "Status changed to: %s" % self.cart.status
                self.cart.addlog(msg)
                context['cart'] = self.cart
                logger.info("Cart updated")
                return render_template('cart/confirmation.html', **context)
            except Exception as e:
                msg = "Cart not found: {} - {}".format(reference, e)
                logger.error(msg)
        return render_template('cart/simple_confirmation.html', **context)
示例#27
0
 def forbidden_page(error):
     """
     The server understood the request, but is refusing to fulfill it.
     Authorization will not help and the request SHOULD NOT be repeated.
     If the request method was not HEAD and the server wishes to make public
     why the request has not been fulfilled, it SHOULD describe the
     reason for
     the refusal in the entity. If the server does not wish to make this
     information available to the client, the status code 404 (Not Found)
     can be used instead.
     """
     return render_template("errors/access_forbidden.html"), 403
示例#28
0
 def __call__(self, field, **kwargs):
     c = kwargs.pop('class', '') or kwargs.pop('class_', '')
     kwargs['class'] = u'%s %s' % (self.css_cls, c)
     kwargs['rows'] = self.rows
     kwargs['cols'] = self.cols
     s = kwargs.pop('style', '') or kwargs.pop('style_', '')
     kwargs['style'] = u"%s %s" % (self.style_, s)
     html = super(TextEditor, self).__call__(field, **kwargs)
     html += render_template('admin/texteditor/%s.html' % self.editor,
                             theme=current_app.config.get(
                                 'ADMIN_THEME', 'admin'),
                             selector='.' + self.css_cls)
     return html
示例#29
0
 def __call__(self, field, **kwargs):
     c = kwargs.pop("class", "") or kwargs.pop("class_", "")
     kwargs["class"] = u"%s %s" % (self.css_cls, c)
     kwargs["rows"] = self.rows
     kwargs["cols"] = self.cols
     s = kwargs.pop("style", "") or kwargs.pop("style_", "")
     kwargs["style"] = u"%s %s" % (self.style_, s)
     html = super(TextEditor, self).__call__(field, **kwargs)
     html += render_template(
         "admin/texteditor/%s.html" % self.editor,
         theme=current_app.config.get("ADMIN_THEME", "admin"),
         seletor="." + self.css_cls,
     )
     return html
示例#30
0
 def __call__(self, field, **kwargs):
     c = kwargs.pop('class', '') or kwargs.pop('class_', '')
     kwargs['class'] = u'%s %s' % (self.css_cls, c)
     kwargs['rows'] = self.rows
     kwargs['cols'] = self.cols
     s = kwargs.pop('style', '') or kwargs.pop('style_', '')
     kwargs['style'] = u"%s %s" % (self.style_, s)
     html = super(TextEditor, self).__call__(field, **kwargs)
     html += render_template(
         'admin/texteditor/%s.html' % self.editor,
         theme=current_app.config.get('ADMIN_THEME', 'cosmo'),
         selector='.' + self.css_cls
     )
     return html
示例#31
0
 def page_not_found(error):
     """
     The server has not found anything matching the Request-URI.
     No indication
     is given of whether the condition is temporary or permanent.
     The 410 (Gone)
     status code SHOULD be used if the server knows, through some internally
     configurable mechanism, that an old resource is permanently unavailable
     and has no forwarding address. This status code is commonly used when
     the
     server does not wish to reveal exactly why the request has been
     refused,
     or when no other response is applicable.
     """
     return render_template("errors/page_not_found.html"), 404
示例#32
0
文件: views.py 项目: makeclan/quokka
    def post(self, long_slug):
        context = self.get_context(long_slug)
        form = context.get('form')

        if form.validate():
            comment = Comment()
            form.populate_obj(comment)

            content = context.get('content')
            content.comments.append(comment)
            content.save()

            return redirect(url_for('.detail', long_slug=long_slug))

        return render_template('content/detail.html', **context)
示例#33
0
 def process(self, *args, **kwargs):
     kwargs.update(self._record.config)
     kwargs.update(self.cart.config)
     response = self.pg.checkout(**kwargs)
     self.cart.addlog(("lib checkout data:{pg.data}\n"
                       " code:{r.code} url:{r.payment_url}\n"
                       " errors: {r.errors}\n"
                       " xml: {r.xml}\n").format(pg=self.pg, r=response))
     if not response.errors:
         self.cart.checkout_code = response.code
         self.cart.addlog("PagSeguro processed! {}".format(response.code))
         return redirect(response.payment_url)
     else:
         self.cart.addlog('PagSeguro error processing {}'.format(
             response.errors))
         return render_template("cart/checkout_error.html",
                                response=response,
                                cart=self.cart)
示例#34
0
文件: views.py 项目: iapilgrim/quokka
    def get(self, tag):

        now = datetime.now()
        filters = {
            'published': True,
            'available_at__lte': now
        }
        contents = Content.objects(**filters).filter(tags=tag)

        if current_app.config.get("PAGINATION_ENABLED", True):
            pagination_arg = current_app.config.get("PAGINATION_ARG", "page")
            page = request.args.get(pagination_arg, 1)
            per_page = current_app.config.get(
                "PAGINATION_PER_PAGE", 10
            )
            contents = contents.paginate(page=int(page), per_page=per_page)

        return render_template(self.get_template_names(),
                               contents=contents)
示例#35
0
    def get(self, long_slug):
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath)

        if not channel.is_homepage:
            contents = Content.objects(__raw__={'mpath': {
                '$regex': mpath
            }},
                                       published=True,
                                       available_at__lte=now,
                                       show_on_channel=True)
        else:
            contents = Content.objects(published=True,
                                       available_at__lte=now,
                                       show_on_channel=True)

        return render_template('content/list.html', contents=contents)
示例#36
0
文件: base.py 项目: jstacoder/quokka
 def _preprocess(self):
     try:
         ret = self.process()  # the only overridable method
         if not ret:
             ret = self.go()
         if isinstance(ret, CartPipeline):
             session['cart_pipeline_index'] = ret.index
             return ret._preprocess()
         else:
             session['cart_pipeline_index'] = self.index
             return ret
     except PipelineOverflow as e:
         ret = self.cart.checkout()
         self.del_sessions()
         return ret
     except Exception as e:
         self.del_sessions()
         self.cart.addlog(
             u"{e} {p.index} {p} cart: {p.cart.id}".format(p=self, e=e)
         )
         return render_template('cart/pipeline_error.html',
                                pipeline=self,
                                error=e)
示例#37
0
文件: views.py 项目: Motoma/quokka
    def get(self, long_slug):
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath)

        if not channel.is_homepage:
            contents = Content.objects(
                __raw__={'mpath': {'$regex': mpath}},
                published=True,
                available_at__lte=now,
                show_on_channel=True
            )
        else:
            contents = Content.objects(
                published=True,
                available_at__lte=now,
                show_on_channel=True
            )

        return render_template('content/list.html', contents=contents)
示例#38
0
    def get(self, long_slug):
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath)

        if channel.render_content:
            return ContentDetail().get(
                channel.render_content.content.long_slug, True)

        self.channel = channel

        base_filters = {}

        filters = {
            'published': True,
            'available_at__lte': now,
            'show_on_channel': True
        }

        if not channel.is_homepage:
            base_filters['__raw__'] = {
                'mpath': {
                    '$regex': "^{0}".format(mpath)
                }
            }

        filters.update(channel.get_content_filters())
        contents = Content.objects(**base_filters).filter(**filters)

        themes = channel.get_themes()
        return render_template(self.get_template_names(),
                               theme=themes,
                               contents=contents,
                               channel=channel)
示例#39
0
 def get(self, slug):
     context = self.get_context(slug)
     return render_template('medias/detail.html', **context)
示例#40
0
文件: views.py 项目: zming619/quokka
 def render_context(path, form):
     comments = Comment.objects(path=path, published=True)
     return render_template('content/comments.html',
                            comments=comments,
                            form=form,
                            path=path)
示例#41
0
 def get(self):
     logger.info('getting list of media')
     medias = Media.objects.all()
     return render_template('media/list.html', medias=medias)
示例#42
0
文件: admin.py 项目: jstacoder/quokka
 def get(self):
     return render_template('test.html',
                            form_a=self.forms[0],
                            form_b=self.forms[1])
示例#43
0
 def server_error_page(error):
     return render_template("errors/server_error.html"), 500
示例#44
0
文件: views.py 项目: Cetids/quokka
    def get(self, long_slug):
        # !!! filter available_until
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath, published=True)

        if not is_accessible(roles_accepted=channel.roles):
            raise abort(403, "User has no role to view this channel content")

        if channel.is_homepage and request.path != channel.get_absolute_url():
            return redirect(channel.get_absolute_url())

        published_channels = Channel.objects(published=True).values_list('id')

        if channel.redirect_url:
            url_protos = ('http://', 'mailto:', '/', 'ftp://')
            if channel.redirect_url.startswith(url_protos):
                return redirect(channel.redirect_url)
            else:
                return redirect(url_for(channel.redirect_url))

        if channel.render_content:
            return ContentDetail().get(
                channel.render_content.content.long_slug, True)

        self.channel = channel

        base_filters = {}

        filters = {
            'published': True,
            'available_at__lte': now,
            'show_on_channel': True,
            'channel__in': published_channels
        }

        if not channel.is_homepage:
            base_filters['__raw__'] = {
                '$or': [
                    {'mpath': {'$regex': "^{0}".format(mpath)}},
                    {'related_mpath': {'$regex': "^{0}".format(mpath)}}
                ]
            }
        else:
            # list only allowed items in homepage
            user_roles = [role.name for role in get_current_user().roles]
            if 'admin' not in user_roles:
                base_filters['__raw__'] = {
                    "$or": [
                        {"channel_roles": {"$in": user_roles}},
                        {"channel_roles": {"$size": 0}},
                        # the following filters are for backwards compatibility
                        {"channel_roles": None},
                        {"channel_roles": {"$exists": False}}
                    ]
                }

        filters.update(channel.get_content_filters())
        contents = Content.objects(**base_filters).filter(**filters)

        sort = request.args.get('sort')
        if sort:
            contents = contents.order_by(sort)
        elif channel.sort_by:
            contents = contents.order_by(*channel.sort_by)

        disabled_pagination = False
        if not current_app.config.get("PAGINATION_ENABLED", True):
            disabled_pagination = contents.count()

        pagination_arg = current_app.config.get("PAGINATION_ARG", "page")
        page = request.args.get(pagination_arg, 1)
        per_page = (
            disabled_pagination or
            request.args.get('per_page') or
            channel.per_page or
            current_app.config.get("PAGINATION_PER_PAGE", 10)
        )
        contents = contents.paginate(page=int(page),
                                     per_page=int(per_page))

        themes = channel.get_themes()
        return render_template(self.get_template_names(),
                               theme=themes,
                               contents=contents,
                               channel=channel)
示例#45
0
文件: views.py 项目: Cetids/quokka
 def get(self, tag):
     contents = self.get_contents(tag)
     return render_template(self.get_template_names(),
                            contents=contents)
 def render_template(self, *args, **kwargs):
     return render_template(*args, **kwargs)
示例#47
0
 def server_error_page(*args, **kwargs):
     return render_template("errors/server_error.html"), 500
示例#48
0
    def get(self, long_slug):
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath, published=True)

        if not is_accessible(roles_accepted=channel.roles):
            raise abort(403, "User has no role to view this channel content")

        # if channel.is_homepage and request.path != "/":
        #     return redirect("/")

        if channel.redirect_url:
            return redirect(channel.redirect_url)

        if channel.render_content:
            return ContentDetail().get(
                channel.render_content.content.long_slug, True)

        self.channel = channel

        base_filters = {}

        filters = {
            'published': True,
            'available_at__lte': now,
            'show_on_channel': True
        }

        if not channel.is_homepage:
            base_filters['__raw__'] = {
                '$or': [{
                    'mpath': {
                        '$regex': "^{0}".format(mpath)
                    }
                }, {
                    'related_mpath': {
                        '$regex': "^{0}".format(mpath)
                    }
                }]
            }
        else:
            # list only allowed items in homepage
            user_roles = [role.name for role in get_current_user().roles]
            if 'admin' not in user_roles:
                base_filters['__raw__'] = {
                    "$or": [
                        {
                            "channel_roles": {
                                "$in": user_roles
                            }
                        },
                        {
                            "channel_roles": {
                                "$size": 0
                            }
                        },
                        # the following filters are for backwards compatibility
                        {
                            "channel_roles": None
                        },
                        {
                            "channel_roles": {
                                "$exists": False
                            }
                        }
                    ]
                }

        filters.update(channel.get_content_filters())
        contents = Content.objects(**base_filters).filter(**filters)

        sort = request.args.get('sort')
        if sort:
            contents = contents.order_by(sort)
        elif channel.sort_by:
            contents = contents.order_by(*channel.sort_by)

        if current_app.config.get("PAGINATION_ENABLED", True):
            pagination_arg = current_app.config.get("PAGINATION_ARG", "page")
            page = request.args.get(pagination_arg, 1)
            per_page = (request.args.get('per_page') or channel.per_page
                        or current_app.config.get("PAGINATION_PER_PAGE", 10))
            contents = contents.paginate(page=int(page),
                                         per_page=int(per_page))

        # this can be overkill! try another solution
        # to filter out content in unpublished channels
        # when homepage and also in blocks
        # contents = [content for content in contents
        #             if content.channel.published]

        themes = channel.get_themes()
        return render_template(self.get_template_names(),
                               theme=themes,
                               contents=contents,
                               channel=channel)
示例#49
0
    def post(self):
        course_id = request.form.get('course_id')
        classroom = request.form.get('classroom')
        phone = request.form.get('phone')
        name = request.form.get('name')
        email = request.form.get('email')
        variant = request.form.get('variant')

        self.current_user = get_current_user()
        self.cart = Cart.get_cart()

        try:
            course = Course.objects.get(id=course_id)
        except:
            self.cart.addlog("Error getting course %s" % course_id)
            return render_template('classes/subscription_error.html')

        student = self.get_student(email, name, phone)
        if not student:
            self.cart.addlog("Error getting student")
            return render_template('classes/subscription_error.html')

        if not variant in ['regular', None, False, '']:
            course_variant = course.variants.get(slug=variant)
            _variant = CourseVariant(
                title=course_variant.title +
                "<!-- {0}  -->".format(str(random.getrandbits(8))),
                description=course_variant.description,
                unity_value=course_variant.unity_value,
                slug=course_variant.slug)
        else:
            _variant = None

        subscription = CourseSubscription(
            subscriber=self.get_subscriber(),  # if none will set on pipeline
            student=student,
            course=course,
            classroom=classroom,
            variant=_variant,
            cart=self.cart)

        subscription.save()

        item = Item(
            uid=subscription.get_uid(),
            product=course,
            reference=subscription,
            title=subscription.get_title(),
            description=subscription.get_description(),
            unity_value=subscription.get_unity_value(),
        )

        self.cart.items.append(item)

        # think on this
        # in sites with multiple e-commerce apps
        # if cart has items from multiple apps ex:
        #   items: course, product, signature etc..
        # which app has precedence in cart settings?

        self.cart.requires_login = current_app.config.get(
            "CLASSES_CART_REQUIRES_LOGIN", self.cart.requires_login)
        self.cart.continue_shopping_url = current_app.config.get(
            "CLASSES_CART_CONTINUE_SHOPPING_URL",
            self.cart.continue_shopping_url)
        self.cart.pipeline = current_app.config.get("CLASSES_CART_PIPELINE",
                                                    self.cart.pipeline)
        self.cart.config = current_app.config.get("CLASSES_CART_CONFIG",
                                                  self.cart.config)
        self.cart.course_subscription_id = subscription.id
        self.cart.addlog(u"Item added %s" % item.title, save=True)

        return redirect(url_for('cart.cart'))
示例#50
0
 def get(self, user_id):
     return render_template('accounts/profile.html')
示例#51
0
    def get(self, long_slug):
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath, published=True)

        # if channel.is_homepage and request.path != "/":
        #     return redirect("/")

        if channel.redirect_url:
            return redirect(channel.redirect_url)

        if channel.render_content:
            return ContentDetail().get(
                channel.render_content.content.long_slug, True)

        self.channel = channel

        base_filters = {}

        filters = {
            'published': True,
            'available_at__lte': now,
            'show_on_channel': True
        }

        if not channel.is_homepage:
            base_filters['__raw__'] = {
                'mpath': {
                    '$regex': "^{0}".format(mpath)
                }
            }

        filters.update(channel.get_content_filters())
        contents = Content.objects(**base_filters).filter(**filters)

        sort = request.args.get('sort')
        if sort:
            contents = contents.order_by(sort)
        elif channel.sort_by:
            contents = contents.order_by(*channel.sort_by)

        if current_app.config.get("PAGINATION_ENABLED", True):
            pagination_arg = current_app.config.get("PAGINATION_ARG", "page")
            page = request.args.get(pagination_arg, 1)
            per_page = (request.args.get('per_page') or channel.per_page
                        or current_app.config.get("PAGINATION_PER_PAGE", 10))
            contents = contents.paginate(page=int(page),
                                         per_page=int(per_page))

        # this can be overkill! try another solution
        # to filter out content in unpublished channels
        # when homepage and also in blocks
        # contents = [content for content in contents
        #             if content.channel.published]

        themes = channel.get_themes()
        return render_template(self.get_template_names(),
                               theme=themes,
                               contents=contents,
                               channel=channel)
示例#52
0
 def get(self, tag):
     contents = self.get_contents(tag)
     return render_template(self.get_template_names(), contents=contents)