Python 后端与 JS 前端

Python backend with JS frontend

我正在创建一个由 Python 驱动的 Web 框架,旨在尽可能少地使用 javascript。需要做一些像 uilang 这样的轻量级的东西来将事件传递给我的 Python 代码。我想这应该是 jQuery 以某种方式对观察者对象执行 ping 操作(?)的解决方案。

我发现了一些创建纯 Python 界面的努力,例如 Remi 但仍然不知道我应该如何在我的代码中重新实现它。

假设我做了一个 class 这样的:

class WebView():
    def __init__(self, template, **callbacks):
        """
        Callbacks are dict, {'object': callback}
        """
        self.template = template
        self.customJS = None
        for obj, call in callbacks:
            self.setCallback(obj, call)

    def __call__():
        """
        Here I return template
        Assume {{customJS}} record in template, to be simple
        """
        return bottle.template(self.template, customJS = self.customJS)

    def setCallback(self, obj, call):
        """
        Build custom js to insert 
        """
        self.customJS += ('<script ....%s ... %s' % (obj, call))

那么,我怎样才能让 JS 将事件从按下按钮传递回我的回调?

我知道这个问题可能过于宽泛,但我只是想尽可能地描述性,因为我真的根本不了解 JS。

问题是您不需要 javascript 用于 python 网络框架。您可以使用 flask 或 django 服务页面而无需单行 JS。

这些页面将是相当静态的,只有一些表单,但可以完美地工作。

现在,如果您想拥有更多动态内容和交互,您可能需要 JS,并使用 XMLHttpRequests 异步调用事件后端 python。但是为了正确地做到这一点,你应该从学习 JS 开始。

您可能可以在 python 端使用 websockets too, however i don't think it's the best way. You can use websocket-python 库来完成此操作,而在网站上,您只需在每个按钮点击回调时发送一个 websocket 消息。