json_context.py 文件源码

python
阅读 21 收藏 0 点赞 0 评论 0

项目:socialhome 作者: jaywink 项目源码 文件源码
def json_context(context, raise_error=False):
    """Generate a JS <script> tag from context

    Serializes ``context["json_context"]`` into JSON and generates a JS
    script to attach it to ``window.context``

    If ``raise_error`` is False, values in context that are not
    JSON serialisable will be converted to string. Otherwise, it
    raises TypeError

    :param context: Current view context
    :param raise_error: Control whether to raise an error on non-JSON serialisable values
    :return: ``<script>window.context = {<context["json_context"]>}</script>``
    """
    if not context.get("json_context"):
        return ""

    json_default = None if raise_error else lambda obj: str(obj)

    json_dump = json.dumps(context["json_context"], default=json_default)
    return mark_safe("<script>window.context = %s;</script>" % json_dump)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号