USB-Herelist/MOS

aus Metalab Wiki, dem offenen Zentrum für meta-disziplinäre Magier und technisch-kreative Enthusiasten.
Zur Navigation springenZur Suche springen

Not the best code you'll ever see.

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('examples.hello.views',
    (r'^mainpage/$', 'mainpage'),
    (r'^update-herelist/$', 'update_herelist'),
)


views.py

from django.http import HttpResponse
from django.utils.html import escape
import os
import os.path
import time

def mainpage(request):
	r = HttpResponse()
	r.write('<h1>Mainpage</h1>')
	r.write('<p>this is the mainpage</p>')
	r = add_herelist(r)
	return r
	

def add_herelist(r):
	MEDIA_ROOT = '/home/exp/data/'
	filename = '%s/%s' % (MEDIA_ROOT, 'herelist.txt')
	try:
		# a) empty file
		if os.path.getsize(filename) <= 0:
			return r
		# b) too old file: > 30 minutes
		if time.time() - os.path.getmtime(filename) > 60*30:
			return r
		# c) print it
		r.write('<h3>Derzeit im Metalab:</h3><ul class="herelist">')
		fd = open(filename, 'rb')
		try:
			for line in fd:
				r.write('<li>' + line + '</li>')
		finally:
			fd.close()
			r.write('</ul>')
	except os.error:
		r.write('add_herelist had an os.error exception.')
	else:
		return r

def update_herelist(request):
	MEDIA_ROOT = '/home/exp/data/'
	r = HttpResponse()
	if request.FILES:
		for k, v in request.FILES.items():
			if v['content-type'] == 'text/plain' and k == 'herelist':
				fd = open('%s/%s' % (MEDIA_ROOT, 'herelist.txt'), 'wb')
				fd.write(v['content'])
				fd.close()
				r.write('accepted update')
			else:
				r.write('unexpected content-type or name')
	return r