9月 24

python 判断“NoneType”

  使用python+tornado,在数据库中根据用户id取用户名出错了。经查看是由于,手动删除了值,什么数据都没有取回,所以报错。这个用try是不行的,也不想用import types,搞个简单的,使用if判断一下,出错的人都叫“haha”。

_get_user_name = db_get_user(userid)
if type(_get_user_name) == type(None):
    _get_user_name = "haha"
7月 30

tornado 获得复选框组的值

  一个比较二的问题,因为在网上查了一下没有查到,用web.py的架构查看此类问题,有的说是用什么input之类。最后还是自己看看内建文档,原来就这么简单,加个s就搞定了。郁闷呀!
html如下:




tornado获得参数如下:
class xxxxHandler(BaseHandler):
def get(self):
_get_test_list = self.get_arguments(‘CheckboxGroup1’)
print “test values %s”%_get_test_list

7月 19

python邮件内容格式问题

发送邮件,内容需要是html格式,content为邮件内容,我使用的都是utf-8编码。实现如下:

引用
from email.mime.text import MIMEText

以网页方式发送
msg = MIMEText(content.encode(‘utf8′), _subtype=’html’, _charset=’utf8′)

以纯文本方式发送
msg = MIMEText(content.encode(‘utf8′), _subtype=’plain’, _charset=’utf8′)

默认以纯文本方式发送

6月 20

nginx 自动封 ip 过高连接

  用命令查看web连接过高的IP地址,但是需要人工智能去封,太麻烦了,直接写个脚本自动解决。web服务器是用nginx,python为2.6
  首先在nignx的config中建立空文件deny.ip, 然后在nginx.conf 的http标签中添加“include deny.ip;”。在nginx下sbin的目录中放入自动脚本。脚本可以查到连接最大的IP,并插入屏蔽列表中,验证正确性后导入配置。全部完成或者出错后发送邮件。被封ip再次访问会报403错误,如果不希望报错可以跳转到其它页面。源码如下:

check_deny_up.py

#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-20
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import os
from string import strip
from email.mime.text import MIMEText
import smtplib

####
check_comm = "/bin/netstat -antp|grep :80|awk ' ''{print $5}'|awk -F: '{print $1}'|sort -r|uniq -c|sort -n -k1 -r"
max_ip = 100
mail_host = ‘’;
mail_user = ‘’;
mail_pwd = ‘’;
mail_to = ‘’;
mail_cc = ‘’;


def reboot_nginx_sendmail(ip_list):
    #### reboot nginx
    _get_check_confile = os.popen('./nginx -t').readlines()
    if str(_get_check_confile.find('ok')) != '-1':
        os.system('./nginx -s reload')
        _mail_content = ip_list
    else:
        _mail_content = 'Error'
    #### send mail
    msg = MIMEText(_mail_content)
    msg['From'] = mail_user
    msg['Subject'] = ' force ip.'
    msg['To'] = mail_to
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user, mail_pwd)
        s.sendmail(mail_user, [mail_to, mail_cc], msg.as_string())
        s.close()
    except Exception, e:
        print e


#### force out IP
def force_out(_deny_ip):
    _write_status = 0
    _read_force_file = open('../conf/deny.ip', 'rb').read()
    if  str(_read_force_file.find(_deny_ip)) == '-1':
        try:
            _get_force_file = open('../conf/deny.ip', 'ab')
            _get_force_file.write('deny %s ;\n' % _deny_ip)
            _get_force_file.close()
            _write_status = 1
            return _write_status
        except:
            return _write_status
            reboot_nginx_sendmail("Error !")
    return _write_status


def main():
    get_high_ip = os.popen('%s' % check_comm).readlines()
    _count_force_ip = 0
    _force_ip_list = ''
    for i in xrange(3):
        try:
            _get_count = strip(get_high_ip[i]).split(' ')[0]
            _get_ip = strip(strip(get_high_ip[i]).split(' ')[1])
        except:
            _get_count = 0
            _get_ip = ''
        # Maximum connection IP is Beyond the limit value
        if (int(_get_count) > max_ip) and (len(_get_ip) > 0):
            force_ip = _get_ip
            _get_status = force_out(force_ip)
            # check maximum is added in the deny.ip file
            if str(_get_status) == '1':
                _count_force_ip += 1
                _force_ip_list += ' %s ' % force_ip
#    if _count_force_ip > 0:
#        reboot_nginx_sendmail(_force_ip_list)


if __name__ == '__main__':
    main()

启动i脚本
check_deny_up.sh

#! /bin/bash
#
# make simon-zzm@163.com
#
#
### END INIT INFO

# Source function library.
. /etc/profile
cd /Data/apps/nginx/sbin/

# See how we were called.
case "$1" in
  start)
      /usr/local/bin/python check_ip_deny.py
      ;;
  *)
        echo $"Usage: $0 {start}"
        exit 1
esac

exit

将启动脚本放在crontab中运行。

6月 18

tornado学习笔记(二)

主要模块

web – FriendFeed 使用的基础 Web 框架,包含了 Tornado 的大多数重要的功能
escape – XHTML, JSON, URL 的编码/解码方法
database – 对 MySQLdb 的简单封装,使其更容易使用
template – 基于 Python 的 web 模板系统
httpclient – 非阻塞式 HTTP 客户端,它被设计用来和 web 及 httpserver 协同工作
auth – 第三方认证的实现(包括 Google OpenID/OAuth、Facebook Platform、Yahoo BBAuth、FriendFeed OpenID/OAuth、Twitter OAuth)
locale – 针对本地化和翻译的支持
options – 命令行和配置文件解析工具,针对服务器环境做了优化

底层模块

httpserver – 服务于 web 模块的一个非常简单的 HTTP 服务器的实现
iostream – 对非阻塞式的 socket 的简单封装,以方便常用读写操作
ioloop – 核心的 I/O 循环

  首先在建立一个mysql数据库,库名为test_tornado,建立一个有用户表,表中包含用户名密码,脚本如下。

CREATE TABLE `user` (
  `id` int(100) NOT NULL DEFAULT '0',
  `user` varchar(20) DEFAULT NULL,
  `passwd` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
);


INSERT INTO `user` VALUES ('0', 'simonzhang', '123456');

  建立监听,和url,启停脚本见上次笔记。
main.py

#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import sys
import tornado.ioloop
import tornado.web
from login import *


application = tornado.web.Application([
    (r"/", LoginHandler),
],  cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=")


if __name__ == "__main__":
    listen_port =  sys.argv[1]
    application.listen(listen_port)
    tornado.ioloop.IOLoop.instance().start()

  在同级目录下建立templates目录,在templates目录下建立login.html。login.html的源码是


   
      {{title}}
   
   
        
User Name:
Password:

  做一个简单的验证页面,只是个简单判断,学习使用,权限认证和cookie部分不做记录了。编辑login.py源码

#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import sys
import tornado.ioloop
import tornado.locale
import tornado.web
import tornado.database
from dbmodel import *


class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("templates/login.html", title="simonzhan.net")
    def post(self):
        try:
            name = self.get_argument("login_username")
            passwd = self.get_argument("login_password")
            _passwd = get_passwd(name)
            if _passwd is not None:
                if _passwd == _passwd:
                    self.write("hello %s" % (_passwd))
                else:
                    self.render("templates/login.html", title="simonzhan.net")
            else:
               self.render("templates/login.html", title="simonzhan.net")
            #self.write("hello %s" % (name))
        except:
            self.render("templates/login.html", title="simonzhan.net")
            return

  因为要查数据,所以要用到database,将数据库部分放到一文件中去。编辑dbmodol.py源码如下:

#!/bin/env python
# -*- coding: utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
from tornado import database


def get_passwd(user_name):
    db = database.Connection("192.168.1.41","test_tornado","123456","simonzhang")
    for projects in db.query("SELECT user,passwd from user where user='%s'" % user_name):
        return projects.passwd

  启动服务,在ie里能看到页面,输入正确的账户密码,可以看到经典的话了。基本框架完成,剩下的慢慢学习,慢慢发挥了。