Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Разъяснения Рассела
В недавнем посте с интервью с Джанго-разработчиками меня попросили уточнить, что имел в виду Рассел Кит-Маги, говоря про WSGI и валидацию моделей. У меня и у самого эти два пункты вызывали недопонимание, поэтому я попросил его их разъяснить. Вот перевод его ответа: Так, первый пункт: WSGI на самом деле хорошо заточен под классическую задачу "показать целиком веб-страницу". Он был спроектирован как самый простой рабочий "наименьший общий делитель" — фактически Питоний вариант CGI. То есть он очень хорошо спроектирован для веба 1995 года, но не настолько хорошо для веба 2011, с его long polling'ом и другими вкусными push-технологиями и серверными плюшками, которые теперь используются повсеместно. Многие уже написали гораздо подробней и об этой проблеме, и о WSGI вообще: http://lucumr.pocoo.org/2011/7/27/the-pluggable-pipedream/ http://www.b-list.org/weblog/2009/aug/10/wsgi/ На самом деле, это не обязательно является проблемой самой Джанго — она использует WSGI всего лишь как API для общения с сервером. Можно использовать любой другой интерфейс, если он кем-то специфицирован. Например, Джанго поддерживает fcgi и mod_python — последний хоть и устарел, но показывает, что метод, который используется для запуска Джанго не зависит от Джанго, как библиотеки по обслуживанию веб-запросов. Я также должен заметить, что на WSGI тоже возможно реализовать long poll и другие push-технологии, просто это спецификация не обязательно лучше … -
Django Facebook 3.2 – Simple image upload and wall posts
Most of the Facebook examples are written in PHP and unfortunately for us they always seem so damn simple. I think the Python libraries should allow you to write more elegant code and the new version of Django Facebook let’s you do just that. Much of the new found simplicity comes from the facebook_required decorator. This decorator is similar to login_required, but instead checks the Facebook permissions given to you. Writing the input of a form to someone’s wall is now as simple as this: @facebook_required(scope='publish_stream') def wall_post(request): fb = get_persistent_graph(request) message = request.POST.get('message') fb.set('me/feed', message=message) messages.info(request, 'Posted the message to your wall') return next_redirect(request) Another example would be uploading some photos to a user’s timeline: @facebook_required(scope='publish_stream,user_photos') def image_upload(request): fb = get_persistent_graph(request) pictures = request.POST.getlist('pictures') for picture in pictures: fb.set('me/photos', url=picture, message='the writing is one The ' 'wall image %s' % picture) messages.info(request, 'The images have been added to your profile!') return next_redirect(request) As you can see the syntax is very straightforward. You no longer have any technical excuse against integrating Facebook. More examples and installation instructions can be found on Django Facebook’s github. Share and Enjoy: -
Using Haml in Django Projects
-
Beating Google With CouchDB, Celery and Whoosh (Part 8)
In the previous seven posts I’ve gone through all the stages in building a search engine. If you want to try and run it for yourself and tweak it to make it even better then you can. I’ve put the code up on GitHub. All I ask is that if you beat Google, you give me a credit somewhere. When you’ve downloaded the code it should prove to be quite simple to get running. First you’ll need to edit settings.py. It should work out of the box, but you should change the USER_AGENT setting to something unique. You may also want to adjust some of the other settings, such as the database connection or CouchDB urls. To set up the CouchDB views type python manage.py update_couchdb. Next, to run the celery daemon you’ll need to type the following two commands: python manage.py celeryd -Q retrieve python manage.py celeryd -Q process This sets up the daemons to monitor the two queues and process the tasks. As mentioned in a previous post two queues are needed to prevent one set of tasks from swamping the other. Next you’ll need to run the full text indexer, which can be done with python manage.py … -
Open sourcing your Django site
This is the first in series of posts, focusing on issues around open sourcing your Django site and data privacy in Django. A lot of people focus on open sourcing their Django libraries, but at Mozilla we open source the entire site. Releasing your entire source code can lead to a few problems, firstly let’s [...] -
Open sourcing your Django site
This is the first in series of posts, focusing on issues around open sourcing your Django site and data privacy in Django. A lot of people focus on open sourcing their Django libraries, but at Mozilla we open source the entire site. Releasing your entire source code can lead to a few problems, firstly let’s look at your Django settings file. Separating your settings All Django sites come with a settings.py file. This file contains some key settings that you should not be releasing to the general public, such as database configuration and the secret key. The simple way to do this is have another file that contains the secret settings and then import it from settings.py. For example include this at the bottom of your settings.py: All your sensitive settings can now kept in that local file on your server and should not be published as part of your site code. This file will override the base settings file. There are plenty of other examples on different ways to do this. You can do it in manage.py, or turn your settings.py into a folder that Python can import. Make sure that you ignore your settings_local.py file in your source … -
PEP712 - Proposal to make unittest2 more accurate
PEP712 - Proposal to make unittest2 more accurate -
Generar arxius xls amb Python II
A l'article anterior havíem fet un petit "hello world" en format xls, ara toca fer alguna cosa més de profit, així que veurem com podem generar un full de càlcul a partir de dades. En altres temps, quan donava formació ofimàtica, un dels exercicis que feia fer als alumnes quan tocava el tema de les fulles de càlcul era el de fer una taula de multiplicar, serveix per perdre la por a la cosa aquesta dels nombres i mostra els conceptes fonamentals, ara podem fer el mateix. Per no fer-ho molt complicat anem per la taula del dos #!/usr/bin/env python #-*- coding: UTF-8 -*- import xlwt fmt = xlwt.easyxf h1 = fmt('font: name Arial, height 200, bold on;') wbk = xlwt.Workbook() full = wbk.add_sheet('Taula del 2') full.write(0, 0, "Taula del 2", h1) for x in range(1, 11): full.write(x, 0, 2) full.write(x, 1, "x") full.write(x, 2, x) full.write(x, 3, "=") full.write(x, 4, xlwt.Formula('A%s*C%s' % (x+1, x+1))) wbk.save('taula.xls') Podem veure com hem creat fàcilment una fórmula per a fer la multiplicació. També podem veure com per posar les fórmules hem de tenir en compte que s'ha de fer en la notació de files i columnes pròpia de les fulles de càlcul, és … -
Fabric - A Deployment Tool for Rubyists and Pythonists Alike
If you're coming from the Ruby/Rails world, the industry standard tool for deployment is clearly Capistrano. In some cases, though, using Fabric might make more sense. If you've got a simple web app and want to try something different for deployment, have a look at Fabric. It's a terse, lightweight Python deployment tool and a good alternative to Capistrano. Most importantly, it's SUPER EASY to learn and you don't need ANY Python experience.I like how Fabric's tutorial shows a version-control-agnostic deployment pattern. The fabfile is part of the project we want to deploy, and whatever is in our project directory will be deployed. With this pattern, Fabric doesn't need any information about our version control system or repository.For example, I use git for most of my projects. If I'm running the master branch on my development machine and want to deploy master, I just run$ fab deployWhat if I want to deploy my release branch instead of the master branch? I just do the following:$ git checkout my-release-branch$ fab deploySuper easy. We can manage the code we're deploying with the tools already built in to our version control system; we don't have to implement those controls again with our deployment … -
Custom Date Formats in the Django Admin
For better or for worse, subclassing Django components to add custom functionality is a common technique. The workflow usually goes something like this:Subclass a django componentOverride a specific methodSet some custom configuration options in the methodCall super() For our Django 1.1 app, we needed to customize the behavior of a DateField so it would accept dates entered in the standard US format, MM-DD-YYYY, instead of the default behavior, YYYY-MM-DD. We'll create a new field called USADateField.First, let's add a new module to our app, fields.py:In fields.py, subclass the Datefield form, adding the MM-DD-YYY format to the tuple of default formats:class USADateFormField(forms.DateField): def __init__(self, *args, **kwargs): kwargs.update({'input_formats': ("%m-%d-%Y",)+DEFAULT_DATE_INPUT_FORMATS}) super(USADateFormField, self).__init__(*args, **kwargs)Then, subclass the django model DateField to use the new USADateFieldForm:class USADateField(models.DateField): def formfield(self, **kwargs): kwargs.update({'form_class': USADateFormField}) return super(USADateField, self).formfield(**kwargs)When you're done, your new module will look like this:Finally, import fields in your models.py module and use it! Your model might look something like this:class Appointment(models.Model): scheduled_date = USADateField(blank=True)I like approaches like this, which push logic back into the models. The functionality would be tougher to test and maintain if we wrote custom front-end code for the field. -
Tutorial: My Fabric Presentation from RIRUG
Slides are up from my presentation during the June meeting of the RI Ruby Users Group!Fabric: A Capistrano AlternativeView more presentations from Panoptic Development, Inc.. -
Web App Security: Django and the OWASP Top 10
Security threat: Neutralized.At my company, Panoptic Development, we've built several applications for the healthcare industry. Since we often deal with sensitive patient medical data, web application security is a huge concern. Enter the OWASP Top 10, a collection of best practices for web application security.What's OWASP?From Wikipedia:The Open Web Application Security Project (OWASP) is an open-source application security project. The OWASP community includes corporations, educational organizations, and individuals from around the world. This community works to create freely-available articles, methodologies, documentation, tools, and technologies. What's the Top 10?From the OWASP Wiki:The OWASP Top Ten provides a powerful awareness document for web application security. The OWASP Top Ten represents a broad consensus about what the most critical web application security flaws are. Project members include a variety of security experts from around the world who have shared their expertise to produce this list. Versions of the 2007 were translated into English, French, Spanish, Japanese, Korean and Turkish and other languages. Translation efforts for the 2010 version are underway and they will be posted as they become available....As you help us spread the word, please emphasize:OWASP is reaching out to developers, not just the application security communityThe Top 10 is about managing risk, not just … -
Vídeo y diapositivas del taller de Introducción a Django
vasdf -
Beating Google With CouchDB, Celery and Whoosh (Part 7)
The key ingredients of our search engine are now in place, but we face a problem. We can download webpages and store them in CouchDB. We can rank them in order of importance and query them using Whoosh but the internet is big, really big! A single server doesn’t even come close to being able to hold all the information that you would want it to – Google has an estimated 900,000 servers. So how do we scale this the software we’ve written so far effectively? The reason I started writing this series was to investigate how well Celery’s integration with CouchDB works. This gives us an immediate win in terms of scaling as we don’t need to worry about a different backend, such as RabbitMQ. Celery itself is designed to scale so we can run celeryd daemons as many boxes as we like and the jobs will be divided amongst them. This means that our indexing and ranking processes will scale easily. CouchDB is not designed to scale across multiple machines, but there is some mature software, CouchDB-lounge that does just that. I won’t go into how to get set this up but fundamentally you set up a proxy … -
Speeding up a Django web site without touching the code
I’ve recently been tweaking my server setup for a Django 1.3 web site with the goal of making it a bit faster. Of course, there is a lot of speed to gain by improving e.g. the number of database queries needed to render a web page, but the server setup also has an effect on the web site performance. This is a log of my findings. All measurements have been done using the ab tool from Apache using the arguments -n 200 -c 20, which means that each case have been tested with 20 concurrent requests up to 200 requests in total. The tests was run from another machine than the web server, with around 45ms RTT to the server. This is not a scientific measurement, but good enough to let me quickly test my assumptions on what increases or decreases performance. The Django app isn’t particularly optimized in itself, so I don’t care much about the low number of requests per second (req/s) that it manages to process. The main point here is the relative improvement with each change to the server setup. The baseline setup is a Linode 1024 VPS (Referral link: I get USD 20 off my … -
Using dev_appserver with Python 2.7 on App Engine
Starting with SDK 1.6.0 the App Engine fully supports Python 2.7. This article originally described a workaround for getting Python 2.7 running on SDK 1.5.5. Now it only describes how to port your app.yaml and request handlers to Python 2.7. The following instructions work with any WSGI-compliant web framework. I'll explain how to use Python 2.7 with djangoappengine/Django-nonrel at the end of this post. Yes, Django-nonrel works with Python 2.7 on App Engine. This blog (All Buttons Pressed) is already running on Python 2.7 with threadsafe: yes. Let's start with a simple app.yaml for Python 2.5: application: yourappid version: 1 runtime: python api_version: 1 handlers: - url: /.* script: handler.py The handler.py file looks like this: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # This can be any WSGI handler. Here we just use webapp. application = webapp.WSGIApplication(...) def main(): run_wsgi_app(application) if __name__ == '__main__': main() In order to use Python 2.7 you have to change your app.yaml like this: application: yourappid version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /.* script: handler.application Here we've changed the runtime to python27, added threadsafe: yes and modified the last line (script) to point to the WSGI handler directly … -
Generar arxius xls amb Python I
Una de les coses que volia que l'aplicació de gestió de comunitat de propietaris que fem és la de tenir algun tipus de via per a poder exportar la informació introduïda. D'aquesta manera el client no està captiu i les seves dades són realment seves, però a més també volia que aquesta informació es presentàs de manera que també pogués ser útil. El format csv està prou bé, però és massa simple a l'hora de presentar les dades. Necessitava quelcom del format del qual fora prou potent per poder aplicar estils i format bàsic, i al mateix temps que no implicàs una despesa addicional per al client. Cercant, cercant vaig arribar a la llibreria xlwt. Aquesta llibreria permet crear fitxers en format xls (Excel) d'una manera prou senzilla i ràpida com per a ser just el que necessitàvem. El format es pot llegir tant mitjançant aplicacions privatives, que de d'aquí no recomanaré, o des d'aplicacions lliures com l'OpenOffice o LibreOffice. Per a qui vulgui saber-ho tot podeu fer una ullada al codi font, però si us conformau amb un poquet menys, podeu llegir-vos el tutorial. Si voleu anar per feina podeu seguir llegint i us ne faré cinc cèntims de … -
Announcing the Yipit Django Blog: Sharing Everything We’re Learning
Yipit has been using Django since its inception nearly two years ago. If it wasn’t for a modern web framework like Django, we probably wouldn’t exist. Two years and hundreds of thousands of users later, we’ve gotten deep into the core of Django and many of the contributed packages. Our goal now is to truly master Django. While one can learn a lot by doing, we tend to believe that you can learn even more by teaching what you’ve learned. Accordingly, we’re going to be spending significant time sharing what we’ve learned and are learning about using and scaling Django. Topics We Will Cover Some of the topics we will be regularly discussing on our new Yipit Django blog include: System configurations: Using Chef and Fabric to deploy our Github-hosted code to Ubuntu servers on Amazon ec2. Running Gunicorn as the application server. Database Migrations: South handling model changes and generating appropriate migrations. Data Storage: A combination of MySQL, Memcache, and MongoDB for storing our data Queueing Tasks: Celery for queueing asynchronous processes. Amazon’s SQS to manage the underlying queue. Templating: Inheritance and custom inclusion tags. Testing: Automated testing tools including Nose, Splinter, and Lettuce We hope that by sharing … -
(Dutch) Python/Django vacature in Utrecht
-
I want to solve the uploads problem
Making file uploads is a frequent, but yet to be solved properly task. I believe we can, and should, do better. For some time now we've been working on a web service which handles file uploads for you, my fellow web developer. -
Postgres and Django
Frank Wiles gave a great talk [Secrets of PostgreSQL Performance][SoPP] ## Don't do dumb things * Dedicate a single server to your database * Only fetch what you need ## Do smart things * cache everything * limit number of queries ## Tuning * shared\_buffers : 25% of available RAM * effective\_cache\_size : OS disk cache size * work_mem : in-memory sort size ### Less important * wal\_buffers : set to 16MB * checkpoint\_segments : at least 10 * maintenance\_work\_mem : 50MB for every GB of RAM Can also transactionally turn on grouping of transactions. ## Hardware * As much RAM as you can afford - fit whole db if you can. * Faster disks. - Disk speed is important - RAID5 is bad - RAID-1+0 is good - WAL on own disk → 4x write performance * CPU speed - unlikely to be the limiting factor. ## Other * use pg_bouncer to pool connections * use tablespaces to move tables/indexes onto other disks + ie, indexes on fastest disk + stuff that might run in background and hit only specific tables that are not used by other bits [SoPP]: http://blip.tv/djangocon/secrets-of-postgresql-performance-5572403?utm\_medium=twitter&utm\_source=twitterfeed -
I got lots of "Solid Django" book feedback
-
Разъяснения Рассела
В недавнем посте с интервью с Джанго-разработчиками меня попросили уточнить, что имел в виду Рассел Кит-Маги, говоря про WSGI и валидацию моделей. У меня и у самого эти два пункты вызывали недопонимание, поэтому я попросил его их разъяснить. Вот перевод его ответа: Так, первый пункт: WSGI на самом деле хорошо заточен под классическую задачу "показать целиком веб-страницу". Он был спроектирован как самый простой рабочий "наименьший общий делитель" — фактически Питоний вариант CGI. То есть он очень хорошо спроектирован для веба 1995 года, но не настолько хорошо для веба 2011, с его long polling'ом и другими вкусными push-технологиями и серверными плюшками, которые теперь используются повсеместно. Многие уже написали гораздо подробней и об этой проблеме, и о WSGI вообще: http://lucumr.pocoo.org/2011/7/27/the-pluggable-pipedream/ http://www.b-list.org/weblog/2009/aug/10/wsgi/ На самом деле, это не обязательно является проблемой самой Джанго — она использует WSGI всего лишь как API для общения с сервером. Можно использовать любой другой интерфейс, если он кем-то специфицирован. Например, Джанго поддерживает fcgi и mod_python — последний хоть и устарел, но показывает, что метод, который используется для запуска Джанго не зависит от Джанго, как библиотеки по обслуживанию веб-запросов. Я также должен заметить, что на WSGI тоже возможно реализовать long poll и другие push-технологии, просто это спецификация не обязательно лучше … -
Utilizar javascript o CSS en el admin de Django
Es realmente sencillo utilizar javascript o CSS propio en el sitio de administración de nuestro proyecto Django. Para ello podemos añadir en nuestros ModelAdmin los archivos JS o CSS que necesitemos utilizando la clase Media en los modelos de administración... -
Kiwi PyCon, DjangoCon US, and PyCodeConf Recap
I just got back from a long conference circuit, attending and speaking at PyCon Australia, Kiwi PyCon, DjangoCon US, and PyCodeConf. It was a ton of work, but it was a blast. I got to blog about PyCon Australia already, but then the time in between the other conferences was just a bit too hectic to blog. Kiwi PyCon 2011 I gave the opening keynote speech at Kiwi PyCon in Wellington, New Zealand. The talk was meant to be mildly provocative but in an inspiring, "go out and code" kind of way. Kiwi PyCon 2011 - Audrey Roy Keynote Speech View more presentations from Audrey Roy The Pythonistas of New Zealand are amazing. I met more Twisted devs than I've ever met in my life, attended tons of hardcore Python talks by women, and ones by men too, and learned all sorts of new things. I was also blown away by the hospitality of the conference organizers, particularly Tim McNamara and Richard Shea. After the conference, I spent a couple of days going around the countryside and southern island coastal towns with Danny. It was spectacular. DjangoCon US 2011 I co-presented the Django Package Thunderdome with Daniel Greenfeld. Here …