异常简单的一个代码生成器(python)

首先上一段生成的代码,很简单。但数据量很大时候也可以省下一小部分的工作量。


# -*- coding:utf-8 -*-
from core.dal.base_handler import BaseHandler
 
class GroupsHandler(BaseHandler):
 
    def select(self):
        return self.db.query("SELECT `g_id`, `g_name`, `create_time`, `status` FROM `groups` ORDER BY `g_id` DESC")
 
    def delete(self, id):
        return self.db.execute("DELETE FROM `groups` WHERE `g_id` = %s", id)
 
    def insert(self, g_name):
        return self.db.execute("INSERT INTO `groups` (`g_name`) VALUES (%s)", g_name)

重要的是这个生成器只有简单的百多行代码。再加上一些简单的生成services层的逻辑,短时间做一些对表的增删查还是很方便的,至于更复杂的慢慢扩充吧。

生成器下载地址:http://chairo.free.fr/down/build.py

生成器中用到的BaseHandler下载地址: http://chairo.free.fr/down/base_handler.py

Via:Chairo@2012年02月21日-EOF-

python下载数据

亲爱的BSSN给了一个flash游戏的数据库,还给了一个通过wget下载其中flash游戏数据的教程。测试中发现那个教程中wget方式下载数据经常下载到一半碰到出错或者什么原因给自动退出了。

趁这两天换工作有点时间,操刀python写了一段小脚本:

# -*- coding:utf-8 -*-
import os.path
import urllib2
 
def header(url):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
        'Referer':'http://www.xxx.net/'
    }
 
    req = urllib2.Request(
        url = url,
        headers = headers
    )
    result = urllib2.urlopen(req).read()
    return result
 
f = open('flash.txt', 'r')
for line in open('flash.txt', 'rb'):
    if not os.path.isfile(line.rstrip()):
        _file = line.rsplit('/',1)[1]
        try:
            File = open('files/flash/%s'%_file.rstrip(), "wb" )
            File.write(header("http://www.xxx.net/games/files/%s"%_file.rstrip()))
            File.close()
        except Exception, what:
            print what
        print _file

下载完共6G多的数据,周五再调试一下准备弄一个简单站点把这些数据放上去看看效果了。

Via:Chairo@2012年02月16日-EOF-

python所谓文艺短网址生成方式代码

最近都没有写什么python和php的代码,工作非常充实,晚上也没有什么精神继续写代码。今天翻到一段写生成短网址的算法blog,发现俺用的是最2B的随机数方式……

为了表示不那么2B,特意写了段生产短地址的在该文章中所写的文艺代码:


def shortByHex(url):
    '''url缩短'''
    import hashlib
    _seed = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    _hex = hashlib.md5(url).hexdigest()
    _hexLen = len(_hex)
    _subHexLen = _hexLen / 8
    _output = []
 
    for i in xrange(0, _subHexLen):
        _subHex = _hex[i*8:i*8+8]
        _subHex = 0x3FFFFFFF&int(1*('0x%s'%_subHex), 16)
        _o = []
        for n in xrange(0, 6):
            _index = 0x0000003D & _subHex
            _o.append(_seed[int(_index)])
            _subHex = _subHex >> 5
        _output.append(''.join(_o))
    return _output
 
print shortByHex("password")
Via:Chairo@2012年01月12日-EOF-

微博把妞利器预览版开源了

痛恨各种年终总结,所以年底不写总结。好久没有更新博客内容了,一则因为最近学习的Java是自己并不是很喜欢的东西,二则是一松弛下来就变的很懒。

前一阵申请了SAE的python测试,拖了性浪微博的一个python SDK写了一个简单的半成品脚本。名字比较唬人,应用叫做“微博把妞利器”,这个闷骚的名字可能名不副实,不过已经一年多两年没折腾过性浪微博接口了,生疏了很多。

微博把妞利器这个东西可以填写你需要关注的微博用户个性域名(不包含http://weibo.com/),然后页面打开状态会自动每隔一分钟(这一版暂定此种方式)抓取一次最后一次微博时间然后显示出来。

源代码地址:https://bitbucket.org/chairo/7ats

此次代码使用了bottle框架+sinaweibopy

如图:
20120101000600.png

因为是短时间作为熟悉性浪微博SDK的产物,请不要期待功能很完善。之后版本预计会增加各种邮件、QQ机器人等方式自动提醒功能…

Via:Chairo@2012年01月01日-EOF-

给tornado的database.py增加dbutils支持

忘记什么时候在邮件订阅中看到smallfish的一个给tornado的database.py增加dbutils支持的文章了,去smaillfish的blog看了一下居然是09年写的一篇文章。小鱼修改的代码为:

def reconnect(self):
        """Closes the existing database connection and re-opens it."""
        self.close()
        try:
            from DBUtils import PooledDB
            pool_con = PooledDB.PooledDB(creator=MySQLdb, **self._db_args)
            self._db = pool_con.connection()
        except:
            self._db = MySQLdb.connect(**self._db_args)
            self._db.autocommit(True)

小鱼干掉了原有的设置autocommit(True)这一行代码,我估计主要是因为DBUtils没有autocommit()这个方法。干掉此行代码后会有一个小问题,就是如果mysql配置的autocommit=0的话,每次对数据库的修改是不会实时反馈给mysql数据库的。而原版的self._db.autocommit(True)这一行就是为了在保证在执行完一条SQL后,修改内容马上反馈给mysql。

Google一圈后我找到两个解决方案:

  • 一个是利用DBUtils的的setsession命令:
    def reconnect(self):
            """Closes the existing database connection and re-opens it."""
            self.close()
            try:
                from DBUtils import PooledDB
                pool_con = PooledDB.PooledDB(creator=MySQLdb, setsession=['SET AUTOCOMMIT = 1'], **self._db_args)
                self._db = pool_con.connection()
            except:
                self._db = MySQLdb.connect(**self._db_args)
                self._db.autocommit(True)
  • 另一个就是类似tornado的做法给每个cursors的connection设置autocommit属性为True
    def reconnect(self):
            """Closes the existing database connection and re-opens it."""
            self.close()
            try:
                from DBUtils import PooledDB
                pool_con = PooledDB.PooledDB(creator=MySQLdb, **self._db_args)
                self._db = pool_con.connection()
                self._db.cursor().connection.autocommit(True)
            except:
                self._db = MySQLdb.connect(**self._db_args)
                self._db.autocommit(True)

Via:Chairo@2011年12月05日-EOF-