python: django ; some code 
../clcreviewer/settings.py

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/home/xxx/clcreviewer/clcreviewer/sqlite3.db', # 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.
}
}

...

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',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'logcheck' <-----
)

...

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.
'/home/.../clcreviewer/templates/',
)



../clcreviewer/clcreviewer/urls.py

from django.conf.urls import patterns, include, url from logcheck.views import index

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'clcreviewer.views.home', name='home'),
# url(r'^clcreviewer/', include('clcreviewer.foo.urls')),

# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),

url(r'^logcheck/', index ), <-----
)



../clcreviewer/logcheck/models.py

from django.db import models

# Create your models here.

class Server(models.Model):
name = models.CharField(max_length=200)
ip_address = models.CharField(max_length=18)
cpu_count = models.IntegerField(default=1)



../clcreviewer/logcheck/forms.py

from django import forms
from models import Server

class ServerForm(forms.ModelForm):

class Meta:
model = Server



../clcreviewer/logcheck/views.py

# Create your views here.
from django.http import HttpResponse
from django.template import Context, Template from django.shortcuts import render_to_response from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect

from forms import ServerForm

def index(request):
form = ServerForm()
return render(request, 'logcheck_index.html', {'form': form})


class form_servers(forms.Form):
platform = forms.CharField(max_length=16)
servers = forms.CharField(widget=forms.Textarea, max_length=65535)
hiddenX = forms.CharField(widget=forms.HiddenInput,required=False)


def index2(request):
if request.method == 'POST': # If the form has been submitted...
form = form_servers(request.POST) # A form bound to the POST data
print request.POST
print str(form)
if form.is_valid(): # All validation rules pass
#return HttpResponseRedirect('/thanks/') # Redirect after POST
#return HttpResponse("Hello world")
servers = form.cleaned_data['servers']
platform = form.cleaned_data['platform']
hiddenfield = request.POST['hiddenfield']
#return HttpResponse( out )
return render_to_response( 'logcheck_output.html', { 'platform': platform, 'servers': servers } )

else:
form = form_servers() # An unbound form
print str(form)
return render(request, 'logcheck_index.html', {
'form': form,
})


../clcreviewer/logcheck_index.html

<form action="/logcheck/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="hidden" name="hiddenfield" value="hidden123" />
<input type="submit" value="Submit" /> </form>




[ add comment ] ( 7 views )   |  [ 0 trackbacks ]   |  permalink
CSS/tutprial, a web template sources 
http://www.cssbasics.com/introduction-to-css/

http://www.freecsstemplates.org/

[ add comment ] ( 3 views )   |  [ 0 trackbacks ]   |  permalink
python: date, datetime, delta, file 
#!/usr/local/bin/python

from datetime import date, timedelta
from os import path
import sys

def main( server ):
type = "unix"
date_to_check = ( date.today() - timedelta( days = 1 ) ).strftime( "%F" )
folder_to_check = "/var/log/clc/%s/%s/" %( date_to_check, type )

#for server in open( "/tmp/hosts.txt", "r" ).readlines():
#server = argv[1]

file_type = "messages"
file_to_check = "%s%s-%s" %( folder_to_check, server.lower().rstrip(), file_type )

if path.isfile( file_to_check ):
print "OK: %s log found" %( server.lower().rstrip() )
return
else:
print "ERROR: %s log not found" %( server.lower().rstrip() )
return

if __name__ == '__main__':
''' program returns if the logfile for server in argument is found or not '''
main( sys.argv[1] )


[ add comment ] ( 3 views )   |  [ 0 trackbacks ]   |  permalink
python: django - Template and Context 

>>> from django.template import Context, Template
>>> t = Template( "{ % for item in item_list % } <li> {{ item }} </li> {
>>> % endfor % }" ) c = Context( { 'item_list': ['one', 'two', 'three' ]
>>> } )
>>> t.render(c)
u'{ % for item in item_list % } <li> </li> { % endfor % }'



[ add comment ] ( 4 views )   |  [ 0 trackbacks ]   |  permalink
python: django - show picture in admin interface 
create method in object which prints html


def admin_picture(self):
return '<img src="%s"/>' % self.picture_url
admin_picture.allow_tags = True


add this method to list_display as the ordinary db field

[ add comment ] ( 5 views )   |  [ 0 trackbacks ]   |  permalink
python: django - models and admin interface  
models.py in the application folder is where all the the models sit


from django.db import models

# Create your models here.

from django.db import models

class PictureCategory(models.Model):
picture_type = models.CharField(max_length=3)
picture_description = models.CharField(max_length=30)

def __unicode__(self):
return self.picture_description

class Picture(models.Model):
piture_name = models.CharField(max_length=200)
picture_url = models.URLField(max_length=200)
picture_type = models.ForeignKey(PictureCategory)

def __unicode__(self):
return '%s (%s)' % (self.piture_name, self.picture_type.picture_description)





admin.py this file in the application folder causes the respective class is added to the admin interface


from polls.models import Poll
from polls.models import Picture
from polls.models import PictureCategory

from django.contrib import admin

class PictureAdmin(admin.ModelAdmin):
fieldsets = [
('Picture Naaaame', {'fields': ['piture_name']}),
('Picture deescriiptionn', {'fields': ['picture_url']}),
('Picture category', {'fields': ['picture_type']}),
]
list_display = ( 'piture_name', 'picture_url' )
list_filter = ['picture_type', 'picture_url']

search_fields = ['piture_name', 'picture_url']


admin.site.register(Poll, PollAdmin)
admin.site.register(Picture, PictureAdmin)
admin.site.register(PictureCategory)




------------------------------------
2 check
https://django-grappelli.readthedocs.org/en/2.4.2/

2check
https://github.com/sehmaschine/django-filebrowser



[ add comment ] ( 5 views )   |  [ 0 trackbacks ]   |  permalink
pyhthon: DJANGO models 
create application within project


python manage.py startapp polls


Edit the settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls'.
Edit models.py, add your models.


from django.db import models

class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()


create database, list db create


>> python manage.py syncdb
>> python manage.py sql polls


add data to db


./manage.py shell
>>> from polls.models import Poll, Choice
>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())
>>> p.save()
...


add data to db, in a loop


>>>> for a in range(10):
... Poll(question="hey, you seemt to like number {0}".format(a), pub_date=datetime.datetime.now()).save()
...



lets see what we have


>>> Poll.objects.all()
[<Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>]


read all the object data; in a loop print the question


>>> for foo in Poll.objects.all():
... foo.question
...
u'hey, you seems to like number 0'
u'hey, you seems to like number 1'
u'hey, you seems to like number 2'
u'hey, you seems to like number 3'
u'hey, you seems to like number 4'
...



select specific data (by id) - filter returns a list of matches


>>> a = Poll.objects.filter(id=1)
>>> a
[<Poll: Poll object>]

>>> len(a)
1

>>> a[0]
<Poll: Poll object>

>>> a = Poll.objects.filter(id=1)
>>> a[0].question
u'Anybody there?'


read in a loop, filter id_gte = 2


>>> x = Poll.objects.filter( id__gte = 2 ) x
[<Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>, <Poll: Poll object>]
>>> for entry in x:
... entry.question
...
u'Yet 2nd question'
u'Kolik meri jirka'
u'Question_0'
u'Question_1'
u'Question_2'
...



using get you will have a single object itself, not the list of objects


>>> a = Poll.objects.get(id=1)
>>> a
<Poll: Poll object>
>>> a.question
u'Anybody there?'


if get matches more objects


>>> a = Poll.objects.get(id__gte=1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 131, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 368, in get
% (self.model._meta.object_name, num, kwargs))
MultipleObjectsReturned: get() returned more than one Poll -- it returned 24! Lookup parameters were {'id__gte': 1}



[ add comment ] ( 7 views )   |  [ 0 trackbacks ]   |  permalink
python: basics 
get all the processes on system


import sys
my_process = os.popen("ps -ef")
for program in my_process.readlines():
print program[:-1]


make list from processes / per line, separate fields to list, print one field from lists


import os
import sys
import strings
my_process = os.popen("ps -ef")
for program in my_process.readlines():
program = program[:-1].split()
program[7]


write as function, return all programs running


import os
import sys
import strings

def list_programs():
list = []
for program in os.popen("ps -ef").readlines():
program = program[:-1].split()
list.append(program[7])
return list

if __name__ == "__main__":
for pgm in list_programs():
print pgm



using classess


class acl:
readgroups = []
def readwho(self):
print self.readgroups

newc = acl()
newc.readgroups = [ "aaaa" ]
newc.readwho()
['aaaa']


nesting classess


class allattrs(acl,version):
''' just a class '''
ou = allattrs()
ou.version="2"
ou.version
'2'




[ add comment ] ( 8 views )   |  [ 0 trackbacks ]   |  permalink
py: regular expressions in python 

>>> import re
>>> ip = re.compile('(\d{1,3})\.(\d+)\.(\d+)\.(\d+)'



>>> x = ip.search('ip: 5.6.7.8')
>>> x is None
False

>>> x = ip.match('ip: 5.6.7.8')
>>> x is None
True



>>> x.groups()
...
('5', '6', '7', '8')



>>> x.group()[2]
'6'

>>> x.group(2)
'6'



[ add comment ] ( 5 views )   |  [ 0 trackbacks ]   |  permalink
Various synthetisers - schemes  
http://rubidium.dyndns.org/cag/

Temperature compensated antilog circuit
http://www.seekic.com/circuit_diagram/B ... ERTER.html

A BJT is a Current Operated Transistor
http://www.learnabout-electronics.org/b ... ors_06.php


[ add comment ] ( 7 views )   |  [ 0 trackbacks ]   |  permalink

<<First <Back | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | Next> Last>>