Search This Blog

Monday, November 24, 2014

django project + gunicorn + supervisord + logrotate

/etc/supervisord.conf

[supervisord]
http_port=/var/tmp/supervisor.sock
logfile=/var/log/supervisor/supervisord.log
logfile_maxbytes=50MB
logfile_backups=20
loglevel=info
pidfile=/var/run/supervisord.pid
nodaemon=false
minfds=1024
minprocs=200

[supervisorctl]
serverurl=unix:///var/tmp/supervisor.sock

[program:guni_prj]
command=/usr/bin/gunicorn prj.wsgi -c /opt/prj/gunicorn.conf.py
directory=/opt/prj
user=prjuser
autostart=true
autorestart=true
log_stdout=true
log_stderr=true
#redirect_stdout=true
redirect_stderr=true
logfile=/var/log/supervisor/guni_prj.log
logfile_maxbytes=50MB
logfile_backups=20


/opt/prj/gunicorn.conf.py

bind = ['127.0.0.1:8090']
workers = 2
worker_class = 'gevent'
user = 'prjuser'
group = 'prjgroup'
daemon = False

import os
chdir = os.path.dirname(os.path.abspath(__file__))

# logging.handlers.WatchedFileHandler  # python logging file handler, safe for logrotate scripts

# logconfig = '%s/gunicorn.log.conf' % os.path.dirname(os.path.abspath(__file__))  # path to standart logging conf
# accesslog = '-'  # logging to stderr
# errorlog = '-'  # logging to stderr

# accesslog = '/var/log/prj/guni_prj_access.log'  # simple logging to file
# errorlog = '/var/log/prj/guni_prj_error.log'  # simple logging to file


/etc/logrotate.d/supervisor

/var/log/supervisor/*.log {
    missingok
    rotate 60
    daily
    compress
    delaycompress
    notifempty
    postrotate
        /bin/kill -SIGUSR2 $(cat /var/run/supervisord.pid 2>/dev/null) 2>/dev/null
    endscript
}


If you dont want use supervisord, gunicorn can write logs by it self (with standard logging)
Don't forget set "logconfig" option in gunicorn configuration
Logging config for example:

 /opt/prj/gunicorn.log.conf

[loggers]
keys=root, gunicorn.error, gunicorn.access

[handlers]
keys=console, error_file, access_file

[formatters]
keys=generic, access

[logger_root]
level=INFO
handlers=console

[logger_gunicorn.error]
level=INFO
handlers=error_file
propagate=0
qualname=gunicorn.error

[logger_gunicorn.access]
level=INFO
handlers=access_file
propagate=0
qualname=gunicorn.access

[handler_console]
class=StreamHandler
formatter=generic
args=(sys.stdout, sys.stderr, )

[handler_error_file]
class=logging.handlers.WatchedFileHandler
formatter=generic
args=('/var/log/prj/guni_prj_error.log',)

[handler_access_file]
class=logging.handlers.WatchedFileHandler
formatter=access
args=('/var/log/prj/guni_prj_access.log',)

[formatter_generic]
format=%(asctime)s [%(process)d] [%(levelname)s] %(message)s
datefmt=%Y-%m-%d %H:%M:%S
class=logging.Formatter

[formatter_access]
format=%(message)s
class=logging.Formatter



Wednesday, November 12, 2014

Python RESTful webservices with Python: Flask & Django solutions


Maximum results with minimum cost
- that’s ideal of all business and software development processes. How to get such a results in project with tight deadline and big performance expectations? Unfortunately there is no easy way: quality of software needs time and money, but .. choice of technologies, tools, solutions can be critical for product lifecycle. We can improve total time and cost of development and maintenance by choosing appropriate solutions.

The basis of effective software development is deep research and experience built on previous projects and  also mistakes. In our firm we carry out systematic research of technologies dedicated web and mobile development. We create internal projects and test to detect potential problems. Today I wont to present you short review of verified RESTful solutions for Python which really speed up development time.
Technology research and benchmarks
The picture below presents a benchmark of  peak JSON response per second for many technologies also Python. There are 3 Python approaches with the following results:
  • Django-stripped (Django without context processors and middlewares) – 13 269 per sec
  • Flask – 11 506 per sec
  • Django – 7122 per sec

Friday, August 8, 2014

Swap usage by PID


#> for i in `find /proc -maxdepth 1 -type d|xargs -i basename {}`; do echo -n "PID: $i SWAP: "; cat /proc/$i/smaps|fgrep Swap|awk '{s=s+$2}END{print s}'; done|sort -k4n

WINE + winetricks + WoT + Steam

Small note about installation and configuration process

#> WINEARCH=win32 winecfg

#> wget http://winetricks.org/winetricks
#> chmod +x winetricks
#> sudo cp winetricks /usr/local/bin

#> cd .wine/drive_c/
#> winetricks  d3dx9_36 vcrun2008 corefonts wininet msls31
#> winetricks  msxml3
#> winetricks  ie8

#> wine  WoT_internet_install_ru.exe
#> winecfg
Libraries:  Add: msvcp110 (native, buildin), msvcr110 (native, buildin)

#> wine msiexec /i SteamInstall.msi
#> wine Steam/Steam.exe -no-dwrite

Wednesday, August 6, 2014

SQLite...


Client configuration - rc file for sqlite3
~/.sqliterc
.headers ON
.timer ON



Create table with autoincrement primary key - id

CREATE TABLE table_name (id INTEGER PRIMARY KEY AUTOINCREMENT);


Order of field option important, don't swap it.

Friday, August 1, 2014

Xorg - adding undetected resolutions


Due to buggy hardware or drivers, your monitor's correct resolutions may not always be detected. For example, the EDID data block queried from your monitor may be incorrect.
If the mode already exists, but just isn't associated for the particular output, you can add it like this:
  • $ xrandr --addmode S-video 800x600
If the mode doesn't yet exist, you'll need to create it first by specifying a modeline:
  • $ xrandr --newmode <Mode``Line>
You may create a modeline using the gtf or cvt utility. For example, if you want to add a mode with resolution 800x600 at 60 Hz, you can enter the following command: (The output is shown following.)
  • $ cvt 800 600 60
    # 800x600 59.86 Hz (CVT 0.48M3) hsync: 37.35 kHz; pclk: 38.25 MHz
    Modeline "800x600_60.00"   38.25  800 832 912 1024  600 603 607 624 -hsync +vsync
Then copy the information after the word "Modeline" into the xrandr command:

$ xrandr --newmode "800x600_60.00"   38.25  800 832 912 1024  600 603 607 624 -hsync +vsync

Tuesday, July 29, 2014

X tuning

Some useful software for low level tuning X

xprop - WM classes and etc
xwininfo - window id*, position, style, owner and etc

 * xkill -id window_id_from_xwininfo

Friday, July 11, 2014

quote

You say you love rain, but you use an umbrella to walk under it.
You say you love sun, but you seek shelter when it is shining.
You say you love wind, but when it comes, you close your window.
So that's why I'm scared when you say you love me.


Bob Marley

Tuesday, June 10, 2014

small notes about django and etc


Just to remember, how to get project bse directory in django projects: 

settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print(BASE_DIR)



# How to tell django ignore requests like /favicon.ico and etc.

settings.py

import re
IGNORABLE_404_URLS = (
    re.compile(r'^/favicon\.ico$'),
    re.compile(r'^/robots\.txt$'),
)



# How to serve static files in dev

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = '/s/'
STATIC_ROOT = ''
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),  # <- only one static files directory
)



Some magic in widget configuration

widget = forms.Select(attrs = {'onchange': 'this.form.submit();'})



pip freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs pip install -U 

Monday, May 26, 2014

Self-signed SSL Certificate with OpenSSL


I lost previous post :(

openssl req -x509 -nodes -newkey rsa:2048 -days 3650 -keyout server.pem -out server.pem

Friday, May 16, 2014

Little bit more about snake



a

Common Mistake #1: Misusing expressions as defaults for function arguments

Python allows you to specify that a function argument is optional by providing a default value for it. While this is a great feature of the language, it can lead to some confusion when the default value is mutable. For example, consider this Python function definition:
>>> def foo(bar=[]):        # bar is optional and defaults to [] if not specified
...    bar.append("baz")    # but this line could be problematic, as we'll see...
...    return bar
A common mistake is to think that the optional argument will be set to the specified default expression each time the function is called without supplying a value for the optional argument. In the above code, for example, one might expect that calling foo() repeatedly (i.e., without specifying a bar argument) would always return 'baz', since the assumption would be that each time foo() is called (without a bar argument specified) bar is set to [] (i.e., a new empty list).
But let’s look at what actually happens when you do this:
>>> foo()
["baz"]
>>> foo()
["baz", "baz"]
>>> foo()
["baz", "baz", "baz"]
Huh? Why did it keep appending the default value of "baz" to an existing list each time foo() was called, rather than creating a new list each time?
The answer is that the default value for a function argument is only evaluated once, at the time that the function is defined. Thus, the bar argument is initialized to its default (i.e., an empty list) only when foo() is first defined, but then calls to foo() (i.e., without a bar argument specified) will continue to use the same list to which bar was originally initialized.
FYI, a common workaround for this is as follows:
>>> def foo(bar=None):
...    if bar is None:  # or if not bar:
...        bar = []
...    bar.append("baz")
...    return bar
...
>>> foo()
["baz"]
>>> foo()
["baz"]
>>> foo()
["baz"]

Common Mistake #2: Using class variables incorrectly

Consider the following example:
>>> class A(object):
...     x = 1
...
>>> class B(A):
...     pass
...
>>> class C(A):
...     pass
...
>>> print A.x, B.x, C.x
1 1 1
Makes sense.
>>> B.x = 2
>>> print A.x, B.x, C.x
1 2 1
Yup, again as expected.
>>> A.x = 3
>>> print A.x, B.x, C.x
3 2 3
What the $%#!&?? We only changed A.x. Why did C.x change too?
In Python, class variables are internally handled as dictionaries and follow what is often referred to as Method Resolution Order (MRO). So in the above code, since the attribute x is not found in class C, it will be looked up in its base classes (only A in the above example, although Python supports multiple inheritance). In other words, C doesn’t have its own x property, independent of A. Thus, references to C.x are in fact references to A.x.

Common Mistake #3: Specifying parameters incorrectly for an exception block

Suppose you have the following code:
>>> try:
...     l = ["a", "b"]
...     int(l[2])
... except ValueError, IndexError:  # To catch both exceptions, right?
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: list index out of range
The problem here is that the except statement does not take a list of exceptions specified in this manner. Rather, In Python 2.x, the syntax except Exception, e is used to bind the exception to the optional second parameter specified (in this case e), in order to make it available for further inspection. As a result, in the above code, the IndexError exception is not being caught by the except statement; rather, the exception instead ends up being bound to a parameter named IndexError.
The proper way to catch multiple exceptions in an except statement is to specify the first parameter as a tuple containing all exceptions to be caught. Also, for maximum portability, use the as keyword, since that syntax is supported by both Python 2 and Python 3:
>>> try:
...     l = ["a", "b"]
...     int(l[2])
... except (ValueError, IndexError) as e:  
...     pass
...
>>>

Common Mistake #4: Misunderstanding Python scope rules

Python scope resolution is based on what is known as the LEGB rule, which is shorthand for Local, Enclosing, Global, Built-in. Seems straightforward enough, right? Well, actually, there are some subtleties to the way this works in Python. Consider the following:
>>> x = 10
>>> def foo():
...     x += 1
...     print x
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'x' referenced before assignment
What’s the problem?
The above error occurs because, when you make an assignment to a variable in a scope, that variable is automatically considered by Python to be local to that scope and shadows any similarly named variable in any outer scope.
Many are thereby surprised to get an UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function. (You can read more about this here.)
It is particularly common for this to trip up developers when using lists. Consider the following example:
>>> lst = [1, 2, 3]
>>> def foo1():
...     lst.append(5)   # This works ok...
...
>>> foo1()
>>> lst
[1, 2, 3, 5]

>>> lst = [1, 2, 3]
>>> def foo2():
...     lst += [5]      # ... but this bombs!
...
>>> foo2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'lst' referenced before assignment
Huh? Why did foo2 bomb while foo1 ran fine?
The answer is the same as in the prior example, but is admittedly more subtle. foo1 is not making an assignment to lst, whereas foo2 is. Remembering that lst += [5] is really just shorthand for lst = lst + [5], we see that we are attempting to assign a value to lst (therefore presumed by Python to be in the local scope). However, the value we are looking to assign to lst is based on lst itself (again, now presumed to be in the local scope), which has not yet been defined. Boom.
Editor's note: want posts just like this delivered straight to your inbox? Subscribe below to receive our latest engineering articles.

Common Mistake #5: Modifying a list while iterating over it

The problem with the following code should be fairly obvious:
>>> odd = lambda x : bool(x % 2)
>>> numbers = [n for n in range(10)]
>>> for i in range(len(numbers)):
...     if odd(numbers[i]):
...         del numbers[i]  # BAD: Deleting item from a list while iterating over it
...
Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
IndexError: list index out of range
Deleting an item from a list or array while iterating over it is a faux pas well known to any experienced software developer. But while the example above may be fairly obvious, even advanced developers can be unintentionally bitten by this in code that is much more complex.
Fortunately, Python incorporates a number of elegant programming paradigms which, when used properly, can result in significantly simplified and streamlined code. A side benefit of this is that simpler code is less likely to be bitten by the accidental-deletion-of-a-list-item-while-iterating-over-it bug. One such paradigm is that of list comprehensions. Moreover, list comprehensions are particularly useful for avoiding this specific problem, as shown by this alternate implementation of the above code which works perfectly:
>>> odd = lambda x : bool(x % 2)
>>> numbers = [n for n in range(10)]
>>> numbers[:] = [n for n in numbers if not odd(n)]  # ahh, the beauty of it all
>>> numbers
[0, 2, 4, 6, 8]

Common Mistake #6: Confusing how Python binds variables in closures

Considering the following example:
>>> def create_multipliers():
...     return [lambda x : i * x for i in range(5)]
>>> for multiplier in create_multipliers():
...     print multiplier(2)
...
You might expect the following output:
0
2
4
6
8
But you actually get:
8
8
8
8
8
Surprise!
This happens due to Python’s late binding behavior which says that the values of variables used in closures are looked up at the time the inner function is called. So in the above code, whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at the time it is called (and by then, the loop has completed, so i has already been assigned its final value of 4).
The solution to this is a bit of a hack:
>>> def create_multipliers():
...     return [lambda x, i=i : i * x for i in range(5)]
...
>>> for multiplier in create_multipliers():
...     print multiplier(2)
...
0
2
4
6
8
Voilà! We are taking advantage of default arguments here to generate anonymous functions in order to achieve the desired behavior. Some would call this elegant. Some would call it subtle. Some hate it. But if you’re a Python developer, it’s important to understand in any case.

Common Mistake #7: Creating circular module dependencies

Let’s say you have two files, a.py and b.py, each of which imports the other, as follows:
In a.py:
import b

def f():
    return b.x
 
print f()
And in b.py:
import a

x = 1

def g():
    print a.f()
First, let’s try importing a.py:
>>> import a
1
Worked just fine. Perhaps that surprises you. After all, we do have a circular import here which presumably should be a problem, shouldn’t it?
The answer is that the mere presence of a circular import is not in and of itself a problem in Python. If a module has already been imported, Python is smart enough not to try to re-import it. However, depending on the point at which each module is attempting to access functions or variables defined in the other, you may indeed run into problems.
So returning to our example, when we imported a.py, it had no problem importing b.py, since b.py does not require anything from a.py to be defined at the time it is imported. The only reference in b.py to a is the call to a.f(). But that call is in g() and nothing in a.py or b.py invokes g(). So life is good.
But what happens if we attempt to import b.py (without having previously imported a.py, that is):
>>> import b
Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "b.py", line 1, in <module>
    import a
     File "a.py", line 6, in <module>
 print f()
     File "a.py", line 4, in f
 return b.x
AttributeError: 'module' object has no attribute 'x'
Uh-oh. That’s not good! The problem here is that, in the process of importing b.py, it attempts to import a.py, which in turn calls f(), which attempts to access b.x. But b.x has not yet been defined. Hence the AttributeError exception.
At least one solution to this is quite trivial. Simply modify b.py to import a.py within g():
x = 1

def g():
    import a # This will be evaluated only when g() is called
    print a.f()
No when we import it, everything is fine:
>>> import b
>>> b.g()
1 # Printed a first time since module 'a' calls 'print f()' at the end
1 # Printed a second time, this one is our call to 'g'

Common Mistake #8: Name clashing with Python Standard Library modules

One of the beauties of Python is the wealth of library modules that it comes with “out of the box”. But as a result, if you’re not consciously avoiding it, it’s not that difficult to run into a name clash between the name of one of your modules and a module with the same name in the standard library that ships with Python (for example, you might have a module named email.py in your code, which would be in conflict with the standard library module of the same name).
This can lead to gnarly problems, such as importing another library which in turns tries to import the Python Standard Library version of a module but, since you have a module with the same name, the other package mistakenly imports your version instead of the one within the Python Standard Library. This is where bad stuff happens.
Care should therefore be exercised to avoid using the same names as those in the Python Standard Library modules. It’s way easier for you to change the name of a module within your package than it is to file a Python Enhancement Proposal (PEP) to request a name change upstream and to try and get that approved.

Common Mistake #9: Failing to address differences between Python 2 and Python 3

Consider the following file foo.py:
import sys

def bar(i):
    if i == 1:
        raise KeyError(1)
    if i == 2:
        raise ValueError(2)

def bad():
    e = None
    try:
        bar(int(sys.argv[1]))
    except KeyError as e:
        print('key error')
    except ValueError as e:
        print('value error')
    print(e)

bad()
On Python 2, this runs fine:
$ python foo.py 1
key error
1
$ python foo.py 2
value error
2
But now let’s give it a whirl on Python 3:
$ python3 foo.py 1
key error
Traceback (most recent call last):
  File "foo.py", line 19, in <module>
    bad()
  File "foo.py", line 17, in bad
    print(e)
UnboundLocalError: local variable 'e' referenced before assignment
What has just happened here? The “problem” is that, in Python 3, the exception object is not accessible beyond the scope of the except block. (The reason for this is that, otherwise, it would keep a reference cycle with the stack frame in memory until the garbage collector runs and purges the references from memory. More technical detail about this is available here).
One way to avoid this issue is to maintain a reference to the exception object outside the scope of the except block so that it remains accessible. Here’s a version of the previous example that uses this technique, thereby yielding code that is both Python 2 and Python 3 friendly:
import sys

def bar(i):
    if i == 1:
        raise KeyError(1)
    if i == 2:
        raise ValueError(2)

def good():
    exception = None
    try:
        bar(int(sys.argv[1]))
    except KeyError as e:
        exception = e
        print('key error')
    except ValueError as e:
        exception = e
        print('value error')
    print(exception)

good()
Running this on Py3k:
$ python3 foo.py 1
key error
1
$ python3 foo.py 2
value error
2
Yippee!
(Incidentally, our Python Hiring Guide discusses a number of other important differences to be aware of when migrating code from Python 2 to Python 3.)

Common Mistake #10: Misusing the __del__ method

Let’s say you had this in a file called mod.py:
import foo

class Bar(object):
        ...
    def __del__(self):
        foo.cleanup(self.myhandle)
And you then tried to do this from another_mod.py:
import mod
mybar = mod.Bar()
You’d get an ugly AttributeError exception.
Why? Because, as reported here, when the interpreter shuts down, the module’s global variables are all set to None. As a result, in the above example, at the point that __del__ is invoked, the name foo has already been set to None.
A solution would be to use atexit.register() instead. That way, when your program is finished executing (when exiting normally, that is), your registered handlers are kicked off before the interpreter is shut down.
With that understanding, a fix for the above mod.py code might then look something like this:
import foo
import atexit

def cleanup(handle):
    foo.cleanup(handle)


class Bar(object):
    def __init__(self):
        ...
        atexit.register(cleanup, self.myhandle)
This implementation provides a clean and reliable way of calling any needed cleanup functionality upon normal program termination. Obviously, it’s up to foo.cleanup to decide what to do with the object bound to the name self.myhandle, but you get the idea.

Wrap-up

Python is a powerful and flexible language with many mechanisms and paradigms that can greatly improve productivity. As with any software tool or language, though, having a limited understanding or appreciation of its capabilities can sometimes be more of an impediment than a benefit, leaving one in the proverbial state of “knowing enough to be dangerous”.
Familiarizing oneself with the key nuances of Python, such as (but by no means limited to) the issues raised in this article, will help optimize use of the language while avoiding some of its more common pitfalls.
You might also want to check out our Insider’s Guide to Python Interviewing for suggestions on interview questions that can help identify Python experts.
We hope you’ve found the pointers in this article helpful and welcome your feedback.

Tuesday, January 21, 2014

A little note about ALSA and x220i thinkpad


First of all you need to find out sound cards indexes.
#> cat /proc/asound/cards
0 [PCH]:         HDA-Intel - HDA Intel PCH
                 HDA Intel PCH at 0xf2520000 irq 42
29 [ThinkPadEC]: ThinkPad EC - ThinkPad Console Audio Control
                 ThinkPad Console Audio Control at EC reg 0x30, fw unknown
so HDA Intel PCH has index 0

#> /etc/asound.conf
pcm.!default {
   type hw
   card 0
}
ctl.!default {
   type hw
   card 0
}


cat /etc/modprobe.d/alsa-base
options snd-hda-intel model=laptop index=0
options snd-hda-intel model=thinkpad

Monday, January 20, 2014

Remote reset or reboot Yealink T20\T22


Just send HTTP POST to:
http://192.168.1.2/cgi-bin/ConfigManApp.com (192.168.1.2 - phone address)
with header for basic auth:
'Authorization: Basic KJDSGHj54KLDSJ3='
and content:
PAGEID=7&CONFIG_DATA=RESETFACTORY - for reset

PAGEID=7&CONFIG_DATA=REBOOT - for reboot

Python example

#> python
import urllib2
post = urllib2.Request('http://192.168.1.2/cgi-bin/ConfigManApp.com?Id=7')
post.add_header('Authorization','Basic KJDSGHj54KLDSJ3=')
response = urllib2.urlopen(post, 'PAGEID=7&CONFIG_DATA=RESETFACTORY')

response.msg.lower() == 'ok'
response.code == 200

response.read()
>>> '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html><body><script type="text/javascript">if(parent && parent.onloadIFrame)\n   parent.onloadIFrame("Talking");\nelse\n   window.location.replace(\'/cgi-bin/ConfigManApp.com?Id=13\');\n</script></body></html>'

>>> '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html><body><script type="text/javascript">if(parent && parent.onloadIFrame)\n   parent.onloadIFrame("RESETFACTORY");\nelse\n   window.location.replace(\'/cgi-bin/ConfigManApp.com?Id=13\');\n</script></body></html>'