我已经在Python Shell中安装了正确的环境,python 2.7.5,Twisted安装和导入工作。
我有一个非常简单的Server实例来显示在本地计算机上运行良好的登录页面。
from twisted.web import http
class MyRequestHandler(http.Request):
pages={
'/': '<h1>Geo-Address Server</h1>Twisted Server is Up and Running..',
'/test': '<h1>Test</h1>Test page',
}
def process(self):
print self.path
if self.pages.has_key(self.path):
self.write(self.pages[self.path])
else:
self.setResponseCode(http.NOT_FOUND)
self.write("<h1>Not Found</h1>Sorry, page does not exist")
self.finish()
class MyHttp(http.HTTPChannel):
requestFactory=MyRequestHandler
class MyHttpFactory(http.HTTPFactory):
protocol=MyHttp
if __name__=='__main__':
from twisted.internet import reactor
reactor.listenTCP(8080, MyHttpFactory())
reactor.run()
但是,在Openshift服务器上部署它无法运行。如果我尝试运行脚本
python script.py &
我明白了:
reactor.listenTCP(8080,MyHttpFactory())文件 “/var/lib/openshift/5378ea844382ec89da000432/python/virtenv/lib/python2.7/site-packages/twisted/internet/posixbase.py” 第495行,在listenTCP中 p.startListening()文件“/var/lib/openshift/5378ea844382ec89da000432/python/virtenv/lib/python2.7/site-packages/twisted/internet/tcp.py”, 第979行,在startListening中 raise CannotListenError(self.interface,self.port,le)twisted.internet.error.CannotListenError:无法侦听任何:8080: [Errno 13]许可被拒绝。
通过SO阅读,大多数人只是说绑定到端口8080(我已经完成了),但我仍然得到同样的错误。
答案 0 :(得分:0)
正如kb所说
请注意:我们不允许任意绑定端口 外部可访问的IP地址。
可以使用端口范围绑定到内部IP:15000 - 35530.所有其他端口都保留用于特定进程以避免冲突。由于我们绑定到内部IP,您需要 使用端口转发来访问它: https://openshift.redhat.com/community/blogs/getting-started-with-port-forwarding-on-openshift
因此,只需找出$ OPENSHIFT_PYTHON_IP
echo $OPENSHIFT_PYTHON_IP
然后将该地址添加到reactor侦听器的接口
reactor.listenTCP(15000, MyHttpFactory(), interface='127.X.X.X')
替代(以及最好)的方法是选择代码中的值。这样,如果IP动态变化,您仍然可以获得当前的IP
import os
local_hostname =os.getenv("OPENSHIFT_INTERNAL_IP")
..
..
reactor.listenTCP(15000, MyHttpFactory(), interface=local_hostname)
注意:您只能绑定到端口范围(15000-35530)