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


UCC Code Repository

Diff of /snips/snips/snips.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 47 by theodore, Thu Jun 26 02:52:06 2008 UTC revision 48 by theodore, Sat Jun 28 09:58:29 2008 UTC
# Line 1  Line 1 
1  import re  import re
2  import time  import time
3  import MySQLdb  import MySQLdb
4    import ConfigParser
5    
6  from os import sys  from os import sys
7  from string import join  from string import join
8    
9  """  """
# Line 15  import pygments Line 16  import pygments
16  from pygments import highlight  from pygments import highlight
17  from pygments.lexers import (guess_lexer, get_all_lexers, get_lexer_by_name)  from pygments.lexers import (guess_lexer, get_all_lexers, get_lexer_by_name)
18  from pygments.formatters import HtmlFormatter  from pygments.formatters import HtmlFormatter
19    from mako.template import Template
20    
21  del sys.path[0]  del sys.path[0]
22    
23  db_host         = "localhost"  config = ConfigParser.ConfigParser()
24  db_user         = "theodore"  config.read("./snips.cfg")
 db_password     = "Ko6aaWei"  
 db_database     = "test"  
   
 html_header = "Status: %s\nContent-Type: text/html\r\n\n"  
   
 homepage = """  
 <html>  
 <head>  
 <title><@[email protected]></title>  
 <link rel="stylesheet" type="text/css" href="css/snips.css" />  
 <link rel="stylesheet" type="text/css" href="css/pygment.css" />  
 <script></script>  
 </head>  
 <div id="sidebar">  
 <h3>Snap Cloud</h3>  
 <@[email protected]>  
 </div>  
 <div id="header">  
 <h1>Snips</h1>  
 <span>  
 <@[email protected]>  
 </span>  
 </div>  
 <div id="main">  
 <@[email protected]>  
 </div>  
 </html>  
 """  
25    
26  form = """  db_user     = config.get("database", "user")
27  <div id="%ssnip">  db_password = config.get("database", "password")
28  <form >  db_host     = config.get("database", "hostname")
29          <h3>Making a snip is as easy as py</h3>  db_database = config.get("database", "database")
           
         <label for="sniptags">Give your snip some tags:</label><br/>  
         <input type="text" name="tags" id="sniptags" value="%s" size="100"></input></br>  
           
         <label for="language">Pick your language</label>  
         <select name="language" id="language" value="" >%s</select></br>  
   
         <label for="sniptext">Add a description:</label><br/>  
         <textarea name="text" id="sniptext" rows="3" cols="100">%s</textarea></br>  
   
         <label for="snipcode">Add your code:</label><br/>  
         <textarea name="code" id="snipcode" rows="23" cols="100">%s</textarea></br>  
   
         <input type="submit" name="submit" value="%s"></input>  
         %s  
 </form>  
 </div>  
 """  
30    
31  snip = """  html_header = "Content-Type: text/html\r\n\n"
 <div id="code">  
 <@[email protected]>  
 </div>  
 """  
32    
33  def display_home():  def display_home():
34          main ="""          mytemplate = Template(filename="templates/home.txt", module_directory='./tmp/mako')
35          Welcome to Snips.          main = mytemplate.render()
         """  
36          header = "Snips Homepage"          header = "Snips Homepage"
37          title = "Snips Homepage"          title = "Snips Homepage"
38          print_page(title, main)          print_page(title, main)
39    
40  def new_snip():  def new_snip():
41          main = form % ('new', '', get_languages(), '', '', 'And Save It', '')          mytemplate = Template(filename="templates/form.txt", module_directory='./tmp/mako')
42          print_page("Snips - Create new snip", main)          main = mytemplate.render(action = 'new', tags = '', languages = get_languages(), description = '', code = '', submit = 'And Save It', hidden = '')
43          pass          print_page("Snips - Create new snip", main, "Create new snip")
44    
45  def edit_snip(index):  def edit_snip(index):
46                    
# Line 99  def edit_snip(index): Line 50  def edit_snip(index):
50                  tags.append('None')                  tags.append('None')
51          tags = join(tags, ' ')          tags = join(tags, ' ')
52                    
53          main = form % ('edit', tags, get_languages(language), description, code, 'Save Changes', '<input type="hidden" name="snip_id" value="%s"></input>' % (snip_id,) )          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)          title = "Editing snip - %s" % (snip_id)
57          header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a>" % (time.ctime(timesaved), snip_id)          header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a>" % (time.ctime(timesaved), snip_id)
# Line 107  def edit_snip(index): Line 59  def edit_snip(index):
59          print_page(title, main, header)          print_page(title, main, header)
60    
61  def get_languages(language = ''):  def get_languages(language = ''):
62          lexers = get_all_lexers()          lexers = []
63          list = '<option value="guess">Guess</option>'          list = '<option value="guess">Guess</option>'
64          for lexer in lexers:          for lexer in get_all_lexers():
65                  name = lexer[0]                  name = lexer[0]
66                  alias = lexer[1][0]                  alias = lexer[1][0]
67                    lexers.append((name,alias))
68            lexers.sort()
69            for name, alias in lexers:
70                  selected = ''                  selected = ''
71                  if alias == language:                  if alias == language:
72                          selected = 'selected="selected"'                          selected = 'selected="selected"'
73                  list += '<option value="%s" %s>%s</option>' % (alias, selected, name)                  list += '<option value="%s" %s>%s</option>' % (alias, selected, name)
74          return list          return list
75    
76  def sidebar():  def sidebar(sidebar = True):
77          return "Sidebar"          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():  def dbh_open():
89          global conn          global conn
# Line 143  def submit_new_snip(snip, description, l Line 107  def submit_new_snip(snip, description, l
107          snip_id = cursor.fetchone ()[0]          snip_id = cursor.fetchone ()[0]
108          snip_id = int(snip_id)          snip_id = int(snip_id)
109          for tag in tags:          for tag in tags:
110                  cursor.execute ("INSERT INTO snips_tags (snip_id, snap_tag) VALUES (%s, %s); ", (snip_id, tag))                  cursor.execute ("INSERT INTO snips_tags (snip_id, tag) VALUES (%s, %s); ", (snip_id, tag))
111    
112          dbh_close()          dbh_close()
113          error = "Snip ID is : %s <br> %s" % (snip_id,tags)          redirect(snip_id)
114          print_error(error)  
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 = []):  def update_current_snip(snip_id, code, description, language, tags = []):
120          cursor = dbh_open()              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))          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,))          cursor.execute ("DELETE FROM snips_tags WHERE snip_id = %s; ", (snip_id,))
125          for tag in tags:          for tag in tags:
126                  cursor.execute ("INSERT INTO snips_tags (snip_id, snap_tag) VALUES (%s, %s); ", (snip_id, tag))                  cursor.execute ("INSERT INTO snips_tags (snip_id, tag) VALUES (%s, %s); ", (snip_id, tag))
127    
128          dbh_close()          dbh_close()
129            redirect(snip_id)
130    
131  def get_snip(index):  def get_snip(index):
132          cursor = dbh_open()              cursor = dbh_open()    
133          cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip WHERE id = %s; ", (index,))          cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip WHERE id = %s; ", (index,))
134          snip_id, code, description, language, timesaved = cursor.fetchone ()          snip_id, code, description, language, timesaved = cursor.fetchone ()
135          cursor.execute ("SELECT snap_tag FROM snips_tags WHERE snip_id = %s; ", (snip_id,))          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          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 = []          tags = []
138          for tuple in tupletags:          for tuple in tupletags:
# Line 180  def print_snip(index): Line 149  def print_snip(index):
149                  tags.append('None')                  tags.append('None')
150          tags = join(tags, ', ')          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:          try:
164                  language = get_lexer_by_name(language)                  mylexer = get_lexer_by_name(language)
165          except:          except:
166                  try:                  try:
167                          language = guess_lexer(code)                          mylexer = guess_lexer(code)
168                  except:                  except:
169                          language = get_lexer_by_name('text')                          mylexer= get_lexer_by_name('text')
170            return mylexer
         formatter = HtmlFormatter(linenos=True, cssclass="source")  
         code = highlight(code, language, formatter)  
           
         main = """  
                 <div class=description">  
                 %s  
                 </div>  
                 <div class="snaps">  
                 Tags = %s  
                 <div>  
                 <div class="code">  
                 %s  
                 </div>  
         """ % (description, tags,  code)  
         title = "Viewing snip - %s" % (snip_id)  
         header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a>" % (time.ctime(timesaved), snip_id)  
171    
         print_page(title, main, header)  
172    
173  def tagify(tags):  def tagify(tags):
174          tags = re.split(r'\s*', tags)          tags = re.split(r'\s*', tags)
# Line 217  Prints Page with required variables Line 180  Prints Page with required variables
180  def print_page(title, main, header = ''):  def print_page(title, main, header = ''):
181          if header == '':          if header == '':
182                  header = title                  header = title
183          snapcloud = get_snapcloud()          mytemplate = Template(filename='./templates/main.txt', module_directory='./tmp/mako')
184          page = homepage          print html_header
185          page = page.replace("<@[email protected]>"                 , title)          print mytemplate.render(title = title, header = header, sidebar = sidebar(), main = main)
186          page = page.replace("<@[email protected]>"                , header)  
         page = page.replace("<@[email protected]>"             , snapcloud)  
         page = page.replace("<@[email protected]>"                  , main)  
         print html_header + page  
187          sys.exit(0)          sys.exit(0)
188    
189  def print_error(error):  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>'          error = '<div id="error"><em>An error has occurred processing your request please review the errors below</em><p>' + error + '</p></div>'
193          print_page("Snips - ERROR",error)          
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 get_snapcloud():  def show_all_tags():
227          cloud = ''          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()              cursor = dbh_open()    
238          cursor.execute ("SELECT snap_tag, COUNT(*) FROM snips_tags GROUP BY snap_tag ORDER BY COUNT(*) DESC LIMIT 20;")          cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip ORDER BY timesaved DESC LIMIT 10;")
239          for tag, count in cursor.fetchall ():          snips = cursor.fetchall ()
                 cloud += "<h4>%s - %s</h4>" % (tag, count)  
240          dbh_close()          dbh_close()
         return cloud  
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)

Legend:
Removed from v.47  
changed lines
  Added in v.48

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26