Special sessions是什么意思 proposals 是啥意思

当前访客身份:游客 [
专注于web技术学习研究:项目管理、Django、PHP、Ubuntu、LAMP、前端技术。。。
:laravel5出了,博主更新吧
:给力,收藏
:laravel5出了,可以更新下啦
:介绍的再详细点就好了。 ...
:方便把代码给我学习一下吗 ?...
:引用来自“fate-testarossa”的评论您好,盛大的...
:mark 留个脚印
:您好,盛大的那个博客(盛大在线运维团队博客)进...
今日访问:37
昨日访问:35
本周访问:156
本月访问:128
所有访问:87377
列表模式: |
是一个Python Library,可以把大量频繁使用的ssh操作写到一个脚本中,通常用于部署或者系统维护等任务,我现在部署Django应用时都会用它,节省了大量时间。
首先当然要安装Fabric,通过pip安装最方便:
pip install fabric
之后编写Fabric脚本fabfile.py,根据自己的部署流程需要来写即可:
from fabric.api import * env.hosts = ['123.456.78.90:1234']&
env.user = &root&
def update_django_project():
&&& Updates the remote django project.
with cd('/home/****/www/****/******'):
run('git pull origin master')
with prefix('source ../bin/activate'):
run('pip install -r requirements.txt')
run('python manage.py syncdb')
# run('python manage.py schemamigration **** --auto')
run('python manage.py migrate ****')
run('python manage.py collectstatic --noinput')
def restart_webserver():
&&& Restarts remote nginx and uwsgi
sudo(&killall -s HUP /home/****/www/****/bin/uwsgi&)
sudo(&nginx -s stop&)
sudo(&/etc/rc.d/nginx start &)
def deploy():
&&& Deploy Django Project.
update_django_project()
restart_webserver()
先把最新代码push到master:
git push origin master
再执行Fabric脚本部署:
fab -f fabfile.py deploy
发布于 4年前,
阅读(1455) | 评论(1) |
投票(0) | 收藏(8)
http://www.lightbird.net/dbe/index.html
发布于 4年前,
阅读(211) | 评论(0) |
投票(0) | 收藏(0)
__exact & & & &精确等于 like 'aaa'
__iexact & &精确等于 忽略大小写 ilike 'aaa'
__contains & &包含 like '%aaa%'
__icontains & &包含 忽略大小写 ilike '%aaa%',但是对于sqlite来说,contains的作用效果等同于icontains。
__gt & &大于
__gte & &大于等于
__lt & &小于
__lte & &小于等于
__in & & 存在于一个list范围内
__startswith & 以...开头
__istartswith & 以...开头 忽略大小写
__endswith & & 以...结尾
__iendswith & &以...结尾,忽略大小写
__range & &在...范围内
__year & & & 日期字段的年份
__month & &日期字段的月份
__day & & & &日期字段的日
__isnull=True/False
__isnull=True 与 __exact=None的区别
class Blog(models.Model):
& & name = models.CharField(max_length=100)
& & tagline = models.TextField()
& & def __unicode__(self):
& & & & return self.name
class Author(models.Model):
& & name = models.CharField(max_length=50)
& & email = models.EmailField()
& & def __unicode__(self):
& & & & return self.name
class Entry(models.Model):
& & blog = models.ForeignKey(Blog)
& & headline = models.CharField(max_length=255)
& & body_text = models.TextField()
& & pub_date = models.DateTimeField()
& & authors = models.ManyToManyField(Author)
& & def __unicode__(self):
& & & & return self.headline
这 是model,有blog,author,以及entry;其中entry分别与blog与author表关 联,entry与blog表是通过 外键(models.ForeignKey())相连,属于一对多的关系,即一个entry对应多个blog,entry与author是多对多的关系, 通过modles.ManyToManyField()实现。&
一、插入数据库,用save()方法实现,如下:&
&&& from mysite.blog.models import Blog&
&&& b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')&
&&& b.save()
二、更新数据库,也用save()方法实现,如下:&
&& b5.name = 'New name'&
&& b5.save()
保存外键和多对多关系的字段,如下例子:&
更新外键字段和普通的字段一样,只要指定一个对象的正确类型。&
&&& cheese_blog = Blog.objects.get (name=&Cheddar Talk&)&
&&& entry.blog = cheese_blog&
&&& entry.save()
更新多对多字段时又一点不太一样,使用add()方法添加相关联的字段的值。&
&& joe = Author.objects.create(name=&Joe&)&
&& entry.authors.add(joe)
三、检索对象
&&& Blog.objects&
&django .db.models.manager.Manager object at ...&&
&&& b = Blog(name='Foo', tagline='Bar')&
&&& b.objects&
Traceback:&
AttributeError: &Manager isn't accessible via Blog instances.&
1、检索所有的对象
&&& all_entries = Entry.objects.all()
使用all()方法返回数据库中的所有对象。
2、检索特定的对象&
使用以下两个方法:&
fileter(**kwargs)&
返回一个与参数匹配的QuerySet,相当于等于(=).&
exclude(**kwargs)&
返回一个与参数不匹配的QuerySet,相当于不等于(!=)。
Entry.objects.filter (pub_date__year=2006)&
不使用Entry.objects.all().filter (pub_date__year=2006),虽然也能运行,all()最好再获取所有的对象时使用。&
上面的例子等同于的sql语句:&
slect * from entry where pub_date_year='2006'
链接过滤器:&
&&& Entry.objects.filter (&
... & & headline__startswith='What'&
... ).exclude(&
... & & pub_date__gte=datetime.now()&
... ).filter (&
... & & pub_date__gte=datetime()&
最后返回的QuerySet是headline like 'What%' and put_date&now() and pub_date&
另外一种方法:&
&& q1 = Entry.objects.filter (headline__startswith=&What&)&
&& q2 = q1.exclude(pub_date__gte=datetime.now())&
&& q3 = q1.filter (pub_date__gte=datetime.now())&
这种方法的好处是可以对q1进行重用。
QuerySet是延迟加载&
只在使用的时候才会去访问数据库,如下:&
&&& q = Entry.objects.filter (headline__startswith=&What&)&
&&& q = q.filter (pub_date__lte=datetime.now())&
&&& q = q.exclude(body_text__icontains=&food&)&
&&& print q&
在print q时才会访问数据库。
其他的QuerySet方法&
&&& Entry.objects.all()[:5]&
这是查找前5个entry表里的数据
&&& Entry.objects.all()[5:10]&
这是查找从第5个到第10个之间的数据。
&&& Entry.objects.all()[:10:2]&
这是查询从第0个开始到第10个,步长为2的数据。
&&& Entry.objects.order_by('headline')[0]&
这是取按headline字段排序后的第一个对象。
&&& Entry.objects.order_by('headline')[0:1].get ()&
这和上面的等同的。
&&& Entry.objects.filter (pub_date__lte='')&
等同于SELECT * FROM blog_entry WHERE pub_date &= '';
&&& Entry.objects.get (headline__exact=&Man bites dog&)&
等同于SELECT ... WHERE headline = 'Man bites dog';
&&& Blog.objects.get (id__exact=14) &# Explicit form&
&&& Blog.objects.get (id=14) & & & & # __exact is implied&
这两种方式是等同的,都是查找id=14的对象。
&&& Blog.objects.get (name__iexact=&beatles blog&)&
查找name=&beatles blog&的对象,不去饭大小写。
Entry.objects.get (headline__contains='Lennon')&
等同于SELECT ... WHERE headline LIKE '%Lennon%';
startswith 等同于sql语句中的 name like 'Lennon%',&
endswith等同于sql语句中的 name like '%Lennon'.
&&& Entry.objects.filter (blog__name__exact='Beatles Blog')&
查找entry表中外键关系blog_name='Beatles Blog'的Entry对象。
&&& Blog.objects.filter (entry__headline__contains='Lennon')&
查找blog表中外键关系entry表中的headline字段中包含Lennon的blog数据。
Blog.objects.filter (entry__author__name='Lennon')&
查找blog表中外键关系entry表中的author字段中包含Lennon的blog数据。
Blog.objects.filter (entry__author__name__isnull=True)&
Blog.objects.filter (entry__author__isnull=False,entry__author__name__isnull=True)&
查询的是author_name为null的值
Blog.objects.filter (entry__headline__contains='Lennon',entry__pub_date__year=2008)&
Blog.objects.filter (entry__headline__contains='Lennon').filter ( &entry__pub_date__year=2008)&
这两种查询在某些情况下是相同的,某些情况下是不同的。第一种是限制所有的blog数据的,而第二种情况则是第一个filter 是
限制blog的,而第二个filter 则是限制entry的
&&& Blog.objects.get (id__exact=14) # Explicit form&
&&& Blog.objects.get (id=14) # __exact is implied&
&&& Blog.objects.get (pk=14) # pk implies id__exact&
等同于select * from where id=14
# Get blogs entries with id 1, 4 and 7&
&&& Blog.objects.filter (pk__in=[1,4,7])&
等同于select * from where id in{1,4,7}&
# Get all blog entries with id & 14&
&&& Blog.objects.filter (pk__gt=14)&
等同于select * from id&14
&&& Entry.objects.filter (blog__id__exact=3) # Explicit form&
&&& Entry.objects.filter (blog__id=3) & & & &# __exact is implied&
&&& Entry.objects.filter (blog__pk=3) & & & &# __pk implies __id__exact&
这三种情况是相同的
&&& Entry.objects.filter (headline__contains='%')&
等同于SELECT ... WHERE headline LIKE '%\%%';
Caching and QuerySets
&&& print [e.headline for e in Entry.objects.all()]&
&&& print [e.pub_date for e in Entry.objects.all()]&
应改写为:&
&& queryset = Poll.objects.all()&
&&& print [p.headline for p in queryset] # Evaluate the query set.&
&&& print [p.pub_date for p in queryset] # Re-use the cache from the evaluation.、&
这样利用缓存,减少访问数据库的次数。
四、用Q对象实现复杂的查询
Q(question__startswith='Who') | Q(question__startswith='What')&
等同于WHERE question LIKE 'Who%' OR question LIKE 'What%'
Poll.objects.get (&
& & Q(question__startswith='Who'),&
& & Q(pub_date=date()) | Q(pub_date=date())&
等同于SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '' OR pub_date = '')
Poll.objects.get (&
& & Q(pub_date=date()) | Q(pub_date=date()),&
& & question__startswith='Who')&
等同于Poll.objects.get (question__startswith='Who', Q(pub_date=date()) | Q(pub_date=date()))
五、比较对象
&&& some_entry == other_entry&
&&& some_entry.id == other_entry.id
Entry.objects.filter (pub_date__year=2005).delete()
b = Blog.objects.get (pk=1)&
# This will delete the Blog and all of its Entry objects.&
b.delete()
Entry.objects.all().delete()&
七、一次更新多个值
# Update all the headlines with pub_date in 2007.&
Entry.objects.filter (pub_date__year=2007).update(headline='Everything is the same')
&&& b = Blog.objects.get (pk=1)&
# Change every Entry so that it belongs to this Blog.&
&&& Entry.objects.all().update(blog=b)
如果用save()方法,必须一个一个进行保存,需要对其就行遍历,如下:&
for item in my_queryset:&
& & item.save()
one-to-many&
&&& e = Entry.objects.get (id=2)&
&&& e.blog # Returns the related Blog object.
&&& e = Entry.objects.get (id=2)&
&&& e.blog = some_blog&
&&& e.save()
&&& e = Entry.objects.get (id=2)&
&&& e.blog = None&
&&& e.save() # &UPDATE blog_entry SET blog_id = NULL ...;&
&&& e = Entry.objects.get (id=2)&
&&& print e.blog &# Hits the database to retrieve the associated Blog.&
&&& print e.blog &# Doesn' uses cached version.
&&& e = Entry.objects.select_related().get (id=2)&
&&& print e.blog &# Doesn' uses cached version.&
&&& print e.blog &# Doesn' uses cached version
&&& b = Blog.objects.get (id=1)&
&&& b.entry_set.all() # Returns all Entry objects related to Blog.
# b.entry_set is a Manager that returns QuerySets.&
&&& b.entry_set.filter (headline__contains='Lennon')&
&&& b.entry_set.count()
&&& b = Blog.objects.get (id=1)&
&&& b.entries.all() # Returns all Entry objects related to Blog.&
# b.entries is a Manager that returns QuerySets.&
&&& b.entries.filter (headline__contains='Lennon')&
&&& b.entries.count()
You cannot access a reverse ForeignKey Ma it must be accessed from an instance:&
&&& Blog.entry_set
add(obj1, obj2, ...)&
& & Adds the specified model objects to the related object set.&
create(**kwargs)&
& & Creates a new object, saves it and puts it in the related object set. Returns the newly created object.&
remove(obj1, obj2, ...)&
& & Removes the specified model objects from the related object set.&
& & Removes all objects from the related object set.&
many-to-many类型:&
e = Entry.objects.get (id=3)&
e.authors.all() # Returns all Author objects for this Entry.&
e.authors.count()&
e.authors.filter (name__contains='John')&
a = Author.objects.get (id=5)&
a.entry_set.all() # Returns all Entry objects for this Author.
one-to-one 类型:&
class EntryDetail(models.Model):&
& & entry = models.OneToOneField(Entry)&
& & details = models.TextField()
ed = EntryDetail.objects.get (id=2)&
ed.entry # Returns the related Entry object
使用sql语句进行查询:
def my_custom_sql(self):&
& & from django .db import connection&
& & cursor = connection.cursor()&
& & cursor.execute(&SELECT foo FROM bar WHERE baz = %s&, [self.baz])&
& & row = cursor.fetchone()&
& & return row
发布于 5年前,
阅读(2106) | 评论(0) |
投票(0) | 收藏(2)
这段时间一直在学python和django,准备写个小小的blog巩固下自己学到的东西,看到了GAE上的一些程序,大部分都是纯python的,想找一些基于django的,还真是难。无意中搜索到一篇文章,就翻译一下,渣技术,实在不行,就去看en文的吧。
Michael Trier在两年以前就写了一篇叫“基于django的blog引擎在哪儿?”。James Bennett随后也跟着写了一篇名叫“哪儿才有django的blog应用”,他论述了为什么最终没有Django blog engine(也就是基于django的博客引擎)。最近Daniel Greenfeld写了一篇“向哥展示你们的开源Django blog吧”,它里面,他定义了这个Django blog项目所需要的各项要求。自从读了那篇文章以后,我就开始一直写现在的这篇文章。
下面我挑选了一些我相信你应该会注意的blog引擎,并且根据它们最近的更新日期排列。如果这些blog engine的作者描述了他们的blog,那么我就直接引用作者们的描述,如果没有,那哥就总结一下我对该项目的一些了解。如果你有自己开发的blog引擎并且值得哥注意的,那么就在下面留言吧,记得加上姓名和地址。
博客程序并没有被包含在下面,这是因为这个项目在我写这片博客之前就已经关闭了下载的地址(= =!)。
标语: 的blog程序一般适用于企业或者项目级别的引用。
源码地址:
最后更新:号
在线的demo:
描述:Bilion是的一个已经被提取和开源的blog程序,这个blog目前的定位是,它能够被应用于类似的和这样的网站或者博客项目。一旦我们完成Bilion的功能,那么我们就用它去代替内部的Pinax博客程序。
1.多渠道支持(比如:技术对业务) & & &#这句真没看懂啥意思
2.使用Creole作为标记格式
3.Atom feeds & & & & & &#求翻译帝现身
4.在博客发布前预览其效果
5.可以选择同步推特
Django-article
标语:牛X的基于django开发的博客引擎
最后更新:号
现在demo:
描述:作者是Josh VanderLinden,牛X的基于django开发的博客引擎。
显著特点:
1.标签系统
2.在django的后台中自动完成标签功能
3.支持草稿(就是现预存,以后再发布)
4.文章到期设定 & & #这是啥设定啊,还翻译有毛病
5.可以使用文本或者HTML或者使用Markdown或者ReStructured Text或者Textile markup来写文章。 & & & & & & & & &#这里面有几个属于不是很懂
6.支持相关文章显示
7.支持后续文章(就是上一篇下一篇)
8.支持Disqus评论系统 & & & & & & & #想知道s是啥,请猛击。
9.文章分页存档
10.支持多语言(国际化个锤子)
11.支持为每篇文章添加个单独的链接,并且检测该链接。 &#连wordpress的url设定差不多。- -,我猜的。
12.字数统计 & & & & & & #这个功能到底有个啥锤子用啊
13.支持最新文章的RRS Feeds
14.支持最新的文章标签的RRS Feeds
发布于 5年前,
阅读(620) | 评论(2) |
投票(0) | 收藏(0)
Django resources
This page lists open source projects and applications regarding Django, the framework for perfectionists with deadlines.
Feel free to update this page to improve the content as you see an opportunity to add or modify a resource, or to remove any unmaintained project from the list.
Things people can do to improve this page includes:
Relocating unmaintained projects to a &Discontinued resources& section.
Maintain a dynamically generated changelog
Sites using Django
: View and list your Django powered site(s) (replaces&)
References & Development Aides
&- A list of open-source apps/projects for Django, focused on comparing similiar apps.
&- A vertical search engine addressing the Django community. Warning - link appears dead, redirects
&- A multilingual search engine for Django and archive of all articles.
&- Code-sharing site with source code available.
&- A catalog of complete django applications
&- An aggregator for the newest and most popular Django links
Django books
- Develop AJAX applications using Django and jQuery.
- A beginner's tutorial to building web applications, quickly and cleanly, with the Django application framework.
- A practical guide to Django template development with custom tags, filters, multiple templates, caching, and more.
- Build powerful web applications, quickly and cleanly, with the Django application framework.
- Building rigorously tested and bug-free Django applications.
- Build powerful e-commerce applications using Django, a leading Python web framework
&- Learn how to build e-commerce shopping cart web applications with Django
Django application components
These are open-source application components that you can plug into any project. See&&for other resources for finding and evaluating re-usable apps.
OpenID, OAuth
&- Authenticate users through OpenID/OAuth/Facebook/Vkontakte
&- Allows logging in via Facebook, Yahoo, Gmail, Twitter and Openid
&- Another OpenID + OAuth + OAuth2 (Facebook) solution
&- Django authentication application with openid using django auth contrib
&(django_openidconsumer)
&- fork of django-openid, to add OpenID 2 support
&- OpenID integration for django.contrib.auth, with xsupport for the Simple Registration and Attribute Exchange extensions.
See a short feature comparison at&
User registration, signup, authentication, security
&- A simple, generic user-registration application for Django
&- A pluggable signup application for Django
&YaleCAS (Central Authentication Service) plugin for user authentication
&- Allows you to protect views with HTTP digest authentication.
&- Extremely simple, yet highly customizable Django application to add captcha images to any Django form.
&- Allows you to access LDAP entries through Django Models.
&- Experimental implementation of Account Management and Session Identification by Mozilla Labs
&- Role based per object permissions.
&- A full-text search integration with Django using the Sphinx engine
&- A full-text search integration with Django using Xapian
&- Django search with Lucene is Tightly integrated the Lucene in Django, so use search content using django model filtering expressions.
&- Modular search for Django.
CMS (&available)
&- A free, BSD-licensed content management system for Django, supporting a hierarchical page structure, internationalization and more. Notice: it doesn't supports Chinese(non-ASCII).
&A free, LGPL-Licensed content management system for Django. It’s not only a plug-and-play CMS but a framework to build CMS sites at top speed with clean and re-usable code
&- A simple cms As Simple As Possible but Extensible.
&- A simple, but powerful wiki supporting hierarchy, relations, attachments and permissions.
&A simple multilingual paged cms for Django
&- A lightweight content management system. Ideal for Shared-Webhosting: No shell account needed. Run at least with CGI. (GPL)
&- An easier way to build Web apps like an blog or CMS more quickly and with almost no code.
&- A taxonomy tool to integrate in your django sites/CMS. Can also be used as a menu structure.
&- A content management platform built on top of Django with many features including hierarchical pages, blogging, tagging, threaded comments and custom content types. BSD licensed.
&- Hierarchical pages, blogging, tagging, threaded comments and custom content types, workflows, role based permissions, multi-languages. BSD licensed.
Forums and comments (&available)
&- Django Bulletin Board
&- Python&-Board for Django
&- (SCT) django forum (bulletin board) and wiki applications which can be easily integrated into custom django projects. BSD.
: A wiki and forum. GPL.
&- A lightweight Forum application that plugs straight into your existing Django project.
&A comment application to allow users top post comment on your website. Inspired by freecomments.
&- a simple blog run in&. Has built in mobile UI.
&- A pluggable weblog application for Django Web Framework.
&-A full-featured, production-quality blogging application with support for trackback, ping and comment honeypots
&- Extensible Blog Engine with many features and a clean codebase.
&- a blog engine leveraging reusable Django apps for all its features.
Aggregation, RSS, feeds, lifestreams
&- A component which allows for (simplistic) aggregation of data about Django models.
&- A generic application for the Django framework that lets you combine multiple RSS and Atom feeds into one lifestream-style page.
&– The lifestreaming application that
&- Pingback implementation for Django
&- A generic tagging application for Django
&– A generic, easy-to-use location-awareness application.
&- get your site GoogleMaps-enabled (in development)
&- Displays your data in colorful maps like Wikipedia.
&- Simple Django Apps highlighting&&integration
Hierarchy structures in the database
&- Utilities for implementing Modified Preorder Tree Traversal (MPTT) with your Django Model classes and working with trees of Model instances.
&- 3 different efficient tree implementations: Adjacency List, Materialized Path and Nested Sets. They share the same API, so it’s easy to switch between them.
Models, database, history, trails
&- Intelligent schema and data migrations for Django projects
&- A tool to migrate Django databases easily.
&- An external database backend (based on ado-mssql) that allows MS SQL Server to run against Django-trunk
&- An external database backend (based on kinterbasdb) that allows to work with Firebird SQL DBMS
&- Model manager to reduce SQL querycount for nested lists with reverse foreignkeys or m2m relations.
&- Offers an audit trail to be kept for objects being edited, even outside of the admin.
&- A generic review application for Django projects, which allows association of a number of reviews with any Model instance and makes retrieval of reviews simple.
Task, jobs, queues, batch
&- A convenience wrapper for beanstalkd clients and workers in Django using the beanstalkc library for Python
&- A simple tool that allows you to have cron jobs for you applications. It comes with an example to delete expired sessions, and I have one for django-registration to delete expired users. Django Cron is intended to replace anything you would be adding to a bin directory in your own Django App
&- Task queue/Job Queue with Django integration.
&- A lightweight, open-source queueing mechanism along the lines of the Amazon Simple Queue Service.
&- An asynchronous task management daemon, to execute long-running batch tasks (minutes, hours or even days) on a Django server.
Text editing, Wiki
&- A wiki support multiusers.
&- A flexible and embeddable Django wiki engine.
&- A text editor with syntax highlighting.
XML-RPC, Rest, networking
&- a means by which a Django developer can expose their views (or indeed any other function) using XML-RPC.
&- links to several solutions for integrating JavaScript auto-complete fields
&- Allows non-technical users to create website forms containing arbitrary sets of fields for data capture
&- A Template loader for database stored templates with an extensible cache backend
&- Makes Zope3 Page Templates available to Django sites.
&- Makes SimpleTAL Page Templates available to Django sites.
Email integration
&- Provides the ability to send PGP encrypted email and allows non-technical users to manage PGP keys via the Django admin interface, as well as the ability to use the Django templating system to create multi-part emails
&- Django Flatemail System to allow for manageable email templating, much like flat pages.
&- User-to-User messaging system, with gateway to&, moderation and thread management, user & exchange filters, auto-complete support.
&- The Django admin interface optimized for iPhone/iPod touch
&- Django-maintenancemode allows you to temporary shutdown your site for maintenance work.
&- A collection of tools for the django administration interface, it includes a full featured and customizable dashboard, a customizable menu bar and tools to make admin ui theming easier.
Internationalization
&- An internationalization helper for django
&- Rosetta is a Django application that eases the internationalization (i18n) process of Django projects.
&- Specify the page language on the URL.
&Translate dynamic content of existing models without having to change the original model classes (using a registration approach).
&Lightweight model translation application with inbuilt integration of django-localeurl (Compatible with django-rosetta and django-tinymce).
Media, graphics, images, photos, rights management
&- With django-licenses you can give every object a different content license. You can easily manage your licenses and use them in other ways too.
&- Django + Graphiz
&- Django Dynamic Media Serve is the good alternative of the default django.views.static.serve for serving the media files in Django.
&A Django application for uploading, resizing, organizing, grouping, relating and displaying photographs and image galleries.
&Add &Photologue-style& image processing (resizing, effects, etc.) to your models in a simple, unobtrusive way.
&- An extensible graphing engine using the Cairo graphics and&&libraries.
&- Embed multimedia in your pages with flowplayer template tags. Support for playlists, multiple player styles and configurations.
&- Fleshin is a pluggable photo management application for Django Web Framework.
&- Django application that provides resizing and thumbnailing for images and videos with the ability to set the center of attention, heads won't get cut anymore.
&A event calendar application component
&A django application for integration of AJAX with&.
Tracker, ticket integration
&- An Issue synchronisation plugin for tracking systems like&
Other applications
&- A generic voting application for Django
&- A workflow engine for django inspired by the zope2 product Openflow
&- A simple pluggable job board for django
&- Integrate piwik web analytics / tracker into django with admin integration
&- Django Hacks Trac (help django and trac working together)
&- A simple application for Django to manage robots exclusion files (robots.txt) via admin interface
&- A reverse proxy app in django
&- Generic portlets for Django
&- Generic workflow engine for Django
&- Generic reviews for Django
&- CSS and Javascript management for Django
&- Asset management: compiling LESS/SASS/CleverCSS/etc., combining&minifying CSS and Javascript.
&- A file streaming application for Django.
Open-Source Django projects
These are stand-alone applications written using Django.
Community applications, wiki
: See the full code and templates for the Django-powered portions of this site (e.g., everything except the ticket system). The Python code is available under the BSD license, but the templates are copyrighted by World Online and shouldn't be copied.
: A work-in-progress community Web app developed by Greenpeace. LGPL.
: A forum/community application.
&- (SCT) board and wiki applications which can be easily integrated into custom django projects. BSD.
&- 一个类似于&&的站点,适用于小组或者个人做独立的wiki应用.
&- A question & answer system similar to&, based on&.
Photo gallery, photo blog, media, music
: A simple photo gallery by Jason McBrayer.
&- A django based&&client
&- Share media file with small team or family. New BSD.
&- an open-source and standards-compliant photoblog application for the web.
&- A federated profile image hosting service similar to Gravatar
Blog, RSS, feeds, aggregation, lifestream, website
&- a simple blog run in&. Has built in mobile UI.&
&- a simple mobile mini blog likes&,.
: A planet/feed aggregator by Gustavo Pic&n. Sample sites:&,&,.
&- Another RSS feed aggregator, aimed more for personal use than Feedjack.
&Build static websites from Django templates.
e-government, e-democracy, citizen participation
&Application for participative processes (debates, proposals, voting, etc.)&in development.
Geo, Maps, localisation
: Allows you to get the country flag of comments.
Utilities, tools, admin, file management
&- web based files manager. (using jQuery)
: Multi-purposes and fully-extensible web toolkit for advanced Django users and projects requiring extra customizations. (,&)
&- An extension to the Django admin interface.
: Miscellaneous Django utilities.
Tracker, ticket integration
&- a Django app which collects tickets from multiple&&sites into one page
System management, networking, monitoring
&- Nagios Configuration tool written in Django.
&- bcfg2 provides a Reporting Facility based on Django (bcfg2 is a configuration management system like cfengine)
e-commerce, shopping cart
&- the Django e-commerce project. (shopping cart)
&- the Django online-shop.
gaming, games
&- A feature-liberal MUD server based on Django and Twisted. Heavy web integration, easily scriptable/extendable in Python.
Topic-specific, business apps, time management, ...
: A &Get Things Done& to-do list management application.
: A suite for managing open wireless mesh networks
: An open-source Web application for managing small parimutuel betting pools ().
: A project to manage and publish academic catalog information, including programs, courses, and schedules. BSD.
&An open source framework for production planning applications, with a Django user interface.
&- Django based voter file analysis and interaction management application for progressive political campaigns and organizations released under AGPL v3.
&- A complete open source system for manage psychology clinics as well school clinics.
&- An appointment planning tool that helps with finding the right date and time. (GPLv3)
&- A to-do list app that works with Django 1.3
: How to run the Django tests
: Autogenerated Django API documentation
: Code recipes.
: Common developer errors, gotchas, etc.
: A place to put docs that you wish&you&could have found while learning
: how to make an application that is easy to distribute
&as described in&.
&another way to make views generic along with a demo-site which shows how to wrap views into callable objects:
&documentation for Manipulators
: How to extend the auth systems's User class to contain extra data. (Warning: kludge!)
: Adventures in making new form fields.
: extra features for upload fields.
: Documentation about the internals of Django.
: How to do it.
: Automatically changing a table to suit your app & database.
: How to use Django's user database in PureFTPd. Surprisingly
: How to setup your project structure, where to put 3rd party apps, development and production setup.
: An example of how to use Django and Open Office to do advance document templating.
: Discussion about options for adding thumbnails to Django.
: Information on creating models at run-time and how to work with them.
: Lllama's handy how-do-I guide for newforms admin.
: Get Vs Post splitting for scaling and Django.
Installing and configuring Django
: pre-integrated Django installable live CD&
&: Includes ready-to-run versions of Apache, MySQL, PostgreSQL, SQLite, Django and required dependencies. It can be deployed using a native installer, as a virtual machine or in the cloud.
: How to use Django with FCGI, Twisted, etc.
: Includes installing python 2.4 (which isn't required), the latest version of postgresql, and psycopg.
&- install django on Windows in 5 minutes (using sqlite and the internal webserver)
&- install Django on a USB stick using Movable Python
&- Install Django on a USB stick.
&- Install Django on Ubuntu with NginX through FastCGI.
&- Install Django on&.
: a django app to manage easily a lightweight web server as a win32 service.
: using the cherrypy WSGI server as a production/development server
&Install Django (and a couple more tools) on Debian or Ubuntu in one minute.
Development environment
: Very good way to debug Django applications with the Firefox extension Firebug, FirePHP.
: Django &settings inheritance& for different environments, with easy WSGI integration and bash convenience commands for Django, pip, and hg.
: An example of how to set up your development environment.
: Save the typing of DJANGO_SETTINGS_MODULE.
: Hints and tips for using the Vim editor.
: A small python script can be used to read, modify, save settings.py file.
: A small python script can be used to read, modify, save urls.py file.
: How to use the Python hotshot profiler with Django
: Shortens titles to faciliate better tab browsing of Django's documentation
: Very simple method for print debug info.
: A simple print app for debugging.
: Debugging Django apps with Winpdb
: A python script can be used for dumpping and loading data from database.
: A python script to convert uml&&to models.py.
&– Simple tool for managing automated schema migrations
: Patch so&python manage.py test&reports code coverage in HTML.
: Development django with pydev in Eclipse IDE.
: 使用Eclipse和Pydev组建Django开发平台。
: How to debug django web application with autoreload in Eclipse pydev plugin.
&A portable Django development environment for Windows. No installation required, and it can even be run from a USB key.
&How to setup your project with multiple configurations for development, testing and production
: Python script to convert a UML Class diagram directly into a working Django model no coding involved.
&- how to extend a template but re-use parts of that template
&- A quick list of all the template tags.
&- How to use Myghty templates in Django
&– Add-on allowing to use ZPT in Django
&- Integrate Django templates into an existing PHP based site
&- Makes SimpleTAL Page Templates available to Django sites as a templating language
&- Integrate Mako and Genshi with Django ()
&-&&-like syntax for Genshi, which can also be integrated with Django as above
Code examples
&Defining custom template tags with minimal boilerplate code.
&- How-to make pluggable special-tag parser
&- How to read Baldurs Gate II character files and display data about the character
&How to submit a form using Ajax with Dojo.
&How to make ajax work with Django with Yahoo! UI Library.
: Dead-Simple LDAP in Django with Backends
: How to add a rich-text editor to administration pages with Dojo.
: How to create a custom TinyMCE widget using django.newforms
: Spew out simple form fields as a base for modification
: Spew out simple forms for your whole app, including automated urls
: Generate URLs when using generic views
: Add pre/post save/delete callbacks to any model.
: Spews out a custom manipulator for your model, primed and ready for tweaking.
: Simple package with all the installed app modules underneith it.
: Provide template access to your settings variables.
: Simple script to spew out a newform from a given model.
: doing Left Outer Joins with Django's ORM.
: using the new permissions and queryset hooks in newforms-admin.
: Automatically add color to code in a blog, including choosing a language on a per-code-block basis.
Web services/APIs
&- A generic REST interface for Django
&- A wonderful REST framework for Django
&- A lightweight REST framework for Django
&- Integrating Facebook with Django
&Example of doing XML-RPC in Django
&Example of doing JSON-RPC in Django
&A simplistic json-rpc dispatcher-function for Django in 15 lines
: An example showing how to access a web service () using Python.
&- One way of integrating flickr with Django
&- Spell checking&s with&.
&- Using Django with Amazon Site Thumbnail.
&- Version of&&which will store your files on amazon's storage service
&A contrib that makes easily create Google Gadgets for iGoogle and&&websites.
Tutorials on the Web
Presentations
: Currently a partial transcript of the Snakes and Rubies meeting videos.
: Official and unofficial screencasts showing Django development in action.
: A presentation in pseudo-PowerPoint format that provides a good overview. Warning: This link appears to be broken(9th Dec ).
: From the ACCU UK Python track, April 2006
&- &Web Development for Perfectionists with Deadlines&
&- Presentation in June 07 at French Python Days, overview + advanced tips.
Resources in other languages
: A work in progress translation project.
: An Italian Django tutorial step by step. [Italian]
: A Chinese Django tutorial step by step. [Chinese]
: Various Django tips and tutorials [Polish]
: Polish documentation and examples [Polish]
&: French community and documentation.
&: German Django community and documentation.
&: Greek Django community/user group
&: Norwegian Django community/user group
&: Brazilian Django community/user group and documentation.
&: Polish Django community/user group and documentation.
: To organize suggestions and ideas.
&: A Spanish Django community.
&: Django snippets and tutorials [Polish]
: Django news for the German community
: Czech translation of Django documentation.
&: Russian Django community/user group
&: Israeli Django, Python and web-app development community/user group.
&: Japanese Django community/user group
The official&: before you post,&please&read&.
&: A forum devoted to Django development. Good place to get help with your Django questions.
&: A site to help Django developers find like-minded souls near them.
: Community members available to do Django work.
: User community about django.
: Continuous integration testing of the Django development trunk against latest changes to the Python 2.5 maintenance branch and 2.6 development trunk.
: Forum for discussing Django application development
&: A forum devoted to Django Python. Good Place to get help with your Django questions.
Jobs & Employment
: is for listing permanent and freelance&Django / Python Jobs, it's a portal for the Django community.
Cheat Sheets and Quick Starts
&introductory 3 page, concise, example-based cheat sheet to django templates
&introductory 2 page, concise, example-based cheat sheet to url patterns, and generic views
&introductory 2 page, concise, example-based cheat sheet to models.Model
&introductory 2 page, concise, example-based cheat sheet to forms.Form
发布于 5年前,
阅读(659) | 评论(0) |
投票(0) | 收藏(6)
The CSRF middleware and template tag provides easy-to-use protection against&. This type of attack occurs when a malicious Web site contains a link, a form button or some javascript that is intended to perform some action on your Web site, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, ‘login CSRF’, where an attacking site tricks a user’s browser into logging into a site with someone else’s credentials, is also covered.
The first defense against CSRF attacks is to ensure that GET requests (and other ‘safe’ methods, as defined by&) are side-effect free. Requests via ‘unsafe’ methods, such as POST, PUT and DELETE, can then be protected by following the steps below.
How to use it
To enable CSRF protection for your views, follow these steps:
Add the middleware&'django.middleware.csrf.CsrfViewMiddleware'&to your list of middleware classes,. (It should come before any view middleware that assume that CSRF attacks have been dealt with.) Alternatively, you can use the decorator&&on particular views you want to protect (see below).
In any template that uses a POST form, use the&&tag inside the&&form&&element if the form is for an internal URL, e.g.:
&form action=&.& method=&post&&{% csrf_token %}
This should not be done for POST forms that target external URLs, since that would cause the CSRF token to be leaked, leading to a vulnerability.
In the corresponding view functions, ensure that the&'django.core.context_processors.csrf'&context processor is being used. Usually, this can be done in one of two ways:
Use RequestContext, which always uses&'django.core.context_processors.csrf'&(no matter what your TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views or contrib apps, you are covered already, since these apps use RequestContext throughout.
Manually import and use the processor to generate the CSRF token and add it to the template context. e.g.:
from django.core.context_processors import csrf from django.shortcuts import render_to_response def my_view(request):
c.update(csrf(request))
# ... view code here
return render_to_response(&a_template.html&, c)
You may want to write your own&&wrapper that takes care of this step for you.
The utility script&extras/csrf_migration_helper.py&can help to automate the finding of code and templates that may need these steps. It contains full help on how to use it.
While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom&X-CSRFToken&header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request. In jQuery, you can use the&ajaxSend&event as follows:
$(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = ; i & cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
return cookieValue;
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader(&X-CSRFToken&, getCookie('csrftoken'));
Due to a bug introduced in jQuery 1.5, the example above will not work correctly on that version. Make sure you are running at least jQuery 1.5.1.
Adding this to a javascript file that is included on your site will ensure that AJAX POST requests that are made via jQuery will not be caught by the CSRF protection.
The above code could be simplified by using the&&to replace&getCookie, and&in jQuery 1.5 and later to replace&sameOrigin.
In addition, if the CSRF cookie has not been sent to the client by use of&, you may need to ensure the client receives the cookie by using&.
The decorator method
Rather than adding&CsrfViewMiddleware&as a blanket protection, you can use the&csrf_protect&decorator, which has exactly the same functionality, on particular views that need the protection. It must be usedboth&on views that insert the CSRF token in the output, and on those that accept the POST form data. (These are often the same view function, but not always).
Use of the decorator by itself is&not recommended, since if you forget to use it, you will have a security hole. The 'belt and braces' strategy of using both is fine, and will incur minimal overhead.
csrf_protect(
Decorator that provides the protection of&CsrfViewMiddleware&to a view.
from django.views.decorators.csrf import csrf_protect from django.shortcuts import render @csrf_protect def my_view(request):
return render(request, &a_template.html&, c)
Rejected requests
By default, a '403 Forbidden' response is sent to the user if an incoming request fails the checks performed by&CsrfViewMiddleware. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.
The error page, however, is not very friendly, so you may want to provide your own view for handling this condition. To do this, simply set the&&setting.
How it works
The CSRF protection is based on the following things:
A CSRF cookie that is set to a random value (a session independent nonce, as it is called), which other sites will not have access to. This cookie is set by&CsrfViewMiddleware. It is meant to be permanent, but since there is no way to set a cookie that never expires, it is sent with every response that has calleddjango.middleware.csrf.get_token()&(the function used internally to retrieve the CSRF token).
A hidden form field with the name 'csrfmiddlewaretoken' present in all outgoing POST forms. The value of this field is the value of the CSRF cookie. This part is done by the template tag.
For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field must be present and correct. If it isn't, the user will get a 403 error. This check is done by&CsrfViewMiddleware.
In addition, for HTTPS requests, strict referer checking is done by&CsrfViewMiddleware. This is necessary to address a Man-In-The-Middle attack that is possible under HTTPS when using a session independent nonce, due to the fact that HTTP 'Set-Cookie' headers are (unfortunately) accepted by clients that are talking to a site under HTTPS. (Referer checking is not done for HTTP requests because the presence of the Referer header is not reliable enough under HTTP.)
This ensures that only forms that have originated from your Web site can be used to POST data back.
It deliberately ignores GET requests (and other requests that are defined as 'safe' by RFC 2616). These requests ought never to have any potentially dangerous side effects , and so a CSRF attack with a GET request ought to be harmless. RFC 2616 defines POST, PUT and DELETE as 'unsafe', and all other methods are assumed to be unsafe, for maximum protection.
If the&&template tag is used by a template (or the&get_token&function is called some other way),CsrfViewMiddleware&will add a cookie and a&Vary:&Cookie&header to the response. This means that the middleware will play well with the cache middleware if it is used as instructed (UpdateCacheMiddleware&goes before all other middleware).
However, if you use cache decorators on individual views, the CSRF middleware will not yet have been able to set the Vary header or the CSRF cookie, and the response will be cached without either one. In this case, on any views that will require a CSRF token to be inserted you should use the&decorator first:
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
@cache_page(60 * 15)
@csrf_protect
def my_view(request):
The&CsrfViewMiddleware&will usually be a big hindrance to testing view functions, due to the need for the CSRF token which must be sent with every POST request. For this reason, Django's HTTP client for tests has been modified to set a flag on requests which relaxes the middleware and the&csrf_protectdecorator so that they no longer rejects requests. In every other respect (e.g. sending cookies etc.), they behave the same.
If, for some reason, you&want&the test client to perform CSRF checks, you can create an instance of the test client that enforces CSRF checks:
&&& from django.test import Client &&& csrf_client = Client(enforce_csrf_checks=True)
Limitations
Subdomains within a site will be able to set cookies on the client for the whole domain. By setting the cookie and using a corresponding token, subdomains will be able to circumvent the CSRF protection. The only way to avoid this is to ensure that subdomains are controlled by trusted users (or, are at least unable to set cookies). Note that even without CSRF, there are other vulnerabilities, such as session fixation, that make giving subdomains to untrusted parties a bad idea, and these vulnerabilities cannot easily be fixed with current browsers.
Edge cases
Certain views can have unusual requirements that mean they don't fit the normal pattern envisaged here. A number of utilities can be useful in these situations. The scenarios they might be needed in are described in the following section.
csrf_exempt(
This decorator marks a view as being exempt from the protection ensured by the middleware. Example:
from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_view(request):
return HttpResponse('Hello world')
requires_csrf_token(
Normally the&&template tag will not work if&CsrfViewMiddleware.process_view&or an equivalent likecsrf_protect&has not run. The view decorator&requires_csrf_token&can be used to ensure the template tag does work. This decorator works similarly to&csrf_protect, but never rejects an incoming request.
from django.views.decorators.csrf import requires_csrf_token from django.shortcuts import render @requires_csrf_token def my_view(request):
return render(request, &a_template.html&, c)
ensure_csrf_cookie(
This decorator forces a view to send the CSRF cookie.
CSRF protection should be disabled for just a few views
Most views requires CSRF protection, but a few do not.
Solution: rather than disabling the middleware and applying&csrf_protect&to all the views that need it, enable the middleware and use&.
CsrfViewMiddleware.process_view not used
There are cases when may not have run before your view is run - 404 and 500 handlers, for example - but you still need the CSRF token in a form.
Solution: use&
Unprotected view needs the CSRF token
There may be some views that are unprotected and have been exempted by&csrf_exempt, but still need to include the CSRF token.
Solution: use&&followed by&. (i.e.&requires_csrf_token&should be the innermost decorator).
View needs protection for one path
A view needs CRSF protection under one set of conditions only, and mustn't have it for the rest of the time.
Solution: use&&for the whole view function, and&&for the path within it that needs protection. Example:
from django.views.decorators.csrf import csrf_exempt, csrf_protect @csrf_exempt def my_view(request):
@csrf_protect
def protected_path(request):
do_something()
if some_condition():
return protected_path(request)
do_something_else()
Page uses AJAX without any HTML form
A page makes a POST request via AJAX, and the page does not have an HTML form with a&that would cause the required CSRF cookie to be sent.
Solution: use&&on the view that sends the page.
Contrib and reusable apps
Because it is possible for the developer to turn off the&CsrfViewMiddleware, all relevant views in contrib apps use the&csrf_protect&decorator to ensure the security of these applications against CSRF. It is recommended that the developers of other reusable apps that want the same guarantees also use thecsrf_protect&decorator on their views.
A number of settings can be used to control Django's CSRF behavior.
CSRF_COOKIE_DOMAIN
New in Django 1.2:&
Default:&None
The domain to be used when setting the CSRF cookie. This can be useful for easily allowing cross-subdomain requests to be excluded from the normal cross site request forgery protection. It should be set to a string such as&&.&&to allow a POST request from a form on one subdomain to be accepted by accepted by a view served from another subdomain.
Please note that, with or without use of this setting, this CSRF protection mechanism is not safe against cross-subdomain attacks -- see&.
CSRF_COOKIE_NAME
New in Django 1.2:&
Default:&'csrftoken'
The name of the cookie to use for the CSRF authentication token. This can be whatever you want.
CSRF_COOKIE_PATH
New in Django Development version.
Default:&'/'
The path set on the CSRF cookie. This should either match the URL path of your Django installation or be a parent of that path.
This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths, and each instance will only see its own CSRF cookie.
CSRF_COOKIE_SECURE
New in Django Development version.
Default:&False
Whether to use a secure cookie for the CSRF cookie. If this is set to&True, the cookie will be marked as &secure,& which means browsers may ensure that the cookie is only sent under an HTTPS connection.
CSRF_FAILURE_VIEW
New in Django 1.2:&
Default:&'django.views.csrf.csrf_failure'
A dotted path to the view function to be used when an incoming request is rejected by the CSRF protection. The function should have this signature:
def csrf_failure(request, reason=&&)
where&reason&is a short message (intended for developers or logging, not for end users) indicating the reason the request was rejected.
发布于 5年前,
阅读(202) | 评论(0) |
投票(0) | 收藏(1)
1,不要将项目名称包含在引用代码里 & 比如你创建了一个名为&project&的项目,包含一个名为&app&的应用,那么如下代码是不好的: &
Python代码&
& 缺点在于:应用和项目变成了紧耦合,无法将应用轻易变得可重用。如果将来要换一个项目名称,那你可有得受了。 & 推荐的做法是: &
Python代码&
& 请注意,你需要将项目的路径配置在PYTHONPATH中。 & 2,不要硬编码MEDIA_ROOT和TEMPLATE_DIRS & 项目配置文件settings.py中不要使用如下代码: &
Python代码&
& 当你在部署到生产环境,或者迁移服务器的时候,就会发生问题。 & 推荐使用如下方式: &
Python代码&
&(也可以使用abspath,跟realpath的区别请参考&) & 3,不要将静态文件的路径硬编码在模板中 & 模板中链接CSS,javascript或图片的时候,不建议使用如下方式: &
&当你的项目需要将静态文件用其他服务器提供的时候,通常会是另外一个http地址,那么你就得把所有的/appmedia/替换成新的地址,做网站写代码已经够乏味的了。 & 没有后顾之忧的解决方法是使用{{ MEDIA_URL }}代替硬编码的路径: &
&模板上下文变量怎么获取到呢?请使用RequestContext即可: &
Python代码&
&从RequestContext里还可以获取到当前用户等信息,更详细的介绍请参考: & 4,不要将业务逻辑代码写到视图里 & 不要迷惑,虽然你可能看过很多书和例子,它们把逻辑都写在了views.py里,但请你别这么做。因为这样不利于单元测试,不利于重用代码。 & 那我的业务逻辑应该放哪里呢?推荐放到模型里或者单独建立一个辅助(helper)模块。 & 当然,从模型得到一个Author,获取Author列表的代码是可以放到视图里面的。 & 5,部署时别忘记将DEBUG设置成False & 我们常常忘记在部署时禁用DEBUG,有很多种方法自动来处理这个配置: &
Python代码&
& 此方法请参考: & 另一种途径是使用不同的配置文件: &
Python代码&
&此方法请参考: & 6,只加载一次自定义的模板标签 & 当需要使用自定义或者第三方的模板标签和模板过滤器时,通常要在模板中使用: &
Python代码&
&实际情况是,需要在所有用到自定义模板标签和模板过滤器的模板中都使用上面的代码,这样就不DRY了。 &
Python代码&
&请将以上代码放到项目启动时能加载的模块中(settings.py, urls.py, models.py等)即可。 & 上面代码的作用是在项目启动时就把自定义模板标签或过滤器加载进来,模板中任何一个地方都可以使用它们,而不需要{% load template_tags %}。 & 7,合理配置和使用URL & 不要将URL全都配置在一个urls.py文件中,比如: &
Python代码&
&建议的方式是将各应用的URL配置在各自的urls.py中,这样可以使应用更容易重复使用到不同项目里: &
Python代码&
&如下是应用askalumini的urls.py: &
Python代码&
&刚才提到静态文件路径不要硬编码,url的处理方式也尽量不要硬编码,否则当你更改一个地址时会牵涉到多处的修改,可以使用一些url函数来处理。 & 在/project/askalumini/urls.py中,为每一个url定义了name,它可以帮助我们有效地在视图、模板和模型中处理url,而不是硬编码。 & 为保证名称的唯一,请遵照将url命名为&appname&/&somelabel&的习惯用法。 & 举例来说,在views.py文件中有如下代码: &
Python代码&
&请改为: &
Python代码&
& 在模型中使用models.permalink装饰器来格式url: &
Python代码&
&在模板中使用url标签代替硬编码: &
& 8,调试 & 调试通常会借助一些第三方工具来获得更多的运行时信息。 & 一个请求执行了多少句SQL?花了多长时间? & 调用的哪个模板?客户端设置了什么COOKIE?SESSION呢?。。。 & 你可以使用django-debug-toolbar查看上面甚至更多的信息: & 另一个工具是Werkzeug debugger,它可以在错误页面打开python shell,让你更方便的跟踪错误信息,请访问:&获得更多信息。 & 还有pdb,一个强大的调试工具: & 9,了解pinax备用 & django最大的优点是代码重用,DRY,pinax就是这样一个平台,包含了许多可拿来直接使用的代码,比如openid,电子邮件验证等等。请访问: & 10,了解一些著名的第三方应用 & 1)数据库升级工具 & 什么是数据库升级工具?你运行了syncdb,运行了一年之后,对模型做了更改,添加了字段,删除了字段,要再运行syncdb吗?或者ALTER TABLE ...? & django-evolutions可以帮你完成上面的事情,但它好像不够强壮: & South能很强壮地完成上面的事情,但是需要学学怎么用: & 2)模板系统 & django自带的模板系统是可以替换的,并且各自有优缺点。 & template-utils增强了模板的比较标签等功能 ,并提供其他的一些实用特性: & Jinja是一个完整的第三方模板系统,可以替换默认模板系统,它提供了许多优越的特性: & 3)第三方应用 & django&command extensions提供了很多实用的命令行功能: & shell_plus加载所有django模型 & runserver_plus整合了Werkzeug调试工具 & 生成模型图表,你可以展示给你的老板 & …… & 请参考: & Sorl可以生成缩略图: & ………… & ---END--- & 另外,从原文的评论里也有不少发现:
用django.shortcuts的redirect代替HttpResponseRedirect:
使用VirtualEnv部署django项目
django项目规范:&
上面提到的10点中,第2和第4是最容易在新手中发生的。
第6点并不适合于团队协作
发布于 5年前,
阅读(411) | 评论(0) |
投票(0) | 收藏(5)
在一个 models 中使用&FileField&或&ImageField&需要以下步骤:
1. 在你的 settings 文件中, 定义一个完整路径给MEDIA_ROOT&以便让&Django在此处保存上传文件. (出于性能考虑,这些文件并不保存到数据库.) 定义MEDIA_URL&作为该目录的公共 URL. 要确保该目录对 WEB 服务器用户帐号是可写的.
2. 在你的&models.py&中添加&FileField&或&ImageField, 并确保定义了upload_to&选项,以告诉 Django 使用MEDIA_ROOT&的哪个子目录保存上传文件.
3. 你的数据库中要保存的只是文件的路径(相对于&MEDIA_ROOT). 要想得到这个文件的路径可以用.url方法。例如,如果models里有一个取名为&photo&的ImageField,可以在Html模板里通过{{object.photo.url}}得到该图片的路径。
settings.py 设置
媒体文件的绝对路径:
# Absolute path to the directory that holds media. # Example: &/home/media//&&&& MEDIA_ROOT = 'D:\Python26\Lib\site-packages\django\bin\newproj\media'
媒体文件的相对路径: # URL that handles the media served from MEDIA_ROOT. # Example: && MEDIA_URL = '/site_media/'&
设置静态文件路径
STATIC_PATH = 'D:/Python26/Lib/site-packages/django/bin/newproj/media'
urls.py 影射路径
(r'^site_media/(?P&path&.*)$', 'django.views.static.serve',{'document_root': settings.
STATIC_PATH
&的site_media&影射到&settings.STATIC_PATH
models.py 上传图片字段设置
photo = models.ImageField('上传图片',upload_to='photos') 相当于传到&
D:/Python26/Lib/site-packages/django/bin/newproj/media/photos
&目录下,浏览时通过/site_media/photos/&访问。
发布于 5年前,
阅读(380) | 评论(0) |
投票(0) | 收藏(1)
记录了个人在需要时阅读django源码时的一些阅读笔记.所有笔记基于&
django v1.0.4.
django中缓存是一个独立的组件,它定义了一个父类,文件在&
django/core/cache/backend/base.py&这个模块包含了一个父类&
BaseCache&,指定了一些基础的操作.
__init__&:初始化指定了缓存项的过期时间,但是根据具体实现的不同会有不同的解释.&(比如在数据库实现中就是删除数据项)
add&:添加缓存,参数分别为&键,&值,&过期时间&(默认是300秒).这个方法由子类实现.
get&:获取缓存,参数为&键&,&默认值&(默认为None).
set&:改变缓存,参数同&add&函数.
delete&:删除缓存,参数为&键.
get_many&:获取多个缓存, 参数为&键列表.
has_key&:是否存在键, 参数为&键.
__contains__&:判断是否存在的函数, 参数为&键.结果与&has_key&一致.
基于数据库的缓存.模块文件在&django/core/cache/backend/db.py&这个文件包含了一个继承BaseCache的数据库缓存实现. 他还指定了数据库最多存多少缓存项.
其中值得注意的几点是:
使用pickle序列化对象.所以存储任何对象都是可以的,最后都会被转化为数据库支持的字符串.
过期时间是以秒为单位.
每次&set&都会处理序列化,哪怕本身存储的就是字符串.这显然不太合算.
构造缓存管理对象的时候可以指定一个&cull_frequency&参数,作为超过最大项时删除的参考,默认是&3,也就是说每当超过容量限制时,删除1/3的缓存数据项.奇怪的是,这里是根据&cache_key&的大小删除,而不是根据过期时间,这样就可能导致&时效非常久的缓存被提早就给删除&了.
每次获取时进行过期处理,也就是说可能有一些项永远都会存在数据库中.(过期后,自身cache_key非常大,极少有被删除的可能)
测试使用的缓存.模块文件在&
django/core/cache/backend/dummy.py.这个缓存功能相当有限,仅仅只能被用于测试.而且本身无任何逻辑,只是返回一些默认值.
基于文件的缓存.模块文件在&
django/core/cache/backend/filebase.py.这个文件系统缓存,实现了基于每个缓存对象一个文件的对应.只是在处理多文件管理时,使用了一些必要的方法.
构造时传递的第一个为路径地址.
add&方法如果添加已存在的键时不会成功,这和我们寻常的逻辑有点不符,如果还需要调用&add&那么肯定是想指定值,所以如果添加一些已有键,势必会添加一次判断.
每次&set&是都会进行一次目录遍历,搜索所有文件,看是否超过总数.
文件名的生成是对&cache_key&进行一次md5,然后取加密后的字符两个前两位作为一个二级目录存放(比如: ab/cd/*****),这样是为了目录下的文件过多时索引文件非常慢而导致效率很低的问题.但是结合构造函数时接受的最大缓存项来看,默认的&300&根本无法构成对文件索引拖慢的威胁.而&FileBaseCache默认就使用二级目录预估的至少可以存储
项缓存数据(假设缓存文件平均分布).是否是因该有所优化的在构造时加上一个判断,只有在一定数量级之后才启用二级目录,或者增加一个一级目录管理,再或者默认不设目录.
基于内存的缓存,模块文件在&django/core/cache/backend/locamem.py.实现了简单的内存缓存系统.
实现了带锁的内存缓存系统,不过有些瑕疵,好像是为了保证整体统一,不过这种统一难免让人诟病.
构造时内部声明了两个字典,一个存放序列化之后的缓存值,一个存放设置好了的过期时间,并且额外声明了一个异步锁.不过据我所知&Python&的多线程简直就是在自慰,&GIL&使然,你根本无法放开手脚,虽然值得解释器环境更加安全稳定,但是这种&伪多线程&很难让人提起兴趣.
在添加缓存时,获取缓存时,依然不辞幸苦给缓存值进行了序列化.作为的&dict&可能唯一的感受就是嫉妒羡慕恨.
在超出缓存最大值之后,&LocamemCache&将会删除所有与&_cull_frequency&取模为0的值.仅仅是为了使用&生成器表达式?!如果&_cull_frequency&为0时,则清空缓存库.但是当&_cull_frequency&为1时,同样会有清空缓存库的效果.
基于memcached的缓存系统,模块文件在&django/core/cache/backend/memcached.py.简单的对cmemcache或者memcache的封装.
这下django终于机灵了,没有在这里序列化了,因为这些动作会在memcache库中操作.
所有传入的&unicode字符&被转换为&utf-8,从缓存中获取的字符串则被转换为&unicode字符.
如果在&set&或者&add&方法中指定过期时间为&&不过期有可能是无效的,因为&MemcachedCache&在处理默认过期时间时采用了一个&逻辑或&处理,所以导致如果指定为&&被逻辑操作为&传递默认值.
他有一个额外的关闭连接方法(close),默认是不会自己调用的,需要在每次使用之后手动调用.
发布于 5年前,
阅读(138) | 评论(0) |
投票(0) | 收藏(1)
Django的缺点之一,就是它不支持AJAX。好吧,我知道这么一说又会有一群人反驳:Django有各种模块可以提供AJAX功能;写一个XML的view来实现AJAX;整合pyjams就什么功能都有了云云。嘛,都可以,我这也只是分享一个可行的方案,并不是唯一的。如果这个方案正好适合你的项目,那直接拿去用不是更省时间吗?
首先说一下现在项目的情况,前端工程师想用AJAX的方式(依赖于jQuery),通过POST/GET/PUT请求,提交JSON/XML/YAML格式的数据给后台数据库暴露出的一个API地址,以实现对后台数据的操作。如果在view里写一个函数来做比较麻烦,所以使用直接根据定义的model生成一个API。
Install&Begin
需要安装,&,&,&。最近因为某些原因国外的https访问经常会受到影响,所以附上下载链接。当然能用pip/easy_install之类的命令来安装最好,已经给出了模块名,这里不再重复写一次命令了。
还是和以前一样,先以最快的方式先把tastypie跑起来:
创建名为products应用为例,需要编辑products/models.py,新建products/api.py,然后编辑项目的urls.py: products/models.py范例用,超简单,没什么可说的。
from django.db import models class Product(models.Model): &&& name = models.CharField(max_length=16) &&& brand = models.CharField(max_length=32) &&& def __unicode__(self): &&&&&&& return self.title
products/api.py
from tastypie.resources import ModelResource from accounts.models import Product class ProductResource(ModelResource): &&& class Meta: &&&&&&& queryset = Product.objects.all() &&&&&&& resource_name = 'p' #可选,不设置的话默认为product
urls.py,引入在api中定义的ProductResource
from django.conf.urls.defaults import patterns, include, url from accounts.api import ProductResource urlpatterns = patterns('', &&& url(r'^api/', include(ProductResource().urls)), )
api定义完成,访问可以看到JSON格式的数据,如右图。因为我装了JSONView for chrome,所以输出的JSON格式比默认的友好一些。
models.py和urls.py都是基础配置,所以主要说一下api.py。这里使用了ModelResource而不是Django提供的Resource,这样就脱离了Django的ORM,提供了扩展到NOSQL的可能性。网上有一个名为tastymongo的项目,作者的目的似乎是想实现tastypie和mongodb的整合,但是一直没有更新,所以我们项目中是直接利用将这两者整合在一起。
POST & INSERT
以POST请求发送一个JSON数据给/api/p/这个地址实现数据的添加,在views.py中建立一个简单的函数,载入product/add.htm模板。html代码如下:
&html& & &head& &&& &title&Tastyapi&/title& & &/head& & &body& &&& &form& &&&&& &input type=&text& id=&brand& /& &&&&& &input type=&text& id=&name& /& &&&&& &input type=&button& onclick=&ajax_insert()& value=&insert& /& &&& &/form& & &script type=&text/javascript& src=&/ajax/libs/jquery/1.6.1/jquery.min.js& &&/script& & &script type=&text/javascript& &
& function ajax_insert() & { &&& var pname = $('#name').val(); &&& var pbrand = $('#brand').val(); &&& $.ajax({ &&&&& type : &POST&, //要插入数据,所以是POST协议 &&&&& url : &/api/p/&, //注意结尾的斜线,否则会出现500错误 &&&&& data : '{&name& : &'+pname+'&, &brand& : &'+pbrand+'&}', //JSON数据 &&&&& success: function(){ &&&&&&& alert('Submit Success') &&&&& }, &&&&& dataType : 'json', //在ie浏览器下我没有加dataTpye结果报错,所以建议加上 &&&&& contentType : 'application/json', &&& }); & } & &/script& & &/body& &/html&&
这个时候如果进行操作,会返回401错误,因为还没有进行用户验证。毕竟api涉及对后台数据的操作,如果不验证提交者的身份,对于网站安全来说不是什么好事。要实现验证唯一需要修改的是api.py文件:
from tastypie.resources import ModelResource from accounts.models import Product from tastypie.authentication import BasicAuthentication from tastypie.authorization import DjangoAuthorization class ProductResource(ModelResource): &&& class Meta: &&&&&&& queryset = Product.objects.all() &&&&&&& resource_name = 'p' &&&&&&& authorization = DjangoAuthorization() &&&&&&& #authorization = Authorization() &&&&&&& #authentication = BasicAuthentication()
设置只有只有登录的用户能通过API操作数据。L10的Authorization()验证方式是允许任何人使用这个API,L11的BasicAuthentication()是使用 HTTP的验证方式,就是我们常看到的,弹出一个难看的文本框,然后然你输入用户名和密码,这种验证方式不太友好,通常不会提供给普通用户使用。
PUT & DELETE
切换AJAX的请求为PUT或DELETE,可以进行更新或是删除操作,但要指定唯一的id或是slug:
&function ajax_delete() & { &&& $.ajax({ &&&&& type : &DELETE&, &&&&& url : &/api/p/1/&, #删除id为1的记录 &&&&& success: function(){ &&&&&&& alert('Submit Success') &&&&& }, &&& dataType : 'json', &&& contentType : 'application/json', &&& }); & }
更新操作使用PUT请求,可以直接,和添加操作相比,它要指定唯一的slug或是id;和删除操作相比,它要加上提交的data。
Django是一个开放的框架,虽然它已经解决了很多问题,但本身确实有很多做得不够好的地方,不妨碍我们去选择更适合自己的方案。tastypie很适合团队分工合作,即使是完全不懂Django的前端,一样能通过API进行操作,而且可以与NOSQL数据库配合使用,至于其他的功能和用法期待大家挖掘吧。
发布于 5年前,
阅读(581) | 评论(0) |
投票(0) | 收藏(3)}

我要回帖

更多关于 sessions什么意思 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信