8c83b9ee412e — Nolan Prescott 4 years ago
Add 404 handling, set charset to UTF-8
1 files changed, 22 insertions(+), 10 deletions(-)

M glue_boy.py
M glue_boy.py +22 -10
@@ 1,10 1,7 @@ 
 #!/usr/bin/env python3
 '''
-A stupidly simple pastebin.
-
-requires current directory be on PYTHONPATH, e.g.
-  $ export PYTHONPATH=$(pwd)
-  $ twistd -n web --class=glue_boy.resource
+A stupidly simple pastebin. To start the server:
+    $ twist web --class=glue_boy.resource
 '''
 
 import datetime

          
@@ 31,20 28,25 @@ class GluesDatabase():
                                         (datetime.datetime.now(), paste_id))
         content = await self.db_pool.runQuery("SELECT content FROM glues "
                                               "WHERE id = ?", (paste_id,))
-        if content:
+        try:
             return content[0][0]
-        return ""
+        except:
+            raise NotFound()
 
     async def write_paste(self, content):
         '''
         Write string content to the database, return the id it was written with.
         '''
         paste_id = uuid4().hex[:6]
-        await self.db_pool.runOperation("INSERT INTO glues (id, content) VALUES (?, ?)",
-                                        (paste_id, content))
+        await self.db_pool.runOperation("INSERT INTO glues (id, content) "
+                                        "VALUES (?, ?)", (paste_id, content))
         return paste_id
 
 
+class NotFound(Exception):
+    pass
+
+
 class WebApp():
     app = Klein()
     db = GluesDatabase()

          
@@ 65,7 67,17 @@ class WebApp():
 
     @app.route('/content/<paste_id>', methods=['GET'])
     def existing_paste(self, request, paste_id):
-        request.setHeader('Content-Type', 'text/plain')
+        request.setHeader('Content-Type', 'text/plain; charset=utf-8')
         return self.db.get_paste(paste_id)
 
+    @app.handle_errors(NotFound)
+    def not_found(self, request, failure):
+        '''
+        error handling is ... funny, the name of this function doesn't matter
+        because it is resolving through the decorator (by exception type)
+        '''
+        request.setResponseCode(404)
+        return 'Not Found'
+
+
 resource = WebApp().app.resource