Monday, June 29, 2009

Story|耐人深思的故事: 测人们知觉,品味和行为倾向(视频)

耐人深思的故事: 测人们知觉,品味和行为倾向(视频) -6park.com

耐人深思的故事: 测人们知觉,品味和行为倾向(视频)


一个音乐演奏者在华盛顿DC地铁站“L‘Enfant Plaza” 的入口站了许久。 www.6park.com

那就是今年一月份的事,那天温度很低。 www.6park.com

他连续演奏了45分钟。先拉巴哈的,然后拉舒伯特的圣母颂,然后拉Manuel Ponce的,接着拉Massenet的,最候又拉回巴哈的。 www.6park.com

那是大概早上8点,此时此刻,成千上万的上班族通过这个地下通道前往工作地点。 www.6park.com

三分钟后,一个中年男子发现小提琴家在演奏,他缓慢脚步,停留了几秒钟,然后继续又加快了脚步往前走。又过了一分钟后,小提琴家得到了他的第一张钞票:一个女人扔下的一美元,但她没有停下来。再过了几分钟,一个过路人靠在对面�上听他演奏,但看了看表就走掉了。很显然,他要迟到了。 www.6park.com

www.6park.com

对音乐家最感兴趣的是一个三岁的小孩。他的妈妈又拉又扯的,但那小孩就是要停下来看音乐家。最后他妈妈用力拖他才使他继续走。但小孩还一边走一边回头看音乐家。 www.6park.com

在音乐家45分钟的演奏过程中,只有7个人真正停下来听他演奏。 www.6park.com

他一共赚了32美元。当他演奏完毕,没有一个人理他,没有一个人给他鼓掌。一千多个人中只有一个人发现了他。 www.6park.com

没有一个人发现这个音乐家原来就是Joshua Bell – 当今世界上最有名的小提琴手之一。 他在这个地铁站�演奏了世界上最男演奏的曲目, 而他所用的小提琴是意大利斯特拉迪瓦里家族在1713年�作的名琴,价值350万美元! www.6park.com

就在他在地铁站演奏的前两天,他在波士顿的歌剧院�表演,虽然门票上百美元,却座无虚席一票难求! www.6park.com


这是真实的故事。 www.6park.com

Joshua Bell在地铁�演奏一事其实是 «华盛顿邮报» 一手策划的,目的是为了测试人们的知觉、品味和行为倾向。 www.6park.com

要解答的问题是在一个公共场合�,在一个不适宜的时段,我们是否能够欣赏到美呢?我们是否会停下来欣赏呢?我们是否能在一个不适宜的环境下发觉人才呢? www.6park.com

可能的结论如下:如果我们确实是没有时间去停下来听一听世界上最优秀的演奏家演奏世界上最优美的旋律,不知道还有多少美好的东西从我们身边熘走。

Saturday, June 27, 2009

Django|Using Subdomains in Django

Using Subdomains in Django « Things I Learned

Using Subdomains in Django

January 5, 2009

Django's url dispatcher doesn't handle subdomains.  If you want/need to use subdomains you've got to use session middleware.  If you haven't written any middleware yet don't freak out, is easy.  

There's some easy documentation for extra information but for our needs all you need to do is make a Class with a function called process_request.  This function gets called on any request before it is processed by the url dispatcher.  It needs to return either nothing (None) or an HttpResponse object.  Here's the code used to get the subdomain.

  1.  class SubdomainMiddleware:  
  2.     def process_request(self, request):  
  3.         """Parse out the subdomain from the request"""  
  4.         request.subdomain = None  
  5.         host = request.META.get('HTTP_HOST', '')  
  6.         host_s = host.replace('www.', '').split('.')  
  7.         if len(host_s) > 2:  
  8.             request.subdomain = ''.join(host_s[:-2])  
 class SubdomainMiddleware:     def process_request(self, request):         """Parse out the subdomain from the request"""         request.subdomain = None         host = request.META.get('HTTP_HOST', '')         host_s = host.replace('www.', '').split('.')         if len(host_s) > 2:             request.subdomain = ''.join(host_s[:-2]) 
Now your request object has a 'subdomain' attribute you can use in your views.  Alternatively you could return an HttpResponse of any sort including redirects directly from the process_request function.  Make sure to add this class to your middlware classes:
  1. MIDDLEWARE_CLASSES = (   
  2.     'path.to.middlware.SubdomainMiddleware', )  
MIDDLEWARE_CLASSES = (      'path.to.middlware.SubdomainMiddleware', ) 
Using subdomains on localhost can be a pain.  To do so sudo edit your /etc/hosts file and add the following lines replacing test.com with whatever you want to call your test url and the subdomains with your site's subdomains.
127.0.0.1     test.com 127.0.0.1     subdomain1.test.com 127.0.0.1     subdomain2.test.com
This locally alters the DNS for test.com so you can use it as your localhost testing url.  Unfortunately the hosts file has no *.test.com functionality to handle redirecting all subdomains so this method only works if you have a known, finite set of subdomains.  If that's not the case you're going to have to use a development server or set up a proxy.  

Update:  I also forgot to mention that if you want your login sessions to work across all subdomains you can change the SESSION_COOKIE_DOMAIN variable as follows:

  1. SESSION_COOKIE_DOMAIN = '.mysite.com'  
SESSION_COOKIE_DOMAIN = '.mysite.com' 

Entry Filed under: django, python. .

Friday, June 26, 2009

Health|男性易得的6种癌症引关注

迈克尔杰克逊去世引唏嘘 男性易得的6种癌症引关注 -6park.com

迈克尔杰克逊去世引唏嘘 男性易得的6种癌症引关注

新闻来源: 人民网 于June 26, 2009 12:18:27 敬请注意:新闻取自各大新闻媒体,观点内容并不代表本网立场!

  1980年代纵横全球流行乐坛的迈克尔・杰克逊 (MichaelJackson)死于心脏停搏。当日中午12:21,洛杉矶急救中心接到来自于迈克尔位于洛杉矶HolmbyHills家中的电话。当医护人员到达他家中的时候,他已经没有呼吸,随即他被紧急送往加州大学洛杉矶医疗中心,稍后即被宣布死亡。

  今年早期迈克尔・杰克逊被传出患有皮肤癌后就一直受到社会各界的关注。杰克逊的去世不仅引发了大家对一代音乐天王离去的唏嘘,也把焦点引入了关注癌症的话题上。

  据癌症专家介绍,不良生活方式是造成男性更易患癌的最直接原因,以下六种癌症更是男性们应重点防御的“敌人”。

  泌尿系统肿瘤:男人身上的“宝贝”多集中在此部位,除了前列腺癌、睾丸癌、阴茎癌等男人特有的肿瘤外,膀胱肿瘤是该系统最常见的肿瘤。

  专家建议,男性50岁后每年查一次前列腺癌特异抗原(PSA),可以早诊疾病。睾丸癌多发于年轻男性,人们应每月自检一次。如果出现两侧睾丸大小或重量明显不同,要警惕。如果在龟头或包皮存在溃疡或肿块,经10天—14天抗生素治疗无效,就应怀疑是否为阴茎癌。膀胱癌早期会有无痛血尿,可以通过B超和膀胱镜确诊。

  肺癌:位居男性肿瘤的“榜首”,中国医师协会胸外科学分会总干事支修益认为,吸烟是引发肺癌的主要因素,此外,该病和大气污染、生活不规律以及过度劳累也有关。

  大量的研究表明,吸烟尤其是吸纸烟,是肺癌死亡率增加的原因。纸烟中含有苯并芘等多种致癌物质,有吸烟习惯者肺癌发病率比不吸烟者高10倍。开始吸烟的年龄越小,吸烟时间越长,吸烟数量越多,肺癌的发生率与死亡就越高。因此控制吸烟,可以降低肺癌的发病。美国有研究表明,通过有效的控制吸烟,美国肺癌的发病率已经降到一个平台期。此外被动吸烟与厨房油烟也是肺癌的诱因之一,目前女性肺癌的发病增加可能与此有关。

  肝癌:从肝炎—肝硬化—肝癌,“肝病三步曲”一直是男人的梦魇。天津市肿瘤医院肝胆肿瘤科主任宋天强说,一来,定期体检、适量饮酒或戒酒、不吃发霉食物,是所有人预防肝癌的“法宝”。二来,35岁以上乙肝表面抗原阳性、患慢性肝炎、肝硬化5年以上,直系亲属三代中有肝癌家族史的人,每半年应检测一次甲胎蛋白,做次肝脏B超。

  直肠癌:天津市肿瘤医院结直肠肿瘤科主任柳建中指出,男人进食脂肪和蛋白质类食物一般比女人多,而科学研究表明,它们是导致直肠癌的重要原因之一。因此,餐桌上要经常有富含纤维素的蔬菜水果等食品。

  早期直肠癌病变局限于黏膜,医生在指诊下可触及稍隆起的结节,这时病人并无任何症状。癌肿进一步发展,引起继发感染、溃烂,影响肠腔通畅,才出现症状。常为便血,大便次数增加,便秘,里急后重,便前腹痛,大便变细有黏液,骶髂部不明原因性疼痛等。

  直肠癌是肛门、直肠常见病,早期因症状不明显,容易与肛门其他疾病相混淆,常被一些临床医生忽视。肛肠专家指出:直肠癌患者中,80%的癌肿主要可在简单易行、无创伤的肛门指诊检查中发现的。手指可触及不同形状的异物,如息肉样物体,带蒂,可移动;或结节状肿块,质硬,外形不规则,不移动。指套染有黏液,说明有脓血性分泌物。

  总之,只要重视早期肛门指检的普查,直肠癌要比其他消化道癌肿更容易作出早期诊断。所以,肛肠病专家呼吁:切莫忽视早期直肠癌的肛门指诊检查。

  肾癌:天津市肿瘤医院泌尿生殖系统肿瘤科主任姚欣介绍,其发病与肥胖、吸烟等有关,B超和CT都能帮助诊断。

  肾癌的临床表现变化多端,有时无任何症状,但肿瘤在体内已有广泛进展,甚至出现肺、骨等转移征象。血尿、腰痛和肿块在临床上常称为肾癌的三大典型症状。

  (1)血尿为最常见的症状,常表现为间歇性、无痛性肉眼和/或镜下血尿。

  (2)腰痛常表现为持续性钝痛。当肿瘤已侵入神经或腰椎可造成严重疼痛。血尿在输尿管内凝固成索条状血块,随尿排出,可引起腰部疼痛。

  (3)肿块肾癌患者腰部或上腹部可触及肿块者约为10%。在初期肾脏形成的肿瘤难以触知,只有长到直径超过3—5厘米时才有可能在触诊时摸到。肿块往往质硬,表面高低不平,或结节状。在消瘦患者或肿瘤位于肾下极时,体检可扪到肿块。若肿块固定,表示肾周围有浸润,预后不佳。以上三大症状同时出现的机会不多,约占10%一15%,若同时出现往往是晚期的标志。

  口腔癌:台北头颈肿瘤医学会理事长侯胜博说,口腔癌是青壮年男性最易得的癌症,发病率是女性10倍。抽烟、喝酒、吃槟榔都是诱因。他提醒,如果发现口腔溃疡持续2周都不好,一定要及时就诊,这是最重要的口腔癌信号。

  口腔如出现以下五个症状,需警惕口腔癌的可能:

  颜色改变:正常的口腔黏膜是粉红色,如果变成白色、褐色或黑色,意味着黏膜表皮细胞发生了变化。尤其是口腔黏膜变粗糙、变厚或呈硬结,出现口腔黏膜白斑、红斑,很可能已发生癌变。

  溃疡不愈:口腔溃疡的病程一般不超过两周,如果烧灼感、疼痛等症状超过两周仍不见好,需警惕口腔癌的可能。因为,口腔癌常表现为溃疡的形式,四周边缘隆起,中央凹凸不平,并有坏死组织覆盖。

  疼痛明显:早期一般无痛或仅有局部异常摩擦感,溃破后疼痛明显,随着肿瘤进一步侵犯神经,可引发耳部和咽喉痛。

  淋巴结肿大:口腔癌多向附近的颈部淋巴结转移,有时原发病灶很小,甚至症状还不明显,但颈部淋巴结却发现了转移的癌细胞。因此,颈部淋巴结如突然肿大,需检查口腔。

  功能障碍:肿瘤可能侵犯张闭口肌肉和下颌关节,导致开闭口运动受限。

Thursday, June 25, 2009

Django|Using subdomains with Django

Using subdomains with Django — The Uswaretech Blog - Django Web Development

Using subdomains with Django

by shabda on October 10, 2008

Django makes using beautiful urls a snap. However using subdomains with Django is not so obvious. Here is an article explaining this.

Advantages of subdomain

  1. Sometimes looks more professional. Users will prefer someblog.wordpress.com over wordpress.com/someblog.
  2. If each part of your site is Under a different untrusted users, you might want to give them a separate subdomain, so that if they do Blackhat Seo on their part, the main site is not harmed.
  3. Your users can point a Cname to their subdomain to use domain of their choice with their subdomain.

Disadvantages of subdomain

  1. When you need subdomains, you will know it. If you do not if you need it or not, you probably do not.

Getting the current subdomain is ridiculously easy.

bits = urlparse.urlsplit(request.META['HTTP_HOST'])[0].split('.') bits[0] 

now bits[0] is you subdomain.

However if you are using subdomains you are probably going to be needing this,

  1. In all your views.
  2. In all your templates.

So you need to expose the subdomains using

  1. A Middleware for all requests.
  2. A request context for all templates.

A Middleware is nothing but a normal Python class which can implement process_request, process_response and others.

The code to expose subdomains for all requests via a middleware is,

import urlparse  class GetSubdomainMiddleware:      def process_request(self, request):     bits = urlparse.urlsplit(request.META['HTTP_HOST'])[0].split('.')     if not( len(bits) == 3):         pass#Todo Raise an exception etc     request.subdomain = bits[0] 

The way to populate subdomain in all templates is similar

def populate_board(request):     "Populate the board in the template"     return {'board':request.subdomain}#request.subdomain has been populated via the Middleware. 

And now you need to edit you settings.py file to add TEMPLATE_CONTEXT_PROCESSORS and MIDDLEWARE_CLASSES to include your Middleware and context processor.

You are almost ready to go, however your cookies will not work across sub domains. To make your cookies work across subdomains, add this line to your settings.py

SESSION_COOKIE_DOMAIN = '.example.com' if not DEBUG else '.local

Wednesday, June 24, 2009

Django|Using Subdomains with Django

rossp.org - Using Subdomains with Django

Using Subdomains with Django

11:30 a.m., Saturday 28 April, 2007. Tagged geeky, javascript and programming

As a part of my previously mentioned upcoming bridal gift registry project (which, by the way, performed outstandingly in it's most important private beta ever - my own wedding) I'm giving each user (in this sense, a user is a couple close to getting married) their own subdomain off of the main website - instead of having a URL to their registry like http://yourdomain.com/registries/view/?id=1048 there are beautiful URL's like http://couplesnames.yourdomain.com.

Getting this working was really quite simple, and it's something that I can see being useful for SAAS projects - just take a look at the 37signals projects such as Basecamp and the way they handle per-company logins: each company has it's own subdomain.

The first thing that needs to be done is server configuration. Your domain name needs to have a wildcard entry setup (eg *.yourdomain.com), using Bind9 this is as easy as adding the following line to your domain name config. For other setups, speak to your web hosting provider.

*       CNAME   yourdomain.com. 

Next, configure your web server software to answer requests for *.yourdomain.com the same way as www.yourdomain.com. I'm assuming that www.yourdomain.com already works, and that you're using Apache - again, YMMV so speak to your hosting provider. In Apache, just add the following line to your yourdomain.com virtual host configuration:

ServerAlias *.yourdomain.com 

After restarting your DNS & web server software, you'll find that going to http://anything.yourdomain.com shows up the same result as http://www.yourdomain.com. Perfect.

Lastly you need to configure Django to treat subdomains differently. In this case I'm making another assumption, that Django is handling requests for yourdomain.com, and that there is a view already in place (eg via urls.py) for handling requests for the root of the domain. I'm also assuming content for your "main page" (eg, anything that's not a subdomain) is handled by other views, and that your main page is under /mypage/.

My 'index' view therefore looks like this:

def index(request):     django_site = Site.objects.get_current()     if request.META['HTTP_HOST'] == django_site.domain:         # The visitor has hit the main webpage, so redirect to /mypage/          return HttpResponseRedirect('/mypage/')      # Split the domain into it's parts, remove the main part of the domain      # from the requested host, and we're left with one variable: 'subdomain'.     # We also strip out the 'www.' non web-savvy users often type 'www' in      # front of every website they visit, so let's not show them an error message!     domain_parts = django_site.domain.split(".")     domain = ".".join(domain_parts[1:])     subdomain = request.META['HTTP_HOST'].replace(domain, '').replace('.', '').replace('www', '')     # You can now access your data models using 'subdomain', eg:     couple = Couple.objects.get(subdomain=subdomain) 

You can see I'm referring to a model called Couple, with a field named 'Subdomain'. All you need to do is refer to your own model with a 'subdomain' key and you're in business - just remember to enforce unique subdomains at signup time! Lastly, ensure your current Django 'Site' entry (django.contrib.sites) is up to date with the domain set to 'www.yourdomain.com'.

From here you can customise what's shown to the visitor based off of the subdomain they've hit. Very easy to setup, and potentially very powerful - especially in environments where people need something as easy as possible to remember or as unique as possible.

© Copyright 2008 Ross Poulton. All Rights Reserved. Opinions expressed here are my own, and nare not those of my employer or any other party. Powered by Django.

Clicky

Django|Multiple Aliases for a Single Website

rossp.org - Django: Multiple Aliases for a Single Website

Django: Multiple Aliases for a Single Website

7 a.m., Wednesday 3 October, 2007. Tagged django, geeky and programming

In these days of cheap domains, it's often desirable to own multiple domains for a single website. You've probably got each of the .com, .net and .org domain names, along with a country-specific domain. You want each of these to present exactly the same website to the world, but good design says that each web page should have one, and exactly one, URL. So what's the best way to serve this up without having an Apache config for each domain?

I've come across this whilst building a website recently whereby the primary domain is mydomain.com.au, while I've got secondary domains in other popular TLD's to try and reduce domain squatting and the like.

One option is to configure an Apache virtual host for each domain, which serves up a static redirect. Another is to have Apache aliases for the main host, so each of the domains serves up the same content. This works, but leaves each page with multiple URL's.

My solution is to set up Apache aliases, and use a Django middleware to identify any requests that aren't for the main domain name, redirecting them as they're found. The middleware code I use is as follows:

from django.http import HttpResponsePermanentRedirect  class ValidateHostMiddleware(object):     """     Redirect all requests for a domain other than mysite.com.au     """     def process_request(self, request):         if not request.META['HTTP_HOST'].endswith('mysite.com.au'):             return HttpResponsePermanentRedirect('http://www.mysite.com.au%s' % request.path) 

This is nice and simple, and a useful way of having multiple domains (possibly increasing your virtual 'geographical spread') but keeping your search-engine optimisation efforts intact.

Update: Thanks to a note from Brice Carpenter, I've updated the code to do a permanent HTTP redirect (code 301) rather than a temporary (302) redirect. I've also added code from my live environment that sends the visitor to their request path on the new domain - so hitting www.mysite.com/about/policies/ refers the user to www.mysite.com.au/about/policies/.

Sunday, June 21, 2009

Django|资源大全

CssRainBow.cn-关注WEB前端技术;重视WEB标准

Django资源大全

Python Web开发的学习资料在国内还不太丰富,相关的技术网站也不多,不过网上不乏还有一些好的学习资源,有一位仁兄,也非常关注Python Web开发,关于Django框架的应用。以下这些资源就是他整理的。非常好的资源列表。

文章的出处来自zbird :http://zbird.javaeye.com 的wiki。

要找django资源,官网的wiki也是一个不错的地方。

http://code.djangoproject.com/wiki/DjangoResources

资源

使用django搭建的站点

  • django官网 django官网本身使用django搭建,而其提供了代码。django官网的大多功能由整合的trac实现,所以网站的django代码没几行。
  • 海报网 据说这是目前流量最大的django站点。据我的了解,这个网站的流量也确实大的有些超乎想象,该网站应当有接近CSDN的流量。不过这个网站将大量的页面进行了静态化,如果以这个网站的标准来评价django的性能应当不够客观。
  • 好看簿 国内的另一个django站点,目前也有不错的流量。作为该网站的用户,我感觉网站的响应速度并不怎么快。看来好看簿在服务器优化方面还需要更多的努力。

django的开源项目

  • pinax 这是我看到的最有价值的django开源项目。pinax可以看做是django的一个脚手架。她提供了快速开始一个新django项目的方法,同时对大量第三方app的使用方法进行了演示。django的app质量参差不齐,如果你想挑选app,那你可以看看pinax里都集成了哪些app。pinax 里集成了的app通常都不至于太烂。此外pinax自身也带了一些有用的app,比如blog等。
    如果你想以最快的速度了解pinax,可以去 http://cloud27.com/ 看看。这是一个用pinax搭建的SNS网站。
  • Satchmo 网店系统。看她的介绍,似乎已经有不少人在用这东西了。
  • LFS(Lightning Fast Shop) 网店系统,就Demo来看似乎是倾向于房屋交易平台。陆陆续续的也有部分商业网站开始使用该系统了,比如这个
  • reviewboard 非常有前途的一个code review工具。最开始是VMware在用,来后给开源了。

django的可重用app

CMS

Forum

调试

  • django-debug-toolbar 为django站点增加调试功能,支持查看django生成的sql语句,及sql的执行时间等,功能强大。不过由于该组件使用了jquery,似乎会使用部分使用了jquery的站点无法正常工作。
  • django-db-log 将django的异常保存到数据库。
  • django-logging 增加sql日志。直接在站点的网页上查看当前页面所使用sql语句以及执行时间。功能比django-debug-toolbar要弱不少,不过要是django-debug-toolbar把你的页面毁了,那就试试这个吧。

数据库升级

在项目开发过程中表结构的变动总是难免,django目前还不支持表结构的自动更新,不过相关的第三方app倒不少。这些app各有各的特色,具体如何选择就要看个人的喜好了。

  • SchemaEvolution 介绍django数据库升级的wiki页面,相关的app都可以在这个页面找到。

未分类

  • django-registration 注册功能,支持帐户的邮件激活。
  • django-tagging 为站点增加tagging功能
  • django-voting 投票功能
  • django-ajax-validation 使用ajax方式对表单进行校验,需要jquery的支持。这个组件只能校验,如果需要增加ajax提交表单的功能,还需要自己手动做些修改。
  • django-announcements 发送站内公告,该公告只显示一次。可以设置公共的发送对象(所有人,指定用户,登陆用户)。
  • django-avatar 为用户增加设置个人头像的功能。支持 http://www.gravatar.com/ 和用户上传头像。
  • django-dbtemplates 将django的template保存在数据库,并通过cache来加速template的加载。这样可以很方便的通过admin来编辑template。我想这东西应当可以用来实现一些简单的CMS功能,不过似乎用处不是太大。
  • django-microblogging 类似Twitter的微型博客
  • django-notification 消息分发组件,用来实现类似好友最新动态的功能。
  • django-pagination 一组翻页相关的utils,包括用于实现翻页的tag等。
  • django-robots 通过django的admin来管理robots.txt。不过我觉得robots.txt这东西为什么还需要用admin来管理,还不如直接编辑来的方便。
  • django-messages 实现站内消息的功能。目前该组件的功能的功能还比较弱,虽然作者在进行重构,但似乎进展缓慢。如果有需要我可能会自行对该组件进行一些增强。
  • django-threadedcomments 评论组件,可以给任何的models增加评论功能。
  • django-extensions 一些全局的 management extensions。其中包括create_app的增强,使用werkzeug做开发服务器等功能。
  • django-uni-form 以div方式渲染forms
  • django-timezones 时区设置组件,允许用户设置自己所在的时区。
  • django-bookmarks 书签管理组件
  • django-email-confirmation 在用户设置邮件地址后,给用户的邮箱发送一封确认邮件。用户点击邮件里的link来确认邮件地址的有效性。
  • django-mailer 邮件发送的增强组件,会在邮件发送失败时记录失败日志。
  • django-friends 朋友组件,支持邀请用户成为好友等。
  • django-locations 似乎是一个基于地区的社交网络,需要yaohoo map的支持。
  • django-oembed 方面媒体(视频等)内容嵌入,自动将媒体的连接转换成正确的html代码。
  • django-swaps 易物平台,比如用PSP换NDS啥的。
  • django-wikiapp wiki组件,支持多种wiki语法。不过目前该组件的功能还是比较简单,比如不支持附件。
  • django-mptt 用于生成树形列表的app。如果你认为它会自动给你生成一个完整的树,那你就错了,她只是一组工具。我感觉这东西并不是太好用,是否有什么优点,暂时不太清楚。
  • django-photologue 图片管理,上传图片,缩略图显示等。
  • django-filebrowser django-admin的一个扩展,可以直接通过admin对服务器上的文件进行管理。我没用过这东西,不过看介绍,感觉非常棒。
  • goflow Django上的一个工作流引擎,设计灵感来源于OpenFlow。没用过这东西,对工作流也不太了解,所以也不知道这东西好不好。不过这似乎是django上唯一的一个工作流app。

Saturday, June 13, 2009

Django|10 Insanely Useful Django Tips - Nettuts

10 Insanely Useful Django Tips - Nettuts+

10 Insanely Useful Django Tips

Sep 30th in Tools & Tips by Glen Stansberry

There are quite a few great little tricks and tips one could use on their Django projects that would speed up development and save many headaches in the long run. From basic to obscure, these tips can help any skill-level of programmer become more adept with Django and all it's glory.

PG

Author: Glen Stansberry

Glen Stansberry is a web developer and blogger. You can read more tips on web development at his blog Web Jackalope or follow him on Twitter.

Django is an excellent framework for Python. While it may not get as much ink as other popular frameworks like Rails, it is just as much a polished framework as any of the rest. It puts plenty of emphasis on the DRY principle (Don't Repeat Yourself) in clean coding by automating many of the processes in programming.

1. Use relative paths in the configuration

For some reason, projects tend to be moved around in location from time to time. This can be an absolute bear to deal with if you don't first plan ahead for the possibility. Rob Hudson has an excellent technique to ensure that your Django deployments can be moved around with ease, only having to edit a few lines of code in your settings files.

My default Django settings file has changed over time to now include settings that do not depend on the location of the project on the file system. This is great in a team environment where more than one person is working on the same project, or when deploying your project to a web server that likely has different paths to the project root directory.

Rob's post has excellent code examples for setting up your Django installation in a very flexible way.

2. Use the {% url %} tag

Instead of hardcoding individual links, try using the backwards compatible {% url %} tag to achieve the same result. This will give you the absolute URL, so that if, heaven forbid, your Django project moves the links will still remain in tact.

Essentially the {% url %} takes a view name and its parameters and does a reverse lookup to return the queried URL. If you make changes to your urls.py file, the links won't break.

While it's not the most advanced tip, it's an excellent technique to use in your django projects.

3. Use Django admin for your PHP apps

Possibly one of the greatest features of Django is the user authentication system that Django has built straight into the core. It's seriously easy to set up, and it comes packed with a robust system to authenticate users and configure other necessary settings.

This user system is so awesome that it's even been suggested to use Django as your admin area for your PHP application. Here's Jeff Croft on why Django is a great solution for an admin system for any application, regardless of language:

One of the core philosophies of Django is loose coupling. Besides the more alluring free-love connotation, this mean that each of the layers of Django’s “stack” ought to be independent of the others, such that you can choose to use only bits and pieces of it, and/or slide in other components if you prefer. Lucky you, it’s incredibly simple to learn the basics of Django’s model layer, which handles database schema and object-relational mapping — even if you don’t know Python. Anyone can create a database schema in Django and get the crown jewel of the framework -- it's admin interface -- with very little work, even if you plan to write the application logic itself in another language.

4. Use a separate media server

Django allows you to serve static files in your development environment, but not your production environment. Why? It's not efficient. At all. Jacobian.org gives an explanation.

Django deliberately doesn't serve media for you, and it's designed that way to save you from yourself. If you try to serve media from the same Apache instance that's serving Django, you're going to absolutely kill performance. Apache reuses processes between each request, so once a process caches all the code and libraries for Django, those stick around in memory. If you aren't using that process to service a Django request, all the memory overhead is wasted.

By using a separate server to house and serve these static files, your performance won't suffer. If you didn't want to buy a server you could use Amazon S3 to house the files relatively cheaply.

5. Use the Debugger Toolbar

Debugging tools for any language are invaluable. They speed up development by spotting errors in your code and potential pitfalls that might happen. Rob Hudson has recently released the django debug toolbar to help with debugging code, and it could greatly help any developer.

The toolbar itself is a piece of middleware that instantiates each panel object on request, and performs processing and rendering as the response is being written back to the browser. In this way it is essentially a set of middleware classes (the panels) grouped together to display a single toolbar. Each panel subclasses a base panel class and overrides a few methods to render the toolbar.

6. Use Django Unit Testing

Unit testing is a great way to ensure that your changes to the code that it works as expected and doesn't break any older code to maintain backwards compatibility. A great feature in Django is that it's incredibly easy to write unit tests. Django offers the ability to use the doctest or unittest straight out of the box.

Django's documentation offers a great tutorial and some sample code on how to set up unit tests to keep your code running smoothly and spot any nasty bugs.

7. Use a Cheatsheet

Is cheating wrong? I hope not. This nifty 2-page cheatsheet contains some golden nuggets within arm's reach that one might have to dig around the Django documentation to find.

The cheatsheet features these helpful topics:

Templates

  • Template tags and their options
  • Template filters and their options
  • Date formatting syntax quick reference

Models

  • Fields and their options
  • Common field options
  • Meta class options
  • ModelAdmin options

Forms

  • Fields and their options
  • Common field options
  • Standard error_messages keys
We all know time spent looking at documentation is time spent not solving the world’s problems through code. And no good programmer wants that.

8. Utilize django-chunks

Django-chunks is essentially a way to create blocks of reused code in your templates. Except creating the blocks is made even easier by using Django's rich text editor.

Well it essentially allows someone to define "chunks" (I had wanted to call it blocks, but that would be very confusing for obvious reasons) of content in your template that can be directly edited from the awesome Django admin interface. Throwing a rich text editor control on top of it make it even easier.

By replicating bits of reusable code, django-chunks ensures that pieces of the layout can quickly and easily be changed if need be. While django-chunks is really only a model and template tag, it can greatly speed up development by replicating processes.

9. Utilize Memcache

If performance is going to be an issue with your Django-powered application, you'll want to install some sort of caching. While Django offers many options for caching, the best by far is memcached. Installing and using memcached is fairly easy with Django if you use the cmemcache module. Once the module is installed, you just change a single configuration option, and your Django pages will be served lighting fast.

10. Stop hacking scripts together and just use Django

If you still don't fully understand Django's power after reading this article, there's a logical reasoning for using Django in your next project: You save time hacking together designs with different sets of software. Jeff Croft explains why creating a project in Django is much more efficient than trying to hack together scripts.

Now, if you're used to building sites using a blogging app (Wordpress, TXP, etc.) as a CMS, you're used to getting all that for free. But you're also getting a lot of things built-in that maybe you don't want (unless, of course, you're building a blog). The limitation I ran across in using a blogging app for my personal site is that I wanted it to be more than just a blog. As soon as I tried to hack a blog into a photo gallery, or a links feed, or a statistics database, a game of Sudoku, or whatever else I could think of, things started to get crufty. I also built a website in which I tried to use a discussion forums app (vBulletin) as a CMS, and that had the same results. It worked -- sort of -- but it wasn't extensible, was very hackish, and just generally was inelegant. With Django, you get all of these things and none of the limitations of a blogging app.

Django allows you to expand your website into literally any direction without having to worry about hacking the design or making sure the scripts and databases are compatible. It just works.

Django|debug toolbar: Add your own panel

Coulix.org: Django debug toolbar: Add your site SVN version

Django debug toolbar: Add your site


This entry shows a simple way of adding your project current SVN to the django debug toolbar by creating a custom debug panel.

What you need

You need to get django debug toolbar set up on Rob git repository right there

Follow the README.rst on how to install.

The How

from debug_toolbar.panels import DebugPanel from django.utils.version import get_svn_revision import os  class CustomVersionDebugPanel(DebugPanel):     """     Panel that displays your project svn version.     """     name = 'your_site'      def title(self):         return 'your_site_name %s' % ( get_svn_revision(path=os.getcwd()))      def url(self):         return ''      def content(self):         return '' 

Then update the panels settings in settings.py

DEBUG_TOOLBAR_PANELS = (         'base.debugpanels.CustomVersionDebugPanel',         [...] ) 


Django|Setting django dev & prod environment

Yashh // Setting django dev & prod environment

Setting django dev & prod environment

Saturday, 18th October, 2008 // 8:52 p.m.

Here is the quick post on how I setup my django development and production server. I know everybody has their own type of server setup but I just wanted to share mine. So basically I created two apache instances which run production and development servers respectively. If you are with webfaction this would be a piece of cake. However if you are on a slice/ dedicated server setup, you can use another webserver(a little complicated approach) or just use django development server to run on a custom port.

Production: www.domain.com
Development: subdomain.domain.com (Ex: sandbox.domain.com)

Ex: Production:Nginx running on 80 serving media and proxying django requests to Apache/wsgi instance running on a custom port.
Development: You can fire the django development server on a custom port and for media use the same nginix instance.If you are with webfaction you can create 2 seperate django applications and use a Static app to serve the media.

Make use of your Version Control which makes your life easy. In the past I had a very ugly approach of using FTP to connect to the server and then make changes in the code on the fly. This would create a bunch of 500's to the visitors. I realized that there should be a better solution, until I realized this approach. If you are using Subversion you can checkout a copy of the code to the development setup and work on it and then commit the changes back to the repository. After you make sure everything is working, you can simply checkout the code from the repository into the production server and simply restart the server. The same approach would work with GIT, Bazaar as well but with a subtle difference. You can simply add the development repository as a remote and pull updates into the production setup.

Other Advantages would be like:
1. Avoid caching in development setup You can ignore the settings.py file in development setup, so that production settings can be different. In development setup you can disable caching so that you can observe changes immediately.

2. Use a different database for development You can use the same database of the production or setup a different database just for the development purpose. You can create a local_settings.py file where you can put all your development server credentials and include this piece of code at the end of settings.py file so that it overwrites values in settings.py

try:    from local_settings import * except ImportError:    pass 

In this way it tries to import local_settings.py if its not found an error wont be raised. Make sure your version control doesn't track local_settings.py.

3. Make use of Django-debug-toolbar Rob Hudson created a django-debug-toolbar after djangocon which is amazing. You can see all the queries which ran to generate a page and HTTP headers which contain session variables, any form data etc. Its an amazing way to debug a django app. You can install django-debug-toolbar in your local_settings.py and set ignore app on django-debug-toolbar so that your version control doesn't track it.

4. Set DEBUG=TRUE: Of course this is a very common setting to have debug true when you are developing so that you can get a trace back of the error. However if your development server is public you can set DEBUG=False and check your ADMINS emails for the trace back.

On the whole make your development environment same as production environment, so that testing and debugging the project will be easy.

Is there any better way than this so that I can use only one apache instance to serve both dev and production versions?

Django|Some Simple Django Debugging Tools

Defying Classification: Some Simple Django Debugging Tools

Some Simple Django Debugging Tools

Posted at 15:01 +1100

Before you can debug a problem, sometimes before you even know a problem exists, you have to be able to work out what is going on. In many cases, this means somehow capturing the state of the system. Although most people encounter the odd Heisen-bug — a problem that seems to mysteriously vanish whenever you try to observe it — they aren't the common case.

There are a few little items that come with Django, right out of the box, which are not as well known as they might be. I don't always use these, but, at various times, they each play the role of right tool for the job. Nothing too deep here; I'm aiming only to put a few ideas into people's heads.

The general theme is using the template system to display some debugging information. Sometimes I feel that people try to debug problems that aren't template related through the browser a bit too readily (and then they wonder why it's difficult). Part of debugging is removing any unnecessary components, after all. If you're debugging template-level problems, however, these might be useful.

Debug Context Processor

The debug context processor isn't enabled by default, but it's sometimes worth using. Two uses here:

  1. Showing all the SQL statements used to construct the page.
  2. Making a context variable (debug) available to indicate when the debug setting is enabled, which can be used to trigger the display of other information of your own design.

When I've gotten the basic structure of a site together, I'll enable this context processor and start to look at the SQL that's being generated. A few easy optimisations often show up. My own approach for displaying the information is to use the following fragment just before the </html> part of the base template:

{% if debug %}<!--     SQL queries ({{ sql_queries|length }}):     {% for query in sql_queries %}         {{ query.sql|safe|wordwrap:"75" }} ({{ query.time }})     {% endfor %} -->{% endif %} 

The SQL queries are dumped into an HTML comment, formatted with linebreaks so that they display nicely in a standard "view source" window (I don't want to have to keep messing around with enabling line wrapping or whatever).

The "pprint" Template Filter

If you're dumping any raw (or basically unformatted) Python structure into a template for debugging, it will often turn out looking pretty ugly. Being able to read the Python data is as important as being able to display it. Be nice to your eyes, since this is often only the first step of a long process.

Enter the pprint template filter. It passes the contents of the variable it is filtering through Python's pprint(). That will introduce some useful linebreaks and horizontal spacing into the results. Since HTML rendering normally ignores such things, we have to wrap the output display in pre tags as well:

<pre>{{ python_structure|pprint }}</pre> 

Django's auto-escaping behaviour will also play a role here. Any "<" characters, for example, will automatically be turned into "&lt" entities, so they will display as the right character in the rendered result, instead of being interpreted as HTML.

The "debug" Template Tag

Sometimes you just want to know what is contained in the template's context, particularly when something isn't rendering as expected. You want to check if the necessary information is not present at all, or being used incorrectly.

The debug template tag does this. It displays the templates context (the set of variables available for use in the template), as well as the current sys.modules contents.

As with the pprint filter, if the result is to be displayed in an HTML page, we need to use <pre>...</pre> tags to make things display nicely (the debug tag uses Python's pprint module internally to generate raw formatted output). Since debug is a template tag, not a filter, the output isn't automatically run through the auto-escaping process. As it's not always used in HTML (not all templates are HTML output), the debug tag doesn't produce pre-escaped HTML. So we have to escape the results ourself:

<pre>{% filter force_escape %}{% debug %}{% endfilter %}</pre> 

Maybe not as simple as I'd like — it gets a bit tiring having to remember all the extra bits to wrap around the tag — but it's not too onerous and the slight clunkiness is because it also works in non-HTML environments, which is a benefit.

I must admit, I don't find myself using the debug tag very often. Normally, if I want to see what variables are available in the context, I'll add debugging to the appropriate view. Sometimes, though, it's a small push in the right direction. One place I do find it useful is in conjunction with the direct_to_template() view, which is the next tool in the box.

The "direct_to_template" View

This generic view is useful in many ways and it's worth remembering it exists. It's a nice shortcut for rendering a static template, with access to any parameters that might have come in through the URL. All the URL parameters are put into a dictionary called params, which is passed into the template (the context variable is called "params", that is).

When I'm just fleshing out an application and want to stub out some URLs, I'll sometimes create a simple template that looks something like this:

{% extends "base.html" %}  {% block main_content %}     <pre>{% filter force_escape %}{% debug %}{% endfilter %}</pre> {% endblock %} 

This template can be used over and over again as a target for URL patterns. Suppose it's called "dump_input.html". A URL Conf entry might look like:

urlpatterns = patterns('',    url("^help/(?P<help>\w+)/$", direct_to_template, name="help"),    ... ) 

When I'm developing such a site, I can refer to "/help/foo/" and nothing will break. The page won't be finished, but it will look like the rest of the site — I extended the "base.html" template for that reason — and show which help topic is being requested.

The Debug Toolbar

This the only component mentioned here that isn't part of Django itself. It's a useful extension written by Rob Hudson and available here (if you don't use git, you can still click the "download" link to get a tarball or zipfile snapshot). There are a couple of forks for this code around, even on github itself, but Rob seems to be pulling in most of the major changes, so I'll treat his as the main version for my purposes here.

The debug toolbar is a more invasive look at what went into creating a particular page (in the sense that it has both client-side and server-side pieces to collect all the information). It's still work in progress, but Rob seems to take all sensible patches quite readily. If you're like me and don't have monitor that is 2 metres wide and 6.5 billion pixels across (which I believe is standard for those who've sold their soul to the Church Of Mac these days), there are some layout issues. One day I'm hoping to have enough free time to poke at the Javascript (it's jQuery based) and make it scale a bit better to the screen size. More hopefully, though, somebody else will get there first.

In any case, if you're trying to look at things beyond basic functionality problems, the debug-toolbar is probably a good next step. The tools I've mentioned in the previous section are more useful for getting the basic rendering working, whilst the debug-toolbar is more for inspecting things like the number of queries made and other server-side computations. Possibly it would have been better named the introspection-toolbar. Still, we all know that naming is one of the hard areas of Computer Science.