Archive for the 'python' Category

23
Jan
12

unknown encoding: cp0


If you receive this when deploying django on apache, it’s because you have something like:


print "Something %s" % value

The fix is to change it to:


print "Something %s" % str(value)

24
Nov
11

data URI scheme


This ( Data URI scheme ) is very helpful for serving images without storing them on server side.

21
Nov
11

always specify fields for django’s ModelForm as a tuple


So, I had a model that had a FileField called path, for which I wanted a ModelForm. Do not do this:


class MyModelForm(ModelForm):
   class Meta:
      model = MyModel
      fields= ("path")

It led to a strange error, saying django.core.exceptions.FieldError: Unknown field(s) (a, p, t, h). Of course, the fix was to specify the fields like:


class MyModelForm(ModelForm):
   class Meta:
      model = MyModel
      fields= ("path",)

21
Nov
11

django FileField and random names


To ensure that an uploaded file will have a random name, use a custom storage object, like described here.

01
Nov
11

python directory synchronization


I needed to synchronize two folders, and I came up with this:



def sync_dirs(source,dest):
	if not os.path.exists(dest):
		os.makedirs(dest)
		
	def _file_retriever(where):
		dir_ac = []
		file_ac = []
		
		for root,dirs,files in os.walk(where):
			for dir in dirs:
				abs_dir = os.path.join(root,dir)
				dir_ac.append((abs_dir,os.path.relpath(abs_dir,where)))
			for file in files:
				abs_f = os.path.join(root,file)
				file_ac.append((abs_f,os.path.relpath(abs_f,where)))
		return (dir_ac,file_ac)
	
	left_dirs,left_files  = _file_retriever(source)
	right_dirs,right_files = _file_retriever(dest)
	
	for left_dir in left_dirs:
		rel_path = left_dir[1]
		equivalent_right_dir = filter(lambda e:e[1] == rel_path,right_dirs)
		# it's not in the right side, copy it
		if len(equivalent_right_dir) == 0:
			os.makedirs(os.path.join(dest,rel_path))
	# check if only in the right side
	for right_dir in right_dirs:
		rel_path = right_dir[1]
		equivalent_left_dir = filter(lambda e:e[1] == rel_path,left_dirs)
		if(len(equivalent_left_dir) == 0) and (os.path.exists(right_dir[0])):
			shutil.rmtree(right_dir[0])
	
	for left_file in left_files:
		rel_path = left_file[1]
		equivalent_right_file = filter(lambda e:e[1] == rel_path,right_files)
		# file doesn't exist in right side
		if len(equivalent_right_file) == 0:
			shutil.copyfile(left_file[0],os.path.join(dest,rel_path))
		else:
			left_content = open(left_file[0],"rb").read()
			right_content= open(equivalent_right_file[0][0],"rb").read()
			if left_content != right_content:
				shutil.copyfile(left_file[0],os.path.join(dest,rel_path))
	
	for right_file in right_files:
		rel_path = right_file[1]
		equivalent_left_file = filter(lambda e:e[1] == rel_path,left_files)
		if (len(equivalent_left_file) == 0) and (os.path.exists(right_file[0])):
			os.unlink(right_file[0])
	


12
Oct
11

custom using the with statement


import os

class MyTempDir(object):
	def __init__(self,to_dir):
		self.to_dir = to_dir
		self.original_dir = os.path.abspath(os.getcwd())

	def __enter__(self):
		os.chdir(self.to_dir)
		return self.to_dir

	def __exit__(self, type, value, traceback):
		os.chdir(self.original_dir)

if __name__ == "__main__":
	with MyTempDir("c:\\") as value:
		print "Inside %s Confirmation %s" % (value,os.getcwd())

09
Sep
11

python subprocess kill example


A little something for me, so that I can remember in the future how to kill a process started via Popen.


import subprocess
import time
import sys

if __name__ == "__main__":
    if len(sys.argv) != 2:
        exit("need an argument")
    to_run = sys.argv[1]
    proc = subprocess.Popen(to_run)
    print "start process with pid %s" % proc.pid
    time.sleep(50)
    if proc.poll() is None:
        print "Killing process %s with pid %s " % (to_run,proc.pid)
        proc.kill()




Blog Stats

  • 218,505 hits