Esempio n. 1
0
def render_knowl(ID,
                 footer=None,
                 kwargs=None,
                 raw=False,
                 k=None,
                 allow_deleted=False,
                 timestamp=None):
    """
    this method renders the given Knowl (ID) to insert it
    dynamically in a website. It is intended to be used
    by an AJAX call, but should do a similar job server-side
    only, too.

    Note, that the used knowl-render.html template is *not*
    based on any globally defined website and just creates
    a small and simple html snippet!

    the keyword 'raw' is used in knowledge.show and knowl_inc to
    include *just* the string and not the response object.
    """
    # logger.debug("kwargs: %s", request.args)
    kwargs = kwargs or dict(((k, v) for k, v in request.args.items()))
    # logger.debug("kwargs: %s" , kwargs)
    if timestamp is None:
        # fetch and convert the ms timestamp to datetime
        try:
            timestamp = timestamp_in_ms_to_datetime(int(kwargs['timestamp']))
        except KeyError:
            pass

    if k is None:
        try:
            k = Knowl(ID, allow_deleted=allow_deleted, timestamp=timestamp)
        except Exception:
            logger.critical("Failed to render knowl %s" % ID)
            errmsg = "Sorry, the knowledge database is currently unavailable."
            return errmsg if raw else make_response(errmsg)

        # If we are rendering a reviewed knowl on nonbeta,
        # we always include the timestamp
        if timestamp is None and k.status == 1 and not is_beta():
            kwargs['timestamp'] = k.ms_timestamp

    # kw_params is inserted *verbatim* into the url_for(...) function inside the template
    # the idea is to pass the keyword arguments of the knowl further along the chain
    # of links, in this case the title and the permalink!
    # so, this kw_params should be plain python, e.g. "a=1, b='xyz'"
    kw_params = ', '.join(('%s="%s"' % (k, v) for k, v in kwargs.items()))
    logger.debug("kw_params: %s" % kw_params)

    # this is a very simple template based on no other template to render one single Knowl
    # for inserting into a website via AJAX or for server-side operations.
    if request.method == "POST":
        con = request.form['content']
        foot = footer or request.form['footer']
    elif request.method == "GET":
        con = request.args.get("content", k.content)
        foot = footer or request.args.get("footer", "1")

    # authors = []
    # for a in k.author_links():
    #  authors.append("<a href='%s'>%s</a>" %
    #    (url_for('users.profile', userid=a['_id']), a['full_name'] or a['_id'] ))
    # authors = ', '.join(authors)

    render_me = u"""\
  {%% include "knowl-defs.html" %%}
  {%% from "knowl-defs.html" import KNOWL with context %%}
  {%% from "knowl-defs.html" import KNOWL_LINK with context %%}
  {%% from "knowl-defs.html" import KNOWL_INC with context %%}
  {%% from "knowl-defs.html" import TEXT_DATA with context %%}

  <div class="knowl">"""
    if foot == "1":
        render_me += """\
  <div class="knowl-header">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s ) }}">%(title)s</a>
  </div>""" % {
            'ID': k.id,
            'title': (k.title or k.id),
            'kw_params': kw_params
        }

    render_me += """<div><div class="knowl-content">%(content)s</div></div>"""

    review_status = ""
    if foot == "1":
        render_me += """\
  <div class="knowl-footer">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s) }}">permalink</a>
    {%% if user_is_authenticated %%}
      &middot;
      <a href="{{ url_for('.edit', ID='%(ID)s') }}">edit</a>
    {%% endif %%}
    %(review_status)s
  </div>"""
        # """ &middot; Authors: %(authors)s """
        if k.status == 0 and k.type != -2:
            review_status = """&middot; (awaiting review)"""
    render_me += "</div>"
    # render_me = render_me % {'content' : con, 'ID' : k.id }
    con = md_preprocess(con)

    # markdown enabled
    render_me = render_me % {
        'content': md.convert(con),
        'ID': k.id,
        'review_status': review_status,
        'kw_params': kw_params
    }  #, 'authors' : authors }
    # Pass the text on to markdown.  Note, backslashes need to be escaped for
    # this, but not for the javascript markdown parser

    # logger.debug("rendering template string:\n%s" % render_me)

    # TODO improve the error message
    # so that the user has a clue. Most likely, the {{ KNOWL('...') }} has the wrong syntax!
    try:
        data = render_template_string(render_me, k=k, **kwargs)
        if raw:
            # note, this is just internally for the .show method, raw rendering
            # doesn't exist right now and will wrap this into a make_reponse!
            return data
        resp = make_response(data)
        # cache if it is a usual GET
        if request.method == 'GET':
            resp.headers['Cache-Control'] = 'max-age=%d, public' % (
                _cache_time, )
            resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp
    except Exception as e:
        return "ERROR in the template: %s. Please edit it to resolve the problem." % e
Esempio n. 2
0
def render_knowl(ID, footer=None, kwargs=None,
        raw=False, k=None, allow_deleted=False, timestamp=None):
    """
    this method renders the given Knowl (ID) to insert it
    dynamically in a website. It is intended to be used
    by an AJAX call, but should do a similar job server-side
    only, too.

    Note, that the used knowl-render.html template is *not*
    based on any globally defined website and just creates
    a small and simple html snippet!

    the keyword 'raw' is used in knowledge.show and knowl_inc to
    include *just* the string and not the response object.
    """
    # logger.debug("kwargs: %s", request.args)
    kwargs = kwargs or dict(((k, v) for k, v in request.args.iteritems()))
    # logger.debug("kwargs: %s" , kwargs)
    if timestamp is None:
        # fetch and convert the ms timestamp to datetime
        try:
            timestamp = timestamp_in_ms_to_datetime(int(kwargs['timestamp']))
        except KeyError:
            pass

    if k is None:
        try:
            k = Knowl(ID, allow_deleted=allow_deleted, timestamp=timestamp)
        except Exception:
            logger.critical("Failed to render knowl %s"%ID)
            errmsg = "Sorry, the knowledge database is currently unavailable."
            return errmsg if raw else make_response(errmsg)

        # If we are rendering a reviewed knowl on nonbeta,
        # we always include the timestamp
        if timestamp is None and k.status == 1 and not is_beta():
            kwargs['timestamp'] = k.ms_timestamp;



    # kw_params is inserted *verbatim* into the url_for(...) function inside the template
    # the idea is to pass the keyword arguments of the knowl further along the chain
    # of links, in this case the title and the permalink!
    # so, this kw_params should be plain python, e.g. "a=1, b='xyz'"
    kw_params = ', '.join(('%s="%s"' % (k, v) for k, v in kwargs.iteritems()))
    logger.debug("kw_params: %s" % kw_params)

    # this is a very simple template based on no other template to render one single Knowl
    # for inserting into a website via AJAX or for server-side operations.
    if request.method == "POST":
        con = request.form['content']
        foot = footer or request.form['footer']
    elif request.method == "GET":
        con = request.args.get("content", k.content)
        foot = footer or request.args.get("footer", "1")

    # authors = []
    # for a in k.author_links():
    #  authors.append("<a href='%s'>%s</a>" %
    #    (url_for('users.profile', userid=a['_id']), a['full_name'] or a['_id'] ))
    # authors = ', '.join(authors)

    render_me = u"""\
  {%% include "knowl-defs.html" %%}
  {%% from "knowl-defs.html" import KNOWL with context %%}
  {%% from "knowl-defs.html" import KNOWL_LINK with context %%}
  {%% from "knowl-defs.html" import KNOWL_INC with context %%}
  {%% from "knowl-defs.html" import TEXT_DATA with context %%}

  <div class="knowl">"""
    if foot == "1":
        render_me += """\
  <div class="knowl-header">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s ) }}">%(title)s</a>
  </div>""" % {'ID': k.id, 'title': (k.title or k.id), 'kw_params': kw_params}

    render_me += """<div><div class="knowl-content">%(content)s</div></div>"""

    review_status = ""
    if foot == "1":
        render_me += """\
  <div class="knowl-footer">
    <a href="{{ url_for('.show', ID='%(ID)s', %(kw_params)s) }}">permalink</a>
    {%% if user_is_authenticated %%}
      &middot;
      <a href="{{ url_for('.edit', ID='%(ID)s') }}">edit</a>
    {%% endif %%}
    %(review_status)s
  </div>"""
        # """ &middot; Authors: %(authors)s """
        if k.status == 0 and k.type != -2:
            review_status = """&middot; (awaiting review)"""
    render_me += "</div>"
    # render_me = render_me % {'content' : con, 'ID' : k.id }
    con = md_preprocess(con)

    # markdown enabled
    render_me = render_me % {'content': md.convert(con), 'ID': k.id, 'review_status': review_status,
                             'kw_params': kw_params} #, 'authors' : authors }
    # Pass the text on to markdown.  Note, backslashes need to be escaped for
    # this, but not for the javascript markdown parser

    # logger.debug("rendering template string:\n%s" % render_me)

    # TODO improve the error message
    # so that the user has a clue. Most likely, the {{ KNOWL('...') }} has the wrong syntax!
    try:
        data = render_template_string(render_me, k=k, **kwargs)
        if raw:
            # note, this is just internally for the .show method, raw rendering
            # doesn't exist right now and will wrap this into a make_reponse!
            return data
        resp = make_response(data)
        # cache if it is a usual GET
        if request.method == 'GET':
            resp.headers['Cache-Control'] = 'max-age=%d, public' % (_cache_time,)
            resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp
    except Exception, e:
        return "ERROR in the template: %s. Please edit it to resolve the problem." % e