예제 #1
0
 def render(self, **kwargs):
     for r in self._fanstatic_resources:
         r.need()
     if 'autocomplete' in kwargs:
         kwargs.pop('autocomplete')
     request = self.request
     html = renderer.render(self, autocomplete='off', **kwargs)
     kwargs.update(self.jq_options)
     options = dict(
         tag=tag,
         html=html,
         plugin=plugin,
         name=self.name,
         show_input=show_input,
         resources=[url(r, prefix=self.resources_prefix, request=request) for r in self._resources],
     )
     try:
         self.update_options(options, kwargs)
     except AttributeError:
         pass
     try:
         options.update(options=dumps(kwargs))
     except TypeError:
         options.update(options={})
     try:
         return literal(self.template.render_unicode(**options))
     except:
         raise ValueError('Invalid options: %s' % options)
예제 #2
0
    def upvote(self, post, weight, retry_count=None, reply=True):

        if not retry_count:
            retry_count = 0

        if self.config["BOT_ACCOUNT"] in [
                v["voter"] for v in post.get("active_votes", [])
        ]:
            logger.error("Already voted on this. Skipping... {}".format(
                post.identifier))
            return

        try:
            self.steemd_instance.commit.vote(
                post.identifier, weight, account=self.config["BOT_ACCOUNT"])
            logger.info("Casted vote on: %s with weight: %s", url(post),
                        weight)
            time.sleep(3)

        except Exception as error:
            logger.error(error)
            return self.upvote(post, weight, retry_count + 1)

        if reply:
            self.reply(post)
예제 #3
0
def test_middleware_methods_are_called(app, client):
    process_request_called = False
    process_response_called = False

    class CallMiddlewareMethods(Middleware):
        def __init__(self, app):
            super().__init__(app)

        def process_request(self, req):
            nonlocal process_request_called
            process_request_called = True

        def process_response(self, req, resp):
            nonlocal process_response_called
            process_response_called = True

    app.add_middleware(CallMiddlewareMethods)

    @app.route('/')
    def index(req, res):
        res.text = "YOLO"

    client.get(url('/'))

    assert process_request_called is True
    assert process_response_called is True
예제 #4
0
 def render(self, **kwargs):
     for r in self._fanstatic_resources:
         r.need()
     if 'autocomplete' in kwargs:
         kwargs.pop('autocomplete')
     request = self.request
     html = renderer.render(self, autocomplete='off', **kwargs)
     kwargs.update(self.jq_options)
     options = dict(
         tag=tag,
         html=html,
         plugin=plugin,
         name=self.name,
         show_input=show_input,
         resources=[
             url(r, prefix=self.resources_prefix, request=request)
             for r in self._resources
         ],
     )
     try:
         self.update_options(options, kwargs)
     except AttributeError:
         pass
     try:
         options.update(options=dumps(kwargs))
     except TypeError:
         options.update(options={})
     try:
         return literal(self.template.render_unicode(**options))
     except:
         raise ValueError('Invalid options: %s' % options)
예제 #5
0
def trailing_slash(request, response, missing=True, extra=False):
    """Redirect if request.path has (missing|extra) trailing slash."""

    pi = request.path

    if request.index is True:
        if missing:
            if not pi.endswith('/'):
                new_url = url(request, pi + '/', request.qs)
                return Redirect(request, response, new_url)
    elif request.index is False:
        if extra:
            # If pi == '/', don't redirect to ''!
            if pi.endswith('/') and pi != '/':
                new_url = url(request, pi[:-1], request.qs)
                return Redirect(request, response, new_url)
    else:
        return response
예제 #6
0
파일: tools.py 프로젝트: jonnenauha/naali
def trailing_slash(request, response, missing=True, extra=False):
    """Redirect if request.path has (missing|extra) trailing slash."""

    pi = request.path

    if request.index is True:
        if missing:
            if not pi.endswith("/"):
                new_url = url(request, pi + "/", request.qs)
                return Redirect(request, response, new_url)
    elif request.index is False:
        if extra:
            # If pi == '/', don't redirect to ''!
            if pi.endswith("/") and pi != "/":
                new_url = url(request, pi[:-1], request.qs)
                return Redirect(request, response, new_url)
    else:
        return response
예제 #7
0
async def list_(request):
    author = _int_or_none(request.match_info.get('author'))
    allow_nsfw = 'allow_nsfw' in request.query
    if allow_nsfw:
        check_18plus(request)
    before = request.query.get('before')
    after = request.query.get('after')
    page = parse_keyset_params(before, after)
    return await render_template(
        'list.html',
        emotes=await db_cog.all_emotes_keyset(author,
                                              allow_nsfw=allow_nsfw,
                                              page=page),
        author=author,
        request=request,
        url=url(request),
        allow_nsfw=allow_nsfw,
    )
예제 #8
0
 def render(self, **kwargs):
     if 'autocomplete' in kwargs:
         kwargs.pop('autocomplete')
     html = renderer.render(self, autocomplete='off', **kwargs)
     kwargs.update(self.jq_options)
     options = dict(
         tag=tag,
         html=html,
         plugin=plugin,
         name=self.name,
         show_input=show_input,
         resources=[url(r, prefix=self.resources_prefix) for r in resources],
     )
     try:
         options.update(options=dumps(kwargs))
     except TypeError:
         options.update(options={})
     try:
         return literal(self.template.render_unicode(**options))
     except:
         raise ValueError('Invalid options: %s' % options)
예제 #9
0
def RichTextFieldRenderer(use='tinymce', resources_prefix=None, **jq_options):
    """RichTextFieldRenderer using TinyMCE or MarkitUp!:

    .. sourcecode:: python

        >>> from testing import fs
        >>> field = fs.rich.set(renderer=RichTextFieldRenderer(use='tinymce', theme='advanced'))
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <script type="text/javascript">
          jQuery.fa.add_resource("/jquery/tiny_mce/tiny_mce.js");
          jQuery.fa.add_resource("/jquery/tiny_mce/jquery.tinymce.js");
        </script>
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {... "theme": "advanced", ...});
        </script>

    If you want to use your own TinyMCE/MarkitUp! version:

    .. sourcecode:: python

        >>> field = fs.rich.set(renderer=RichTextFieldRenderer(use='tinymce', resources_prefix='/my_js'))
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <script type="text/javascript">
          jQuery.fa.add_resource("/my_js/tiny_mce/tiny_mce.js");
          jQuery.fa.add_resource("/my_js/tiny_mce/jquery.tinymce.js");
        </script>
        ...

    There is also some aliases:

    .. sourcecode:: python

        >>> field = fs.rich.set(renderer=tinymce())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <script type="text/javascript">
          jQuery.fa.add_resource("/jquery/tiny_mce/tiny_mce.js");
          jQuery.fa.add_resource("/jquery/tiny_mce/jquery.tinymce.js");
        </script>
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...

        >>> field = fs.rich.set(renderer=textile())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <script type="text/javascript">
          jQuery.fa.add_resource("/jquery/markitup/jquery.markitup.pack.js");
          jQuery.fa.add_resource("/jquery/markitup/skins/simple/style.css");
          jQuery.fa.add_resource("/jquery/markitup/sets/textile/style.css");
          jQuery.fa.add_resource("/jquery/markitup/sets/textile/set.js");
        </script>
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...
        
        >>> field = fs.rich.set(renderer=markdown())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <script type="text/javascript">
          jQuery.fa.add_resource("/jquery/markitup/jquery.markitup.pack.js");
          jQuery.fa.add_resource("/jquery/markitup/skins/simple/style.css");
          jQuery.fa.add_resource("/jquery/markitup/sets/markdown/style.css");
          jQuery.fa.add_resource("/jquery/markitup/sets/markdown/set.js");
        </script>
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...

        >>> field = fs.rich.set(renderer=bbcode())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <script type="text/javascript">
          jQuery.fa.add_resource("/jquery/markitup/jquery.markitup.pack.js");
          jQuery.fa.add_resource("/jquery/markitup/skins/simple/style.css");
          jQuery.fa.add_resource("/jquery/markitup/sets/bbcode/style.css");
          jQuery.fa.add_resource("/jquery/markitup/sets/bbcode/set.js");
        </script>
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...

    """
    plugin_name = use
    defaults = {}
    if use == 'tinymce':
        resources = ['tiny_mce/tiny_mce.js', 'tiny_mce/jquery.tinymce.js']
        defaults['theme'] = 'advanced'
        defaults['theme_advanced_toolbar_location'] = "top"
        defaults['theme_advanced_toolbar_align'] = "left"
        defaults['theme_advanced_statusbar_location'] = "bottom"
        defaults['theme_advanced_resizing'] = True
        if 'content_css' in jq_options:
            jq_options['content_css'] = [url(c, prefix=resources_prefix) for c in jq_options['content_css']]
    elif use in ('textile', 'bbcode', 'markdown'):
        plugin_name = 'markitup'
        defaults['nameSpace'] = use
        defaults['resizeHandle'] = True
        defaults['previewAutoRefresh'] = True
        defaults['previewParserPath'] = url('markup_parser.html?markup=%s' % use)
        resources = ['markitup/jquery.markitup.pack.js',
                     'markitup/skins/simple/style.css',
                     'markitup/sets/%s/style.css' % use,
                     'markitup/sets/%s/set.js' % use]

    else:
        resources = []

    for k, v in defaults.items():
        if k not in jq_options:
            jq_options[k] = v

    class Renderer(fields.TextAreaFieldRenderer):
        markup = use

        def render_textile(self, **kwargs):
            value = self.raw_value
            return value and render_textile(value) or ''

        def render_bbcode(self, **kwargs):
            value = self.raw_value
            return value and render_bbcode(value) or ''

        def render_markdown(self, **kwargs):
            value = self.raw_value
            return value and  render_markdown(value) or ''

        def render_readonly(self, **kwargs):
            meth = getattr(self, 'render_%s' % self.markup, None)
            if meth is not None:
                return meth()
            return fields.TextAreaFieldRenderer.render_readonly(self, **kwargs)
    return jQueryFieldRenderer(plugin_name, show_input=True, renderer=Renderer,
                               resources_prefix=resources_prefix, resources=resources, **jq_options)
예제 #10
0
    def __init__(self, request, response, urls, status=None):
        if isinstance(urls, basestring):
            urls = [urls]

        abs_urls = []
        for url in urls:
            # Note that urljoin will "do the right thing" whether url is:
            #  1. a complete URL with host (e.g. "http://www.example.com/test")
            #  2. a URL relative to root (e.g. "/dummy")
            #  3. a URL relative to the current path
            # Note that any query string in request is discarded.
            url = _urljoin(utils.url(request), url)
            abs_urls.append(url)
        self.urls = urls = abs_urls

        # RFC 2616 indicates a 301 response code fits our goal; however,
        # browser support for 301 is quite messy. Do 302/303 instead. See
        # http://ppewww.ph.gla.ac.uk/~flavell/www/post-redirect.html
        if status is None:
            if request.protocol >= (1, 1):
                status = 303
            else:
                status = 302
        else:
            status = int(status)
            if status < 300 or status > 399:
                raise ValueError("status must be between 300 and 399.")

        super(Redirect, self).__init__(request, response, status)

        if status in (300, 301, 302, 303, 307):
            response.headers["Content-Type"] = "text/html"
            # "The ... URI SHOULD be given by the Location field
            # in the response."
            response.headers["Location"] = urls[0]

            # "Unless the request method was HEAD, the entity of the response
            # SHOULD contain a short hypertext note with a hyperlink to the
            # new URI(s)."
            msg = {
                300: "This resource can be found at <a href='%s'>%s</a>.",
                301:
                "This resource has permanently moved to <a href='%s'>%s</a>.",
                302:
                "This resource resides temporarily at <a href='%s'>%s</a>.",
                303: "This resource can be found at <a href='%s'>%s</a>.",
                307:
                "This resource has moved temporarily to <a href='%s'>%s</a>.",
            }[status]
            response.body = "<br />\n".join([msg % (u, u) for u in urls])
            # Previous code may have set C-L, so we have to reset it
            # (allow finalize to set it).
            response.headers.pop("Content-Length", None)
        elif status == 304:
            # Not Modified.
            # "The response MUST include the following header fields:
            # Date, unless its omission is required by section 14.18.1"
            # The "Date" header should have been set in Response.__init__

            # "...the response SHOULD NOT include other entity-headers."
            for key in ("Allow", "Content-Encoding", "Content-Language",
                        "Content-Length", "Content-Location", "Content-MD5",
                        "Content-Range", "Content-Type", "Expires",
                        "Last-Modified"):
                if key in response.headers:
                    del response.headers[key]

            # "The 304 response MUST NOT contain a message-body."
            response.body = None
            # Previous code may have set C-L, so we have to reset it.
            response.headers.pop("Content-Length", None)
        elif status == 305:
            # Use Proxy.
            # urls[0] should be the URI of the proxy.
            response.headers["Location"] = urls[0]
            response.body = None
            # Previous code may have set C-L, so we have to reset it.
            response.headers.pop("Content-Length", None)
        else:
            raise ValueError("The %s status code is unknown." % status)
예제 #11
0
async def docs(request):
    return await render_template('api_doc.html',
                                 url=url(request),
                                 urls=urls,
                                 prefix=config['prefixes'][0])
예제 #12
0
파일: wrappers.py 프로젝트: A-K/naali
 def url(self):
     return url(self)
예제 #13
0
 def url(self):
     return url(self)
예제 #14
0
async def index(request):
    return await render_template('index.html',
                                 url=url(request, include_path=False))
예제 #15
0
def RichTextFieldRenderer(use='tinymce', resources_prefix=None, **jq_options):
    """RichTextFieldRenderer using TinyMCE or MarkitUp!:

    .. sourcecode:: python

        >>> from testing import fs
        >>> field = fs.rich.set(renderer=RichTextFieldRenderer(use='tinymce', theme='advanced'))
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {"theme_advanced_toolbar_location": "top", "theme_advanced_toolbar_align": "left", "theme": "advanced", "theme_advanced_statusbar_location": "bottom", "options": [], "theme_advanced_resizing": true});
        </script>
        
        ...

        <script type="text/javascript">
          jQuery.fa.add_resource("/jquery/tiny_mce/tiny_mce.js");
          jQuery.fa.add_resource("/jquery/tiny_mce/jquery.tinymce.js");
        </script>
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {... "theme": "advanced", ...});
        </script>

    If you want to use your own TinyMCE/MarkitUp! version:

    .. sourcecode:: python

        >>> field = fs.rich.set(renderer=RichTextFieldRenderer(use='tinymce', resources_prefix='/my_js'))
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {"theme_advanced_toolbar_location": "top", "theme_advanced_toolbar_align": "left", "theme": "advanced", "theme_advanced_statusbar_location": "bottom", "options": [], "theme_advanced_resizing": true});
        </script>
        
        ...

    There is also some aliases:

    .. sourcecode:: python

        >>> field = fs.rich.set(renderer=tinymce())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {"theme_advanced_toolbar_location": "top", "theme_advanced_toolbar_align": "left", "theme": "advanced", "theme_advanced_statusbar_location": "bottom", "options": [], "theme_advanced_resizing": true});
        </script>
        
        ...

        >>> field = fs.rich.set(renderer=textile())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_markitup"></div>
        <script type="text/javascript">
          jQuery.fa.markitup('Sample--rich', {"previewAutoRefresh": true, "nameSpace": "textile", "options": [], "resizeHandle": true, "previewParserPath": "/jquery/markup_parser.html?markup=textile"});
        </script>

        >>> field = fs.rich.set(renderer=markdown())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_markitup"></div>
        <script type="text/javascript">
          jQuery.fa.markitup('Sample--rich', {"previewAutoRefresh": true, "nameSpace": "markdown", "options": [], "resizeHandle": true, "previewParserPath": "/jquery/markup_parser.html?markup=markdown"});
        </script>
        
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...

        >>> field = fs.rich.set(renderer=bbcode())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_markitup"></div>
        <script type="text/javascript">
          jQuery.fa.markitup('Sample--rich', {"previewAutoRefresh": true, "nameSpace": "bbcode", "options": [], "resizeHandle": true, "previewParserPath": "/jquery/markup_parser.html?markup=bbcode"});
        </script>
        
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...

    """
    plugin_name = use
    defaults = {}

    if use == 'tinymce':
        defaults['theme'] = 'advanced'
        defaults['theme_advanced_toolbar_location'] = "top"
        defaults['theme_advanced_toolbar_align'] = "left"
        defaults['theme_advanced_statusbar_location'] = "bottom"
        defaults['theme_advanced_resizing'] = True
        if 'content_css' in jq_options:
            jq_options['content_css'] = [
                url(c, prefix=resources_prefix)
                for c in jq_options['content_css']
            ]
    elif use in ('textile', 'bbcode', 'markdown'):
        plugin_name = 'markitup'
        defaults['nameSpace'] = use
        defaults['resizeHandle'] = True
        defaults['previewAutoRefresh'] = True
        defaults['previewParserPath'] = url('markup_parser.html?markup=%s' %
                                            use)

    for k, v in defaults.items():
        if k not in jq_options:
            jq_options[k] = v

    class Renderer(fields.TextAreaFieldRenderer):
        markup = use

        def render(self, *args, **kwargs):
            if use == 'tinymce':
                fanstatic_resources.jquery_tinymce.need()
            elif use in ('textile', 'bbcode', 'markdown'):
                getattr(fanstatic_resources, "markitup_%s_set" % use).need()
            return super(Renderer, self).render(*args, **kwargs)

        def update_options(self, options, kwargs):
            request = self.request
            if request and hasattr(request, 'route_url'):
                options['previewParserPath'] = '%s?markup=%s' % (
                    request.route_url('markup_parser'), use)

        def render_textile(self, **kwargs):
            value = self.raw_value
            return value and render_textile(value) or ''

        def render_bbcode(self, **kwargs):
            value = self.raw_value
            return value and render_bbcode(value) or ''

        def render_markdown(self, **kwargs):
            value = self.raw_value
            return value and render_markdown(value) or ''

        def render_readonly(self, **kwargs):
            meth = getattr(self, 'render_%s' % self.markup, None)
            if meth is not None:
                return meth()
            return fields.TextAreaFieldRenderer.render_readonly(self, **kwargs)

    return jQueryFieldRenderer(plugin_name,
                               show_input=True,
                               renderer=Renderer,
                               **jq_options)
예제 #16
0
def RichTextFieldRenderer(use='tinymce', resources_prefix=None, **jq_options):
    """RichTextFieldRenderer using TinyMCE or MarkitUp!:

    .. sourcecode:: python

        >>> from testing import fs
        >>> field = fs.rich.set(renderer=RichTextFieldRenderer(use='tinymce', theme='advanced'))
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {"theme_advanced_toolbar_location": "top", "theme_advanced_toolbar_align": "left", "theme": "advanced", "theme_advanced_statusbar_location": "bottom", "options": [], "theme_advanced_resizing": true});
        </script>
        
        ...

        <script type="text/javascript">
          jQuery.fa.add_resource("/jquery/tiny_mce/tiny_mce.js");
          jQuery.fa.add_resource("/jquery/tiny_mce/jquery.tinymce.js");
        </script>
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {... "theme": "advanced", ...});
        </script>

    If you want to use your own TinyMCE/MarkitUp! version:

    .. sourcecode:: python

        >>> field = fs.rich.set(renderer=RichTextFieldRenderer(use='tinymce', resources_prefix='/my_js'))
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {"theme_advanced_toolbar_location": "top", "theme_advanced_toolbar_align": "left", "theme": "advanced", "theme_advanced_statusbar_location": "bottom", "options": [], "theme_advanced_resizing": true});
        </script>
        
        ...

    There is also some aliases:

    .. sourcecode:: python

        >>> field = fs.rich.set(renderer=tinymce())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_tinymce"></div>
        <script type="text/javascript">
          jQuery.fa.tinymce('Sample--rich', {"theme_advanced_toolbar_location": "top", "theme_advanced_toolbar_align": "left", "theme": "advanced", "theme_advanced_statusbar_location": "bottom", "options": [], "theme_advanced_resizing": true});
        </script>
        
        ...

        >>> field = fs.rich.set(renderer=textile())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_markitup"></div>
        <script type="text/javascript">
          jQuery.fa.markitup('Sample--rich', {"previewAutoRefresh": true, "nameSpace": "textile", "options": [], "resizeHandle": true, "previewParserPath": "/jquery/markup_parser.html?markup=textile"});
        </script>

        >>> field = fs.rich.set(renderer=markdown())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_markitup"></div>
        <script type="text/javascript">
          jQuery.fa.markitup('Sample--rich', {"previewAutoRefresh": true, "nameSpace": "markdown", "options": [], "resizeHandle": true, "previewParserPath": "/jquery/markup_parser.html?markup=markdown"});
        </script>
        
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...

        >>> field = fs.rich.set(renderer=bbcode())
        >>> print field.render() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        <div id="Sample--rich_markitup"></div>
        <script type="text/javascript">
          jQuery.fa.markitup('Sample--rich', {"previewAutoRefresh": true, "nameSpace": "bbcode", "options": [], "resizeHandle": true, "previewParserPath": "/jquery/markup_parser.html?markup=bbcode"});
        </script>
        
        <textarea autocomplete="off" id="Sample--rich" name="Sample--rich"></textarea>
        ...

    """
    plugin_name = use
    defaults = {}

    if use == 'tinymce':
        defaults['theme'] = 'advanced'
        defaults['theme_advanced_toolbar_location'] = "top"
        defaults['theme_advanced_toolbar_align'] = "left"
        defaults['theme_advanced_statusbar_location'] = "bottom"
        defaults['theme_advanced_resizing'] = True
        if 'content_css' in jq_options:
            jq_options['content_css'] = [url(c, prefix=resources_prefix) for c in jq_options['content_css']]
    elif use in ('textile', 'bbcode', 'markdown'):
        plugin_name = 'markitup'
        defaults['nameSpace'] = use
        defaults['resizeHandle'] = True
        defaults['previewAutoRefresh'] = True
        defaults['previewParserPath'] = url('markup_parser.html?markup=%s' % use)

    for k, v in defaults.items():
        if k not in jq_options:
            jq_options[k] = v

    class Renderer(fields.TextAreaFieldRenderer):
        markup = use

        def render(self, *args, **kwargs):
            if use == 'tinymce':
                fanstatic_resources.jquery_tinymce.need()
            elif use in ('textile', 'bbcode', 'markdown'):
                getattr(fanstatic_resources, "markitup_%s_set" % use).need()
            return super(Renderer, self).render(*args, **kwargs)

        def update_options(self, options, kwargs):
            request = self.request
            if request and hasattr(request, 'route_url'):
                options['previewParserPath'] = '%s?markup=%s' % (request.route_url('markup_parser'), use)

        def render_textile(self, **kwargs):
            value = self.raw_value
            return value and render_textile(value) or ''

        def render_bbcode(self, **kwargs):
            value = self.raw_value
            return value and render_bbcode(value) or ''

        def render_markdown(self, **kwargs):
            value = self.raw_value
            return value and  render_markdown(value) or ''

        def render_readonly(self, **kwargs):
            meth = getattr(self, 'render_%s' % self.markup, None)
            if meth is not None:
                return meth()
            return fields.TextAreaFieldRenderer.render_readonly(self, **kwargs)
    return jQueryFieldRenderer(plugin_name, show_input=True, renderer=Renderer,
                               **jq_options)
예제 #17
0
 def test_url_scan_mode(self):
     self.chdir('gendoc')
     utils.scan_mode('htdocs', 'htdocs/fake.md')
     r = utils.url('fake/url')
     self.assertEqual(r, 'fake/url')
예제 #18
0
 def call(self, endpoint, **kwargs):
     api_url = url(API_HOST, endpoint)
     return requests.get(api_url, params=kwargs)
예제 #19
0
 def test_url_scan_mode_dotted(self):
     self.chdir('gendoc')
     utils.scan_mode('htdocs', 'htdocs/s1/s2/s3/fake.md')
     r = utils.url('fake/url')
     self.assertEqual(r, '../../../fake/url')
예제 #20
0
파일: errors.py 프로젝트: Belsepubi/naali
    def __init__(self, request, response, urls, status=None):
        if isinstance(urls, basestring):
            urls = [urls]
        
        abs_urls = []
        for url in urls:
            # Note that urljoin will "do the right thing" whether url is:
            #  1. a complete URL with host (e.g. "http://www.example.com/test")
            #  2. a URL relative to root (e.g. "/dummy")
            #  3. a URL relative to the current path
            # Note that any query string in request is discarded.
            url = _urljoin(utils.url(request), url)
            abs_urls.append(url)
        self.urls = urls = abs_urls
        
        # RFC 2616 indicates a 301 response code fits our goal; however,
        # browser support for 301 is quite messy. Do 302/303 instead. See
        # http://ppewww.ph.gla.ac.uk/~flavell/www/post-redirect.html
        if status is None:
            if request.protocol >= (1, 1):
                status = 303
            else:
                status = 302
        else:
            status = int(status)
            if status < 300 or status > 399:
                raise ValueError("status must be between 300 and 399.")

        super(Redirect, self).__init__(request, response, status)
        
        if status in (300, 301, 302, 303, 307):
            response.headers["Content-Type"] = "text/html"
            # "The ... URI SHOULD be given by the Location field
            # in the response."
            response.headers["Location"] = urls[0]
            
            # "Unless the request method was HEAD, the entity of the response
            # SHOULD contain a short hypertext note with a hyperlink to the
            # new URI(s)."
            msg = {300: "This resource can be found at <a href='%s'>%s</a>.",
                   301: "This resource has permanently moved to <a href='%s'>%s</a>.",
                   302: "This resource resides temporarily at <a href='%s'>%s</a>.",
                   303: "This resource can be found at <a href='%s'>%s</a>.",
                   307: "This resource has moved temporarily to <a href='%s'>%s</a>.",
                   }[status]
            response.body = "<br />\n".join([msg % (u, u) for u in urls])
            # Previous code may have set C-L, so we have to reset it
            # (allow finalize to set it).
            response.headers.pop("Content-Length", None)
        elif status == 304:
            # Not Modified.
            # "The response MUST include the following header fields:
            # Date, unless its omission is required by section 14.18.1"
            # The "Date" header should have been set in Response.__init__
            
            # "...the response SHOULD NOT include other entity-headers."
            for key in ("Allow", "Content-Encoding", "Content-Language",
                        "Content-Length", "Content-Location", "Content-MD5",
                        "Content-Range", "Content-Type", "Expires",
                        "Last-Modified"):
                if key in response.headers:
                    del response.headers[key]
            
            # "The 304 response MUST NOT contain a message-body."
            response.body = None
            # Previous code may have set C-L, so we have to reset it.
            response.headers.pop("Content-Length", None)
        elif status == 305:
            # Use Proxy.
            # urls[0] should be the URI of the proxy.
            response.headers["Location"] = urls[0]
            response.body = None
            # Previous code may have set C-L, so we have to reset it.
            response.headers.pop("Content-Length", None)
        else:
            raise ValueError("The %s status code is unknown." % status)
예제 #21
0
 def test_url(self):
     r = utils.url('fake/url')
     self.assertEqual(r, '/fake/url')