📜 ⬆️ ⬇️

Confused notes about python and django

There are a few small notes / tips about python and django that don't pull on separate topics, so I publish everything at once.

Under the cut:



Django: simplify view code


The django documentation and tutorial examples usually write views like this:
')
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): #  . ,  form.save() # ... return HttpResponseRedirect('/thanks/') #  POST-   else: form = ContactForm() return render_to_response('contact.html', { 'form': form, }, context_instance=RequestContext(request)) 


Probably, this is correct - so to explain, so that a person can better understand what is happening. But in real life, this code is written exactly 2 times shorter:

 def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): #  . ,  form.save() # ... return redirect('url_name', param1=value) return direct_to_template(request, 'contact.html', {'form': form}) 


Chips:


Django: draw graphics


In the article about the admin panel I promised to tell you about the graphics, but all the hands did not reach, it turned out badly. Yes, and there is nothing special to tell, everything is too simple and “stupid” - the graphics are drawn through google charts. In this case, you can do without any libraries: we construct our own schedule to taste here (this is a semi-official tool from Google, it has a link from the api google charts help), and then insert the resulting string into the template and substitute variables for test values.

There is a very thin wrap over google charts: django-chart-tools . The essence is the same: to assemble a graph visually and replace variables, it’s just easier to maintain such graphs with django-chart-tools.

Data sampling can be done simply via django ORM, or, for convenience / speed, via django-qsstats-magic , depending on the task.

As a result (using django-chart-tools and django-qsstats-magic), the daily users' schedule can be displayed like this:

 #   qs = User.objects.filter(is_active=True) end = datetime.today() start = end-timedelta(days=30) #     data = QuerySetStats(qs, 'date_joined').time_series(start, end) values = [t[1] for t in data] captions = [t[0].day for t in data] 


then the variable values ​​and captions are passed to the template, and then we plot the graph in this way:

 {% load chart_tags %} {% bar_chart values captions «580x100» %} 


There are no restrictions on the number of hits from google charts image api, they are only asked to contact them if> 200 thousand hits per day are distributed so that they can distribute the load. So such graphics can be used not only in the admin panel.

Django: tests


Use to write django-webtest tests . I already wrote about this application, but since that time there has been one very important change: django-webtest now provides access to the context of the templates (just like the standard jung test client). Thanks Gregor Müllegger. Now you can write in this style:

  # ... response = page.forms['my-form-id'].submit().follow() assert response.context['user'] == self.user 


standard assertTemplateUsed also works.

django-webtest is better than any integration with twill, because they do not have access to the context of templates and full support for Unicode, and twill does not develop.

django-webtest is better than the standard test client, because provides a simple API (try to add a form with default values ​​through a standard test client). With the standard test client, it is also impossible to test the absence of a csrf-token (or a very black roundabout), and with django-webtest this is trivial (and even automatically). Use django-webtest)

There would be a pop-up plate with features: the django-webtest will have green check marks everywhere, and the twill and the standard test client will have red ones here and there. Even Ian Bicking thinks that django-webtest is “Cool!”.

Django: we write the application for Vkontakte


It is not just simple, but very simple. The difference from the usual sites - only in the way of registration and login users. Instead of django-registration, we install and configure django-vkontakte-iframe . Everything, now all visitors are registered and authorized django-users, otherwise you can develop a regular website. Is that what else to take care of js, to adjust the size of the iframe to the size of the page.

Python / Django: work with Russian


Who does not know, pymorphy is a library library for working with the Russian language. Able to morphological analysis and shoot from a cannon on sparrows: for example, to incline words from the base (or simple phrases) directly in the django template or to put them in the right shape depending on the number - without explicitly listing all declination options.

pymorphy has grown from an article on Habré. I admit, the code was not good at first, because This was my first experience with both python and nlp (natural language processing). But the morphological analyzer was still written - and abandoned for a year.

At the beginning of this year, I resumed work on pymorphy and rewrote a whole lot there. In the spring, a “competition” of morphological analyzers was held at the Dialog-2010 conference. Very serious guys participated there, the results were checked by professional linguists. The pymorphy along the path “Morphology” coped best of all (most likely due to the fact that I just rolled out the work with compound words written with a hyphen). Also, pymorphy was the only participant who sent an analysis of the track with “different texts”. This is all about nothing says, but nice)

Python: a couple of tricks for laying out packages on pypi


1. In setup.py in long_description, you can use ReST markup. It is convenient to put the README.rst file next to the setup.py and then just specify
 long_description = open('README.rst').read() 
After that, on the project page on pypi there will immediately be help on it - it is simple, convenient, and in 90% eliminates the need for a hassle with separate documentation (there is also a remark - if it still seems that the package needs documentation with navigation, etc., then It is worth thinking - maybe the package is doing too much?).

2. There is a relatively little-known hack with setup.py. If the markup does not look like it was wanted, or fixed a typo, or classifier, then there is no need to make a new release to correct these errors: you can simply run ./setup.py register and the data will be ./setup.py register .

Python: decorators and with


Decorators and the with statement in python are often used for the same thing: perform some additional actions before or after a certain piece of code. And this means that you can write such a thing that can be used simultaneously as a decorator and as a context manager for with (for example, like this: gist.github.com/573536 ).

Django: accept payments on the site


If that, through django-robokassa and django-assist-ru made thousands of purchases in production,> million rubles.

Write more who uses what, add to the list.

Python / Django: we show Yandex.kart on the site


To avoid messing with geocoding and caching, you can use the yandex-maps application.

Wow, we will assume that all.

Source: https://habr.com/ru/post/105627/


All Articles