Päiväcirja

Subscribe to RSS feed

Posts tagged with "python"

Python: usage in enterprise environment

,

Flask sessions and unicode_literals

, ,

If you had tried to use Flask sessions and got something like that:

  File "/usr/lib64/python2.7/site-packages/flask/app.py", line 889, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/lib64/python2.7/site-packages/flask/app.py", line 871, in wsgi_app
    with self.request_context(environ):
  File "/usr/lib64/python2.7/site-packages/flask/app.py", line 836, in request_context
    return _RequestContext(self, environ)
  File "/usr/lib64/python2.7/site-packages/flask/ctx.py", line 33, in __init__
    self.session = app.open_session(self.request)
  File "/usr/lib64/python2.7/site-packages/flask/app.py", line 431, in open_session
    secret_key=key)
  File "/usr/lib64/python2.7/site-packages/werkzeug/contrib/securecookie.py", line 308, in load_cookie
    return cls.unserialize(data, secret_key)
  File "/usr/lib64/python2.7/site-packages/werkzeug/contrib/securecookie.py", line 255, in unserialize
    mac = hmac(secret_key, None, cls.hash_method)
  File "/usr/lib64/python2.7/hmac.py", line 133, in new
    return HMAC(key, msg, digestmod)
  File "/usr/lib64/python2.7/hmac.py", line 72, in __init__
    self.outer.update(key.translate(trans_5C))


...you might be obscured. Fear not! The reason may lurk in

from __future__ import unicode_literals


Just declare your SECRET_KEY as `bytes` object and get happy again!

SECRET_KEY = b'smthverrysekret'

Python: вложенный итератор / nested iterator

, ,

Просто образчик вложенного итератора на Python, через рекурсивное выражение yield.
Just a (probably) useful examle of nested Python generator written in Python using recursive yield expression.

Read more...

Tabs and spaces

, ,

That's quite old and well-known, of course, but I now have to deal with code like that (count the spaces!):
class c_integral_type(c_type):
    def __init__(self, name, format, min, max):
       c_type.__init__(self, name, struct.calcsize(format))

or like that (MyOpera replaces tabs, so believe my comments):
    def genMemList( self, members ):              # indented with 4 spaces
#        self.append( '\tdef members(self):\n' )  # indented with one <Tab>

So…




Oh noes! That's what I had to deal with:

  % pylint buratino
   .......
Your code has been rated at -1.79/10


My code isn't perfect, I'd be first to agree, but it scores 7/10, and it's positive 7, mind you!
Bloody hell. So, back to work then

psycopg2 возвращает кортеж из строки / psycopg2 returns tuples of string

, , ,

Игрался я сегодня с базой на PostgreSQL (v8.3, если кому интересно) из Python посредством psycopg2, но внезапно застрял, да как-то неожиданно. Вылез в оболочку bpythonа и узрел…
>>> cur.execute('''SELECT (parent, level) FROM "MsgElems" WHERE msg_id=1;''')
>>> cur.fetchone()
('(0,1)',)
SELECT возвращает кортеж из строки, именно одной строки. Вот это сюрприз. Ни в Python DBAPI PEP, ни в psycopg docs я ничего не нашёл умного, загрустил уже, но потом в голову пришла гениальная (как обычно) идея:
>>> cur.execute('''SELECT parent, level FROM "MsgElems" WHERE msg_id=1;''')
>>> cur.fetchone()
(0, 1)
Вот такие пироги, остерегайтесь. А я тем временем попытаюсь выяснить, что это за ерунда, да и ерунда ли вообще.
Today I was fiddling with PostgreSQL (v8.3, if anyone is interested) database from Python using famous psycopg2, but suddenly got stuck in unexpected place. Had switched to bpython shell I saw the following:
>>> cur.execute('''SELECT (parent, level) FROM "MsgElems" WHERE msg_id=1;''')
>>> cur.fetchone()
('(0,1)',)
SELECT returned tuple of string, one string. Now that's what I call unexpected… I didn't find anything neither in Python DBAPI PEP nor psycopg docs, but after some time a bright idea came:
>>> cur.execute('''SELECT parent, level FROM "MsgElems" WHERE msg_id=1;''')
>>> cur.fetchone()
(0, 1)
Watch out. Meanwhile I'll try to find out, what triggers such weird behaviour, and if it is weird at all.

Пишешь код и видишь результат / Change the code and see the result

, ,

Пришла мне тут в голову интересная идея. Нужно написать генератор кода на C++ (по данным, вытягиваемым из базы данных), так что я установил Jinja2, навострил текстовые редакторы и подумал: «А не будет ли круто сразу видеть результат, прямо по ходу написания кода? Зачем мне два монитора, в конце концов — на одном буду писать, а второй пусть результат кажет.»
An interesting idea came to me several days ago. I have to write C++ code generator (sourcing data from SQL database), so I installed Jinja2, sharpened text editors and then asked myself: „Wouldn't it be beautiful to see the result just as I type Python code, portion by portion? There's a use for two monitors: the first one displays coding, the second one keeps freshly generated result always ready for review.“

Read more...

Matplotlib

, , ,

В помощь начинающим использовать рисовательную библиотеку Matplotlib: тамошняя документация просторна и обширна, но, к сожалению, довольно запутана. Так что после овладения основами рекомендую перейти к галерее примеров, где при некотором навыке можно найти не просто кучу полезных примеров, но и вычленить интересующие элементы.
If you plan to use Matplotlib plotting library, remember, that it has vast, but not-so-well organized documentation, so when you feel yourself familiar with MPL basics, move to examples gallery to find illustrated howtos.