Maybe everyone knows tail program for unix which is print last 10 lines of file by default. E.g.: tail /var/log/message will print last 10 lines of log file and tail -20 /var/log/message will print last 20 lines. So here are a few my realizations of this utility on python. 1. With subprocess import subprocess import os def tail(): filename = raw_input('Enter file location: ') n = int(raw_input('Enter number of lines to print: ')) f = subprocess.Popen(['tail','-%d' % n,filename],\ stdout=subprocess.PIPE,stderr=subprocess.PIPE) for i in range(0, n+1): line = f.stdout.readline() ...
Published ago by AnaPana

Let's see the common case when we have form in template and want to save it in the view. 1. Simple POST example The most trivial way is to write the next: #views.py def my_view(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): form.save() else: form = MyForm() return direct_to_template(request, 'myform.html', {'form' : form}) And the template: <!-- myform.html --> <form id="my-form">{{ csrf_token }} {{ form }} <input type="submit" value="Save form"> </form> Tag {{ csrf_token }} is require...

I read few topics about implementation of switch case statement in Python (it is deprecated in Python btw...) and found out that people like it... really. Frankly speaking, I couldn't join them because I think that this statement is redundant. Effect of switch case could be reached by Python's instruments. It could be considered like a little design pattern. So, let's implement it in python... at least this is interesting. Main idea is make dictionary with options -> function and get function like value.   {'option1': function1, 'option2': function2, 'option3': function3 }['some option']()   Example: ...
Published ago by ochirkov

Sometimes, joint usage of Cmd processor and argparse could be usefull. I'll show you little trick how to use it together. import argparse import cmd parser = argparse.ArgumentParser(description='test handler') subparsers = parser.add_subparsers(help='commands') # Parsers block list_parser = subparsers.add_parser('list', help='List contents') list_extended_parser = subparsers.add_parser('list_extended', help='List contents') list_parser.add_argument('--list', action='store_true', dest='list', help='list values', ...
Published ago by ochirkov

Lets make init script for our python app that it starts with system boot. Follow script below: #!/bin/sh ### BEGIN INIT INFO # Provides: myservice # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Put a short description of the service here # Description: Put a long description of the service here ### END INIT INFO # Change the next 3 lines to suit where you install your script and what you want to call it DIR=/usr/local/bin/myservice DAEMON=$DIR/myservice.py DAEMON_NAME=myservice # This next line determines what user the script runs as. # Root g...
Published ago by ochirkov

I'd like to share with you my implementation of one exercise that my friend has proposed to me. The formulation of the problem was to create variable with name that you don't know beforehand. 1. Using built-ins vars() globals() or locals() So the first and the simpliest way is to use one of built-in functions that returns dictionary with existed methods and variables. They have different behavior depending on place where they are called (module, class, function etc.). In this example I choose vars() built-in function: >>> variable_name = 'counter' >>> variable_value = 123 >>> vars()[variable_name] = variable_value &...
Published ago by AnaPana

Selenium is a great instrument for testing web application with browsers drivers. It provides API for filling forms, pushing buttons, simulation of mouse movings etc. I had some problems with use Selenium on my Ubuntu server because of display abscence. Thats why I want to share here with the requirments to write a small Selenium test in this case. First of all, we will install python-selenium package: sudo apt-get install python-selenium Selenium uses browser drivers, so we need at least one Internet browser installed. You can use different browsers (Firefox, Opera, Chrome, IE and many other) I used Firefox for this purpose: sudo apt-get install firefox We also will...

In this article I'll describe how to create main menu with selected item on page using Django extra tag. The first step is to be sure that you have uncommented the following template loaders in your settings.py file: # settings.py TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', ) In your application root create folder "templatetags" for tags instances. Create there two files: __init__.py and extra_tags.py. Then in templates folder create folder for templates of your tags. I've also called it "templatetags"...
Published ago by AnaPana

In this article I'll try to show a way to connect to MS SQL database using unixODBC package. I've got much info from this docs. I use Ubuntu 12.04 (64 bit) on my client machine. 1. Ingoing The protocol for comunication between MS SQL client and server is called Tabular Data Stream (TDS). Brian Bruns started an open source project to provide an implementation of the TDS protocol to anyone who wanted it. This project is called FreeTDS. FreeTDS comes with several interfaces to TDS including ODBC (Open Database Connectivity). 2. Installing packages So here the list of packages we need to be installed:     - tdsodbc (ODBC driver for connecting to MS SQL se...

Hi there. Today we'll implement another interesting pattern. It looks like dispatcher pattern but there is one important difference. Dispatcher executes only one function which is needed. Chain executes all function step by step, if first function doesn't know how to handle task then this task will be delegated to next function. We'll specify files with different extensions like arguments and our chain approach will decide yourself how to handle it. Less words let's implement:)) formats_handler.py class Handler: def successor(self, successor): self.successor = successor class HandleHTML(Handler): def handle(self, file): ...
Published ago by ochirkov

Python
Web development
Review Linux
Administration
Provisioning CVS
Windows AWS
Continuous Integration
NoSql Logging Web Servers FileSystems Scala
accurev ansible apach2 apache api application approaches architecture archivation argparse arguments artifactory automation awk aws backup bash batch-scripting beaver block build built-in caching call captcha cartridge case certificates cgi chain client cloud cloudformation cluster cmd coding collections command-line commands compression conditionals conversion convert cookbook copy counter cron crud css cut cygwin daemon datatype date dd debpackage decorator delattr deploy deque dict distributed-file-systems django DNS domain driver dropbox dump elasticcache elasticsearch encryption exit ext4 extra-tags failover file filename filters for form format freetds functions gerrit getattribute gid git globals glusterfs hardware hook iam indexing inheritance init install job-interview jquery ldap linux list locals logging logs logstash lookup magicmethods mail main-menu metadata metalogger mongodb moosefs mount mssql multiplatform multithreading mysql netcat nginx nosql open-ssh openldap openshift os packaging parse partition path pattern patterns permissions pid pil pip pipe playbook pool post post-commit processes production provisioning proxy putty python python-mysql recursively redirection redis register replication repr restore return review rotation scala script search selenium server setattr settings setup shipper signals singleton slots snapshot socket splunk ssh ssh-key ssl storage str string style subprocess sugar super switch syntactic syntaxhighlighter systeminfo tail tar templatetags time tls tune2fs tuple ubuntu unicode unique unix unixodbc usage usecases uuid uwsgi variable vars version vi virtualenv volume web web-server windows with_items __getattr__