一 生產環境說明python
1) tornado 4.2mysql
2) Tornado-MySQLlinux
3) supervisor 3.0b2nginx
4) protobuf 2.6.1web
5) python 2.7.6sql
6) nginx/1.4.6 跨域
二 實際問題服務器
1) 問:使用nginx 代理後不能訪問 報錯 WARNING:tornado.access:400 GET /ws (127.0.0.1) 0.79ms websocket
或者 鏈接失敗後 會反覆發起鏈接請求。app
答:須要在nginx 的location中新增以下配置
# websocket proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";
2) 問: a) The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost', but only one is allowed. Origin 'http://localhost' is therefore not allowed access.
b) websocket._exceptions.WebsocketBadStatusException: Handshake status 400
答:Access-Control-Allow-Origin
是HTML5中定義的一種服務器端返回Response header,用來解決資源(好比字體)的跨域權限問題。它定義了該資源容許被哪一個域引用,或者被全部域引用(google字體使用*表示字體資源容許被全部域引用)。
解決辦法:只須要 add_header Access-Control-Allow-Origin 一次就好!
http { ...... add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; ...... }
3) 問:如何調試websocket?
答:能夠經過 websocket-client 寫腳本測試。 具體實例可參看 https://pypi.python.org/pypi/websocket-client/
$ sudo pip install websocket-client $ python Python 2.7.6 [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import websocket >>> websocket <module 'websocket' from '/usr/local/lib/python2.7/dist-packages/websocket/__init__.pyc'>
4) 問:如何實現定時任務 及 stop server 前執行某個任務?
答:能夠經過tornado.ioloop.PeriodicCallback 執行定時任務
在supervisorctl stop/restart program_name 時捕獲 signal.SIGINT signal.SIGTERM 實現
import Queue DIRTY_DATAS = Queue.Queue() a) from tornado.ioloop import PeriodicCallback periodic = PeriodicCallback(lambda: sync_dirty_db_datas(DIRTY_DATAS), 5) periodic.start() b) import signal import tornado.gen import tornado.ioloop @tornado.gen.coroutine def signal_handler(signum, frame): yield sync_dirty_db_datas(DIRTY_DATAS) tornado.ioloop.IOLoop.instance().stop() # receive SIGINT SIGTERM signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler)
5) 問:error: [Errno 24] Too many open files in python and tornado
[E 140102 17:07:37 ioloop:660] Exception in I/O handler for fd 11 Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 653, in start self._handlers[fd](fd, events) File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 241, in wrapped callback(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 136, in accept_handler connection, address = sock.accept() File "/usr/lib/python2.7/socket.py", line 202, in accept error: [Errno 24] Too many open files
答: update the field: open files.
6) 問:operationalerror (1040 'too many connections') in python and mysql
答:
mysql> show variables like "max_connections";
檢查mysql可容許的最大鏈接數 和 自身的應用設置的最大可鏈接數,後者不可超過前者設置的最大值。