简体   繁体   English

Python Autobahn websocket

[英]Python Autobahn websocket

I am impressed by all the things Python can do. Python可以做的所有事情给我留下了深刻的印象。 What I like to know is if I can implement a Python script that can call a JavaScript function. 我想知道的是我是否可以实现一个可以调用JavaScript函数的Python脚本。

The Python code I use is detecting an NFC card and reads the Unique ID. 我使用的Python代码是检测NFC卡并读取唯一ID。 Currently I use a Java applet to interact with an HTML page. 目前,我使用Java applet与HTML页面进行交互。 I think Python is much lighter and better for this. 我认为Python更轻,更好。

What I tried is a simple autobahn script server.py and an index.html file. 我尝试的是一个简单的高速公路脚本server.py和一个index.html文件。

In the server.py script I implemented this code but it is not working.. 在server.py脚本中我实现了这段代码,但它无法正常工作..

#! /usr/bin/env python

from sys import stdin, exc_info
from time import sleep

from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.util import *
import sys

from twisted.internet import reactor
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File

from autobahn.websocket import WebSocketServerFactory, \
                               WebSocketServerProtocol, \
                               listenWS


class EchoServerProtocol(WebSocketServerProtocol):

   # a simple card observer that prints inserted/removed cards
    class printobserver(CardObserver):
        """A simple card observer that is notified
        when cards are inserted/removed from the system and
        prints the list of cards
        """

        def update(self, observable, (addedcards, removedcards)):
            for card in addedcards:
                print "+Inserted: ", toHexString(card.atr)
        #call javascript function with <toHexString(card.atr)> 
            for card in removedcards:
                print "-Removed: ", toHexString(card.atr)
        #call javascript function with <toHexString(card.atr)> 

    try:
        print "Insert or remove a smartcard in the system."
        print "This program will exit in 10 seconds"
        print ""
        cardmonitor = CardMonitor()
        cardobserver = printobserver()
        cardmonitor.addObserver(cardobserver)

        sleep(10)

        # don't forget to remove observer, or the
        # monitor will poll forever...
        cardmonitor.deleteObserver(cardobserver)

        import sys
        if 'win32' == sys.platform:
            print 'press Enter to continue'
            sys.stdin.read(1)

    except:
        print exc_info()[0], ':', exc_info()[1]


if __name__ == '__main__':

   if len(sys.argv) > 1 and sys.argv[1] == 'debug':
      log.startLogging(sys.stdout)
      debug = True
   else:
      debug = False

   factory = WebSocketServerFactory("ws://localhost:9000",
                                    debug = debug,
                                    debugCodePaths = debug)

   factory.protocol = EchoServerProtocol
   factory.setProtocolOptions(allowHixie76 = True)
   listenWS(factory)

   webdir = File(".")
   web = Site(webdir)
   reactor.listenTCP(8080, web)

   reactor.run()

In the index file there is a JavaScript function 在索引文件中有一个JavaScript函数

function NFCid(msg) {
  alert(msg);
}

How can I call this function inside server.py 如何在server.py中调用此函数

NFCid(toHexString(card.atr))

It would in general be possible to set up a WebSocket connection that ferries data from a Python process running a web(sockets) server to a JavaScript function. 通常可以设置WebSocket连接,将运行Web(套接字)服务器的Python进程中的数据传送到JavaScript函数。 However, you'd have to explicitly setup a WebSocket connection from JavaScript and have it connect to the server process. 但是,您必须从JavaScript显式设置WebSocket连接并将其连接到服务器进程。 Then, you can pass any data coming in over the WebSocket connection (eg from Python) to any JavaScript function. 然后,您可以将通过WebSocket连接传入的任何数据(例如,从Python)传递到任何JavaScript函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM