Skip to content

Python apps in Netbeast router

pablopi edited this page Oct 30, 2015 · 6 revisions

This tutorial will show you how to adapt the base application created with the netbeast package manager. We are going to create a Python server that works as a netbeast application. We need to create the app base with netbeast package manager and make some changes.

- Delete node_modules folder (not required but recommended).

- Adapt package.json file.

json{

"name": "pythonServer",
"version": "0.0.1",
"description": "A sample app for you to start building!",
"main": "server.py",                     //change
"devDependencies": {},
"scripts": {
"test": "python server.py 31416",        //change
"start": "python server.py"              //change
},
"keywords": [
"netbeast",
"iot",
"netbeast"
],
"author": "netbeast",
"license": "Apache V2"
}

  • Create the server.
#!/usr/bin/env python

# server.py

import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from optparse import OptionParser
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
parser = OptionParser()

parser.add_option("--port",
action="store", type="int", dest="port", default=50052,
help="set server port")
(options, args) = parser.parse_args()
server_address = ('0.0.0.0', options.port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

There are two major changes:

  • Shebang has changed.
#!/usr/bin/env node    //before

#!/usr/bin/env python  //after
  • Netbeast´s apps need to be able to receive a port number from command line, so in this case, we included a parser.
from optparse import OptionParser

[...]

parser = OptionParser()

parser.add_option("--port",
action="store", type="int", dest="port", default=50052,
help="set server port")
(options, args) = parser.parse_args()

Any doubt reach us at @netbeast_co (twitter) or staff [at] netbeast.co.

Clone this wiki locally