Skip to content

Instantly share code, notes, and snippets.

@bpetit
Created October 29, 2012 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpetit/3973138 to your computer and use it in GitHub Desktop.
Save bpetit/3973138 to your computer and use it in GitHub Desktop.
python snippets
"""
Template settings.py for django 1.4 projects during the developpement.
"""
import os
#store the asolute path of the file for future needs
self_absolute_path = os.path.abspath(__file__)
self_dir_absolute_path = os.path.dirname(self_absolute_path)
self_dir_name = os.path.split(self_dir_absolute_path)[1]
# Django settings for baseproject project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': self_dir_absolute_path+'/defaultdb.sqlite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '+j49eo5x8-*yafuay(a!(3w+x^4z7t_+l)g3^eowj9m%zs7sb+'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
# set the urls module of the project assuming the settings file
# is placed in the main folder (the folder generated with the name
# of the project since django 1.4)
# of the project and the mail urls module is the one of this folder
ROOT_URLCONF = self_dir_name+'.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = self_dir_name+'.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'debug_toolbar',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.version.VersionDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.logger.LoggingPanel',
)
def custom_show_toolbar(request):
return True # Always show toolbar, for example purposes only.
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': True,
'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
'HIDE_DJANGO_SQL': False,
'TAG': 'div',
'ENABLE_STACKTRACES': True,
}
a = 5
b = 6
c = 7
print str(a)+' '+str(b)+' '+str(c)
# we can switch variables values without a temporary variable
a,b,c = b,c,a
print str(a)+' '+str(b)+' '+str(c)
def makedict(**kwargs):
# simplifies a bit the dictonnary declaration (mydict = {'foo':1, 'bar':2})
# to mydict = makedict(foo=1,bar=2)
return kwargs
d = {'foo':1, 'bar':2}
if d.has_key('foo'):
d['foo']
# is equivalent to
try:
d['foo']
except KeyError:
pass
# the better method:
d.get('foo') # return None if not found
# what may replace switch :
animals = []
number_of_felines = 0
def deal_with_a_cat( ):
global number_of_felines
print "meow"
animals.append('feline')
number_of_felines += 1
def deal_with_a_dog( ):
print "bark"
animals.append('canine')
def deal_with_a_bear( ):
print "watch out for the *HUG*!"
animals.append('ursine')
tokenDict = {
"cat": deal_with_a_cat,
"dog": deal_with_a_dog,
"bear": deal_with_a_bear,
}
word = "cat"
functionToCall = tokenDict[word]
functionToCall()
# double comparison is possible
if 5 < 8 < 55:
print "OK"
# a function may return more than one element (in fact a tuple is returned)
def f():
return 1,2,3
res = f()
print res
a,b,c = f()
print str(a)+' '+str(b)+' '+str(c)
# function parameters/arguments
def myfunc(datas, opt_datas=[], *args, **kwargs):
for d in datas: print(d)
print "opt_datas"
for d in opt_datas: print(d)
print "args"
for a in args:
for d in a: print(d)
print "kwargs"
for v in kwargs.values():
for d in v: print(d)
myfunc([1,2])
myfunc([1,2], [3,4])
myfunc([1,2], [3,4], [5,6])
myfunc(datas=[1,2])
myfunc(datas=[1,2], opt_datas=[3,4])
myfunc(datas=[1,2], opt_datas=[3,4], truc=[5,6])
# as the ternary operator in PHP
print(True and "OK" or "KO")
print(False and "OK" or "KO")
# list slices
a = range(11)
print a[:10]
print a[0:10]
print a[10:20] # looking for out of range indice doesn't raise exception
# starting from the end of the list
print a[-1]
print a[-10:]
print a[-10:-1]
# specify the step
print a[-10:-1:2]
# this set the same pointer on a and b:
b = a
# this copies a to b (b gets all the elements of a thanks to the slice)
b = a[:]
# slice and step may be used for loops
for c in a[11:0:-1]:
# equivalent to for index in range(11, 0, -1): print(a[index])
print c
# you can cast tuple to list and list to tuple
ta = tuple(a)
b = list(ta)
# a way to build a dict
c = dict((k,v+5) for k,v in enumerate(a))
print c
# another way: generators
def gen(tab):
for k,v in enumerate(tab):
yield k, v+5
print dict((k,v) for k,v in gen(a))
# sorting list
a = [5,4,1,8,6,9]
print a
a.sort()
print a
# sorting list with defined comparison pattern
def comp(a, b):
return cmp(-a,-b)
a.sort(comp)
print a
import matplotlib
matplotlib.use('Qt4Agg')
from matplotlib.pyplot import plot, xlim, ylim, show, legend, figure
import psycopg2
import datetime
# connecting to the database (replica on a virtual machine)
conn = psycopg2.connect(host='192.168.122.131', user='root', password='root', database='udd')
cursor = conn.cursor()
# querying the db to get timestamps of record after the first of jan. 2010
cursor.execute(
"select ts,vcstype_git,vcstype_svn,vcstype_hg,vcstype_bzr, vcstype_arch, vcstype_cvs from history.sources_count where ts > '"+
str(datetime.datetime(2010, 1, 1, 0, 0, 0))+"'")
# getting the results of the query
results = cursor.fetchall()
# setting the figure properties
figure(figsize=(8,6), dpi=80)
# storing ts and vcstype_git in axis vars
def datas_per_vcs(results):
res = (('blue',[],'git'), ('green',[],'svn'),
('red',[],'hg'), ('yellow',[],'bzr'),
('black',[],'arch'),('brown',[],'cvs'))
x = []
for d in results:
x.append(d[0])
for k,v in enumerate(d):
if 1 <= k <= 6:
res[k-1][1].append(v)
return res, x
def define_plot(color, data, label):
plot(x, data, color=color, linewidth=1.0, linestyle='-', label=label)
datas_per_vcs, x = datas_per_vcs(results)
for d in datas_per_vcs:
define_plot(d[0], d[1], d[2])
def get_max_y():
max_y = max(datas_per_vcs[0][1])
for d in datas_per_vcs:
max_y = max(max_y, max(d[1]))
# setting the dimensions of the graph
xlim(min(x), max(x))
ylim(0, get_max_y())
legend(loc='upper left')
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment