tornado可以直接被外部其他ip 地址的客户端访问到
一:tornado
1.安装
支持windows平台
2.下载文件
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""web server"""
import os
import json
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
#class GetNewAppid(tornado.web.RequestHandler):
# def post(self):
# appid = self.get_argument('appid')
# #noun2 = self.get_argument('noun2')
# #verb = self.get_argument('verb')
# #noun3 = self.get_argument('noun3')
# self.wirte("xiaoyu")
# #self.render('poem.html', roads=noun1, wood=noun2, made=verb,
# # difference=noun3)
class SpockDataIntegrationDownloadHandler(tornado.web.RequestHandler):
def post(self):
#selectname = self.get_argument('selectname')
json_string = {}
"""
将请求参数放到dict中
"""
type = self.get_argument('appid')
#starttime = self.get_argument('starttime')
#endtime = self.get_argument('end_time')
#json_string['starttime'] = starttime
#json_string['endtime'] = endtime
json_string['type'] = type
"""
生成json文件
"""
if json_string:
filepath = './jsonfile.conf'
if os.path.exists(filepath):
os.remove(filepath)
ff = open(filepath, 'w')
json.dump(json_string, ff) # 将json格式数据写入文件
ff.close()
"""
下载文件
"""
filename = "jsonfile.conf"
self.set_header ('Content-Type', 'application/octet-stream')
self.set_header ('Content-Disposition', 'attachment; filename=' + filename)
buf_size = 4096
with open(os.path.join('',filepath), 'rb') as f:
while True:
data = f.read(buf_size)
if not data:
break
self.write(data)
self.finish()
if __name__ == '__main__':
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[(r'/', IndexHandler), (r'/getnewappid', SpockDataIntegrationDownloadHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
python3.8 下报错 File "d:\program files (x86)\python3\lib\asyncio\events.py", line 501, in add_reader raise NotIm
python3.8 asyncio 在 windows 上默认使用 ProactorEventLoop 造成的,而不是之前的 SelectorEventLoop
import tornado.ioloop
import tornado.web
import platform #插入
#--------------插入-------------#
if platform.system()=='Windows':
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
#-------------------------------#
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
3.日志配置,默认是INFO级别
http://www.xuebuyuan.com/296705.html
二:web.py框架
html文件存放路径
render = web.template.render('static/html/')
2.1 web.py + bootstrap
所有的html资源是从static目录开始的,所以如果html在static/myweb下,引用bootstrap资源时就要写成:
<link rel="stylesheet" href="static/myweb/css/bootstrap.min.css">
<img src="static/myweb/img/slide1.png" alt="第一张">
2.2 解析http请求body中的数据 mydata = web.data()
data = web.data()
myjson = {}
try:
myjson = json.loads(data)
except Exception, e:
pass
2.3jquery中的$ 和 web.py中的$有冲突,把$()替换为jQuery()
2.4 web.py多线程
web.py用的是线程池,在使用mysqldb的时候,有崩溃现象,所以我将线程池大小numthreads改为1,原来是10
httpserver.py
server = wsgiserver.CherryPyWSGIServer(server_address, wsgi_app, numthreads=1, server_name="localhost", max= -1)
2.2 web.py + apache部署
升级python到2.7版本,如果有必要(http://www.cnblogs.com/hengwei/p/5464678.html)
参考文章 http://www.cnblogs.com/shadowturtle/archive/2012/11/25/2787690.html
参考:
端口侦听失败:
关闭selinux (setenforence 0)
[Wed Jun 15 00:29:30 2016] [error] [client 10.15.194.202] (13)Permission denied: mod_wsgi (pid=8352): Unable to connect to WSGI daemon process '10086.dev.wanhui.cn' on '/etc/httpd/logs/wsgi.8346.0.1.sock' as user with uid=48.
解决方法:
在http.conf文件中添加WSGISocketPrefix /var/run/wsgi
在apache中使用mod_wsgi的daemon模式运行显示503错误
10 Jun 2011 at 3:51PM
今天在apache安装mod_wsgi模块并以daemon模式运行,按官方意思这种模式运作的方式在类似的FastCGI/SCGI,即在不同的单独进程运行WSGI应用。可以减小对以Apache模块的PHP、Perl或其他语言的Apache子进程服务包括静态文件等干扰。同时daemon模式运行时会生成sockts和锁文件,但如果对于某些Linux发行版本,对其目录有权限限制时就发生 ‘503 Service Temporarily Unavailable’的错误。 在apache的错误日志会产生如下记录:
(13)Permission denied: mod_wsgi (pid=26962): Unable to connect to WSGI daemon process ‘ ‘ on ‘/etc/httpd/logs/wsgi.26957.0.1.sock’ after multiple attempts.
所以需要在httpd.conf中通过WSGISocketPrefix 指令指定一个备用目录:
WSGISocketPrefix run/wsgi
或是使用/var/run目录
WSGISocketPrefix /var/run/wsgi
配置例子:
Listen 10086
<VirtualHost *:10086>
Alias /static/ /usr/ywy/api_manager/bin/static/
WSGIScriptAlias / /usr/ywy/api_manager/bin/api_manager.py
WSGIDaemonProcess 10086.dev.wanhui.cn user=ywy group=ywy processes=1 threads=1
WSGIProcessGroup 10086.dev.wanhui.cn
LogFormat "%{X-Real-IP}i %l %u %t %V \"%r\" %>s %D %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\" \"%{Cookie}i\"" wdaccess
SetEnvIf Remote_Addr "127.0.0.1" nolog
SetEnvIf Remote_Addr "::1" nolog
ErrorLog "|/usr/sbin/rotatelogs /usr/ywy/apache/logs/10086.dev.wanhui.cn-error_log_%Y-%m-%d 86400 +480"
CustomLog "|/usr/sbin/rotatelogs /usr/ywy/apache/logs/10086.dev.wanhui.cn-access_log_%Y-%m-%d 86400 +480 " wdaccess env=!nolog
<Directory /usr/ywy/api_manager/bin>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
注意:如果python有创建文件的操作,需要给user赋予相应文件的权限