python的memcache和json模块

最近时间比较多,想在以后的项目中应用python。今天做了一下测试。一个小工具的编写。工具的目的根据输入的key,在memcache中查找相应的value。并且对value做一些分析。Value是json格式。

首先下载python-memcached-1.40.tar.gz和python-cjson-1.0.5.tar.gz。然后安装。

安装方法很简单,也很标准。Tar xzf  *.tar.gz  然后进入解压后的目录。最后Python setup.py install。这时memcache,json的python都已经可以用了。可在python命令行下测试import memcache, import cjson。如果一切正常说明安装成功。

下面以一段代码分析吧。

if __name__ == ‘__main__’:

    servers = ["127.0.0.1:11211"]

    mc  = Client(servers, debug=1)

    mc.set(‘test_key’,cjson.encode(’test_value’))

    value =  mc.get(‘test_key’)

    value_array = cjson.decode(value)

    if value_array.has_key(‘test_key’) == True:

        print ‘%s : %s’ % (‘test’, value_array[‘test_key’])

    else:

        print “Not have %s” % key_key

        print “%s”  % value_array

代码很简单mc.set(‘test_key’,cjson.encode(’test_value’))。向memcached服务器添加一条key为test_key,value为json格式的记录。Value = Mc.get(‘test’)。这一步会出错。Pickle error。问题的原因就是对json格式进行解码的时候抛异常了。我的修改方法很简单。我不需要库帮我解码。我只需要数据,我在上层自己解码。所以修改了库的返回值,就算是抛了异常也会返回value。但是我感觉这样很恶心。后面的就没什么了。这个小工具也算是做完了。

    习惯了用C去解决问题。突然换成python感觉很爽。简单就是效率

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. Python线程编程的两种方式
  2. python3.0与2.x之间的区别

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu