python开发框架(tornado, web.py)

来源:互联网 发布:软件运维工程师 知乎 编辑:程序博客网 时间:2024/06/11 23:47

一: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()


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部署

参考文章 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错误

今天在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赋予相应文件的权限





 

0 0
原创粉丝点击