Commits

Anonymous committed 623dc78 Draft

Dodaj casovnico za poslance, manjsi cleanup kode.

  • Participants
  • Parent commits df87992

Comments (0)

Files changed (7)

 
   # run
   bin/django runserver
+
+TODO
+====
+
+Setup crontab for bin/django twitter_sync every 30min

delajozate/dz/models.py

 				self.slug = "%s-%d" % (slug, count)
 				count += 1
 		super(Oseba, self).save(*args, **kwargs)
-	
+
+
+class Tweet(models.Model):
+	tweet_id = models.BigIntegerField(blank=False, null=True)
+	text = models.CharField(max_length=250)
+	oseba = models.ForeignKey(Oseba)
+	created_at = models.DateTimeField()
+
 
 class Stranka(models.Model):
 	# kako modelirat kontinuiteto stranke, kadar se preimenuje?

delajozate/dz/templates/poslanec.html

 		{% endfor %}
 		<br />
 		<span class="org">{{ clanstvo.0.stranka|default_if_none:"Nepovezan poslanec" }}</span>
+		<p>Twitter: <a href="https://twitter.com/{{oseba.twitter}}">{{oseba.twitter}}</a></p>
+		<p>Email: {{oseba.email}}</p>
 	</li>
 	{% endwith %}
 </ol>
 
 
+<div>
+	<h1>
+		Časovnica
+	</h1>
+	<ol>
+		<li><h2>Danes</h2></li>
+		{% for item in today_list %}
+		<li>
+			{% include "casovnica_item.html" with item=item only %}
+		</li>
+		{% endfor %}
+		<li><h2>Ta teden</h2></li>
+		{% for item in this_week_list %}
+		<li>
+			{% include "casovnica_item.html" with item=item only %}
+		</li>
+		{% endfor %}
+		<li><h2>Prejšni teden</h2></li>
+		{% for item in last_week_list %}
+		<li>
+			{% include "casovnica_item.html" with item=item only %}
+		</li>
+		{% endfor %}
+		<li><h2>Dva tedna nazaj</h2></li>
+		{% for item in one_week_ago_list %}
+		<li>
+			{% include "casovnica_item.html" with item=item only %}
+		</li>
+		{% endfor %}
+		<li><h2>Mesec dni nazaj</h2></li>
+		{% for item in month_ago_list %}
+		<li>
+			{% include "casovnica_item.html" with item=item only %}
+		</li>
+		{% endfor %}
+		<li><h2>Več kot mesec dni nazaj</h2></li>
+		{% for item in the_rest_list %}
+		<li>
+			{% include "casovnica_item.html" with item=item only %}
+		</li>
+		{% endfor %}
+	</ol>
+</div>
+
+
 
 
 {% endblock %}

delajozate/dz/tests.py

-
-import unittest
 import os
+import datetime
 
 from django.test import Client, TestCase
+from django.test.client import RequestFactory
+
+from dz.views import poslanec
+from dz.models import Tweet, Oseba
+
 
 class DZTest(TestCase):
     fixtures = [
         os.path.join(os.path.dirname(__file__), '../fixtures/delajozate.json')
-        ]
+    ]
+
     def setUp(self):
         self.c = Client()
-    
+
     def test_responses(self):
         resp = self.c.get('/')
         self.assertEqual(resp.status_code, 200)
-        
+
         resp = self.c.get('/poslanci/')
         self.assertEqual(resp.status_code, 301)
-        
+
         resp = self.c.get('/poslanci/danes/')
         self.assertEqual(resp.status_code, 200)
-        
+
         resp = self.c.get('/poslanci/3-mandat/')
         self.assertEqual(resp.status_code, 200)
-        
+
         resp = self.c.get('/osebe/borut-ambrozic/')
         self.assertEqual(resp.status_code, 200)
-        
+
         resp = self.c.get('/seje/')
         self.assertEqual(resp.status_code, 200)
-        
+
         resp = self.c.get('/iskanje/')
         self.assertEqual(resp.status_code, 200)
-        
+
         resp = self.c.get('/robots.txt')
         self.assertEqual(resp.status_code, 200)
-        
+
+
+class PoslanecTest(TestCase):
+    fixtures = [
+        os.path.join(os.path.dirname(__file__), '../fixtures/delajozate.json'),
+        os.path.join(os.path.dirname(__file__), '../fixtures/seja_glasovanje_glas.json'),
+    ]
+
+    def setUp(self):
+        self.c = Client()
+        oseba = Oseba.objects.get(slug="dragutin-mate")
+        self.tweet1 = Tweet.objects.create(text='July', oseba=oseba, tweet_id=1, created_at=datetime.datetime(2012, 7, 7, 0, 0, 0))
+        self.tweet2 = Tweet.objects.create(text='August', oseba=oseba, tweet_id=2, created_at=datetime.datetime(2012, 8, 7, 0, 0, 0))
+
+    def test_order(self):
+        resp = self.c.get('/osebe/dragutin-mate/')
+        self.assertEqual(resp.context['the_rest_list'][0].obj, self.tweet2)
+        self.assertEqual(resp.context['the_rest_list'][1].obj.glasovanje.datum, datetime.date(2012, 7, 13))
+        self.assertEqual(resp.context['the_rest_list'][-1].obj, self.tweet1)
+        self.assertEqual(len(resp.context['the_rest_list']), 18)

delajozate/dz/views.py

-from django.http import HttpResponse
-from django.shortcuts import render
-from dz.utils import get_poslanci_by_mandat, get_poslanci, get_poslanec_stats, null_date, get_mandat_current
-
-from dz.models import Funkcija, ClanStranke, Stranka, Oseba, Mandat
-from magnetogrami.models import Zasedanje
-
+import collections
 import datetime
 import json
 import random
+
+from django.http import HttpResponse
+from django.shortcuts import render
+from django.utils.html import escape
+
+from dz.utils import get_poslanci_by_mandat, get_poslanci, get_poslanec_stats, null_date, get_mandat_current
+from dz.models import Funkcija, ClanStranke, Stranka, Oseba, Mandat, Tweet
+from magnetogrami.models import Zasedanje, Glas
+
 from temporal import END_OF_TIME
 
+
 POSLANCI_RANDOM_LIMIT = 4
 
+
 def home(request):
 	context = {
 		'zasedanja': Zasedanje.objects.all().order_by('-datum')[:5]
 	}
-	
+
 	return render(request, 'home.html', context)
-	
+
 
 def stranka(request, stranka_id):
 	ctx = {
 		'poslanci': get_poslanci({'stranka__pk': stranka_id}, mandat=get_mandat_current()),
 	}
 	return render(request, 'poslanci.html', ctx)
-	
+
 
 def poslanci_list(request, mandat):
 	if mandat == 'danes':
 		'mandati': Mandat.objects.all(),
 	}
 	return render(request, 'poslanci.html', context)
-	
+
 
 def d_squared(tracks, nodepairs):
 	#for a,b in nodepairs:
 		#(tracks[a]-tracks[b])**2
-		
-	return list(sorted([((tracks[a]-tracks[b])**2,a,b) for a,b in nodepairs], reverse=True))
-	
+
+	return list(sorted([((tracks[a] - tracks[b]) ** 2, a, b) for a, b in nodepairs], reverse=True))
+
 
 def stranke_json(request):
 	"json strank za d3.js vizualizacijo"
-	
+
 	stiki = {}
-	
+
 	for s in Stranka.objects.all().order_by('od'):
 		start_sticisce = stiki.setdefault(s.od, {})
 		start_sticisce.setdefault('od', []).append(s)
 		end_sticisce = stiki.setdefault(s.do, {})
 		end_sticisce.setdefault('do', []).append(s)
-	
+
 	from pprint import pprint
-	
+
 	masters = {}
 	steze = {}
 	povezave = {}
 		#print s
 		if len(s.get('od', [])) == 1 and len(s.get('do', [])) == 1:
 			# preimenovanje
-			s_v  = s['od'][0]
+			s_v = s['od'][0]
 			s_iz = s['do'][0]
 			mastr = masters.setdefault(s_iz.id, s_iz.id)
 			while mastr != masters[mastr]:
 			for d in s.get('od', []):
 				do = povezave.setdefault(d.id, [])
 				do.extend([i.id for i in s.get('do', [])])
-	
+
 	for s in Stranka.objects.all().order_by('od'):
 		if not s.id in masters:
 			steza = masters.setdefault(s.id, s.id)
 			steze.setdefault(steza, [s])
-	
+
 	povezave_resolved = []
 	for k, v in povezave.items():
 		for i in v:
 			povezave_resolved.append((masters[k], masters[i]))
-	
-	steze_index = dict([(b,a) for a,b in list(enumerate(steze.keys()))])
-	
+
+	steze_index = dict([(b, a) for a, b in list(enumerate(steze.keys()))])
+
 	#pprint(steze)
-	
+
 	stranke = {}
 	for s in Stranka.objects.all():
 		s_dict = {
 			'spremenila_v': [v.id for v in s.spremenila_v.all()],
 			}
 		stranke[s.id] = s_dict
-	
+
 	condensed = {}
 	for master_id, steza in steze.iteritems():
 		newsteza = []
 			}
 			newsteza.append(s_dict)
 		condensed[master_id] = newsteza
-	
+
 	return HttpResponse(json.dumps({'stranke_all': stranke, 'stranke_condensed': condensed}, indent=3), mimetype='application/json')
-	
+
 
 def poslanec(request, slug):
+	oseba = Oseba.objects.get(slug=slug)
+	tweeti = Tweet.objects.filter(oseba=oseba)
+	glasovi = Glas.objects.filter(oseba=oseba)
+
+	now = datetime.datetime.now()
+	today = now.replace(hour=0, minute=0, second=0, microsecond=0)
+	# TODO: actually count weeks
+	this_week = now - datetime.timedelta(days=-7)
+	last_week = now - datetime.timedelta(days=-14)
+	two_weeks_ago = now - datetime.timedelta(days=-21)
+	month_ago = now - datetime.timedelta(days=-31)
+
+	casovnica = []
+	for tweet in tweeti:
+		casovnica.append((tweet.created_at, tweet, 'tweet'))
+	for glas in glasovi:
+		# convert date to datetime so we can compare it to datetime
+		casovnica.append((datetime.datetime(*(glas.glasovanje.datum.timetuple()[:6])), glas, 'glas'))
+
+	casovnica = sorted(casovnica, key=lambda k: k[0], reverse=True)
+
 	context = {
-		'oseba': Oseba.objects.get(slug=slug),
-		}
-	
+		'oseba': oseba,
+		'today_list': [],
+		'this_week_list': [],
+		'last_week_list': [],
+		'two_weeks_ago_list': [],
+		'month_ago_list': [],
+		'the_rest_list': [],
+	}
+
+	item = collections.namedtuple('Item', 'obj, type')
+
+	for date, obj, type_ in casovnica:
+		if today < date <= now:
+			context['today_list'].append(item._make((obj, type_)))
+		if this_week < date <= today:
+			context['this_week_list'].append(item._make((obj, type_)))
+		if last_week < date <= this_week:
+			context['last_week_list'].append(item._make((obj, type_)))
+		if two_weeks_ago < date <= last_week:
+			context['two_weeks_ago_list'].append(item._make((obj, type_)))
+		if month_ago < date <= last_week:
+			context['month_ago_list'].append(item._make((obj, type_)))
+		if date <= month_ago:
+			context['the_rest_list'].append(item._make((obj, type_)))
+
 	return render(request, "poslanec.html", context)
 
+
 def robots(request):
-	
+
 	robots_txt = """User-agent: *
 Disallow: /iskanje/
 """
-	
-	return HttpResponse(robots_txt, mimetype="text/plain")
+
+	return HttpResponse(robots_txt, mimetype="text/plain")

delajozate/magnetogrami/models.py

 
 class Glasovanje(models.Model):
 	seja = models.ForeignKey(Seja, null=True)
+	# TODO: join ura and datum
 	ura = models.TimeField(null=True, blank=True)
+	datum = models.DateField(null=True, blank=True)
 	url = models.URLField(null=True)
-	datum = models.DateField(null=True, blank=True)
 	dokument = models.CharField(max_length=2000, null=True)
 	naslov = models.CharField(max_length=2000, null=True)
 	faza_postopka = models.CharField(max_length=255, null=True)
     'python-dateutil',
     'django-debug-toolbar',
     'django-haystack',
+    'python-twitter',
 ]
 
 if sys.platform != "darwin":