/[theodore]/snips/snips/snips.py


UCC Code Repository

Contents of /snips/snips/snips.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 48 - (show annotations) (download) (as text)
Sat Jun 28 09:58:29 2008 UTC (12 years, 9 months ago) by theodore
File MIME type: text/x-python
File size: 12948 byte(s)
add stuff before drunken code


1 import re
2 import time
3 import MySQLdb
4 import ConfigParser
5
6 from os import sys
7 from string import join
8
9 """
10 Import modules from modules directory
11 """
12 sys.path.insert(0,'./modules')
13 import yaml
14 import pygments
15
16 from pygments import highlight
17 from pygments.lexers import (guess_lexer, get_all_lexers, get_lexer_by_name)
18 from pygments.formatters import HtmlFormatter
19 from mako.template import Template
20
21 del sys.path[0]
22
23 config = ConfigParser.ConfigParser()
24 config.read("./snips.cfg")
25
26 db_user = config.get("database", "user")
27 db_password = config.get("database", "password")
28 db_host = config.get("database", "hostname")
29 db_database = config.get("database", "database")
30
31 html_header = "Content-Type: text/html\r\n\n"
32
33 def display_home():
34 mytemplate = Template(filename="templates/home.txt", module_directory='./tmp/mako')
35 main = mytemplate.render()
36 header = "Snips Homepage"
37 title = "Snips Homepage"
38 print_page(title, main)
39
40 def new_snip():
41 mytemplate = Template(filename="templates/form.txt", module_directory='./tmp/mako')
42 main = mytemplate.render(action = 'new', tags = '', languages = get_languages(), description = '', code = '', submit = 'And Save It', hidden = '')
43 print_page("Snips - Create new snip", main, "Create new snip")
44
45 def edit_snip(index):
46
47 (snip_id, code, description, language, timesaved, tags) = get_snip(index)
48
49 if tags == []:
50 tags.append('None')
51 tags = join(tags, ' ')
52
53 mytemplate = Template(filename="templates/form.txt", module_directory='./tmp/mako')
54 main = mytemplate.render(action = 'edit', tags = tags, languages = get_languages(language), description = description, code = code, submit = 'Save Changes', hidden = '<input type="hidden" name="snip_id" value="%s"></input>' % (snip_id,) )
55
56 title = "Editing snip - %s" % (snip_id)
57 header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a>" % (time.ctime(timesaved), snip_id)
58
59 print_page(title, main, header)
60
61 def get_languages(language = ''):
62 lexers = []
63 list = '<option value="guess">Guess</option>'
64 for lexer in get_all_lexers():
65 name = lexer[0]
66 alias = lexer[1][0]
67 lexers.append((name,alias))
68 lexers.sort()
69 for name, alias in lexers:
70 selected = ''
71 if alias == language:
72 selected = 'selected="selected"'
73 list += '<option value="%s" %s>%s</option>' % (alias, selected, name)
74 return list
75
76 def sidebar(sidebar = True):
77 if sidebar:
78 try:
79 tagcloud = get_tagcloud()
80 except:
81 tagcloud = ''
82 else:
83 tagcloud = ''
84 mytemplate = Template(filename="templates/sidebar.txt", module_directory='./tmp/mako')
85 sidebar = mytemplate.render(tagcloud = tagcloud)
86 return sidebar
87
88 def dbh_open():
89 global conn
90 try:
91 conn = MySQLdb.connect (host = db_host, user = db_user, passwd = db_password, db = db_database)
92 except:
93 print_error("Database connection problem")
94 global cursor
95 cursor = conn.cursor()
96 return cursor
97
98 def dbh_close():
99 cursor.close ()
100 conn.commit ()
101 conn.close ()
102
103 def submit_new_snip(snip, description, language = '', tags = []):
104 cursor = dbh_open()
105 cursor.execute ("INSERT INTO snips_snip (code, description, language, timesaved) VALUES (%s, %s, %s, %s); ", (snip, description, language, time.time()))
106 cursor.execute ("SELECT LAST_INSERT_ID();")
107 snip_id = cursor.fetchone ()[0]
108 snip_id = int(snip_id)
109 for tag in tags:
110 cursor.execute ("INSERT INTO snips_tags (snip_id, tag) VALUES (%s, %s); ", (snip_id, tag))
111
112 dbh_close()
113 redirect(snip_id)
114
115 def redirect(id, page = "snip"):
116 print "Status: 303 Moved Permanently\nLocation: ./index.cgi?%s=%s\n" % (page,id)
117
118
119 def update_current_snip(snip_id, code, description, language, tags = []):
120 cursor = dbh_open()
121 cursor.execute ("UPDATE snips_snip SET code = %s, description = %s, language = %s, timesaved = %s WHERE id = %s; ", (code, description, language, time.time(), snip_id))
122 cursor.execute ("INSERT INTO snips_story (snip_id, code, description, language, timesaved) SELECT id, code, description, language, timesaved FROM snips_snip ss WHERE ss.id = %s; ", (snip_id,))
123
124 cursor.execute ("DELETE FROM snips_tags WHERE snip_id = %s; ", (snip_id,))
125 for tag in tags:
126 cursor.execute ("INSERT INTO snips_tags (snip_id, tag) VALUES (%s, %s); ", (snip_id, tag))
127
128 dbh_close()
129 redirect(snip_id)
130
131 def get_snip(index):
132 cursor = dbh_open()
133 cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip WHERE id = %s; ", (index,))
134 snip_id, code, description, language, timesaved = cursor.fetchone ()
135 cursor.execute ("SELECT tag FROM snips_tags WHERE snip_id = %s; ", (snip_id,))
136 tupletags = cursor.fetchall () ## fetchall returns a list of one tuples - This 'unzips' it and fetches the 'first' list from the result one-tuple of lists
137 tags = []
138 for tuple in tupletags:
139 tags.append(tuple [0])
140
141 dbh_close()
142 return (snip_id, code, description, language, timesaved, tags)
143
144 def print_snip(index):
145
146 (snip_id, code, description, language, timesaved, tags) = get_snip(index)
147
148 if tags == []:
149 tags.append('None')
150 tags = join(tags, ', ')
151
152 code = format_code(language, code)
153 languagename = get_longname(language)
154
155 mytemplate = Template(filename='./templates/snip.txt', module_directory='./tmp/mako')
156 main = mytemplate.render(description = description, tags = tags, snip = code, language = languagename, snipid = index)
157 title = "Viewing snip - %s" % (snip_id)
158 header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a> | <a href='?snipstory=%s'>snipstory</a>" % (time.ctime(timesaved), snip_id, snip_id)
159
160 print_page(title, main, header)
161
162 def get_lexer(language = "None", code = ""):
163 try:
164 mylexer = get_lexer_by_name(language)
165 except:
166 try:
167 mylexer = guess_lexer(code)
168 except:
169 mylexer= get_lexer_by_name('text')
170 return mylexer
171
172
173 def tagify(tags):
174 tags = re.split(r'\s*', tags)
175 return tags
176
177 """
178 Prints Page with required variables
179 """
180 def print_page(title, main, header = ''):
181 if header == '':
182 header = title
183 mytemplate = Template(filename='./templates/main.txt', module_directory='./tmp/mako')
184 print html_header
185 print mytemplate.render(title = title, header = header, sidebar = sidebar(), main = main)
186
187 sys.exit(0)
188
189 def print_error(error):
190 title = "Snips - error"
191 header = title + error
192 error = '<div id="error"><em>An error has occurred processing your request please review the errors below</em><p>' + error + '</p></div>'
193
194 mytemplate = Template(filename='./templates/main.txt', module_directory='./tmp/mako')
195 print html_header
196 print mytemplate.render(title = title, header = header, sidebar = sidebar(False), main = error)
197
198 def get_tagcloud():
199 tags = get_tags(20)
200 mytemplate = Template(filename="templates/cloud.txt", module_directory='./tmp/mako')
201 cloud = mytemplate.render(tags = tags, size = 'small')
202 return cloud
203
204 def get_tags(limit = 0):
205 cursor = dbh_open()
206 if limit != int(limit):
207 limit = 20
208 if limit > 0:
209 cursor.execute ("SELECT tag, COUNT(*) FROM snips_tags GROUP BY tag ORDER BY COUNT(*) DESC LIMIT %s;", limit)
210 elif limit < 0:
211 cursor.execute ("SELECT tag, COUNT(*) FROM snips_tags GROUP BY tag ORDER BY COUNT(*) DESC LIMIT %s;", limit * -1)
212 else:
213 cursor.execute ("SELECT tag, COUNT(*) FROM snips_tags GROUP BY tag ORDER BY COUNT(*) DESC;")
214 tags = cursor.fetchall ()
215 max = tags[0][1]
216 min = tags[-1][1]
217 tags = list(tags)
218 for i in range(len(tags)):
219 tag, count = tags[i]
220 tags[i] = (tag, int( (count - min + 1.0)/(max - min + 1.0) * 9))
221 tags.sort()
222
223 dbh_close()
224 return tags
225
226 def show_all_tags():
227 cloud = ''
228 tags = get_tags()
229
230 mytemplate = Template(filename="templates/cloud.txt", module_directory='./tmp/mako')
231 main = mytemplate.render(tags = tags, size = 'big')
232
233 title = "Snips - Showing all tags"
234 print_page(title, main)
235
236 def latest_snips():
237 cursor = dbh_open()
238 cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip ORDER BY timesaved DESC LIMIT 10;")
239 snips = cursor.fetchall ()
240 dbh_close()
241
242 main = snips_to_snippets(snips)
243
244 title = "Viewing latest 20 snips"
245 print_page(title, main)
246
247 def get_longname(language = ''):
248 if language == '' or language == 'guess':
249 return "None Given"
250 for lexer in get_all_lexers():
251 if lexer[1][0] == language:
252 return lexer[0]
253 return language
254
255 def view_tag(tag):
256 cursor = dbh_open()
257 cursor.execute ("SELECT ss.id, ss.code, ss.description, ss.language, ss.timesaved FROM snips_snip ss, snips_tags st WHERE st.tag = %s AND st.snip_id = ss.id; ", (tag,))
258 snips = cursor.fetchall ()
259 dbh_close()
260
261 main = snips_to_snippets(snips)
262
263 title = "Viewing all snips tagged '%s'" % tag
264 print_page(title, main)
265
266 def snips_to_snippets(snips):
267 main = ""
268 for snip in snips:
269 (snip_id, code, description, language, timesaved) = snip
270 viewmore = False
271 if len(code) > 500:
272 code = code[:500]
273 viewmore = True
274 languagename = get_longname(language)
275
276 code = format_code(language, code)
277
278 timesaved = time.ctime(timesaved)
279
280 mytemplate = Template(filename='./templates/snippet.txt', module_directory='./tmp/mako')
281 main += mytemplate.render(description = description, snip = code, edittime = timesaved, language = languagename, snipid = snip_id, viewmore = viewmore)
282 return main
283
284 def print_snipstory(snipid):
285 cursor = dbh_open()
286 cursor.execute ("SELECT 0, code, description, language, timesaved FROM snips_snip where id = %s;", (snipid,))
287 latestsnip = cursor.fetchone ()
288 cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_story where snips_story.snip_id = %s ORDER BY timesaved DESC;", (snipid,))
289 snips = cursor.fetchall ()
290 dbh_close()
291
292 snips = list(snips)
293 snips.insert(0, latestsnip)
294
295 main = ""
296 i=0
297 totalsnips = len(snips)
298 mytemplate = Template(filename='./templates/snipstory.txt', module_directory='./tmp/mako')
299 for snip in snips:
300 version = totalsnips - i
301 (id, code, description, language, timesaved) = snip
302
303 languagename = get_longname(language)
304 code = format_code(language, code)
305 timesaved = time.ctime(timesaved)
306
307 main += mytemplate.render(description = description, snip = code, edittime = timesaved, language = languagename, snipid = snipid, snipstoryid = id, total = totalsnips, count = i)
308 i += 1
309
310 title = "Snipstory of snip %s" % (snipid)
311 header = title + " - <a href='?editsnip=%s'>edit</a>" % (snipid,)
312 print_page(title, main, header)
313
314 def format_code(language, code):
315 lexer = get_lexer(language, code)
316 formatter = HtmlFormatter(linenos=True, cssclass="source")
317 code = highlight(code, lexer, formatter)
318 return code
319
320 def revert_snip(snip_id, to_id):
321 cursor = dbh_open()
322
323 cursor.execute ("INSERT INTO snips_story (snip_id, code, description, language, timesaved) SELECT id, code, description, language, timesaved FROM snips_snip ss WHERE ss.id = %s; ", (snip_id,))
324
325 cursor.execute ("UPDATE snips_snip ss, snips_story st SET ss.code = st.code, ss.description = st.description, ss.language = st.language, ss.timesaved = %s WHERE ss.id = %s AND st.id = %s; ", (time.time(), snip_id, to_id))
326
327 dbh_close()
328 redirect(snip_id)
329
330 def add_comment(index):
331
332 (snip_id, code, description, language, timesaved, tags) = get_snip(index)
333
334 if tags == []:
335 tags.append('None')
336 tags = join(tags, ', ')
337
338 code = format_code(language, code)
339 languagename = get_longname(language)
340
341 mytemplate = Template(filename='./templates/snip.txt', module_directory='./tmp/mako')
342 main = mytemplate.render(description = description, tags = tags, snip = code, language = languagename, snipid = index)
343 title = "Add comment about snip - %s" % (snip_id)
344 header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a> | <a href='?snipstory=%s'>snipstory</a>" % (time.ctime(timesaved), snip_id, snip_id)
345
346 mytemplate = Template(filename="templates/newcomment.txt", module_directory='./tmp/mako')
347 main += mytemplate.render(submit = 'Add your 2 cents', snipid = index)
348
349 print_page(title, main)
350
351 def submit_comment(snipid, author, comment):
352 cursor = dbh_open()
353 cursor.execute ("INSERT INTO snips_comments (snip_id, author, comment, timesaved, flagged) VALUES (%s, %s, %s, %s, 0); ", (snipid, author, comment, time.time()))
354 dbh_close()
355 redirect(snipid,'viewcomments')
356
357 def view_comments(snipid):
358 cursor = dbh_open()
359 cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip WHERE id = %s; ", (snipid,))
360 snips = cursor.fetchall ()
361 cursor.execute ("SELECT id, author, comment, timesaved FROM snips_comments WHERE snip_id = %s AND flagged >= %s; ", (snipid,0))
362 comments = cursor.fetchall ()
363 dbh_close()
364
365 main = snips_to_snippets(snips)
366 mytemplate = Template(filename="templates/comment.txt", module_directory='./tmp/mako')
367 count = int((time.time() - snipid) % 123)
368 main += "<div id='container'>"
369 for comment in comments:
370 commentid, author, comment, timesaved = comment
371 color = count % 4 + 1
372 main += mytemplate.render(commentid = commentid, comment = comment, author = author, timesaved = time.ctime(timesaved), color = color)
373 count += count % 7
374 main += "</div>"
375 title = "Viewing comments about snip - %s" % (snipid)
376 print_page(title, main)

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26