Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
uwsgi and uid
So recently, I moved home for this blog. It used to be on AWS EC2 and is now on Digital Ocean. I wanted to start from scratch so I started on a blank new Ubuntu 14.04 and later rsync'ed over all the data bit by bit (no pun intended). When I moved this site I copied the /etc/uwsgi/apps-enabled/peterbecom.ini file and started it with /etc/init.d/uwsgi start peterbecom. The settings were the same as before: # this is /etc/uwsgi/apps-enabled/peterbecom.ini [uwsgi] virtualenv = /var/lib/django/django-peterbecom/venv pythonpath = /var/lib/django/django-peterbecom user = django master = true processes = 3 env = DJANGO_SETTINGS_MODULE=peterbecom.settings module = django_wsgi2:application But I kept getting this error: Traceback (most recent call last): ... File "/var/lib/django/django-peterbecom/venv/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 182, in _cursor self.connection = Database.connect(**conn_params) File "/var/lib/django/django-peterbecom/venv/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) psycopg2.OperationalError: FATAL: Peer authentication failed for user "django" What the heck! I thought. I was able to connect perfectly fine with the same config on the old server and here on the new server I was able to do this: django@peterbecom:~/django-peterbecom$ source venv/bin/activate (venv)django@peterbecom:~/django-peterbecom$ ./manage.py shell Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from … -
Django 1.7 et écriture de tests, petites explorations
Je me suis enfin lancé dans l’écriture d’une app django gérant les badges (ou les succès si vous préférez). L’objectif étant de pouvoir réécrire de zéro histoires de rôlistes. L’idée était de tenter de faire une vraie app django, en mode réutilisable, histoire que peut-être des gens puissent trouver intéressant de l’utiliser. Je me suis retrouvé avec deux problèmes concernant mes tests : Souvent on gagne un badge quand on a créé suffisamment de chose (comme des checkin, des billets de blogs ou des contributions diverses). Sauf que je ne voulais pas créer dans mon app des models ne servant à rien, juste pour pouvoir en créer lors de mes tests. Je voulais pouvoir créer des badges se gagnant sur un critère du style ‘être venu un certain nombre de fois sur une URL.’ Donc mettre en place des décorateurs sur des vues. Mais là encore, je ne voulais pas avoir à créer des vues dans mon application rien que pour les tests. Au final, en lisant un peu de doc, j’ai réussi à faire ce que je voulais. Tester un décorateur sans créer des vues inutiles dans son app. Je savais déjà comment forger des requests avec la RequestFactory. … -
Shout-out to eventlog
If you do things with the Django ORM and want an audit trails of all changes you have two options: Insert some cleverness into a pre_save signal that writes down all changes some way. Use eventlog and manually log things in your views. (you have other options too but I'm trying to make a point here) eventlog is almost embarrassingly simple. It's basically just a model with three fields: User An action string A JSON dump field You use it like this: from eventlog.models import log def someview(request): if request.method == 'POST': form = SomeModelForm(request.POST) if form.is_valid(): new_thing = form.save() log(request.user, 'mymodel.create', { 'id': new_thing.id, 'name': new_thing.name, # You can put anything JSON # compatible in here }) return redirect('someotherview') else: form = SomeModelForm() return render(request, 'view.html', {'form': form}) That's all it does. You then have to do something with it. Suppose you have an admin page that only privileged users can see. You can make a simple table/dashboard with these like this: from eventlog.models import Log # Log the model, not log the function def all_events(request): all = Log.objects.all() return render(request, 'all_events.html', {'all': all}) And something like this to to all_events.html: <table> <tr> <th>Who</th><th>When</th><th>What</th><th>Details</th> </tr> {% for event in … -
Shout-out to eventlog
If you do things with the Django ORM and want an audit trails of all changes you have two options: Insert some cleverness into a pre_save signal that writes down all changes some way. Use eventlog and manually log things in your views. (you have other options too but I'm trying to make a point here) eventlog is almost embarrassingly simple. It's basically just a model with three fields: User An action string A JSON dump field You use it like this: from eventlog.models import log def someview(request): if request.method == 'POST': form = SomeModelForm(request.POST) if form.is_valid(): new_thing = form.save() log(request.user, 'mymodel.create', { 'id': new_thing.id, 'name': new_thing.name, # You can put anything JSON # compatible in here }) return redirect('someotherview') else: form = SomeModelForm() return render(request, 'view.html', {'form': form}) That's all it does. You then have to do something with it. Suppose you have an admin page that only privileged users can see. You can make a simple table/dashboard with these like this: from eventlog.models import Log # Log the model, not log the function def all_events(request): all = Log.objects.all() return render(request, 'all_events.html', {'all': all}) And something like this to to all_events.html: <table> <tr> <th>Who</th><th>When</th><th>What</th><th>Details</th> </tr> {% for event in … -
Passing parameters to Django admin action
This post will show how to pass parameters to custom Django admin actions. This post assumes that you have an idea of Django actions. Django provides a default admin action which is 'Delete selected rows'. Changelist page for all the models registered with admin has this action available. This action allows to select multiple rows and delete them in a single POST request. Problem statement We want to allow following Django action from admin. There is a model called Instrument. It has a field price Allow selecting multiple rows for this model and update the value of price for selected rows. Price should not be hardcoded. Admin should be able to enter the price. We should be able to achieve something like: Solution Setup the project first. Setup project Start a Django project inside virtual environment /tmp $ mkvirtualenv custom-actions (custom-actions)/tmp $ django-admin.py startproject actions (custom-actions)/tmp/actions $ python manage.py startapp instruments Writing the model in instruments/models.py class Instrument(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() def __unicode__(self): return self.name Add instruments to INSTALLED_APPS Run syncdb (custom-actions)/tmp/actions $ python manage.py syncdb Register this model with admin in instruments/admin.py from django.contrib import admin from .models import Instrument admin.site.register(Instrument) You should be able to … -
Travis and coveralls for private repo
Before we begin, i recommend you to read this first Continous integration with travis and coveralls.io for Django apps. Here is how .travis.yml example file looks like: language: python python: - 2.7 install: - pip install -r requirements.txt - pip install coveralls script: coverage run manage.py test after_success: coveralls Setting up coveralls for private repositories requires you to add just one more file .coveralls.yml. 1) Create a .coveralls.yml and make sure it resides in your project's root directory. 2) Add the following to this file: service_name: travis-pro repo_token: **** service_name is to specify where Coveralls should look to find additional information about your builds. You can get the repo_token from your repository's page on Coveralls, if you have the admin privileges. This is to tell which project on Coveralls your project maps to. Make sure your repo_token remains secret and do not add this to your public repository. 3) Add the file, commit it and make a git push. 4) If everything is OK you should see some thing like the below in your travis build: Submitting coverage to coveralls.io... Coverage submitted! Job #22.1 https://coveralls.io/jobs/54864565 Thats it now get a coverage badge from coveralls and add this badge in your … -
Ubuntu PPA madness
I'm going flipping insane. In ye olde days, when I was programming with the python CMS Plone, my dependencies were limited to python and PIL. Perhaps lxml. LXML was a pain to install sometimes, but there were ways around it. Working on OSX was no problem. Server setup? Ubuntu. The only thing you really had to watch in those days was your python version. Does this old site still depends on python 2.4 or is it fine to use 2.6? Plone had its own Zope database, so you didn't even need database bindings. Now I'm working on Django sites. No problem with Django, btw! But... the sites we build with it are pretty elaborate geographical websites with lots of dependencies. Mapnik, matplotlib, numpy, scipy, gdal, spatialite, postgis. And that's not the full list. So developing on OSX is no fun anymore, using a virtual machine (virtualbox or vmware) is a necessity. So: Ubuntu. But... ubuntu 12.04, which we still use on most of the servers, has too-old versions of several of those packages. We need a newer gdal, for instance. And a newer spatialite. The common solution is to use a PPA for that, like ubuntugis-stable. Now for some random … -
Using Arrow for Better Datetime
Learn how to be better at dealing with dates and times in python in a few short minutes. Working with dates and times in python is a lot easier than other languages, but can be convoluted and confusing. Arrow provides a convenient api for working with and manipulating dates and times. See what it takes to get started.Watch Now... -
Contributing Back to the Community - Django Cookbook
In the early beginning of year 2014, the IT book publishing company "Packt Publishing" contacted me with an interesting offer: to share my Django experience in a form of a book. I thought it might be a good challenge for me and also value for the Django community, as I had been working with Django for 7 years or so, and during that time there was quite a lot of knowledge gathered and used practically. So for the next 9 months on late evenings and weekends I was adapting some of the most useful code snippets and describing them in the book. The great staff from the Packt Publishing helped me to structure the content, make everything clear and understandable, and get the grammar correct. Finally, the book was released and it's called "Web Development with Django Cookbook". This book is written for intermediate or advanced Django web developers. When writing the book, my own purpose was not to fully cover every possible web development task, but rather to have enough useful bits of knowledge for those who seek information about web development with Django. The book was written in the format of recipes. There are over 70 recipes giving … -
Useful Shell Aliases For Python (and Django) Developers!
We use almost all same commands everyday. There are a handful of aliases for git & docker written by a few. But it seems no one has mentioned any aliases for python. I just made a handful of aliases so that I can type little bit less in terminal. Here are a few of them.alias py='python'alias ipy='ipython'alias py3='python3'alias ipy3='ipython3'alias wo='workon'alias pf='pip freeze | sort'alias pi='pip install'alias pun='pip uninstall'alias dj="python manage.py"alias drs="python manage.py runserver"alias dsh="python manage.py shell"alias dsm="python manage.py schemamigration"alias dmm="python manage.py makemigration"alias dm="python manage.py migrate"alias ddd="python manage.py dumpdata"alias dld="python manage.py loaddata"alias dt="python manage.py test"# Show all alias related pythonpya() { alias | grep 'python\|workon\|pip' | \ sed "s/^\([^=]*\)=\(.*\)/\1 => \2/"| sed "s/['|\']//g";}These are a few repeatedly used commands. It takes time even to get used to aliases. So I added pya function at the end. In case if you don't remember aliases or if you want to checkout what aliases related to python are present in your dot file, you can use it.Just add the above aliases to your .bashrc or .zshrc or whatever shell you are using and source it. That's it. Hpy alsng! -
Ultimate Front End Development Setup
Ultimate Front End Development Setup -
5 million votes and counting at Rockhall.com
5 million votes and counting at Rockhall.com -
django-html-validator
A couple of weeks ago we had accidentally broken our production server (for a particular report) because of broken HTML. It was an unclosed tag which rendered everything after that tag to just plain white. Our comprehensive test suite failed to notice it because it didn't look at details like that. And when it was tested manually we simply missed the conditional situation when it was caused. Neither good excuses. So it got me thinking how can we incorporate HTML (html5 in particular) validation into our test suite. So I wrote a little gist and used it a bit on a couple of projects and was quite pleased with the results. But I thought this might be something worthwhile to keep around for future projects or for other people who can't just copy-n-paste a gist. With that in mind I put together a little package with a README and a setup.py and now you can use it too. There are however some caveats. Especially if you intend to run it as part of your test suite. Caveat number 1 You can't flood htmlvalidator.nu. Well, you can I guess. It would be really evil of you and kittens will die. If … -
django-html-validator
A couple of weeks ago we had accidentally broken our production server (for a particular report) because of broken HTML. It was an unclosed tag which rendered everything after that tag to just plain white. Our comprehensive test suite failed to notice it because it didn't look at details like that. And when it was tested manually we simply missed the conditional situation when it was caused. Neither good excuses. So it got me thinking how can we incorporate HTML (html5 in particular) validation into our test suite. So I wrote a little gist and used it a bit on a couple of projects and was quite pleased with the results. But I thought this might be something worthwhile to keep around for future projects or for other people who can't just copy-n-paste a gist. With that in mind I put together a little package with a README and a setup.py and now you can use it too. There are however some caveats. Especially if you intend to run it as part of your test suite. Caveat number 1 You can't flood htmlvalidator.nu. Well, you can I guess. It would be really evil of you and kittens will die. If … -
Call for contributors – Stream-Framework 1.1
Reblog, from: Call for contributors – Stream-Framework 1.1 Share and Enjoy: -
Call for contributors - Stream-Framework 1.1
Today we’ve released Stream Framework 1.1. Development has been a bit slow pending the rename from Feedly to Stream-Framework. Fortunately the community is growing faster than ever. Many users of GetStream.io are looking at Stream Framework and vice versa. We would like to take this moment to encourage contributions. We’re actively accepting pull requests and appreciate all the help. Especially the python 3 support on the roadmap is something which you can easily get started with. So if you’ve been searching for a project to contribute to, now is a good time :) Roadmap Python 3 support (pending CQLEngine) Documentation improvements (see issues) Database backend to facilitate small projects Relevancy based feeds (far future) API similar to getstream.io to allow other languages to Stream Framework (far future) Let us know which features you guys are looking forward to! What’s new Since the last blogpost we’ve made the following changes: Ability to customize the Activity object used in feeds and aggregated activity used in aggregated feeds. Hooks to collect metrics Updated CQLengine and Python-Driver Ability to filter Redis & Cassandra feeds using the .filter syntax() Ability to order Redis using the .order syntax (Thanks Anislav) Redis improvements to counts (Again, many … -
We’re a Gold Sponsor of Multiple Template Engines for Django
One of the most common components in Django that is replaced by alternatives is templates. The reason is either or both performance and design related. While there are numerous template bridge libraries to support the use of Jinja2, Mako, and other template languages in Django, there is not a standard API. This is unfortunate, because one of the virtues of using Django is that we can share our efforts across third-party libraries. Fortunately, Django core developer, Aymeric Augustin has started a crowdfunding campaign to create first-class support for third-party template engines in Django. We’re excited! Two Scoops Press is proud to be a gold sponsor for Django core developer Aymeric Augustin’s Multiple Template Engines for Django campaign on Indiegogo. This is the last day of the campaign, so now’s your chance to show support as well. -
We’re a Gold Sponsor of Multiple Template Engines for Django
One of the most common components in Django that is replaced by alternatives is templates. The reason is either or both performance and design related. While there are numerous template bridge libraries to support the use of Jinja2, Mako, and other template languages in Django, there is not a standard API. This is unfortunate, because one of the virtues of using Django is that we can share our efforts across third-party libraries. Fortunately, Django core developer, Aymeric Augustin has started a crowdfunding campaign to create first-class support for third-party template engines in Django. We’re excited! Two Scoops Press is proud to be a gold sponsor for Django core developer Aymeric Augustin’s Multiple Template Engines for Django campaign on Indiegogo. This is the last day of the campaign, so now’s your chance to show support as well. -
We’re a Gold Sponsor of Multiple Template Engines for Django
One of the most common components in Django that is replaced by alternatives is templates. The reason is either or both performance and design related. While there are numerous template bridge libraries to support the use of Jinja2, Mako, and other template languages in Django, there is not a standard API. This is unfortunate, because one of the virtues of using Django is that we can share our efforts across third-party libraries. Fortunately, Django core developer, Aymeric Augustin has started a crowdfunding campaign to create first-class support for third-party template engines in Django. We’re excited! Two Scoops Press is proud to be a gold sponsor for Django core developer Aymeric Augustin’s Multiple Template Engines for Django campaign on Indiegogo. This is the last day of the campaign, so now’s your chance to show support as well. -
Introducing stream-django, our first framework integration
We are proud to announce the first release of Stream-Django, a python package to add activity feeds to Django applications. This package comes with built-in integration for Django models, out-of-the-box feed management and some template helpers to presenting feeds to your users. The package is available on Github, you can find a detailed explanation here. We also updated our example application to use stream-django. Tommaso -
Django runserver_plus with SSL and Firefox 33
So with version 33, Firefox did something rather annoying, they now use a more restrictive library that rejects connections to servers running older versions of SSL. On the one hand, this is pretty awesome because at some point we all need to grow up and start using modern encryption, but on the other, it can make development really difficult when all you really need a an SSL setup -- any SSL setup to make your local development environment Just Work. We've been using django-extenstion's runserver_plus feature, which is awesome because it includes a browser-based debugger and other really cool stuff, but also importantly, it supports the ability for you to run the Django runserver in SSL mode. This means that you can do stuff like: ./manage.py runserver_plus --cert=/tmp/temporary.cert And that's enough for you to be able to access your site over SSL: https://localhost:8000/ However, now that Firefox has thrown this monkeywrench into things, we spent far too much time today trying to figure out what was wrong and how to fix it, so I'm posting the answer here: Basically, you just need a better cert than the one django-extensions creates for you automatically. So, instead of just running --cert=/path/to/file and … -
Reading and writing binary STL files with Numpy
After seeing Sukhbinder’s implementation of reading STL files with Numpy I thought it would be a nice thing to have a simple STL class to both read and write the binary files. import struct import numpy class Stl(object): dtype = numpy.dtype([ ('normals', numpy.float32, (3, )), ('v0', numpy.float32, (3, )), ('v1', numpy.float32, (3, )), ('v2', numpy.float32, (3, )), ('attr', 'u2', (1, )), ]) def __init__(self, header, data): self.header = header self.data = data @classmethod def from_file(cls, filename, mode='rb'): with open(filename, mode) as fh: header = fh.read(80) size, = struct.unpack('@i', fh.read(4)) data = numpy.fromfile(fh, dtype=cls.dtype, count=size) return Stl(header, data) def to_file(self, filename, mode='wb'): with open(filename, mode) as fh: fh.write(self.header) fh.write(struct.pack('@i', self.data.size)) self.data.tofile(fh) if __name__ == '__main__': # Read from STL file stl = Stl.from_file('test.stl') # Increment the X axis by one stl.data['v0'][:, 0] += 1 stl.data['v1'][:, 0] += 1 stl.data['v2'][:, 0] += 1 # Write back to file stl.to_file('test.stl') Link to this post! -
Erste Hamburger Python Unconference
Am 29. und 30. November 2014 veranstalten die Python Usergroup Hamburg und der Fachschaftsrat Informatik der Uni Hamburg zusammen mit dem boot e.V. [1] die 1. Python Unconference Hamburg. Eingeladen sind alle Python-Entwickler aus Wissenschaft und Technik, Finance, BigData, Machine Learning und Webentwicklung vom Anfänger bis zum alten Hasen! Im Barcamp-Stil gibt es Vorträge und Diskussionen aus allen Bereichen der Python Welt. In den Pausen werden nicht nur Speisen und Getränke sondern auch viele Gelegenheiten zum direkten persönlichen Austausch geboten. Bis zum 15.10. gibt es noch Early Bird Tickets für 35,- Euro. Mehr Informationen gibt es unter www.pyunconf.de. [1]Der Verein BOOT - Best Of Open Technologies e.V. ist Träger der PHP Unconference Hamburg und der PHP Unconference Europe sowie auch der JS Unconference Hamburg und der Python Unconference Hamburg. Erfahrung in der Organisation solcher Veranstaltungen ist also vorhanden, auch wenn es sich um die erste Python Unconference handelt. -
Django中如何使用django-celery完成异步任务 (2)
在上一篇博文中, 我们介绍了如何在开发环境中使用Celery. 接下来我们介绍一下如何在部署环境使用Celery. 1. 简单设置 一个简单的Celery堆有一个queue和一个worker进程组成. 使用以下命令启动worker: python manage.py celery worker -B 以上命令是基于django-celery, 当然你也可以celery自身启动worker. 通常我们使用supervisord管理celery worker的启动和重启, 而不是使用手动的方式. supervisord的介绍我们会在今后的文章中作详细介绍. 现在我们只需要知道它是一款进程管理程序即可. 当然, 你也可以选择类似的系统, 例如init.d, upstart, runit或god等. "-B"参数告诉celery在启动worker时同时启动celery beat, 并使用统一进程, 以便执行定期任务. 在部署服务器上, 我们使用Redis或RabbitMQ作为broker. 而在这一简单的celery堆中, 我们用django数据库储存执行结果, 或干脆忽略结果都可. 2. 完整设置 如果简单设置无法满足我们的需要的话, 我们只需要做一些简单的改变就能完整设置Celery异步任务. 完整设置中, 我们使用多个queue来区分任务优先级. 每个queue我们配置一个不同concurrency设置的worker. beat进程也与worker进程分离出来. # 默认 queue python manage.py celery worker -Q celery # 高优先级 queue. 10个 workers python manage.py celery worker -Q high -c 10 # 低优先级 queue. 2个 workers python manage.py celery worker -Q low -c 2 # Beat 进程 python manage.py celery beat 注意, 其中high和low只是queue的名字, 并没有其他特殊意义. 我们通过为高优先级的queue配置高concurrency的worker, 使高优先级queue能够使用更多的资源. 同样的, 这些启动命令通过supervisor管理. 至于broker, 我们还是使用Redis或RabbitMQ. 而任务结果则可以储存在Redis或Memcached这些拥有高写入速度的系统中. 如果有必要, 这些worker进程可以移到其他服务器中, 但最好共享一个broker和结果储存系统. 3. 扩展性 我们不能一味的依靠增加额外的worker来提高性能, 因为每个worker都会占用一定的资源. 默认的concurrency设置是, 都多少CPU便创建多少worker, 并为每个worker创建一个新的进程. 将concurrency设置的太高则会很快的榨干服务器的CPU和内存资源. 对于I/O资源需求较大的任务, 我们则可以指定worker使用gevent或eventlet池, 而不是使用更多进程. 这一配置使用的内存资源会大大降低, 同时提升concurrency的性能. 需要注意的是, 但如果我们涉及到的library没有为greenlet打过补丁的话, 很有可能会阻塞所有的任务! 4. 注意 还有需要注意的是django的transaction. transaction根据django的版本和是否已web request形式传入有所不同, 所以你需要自己查阅相关的文档. -
Django中如何使用Celery完成异步任务 (1)
本篇博文主要介绍在开发环境中的celery使用,请勿用于部署服务器. 许多Django应用需要执行异步任务, 以便不耽误http request的执行. 我们也可以选择许多方法来完成异步任务, 使用Celery是一个比较好的选择, 因为Celery有着大量的社区支持, 能够完美的扩展, 和Django结合的也很好. Celery不仅能在Django中使用, 还能在其他地方被大量的使用. 因此一旦学会使用Celery, 我们可以很方便的在其他项目中使用它. 1. Celery版本 本篇博文主要针对Celery 3.0.x. 早期版本的Celery可能有细微的差别. 2. Celery介绍 Celery的主要用处是执行异步任务, 可以选择延期或定时执行功能. 为什么需要执行异步任务呢? 第一, 假设用户正发起一个request, 并等待request完成后返回. 在这一request后面的view功能中, 我们可能需要执行一段花费很长时间的程序任务, 这一时间可能远远大于用户能忍受的范围. 当这一任务并不需要立刻执行时, 我们便可以使用Celery在后台执行, 而不影响用户浏览网页. 当有任务需要访问远程服务器完成时, 我们往往都无法确定需要花费的时间. 第二则是定期执行某些任务. 比如每小时需要检查一下天气预报, 然后将数据储存到数据库中. 我们可以编写这一任务, 然后让Celery每小时执行一次. 这样我们的web应用便能获取最新的天气预报信息. 我们这里所讲的任务task, 就是一个Python功能(function). 定期执行一个任务可以被认为是延时执行该功能. 我们可以使用Celery延迟5分钟调用function task1, 并传入参数(1, 2, 3). 或者我们也可以每天午夜运行该function. 我们偏向于将Celery放入项目中, 便于task访问统一数据库和Django设置. 当task准备运行时, Celery会将其放入列队queue中. queue中储存着可以运行的task的list. 我们可以使用多个queue, 但为了简单, 这里我们只使用一个. 将任务task放入queue就像加入todo list一样. 为了使task运行, 我们还需要在其他线程中运行的苦工worker. worker实时观察着代运行的task, 并逐一运行这些task. 你可以使用多个worker, 通常他们位于不同服务器上. 同样为了简单起见, 我们这只是用一个worker. 我们稍后会讨论queue, worker和另外一个十分重要的进程, 接下来我们来动动手: 3. 安装Celery 我们可以使用pip在vietualenv中安装: pip install django-celery 4. Django设置 我们暂时使用django runserver来启动celery. 而Celery代理人(broker), 我们使用Django database broker implementation. 现在我们只需要知道Celery需要broker, 使用django自身便可以充当broker. (但在部署时, 我们最好使用更稳定和高效的broker, 例如Redis.) 在settings.py中: import djcelery djcelery.setup_loader() BROKER_URL = 'django://' ... INSTALLED_APPS = ( ... 'djcelery', 'kombu.transport.django', ... ) 第一二项是必须的, 第三项则告诉Celery使用Django项目作为broker. 在INSTALLED_APPS中添加的djcelery是必须的. kombu.transport.django则是基于Django的broker 最后创建Celery所需的数据表, 如果使用South作为数据迁移工具, 则运行: python manage.py migrate 否则运行: (Django 1.6或Django 1.7都可以) python manage.py syncdb 5. 创建一个task 正如前面所说的, 一个task就是一个Pyhton function. 但Celery需要知道这一function是task, 因此我们可以使用celery自带的装饰器decorator: @task. 在django app目录中创建taske.py: from celery import task @task() def add(x, y): return x + y 当settings.py中的djcelery.setup_loader()运行时, Celery便会查看所有INSTALLED_APPS中app目录中的tasks.py文件, 找到标记为task的function, 并将它们注册为celery task. 将function标注为task并不会妨碍他们的正常执行. 你还是可以像平时那样调用它: z = add(1, 2). 6. 执行task 让我们以一个简单的例子作为开始. 例如我们希望在用户发出request后异步执行该task, 马上返回response, 从而不阻塞该request, 使用户有一个流畅的访问过程. 那么, 我们可以使用.delay, 例如在在views.py的一个view中: from myapp.tasks import add ... add.delay(2, 2) ... Celery会将task加入到queue中, 并马上返回. 而在一旁待命的worker看到该task后, 便会按照设定执行它, 并将他从queue中移除. 而worker则会执行以下代码: import myapp.tasks.add myapp.tasks.add(2, 2) 7. 关于import 这里需要注意的是, 在impprt task时, 需要保持一致. 因为在执行djcelery.setup_loader()时, task是以INSTALLED_APPS中的app名, 加.tasks.function_name注册的, 如果我们由于python path不同而使用不同的引用方式时(例如在tasks.py中使用from myproject.myapp.tasks import add形式), Celery将无法得知这是同一task, 因此可能会引起奇怪的bug. …