動作中に改変可能なwebサーバの話
matasitemo benjyoni twisted no sample code ga kaiteattayo.
それtwistedで(ry
大概の言語でkafuaチックにREPLなんてできるんだろうけどpythonの場合は
twisted manholeを使うのがよろしいです。
なんせめっちゃんこ楽っすから!!!
twistedなど非同期系のサーバってマルチなサーバを簡単に構築できるところもステキな点ということを忘れてはならんね。
実際にはtwisted本にも書かれてるけど
from twisted.internet import reactor from twisted.web import server, resource from twisted.cred import portal, checkers from twisted.conch import manhole, manhole_ssh class LinkPage(resource.Resource): isLeaf = 1 def __init__(self, links): resource.Resource.__init__(self) self.links = links def render(self, request): return "<ul>"+"".join([ "<li><a href='%s'>%s</a></li>" % (link, title) for title, link in self.links.items()])+"</ul>" links = {'Twisted':'http://twistedmatrix.com', 'Python':'http://python.org' } site = server.Site(LinkPage(links)) reactor.listenTCP(8080, site) def getManholeFactory(namespace, **passwords): realm = manhole_ssh.TerminalRealm() def getManhole(_): return manhole.Manhole(namespace) realm.chainedProtocolFactory.protocolFactory = getManhole p = portal.Portal(realm) p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords)) f = manhole_ssh.ConchFactory(p) return f reactor.listenTCP(2222, getManholeFactory(globals(), admin = 'aaa')) reactor.run()
こんな感じで
- ssh(shell)サーバ
- webサーバ
が動く。telnetよりもsshだよね!
認証周りとかはPortalの仕組みをそのまま使う。Portalと認証のところはドキュメントかtwisted本読め!
でどうするか。
まず最初にポート8080でアクセスしてwebの画面が出ることを確認。
次、ポート2222にsshでアクセスするとユーザ、パスワードが聞かれる。
admin/aaaと入力するとインタプリター状態になるので後は普通にインタプリターでいろんなものを
操作するだけ。
login as: admin admin@localhost's password: >>> >>> dir() ['LinkPage', '__builtins__', '__doc__', '__file__', '__name__', 'checkers', 'getManholeFactory', 'links', 'manhole', 'manhole_ssh', 'portal', 'reactor', 'resource', 'server', 'site'] >>> links {'Python': 'http://python.org', 'Twisted': 'http://twistedmatrix.com'} >>> links["Google"] = "http://www.google.co.jp/" >>> links {'Python': 'http://python.org', 'Google': 'http://www.google.co.jp/', 'Twisted': 'http://twistedmatrix.com'} >>>
こんな感じで操作できる。
ManholeFactoryにglobalを渡してるのでなんでも操作できるようになっているけどこれは用途に合わせればいいと思う。
linksにデータを追加してるのでこの操作後、webでもう一度表示してみるとgoogleのLinkが増えているというわけ。
突貫工事やデバッグ用にmanholeでクチを空けておくといいかも知れませんよという話。
ホントをいうとここで追加したものを保存できるともっといいのだろうけど。
(シリアライズしてどっかにおくとかいろいろ。)
うくく。