Blog

  • My best project ever!

    By Nuno Mariz, on 14 January 2008 @ 23:14
    Baby Baby
    The project is still under development. My co-worker is doing her best to provide the most beautiful layout.
  • Fullread updates

    By Nuno Mariz, on 10 January 2008 @ 10:34
    New features on Fullread:
    • Feeds in the latest and user bookmarks.
      • http://fullread.com/feeds/latest/[rss/atom]/ (By latest - all users)
      • http://fullread.com/feeds/[username]/[rss/atom]/ (By user)
    • List of users that bookmarked the same URL.
    • Multiple bookmarking service support.

    NOTE: If you are using a bookmarking service that is not available, please let me know: http://fullread.com/contacts/?subject=Bookmarking%20service%20support.

  • A quote from Theo Schlossnagle

    By Nuno Mariz, on 9 January 2008 @ 14:30
    The language is mostly irrelevant. I can’t count the number of times I’ve hear people say "Java doesn’t scale" or "PHP doesn’t scale". No languages scales; solutions scale.
    Theo Schlossnagle in "Scalable Internet Architectures"
  • Fullread

    By Nuno Mariz, on 3 January 2008 @ 19:53
    fullread.com
    Fullread is online. It's just a simple tool that helps you organize your online readings.
    I use del.icio.us a lot, mainly for bookmarking, but right now my account is a complete mess because I’m constantly adding links that I want to read later and I don't delete them.
    Fullread uses a simple concept: I add an URL to my account to read later, then I decide to archive, delete or add it to my del.icio.us account.
    Feel free to send me any feature request or something else.
    I hope you enjoy it.
  • Swim across the Atlantic Ocean

    By Nuno Mariz, on 30 November 2007 @ 14:53
    Google Maps
    Try to get directions from "Belo Horizonte" to "Miami" on Google Maps.
    Here is a shortcut: http://smallr.net/google-maps.
  • Smallr updates

    By Nuno Mariz, on 23 November 2007 @ 17:56
    After I've messed up about the domain issue(see this comments), I've just updated smallr with some features. Now provides an API to access the service by REST.
    Right now only supports JSON, XML will be is also available soon.
    A bookmarklet is also available.
  • Smallr

    By Nuno Mariz, on 22 November 2007 @ 19:51
    small.net
    I've just released smallr. It lets you generate small web addresses with a keyword that make it easy to remember, will not break in emails and will never expire.
    Basically is a TinyURL clone, with a keyword addon.
    There will be an API for webservices with JSON and XML, eventually a Firefox extension.
    Test it and send me some feedback.
    I hope you enjoy it.
  • Weekend in Sintra

    By Nuno Mariz, on 11 October 2007 @ 00:15
    Sintra Quinta das Sequóias
    We went to Sintra this weekend.
    Sintra is a magical place where you feel like you've just entered a time machine and you find yourself in a land of castles and palaces surrounded by a luxurious vegetation. It's inevitable to lose yourself in all the historical details that are related to this place and the numerous points of interest.
    To put the cherry on top of the cake, our choice for accommodation could not have been better! If you are looking for tranquility and be surrounded by all that magical atmosphere and... brace yourselves... have a room view to Pena Palace you will want to discover Quinta das Sequóias. A cosy and warm reception are expecting you as well as a delicious breakfast. We are absolutely going to return there.
    Some photos here.
  • iPhone says Welcome to Django

    By Nuno Mariz, on 20 August 2007 @ 20:50
    Django on iPhone
  • A simple WSGI middleware dispatcher

    By Nuno Mariz, on 8 June 2007 @ 10:41
    The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Having a standard interface makes it easy to use an application that supports WSGI with a number of different web servers.
    One implementation is wsgiref that was added to Python 2.5 Standard Library.
    Here is a simple web application that writes "Hello World":
    def index(environ, start_response):
        start_response("200 Ok", [('content-type', 'text/html')])
        return ['Hello World!']
    
    if __name__ == "__main__":
        from wsgiref.simple_server import make_server
        server = make_server(HOST, PORT, index)
        print 'Starting up HTTP server on port %i...' % PORT
        server.serve_forever()
    

    This is nice, but is not very useful for us, so lets add some kind of controller(or url dispatcher):
    from dispatcher import Dispatcher
    
    dispatcher = Dispatcher()
    dispatcher.add(r'^/$', 'views.index')
    dispatcher.add(r'^/hello/(?P<username>\w+)/$', 'views.hello')
    
    HOST = 'localhost'
    PORT = 8000
    
    if __name__ == "__main__": 
        from wsgiref.simple_server import make_server
        server = make_server(HOST, PORT, dispatcher)
        print 'Starting up HTTP server on port %i...' % PORT
        server.serve_forever()
    

    As you can see I've used a regular expression for the url mapping, just like Django uses.
    Here is the dispatcher(dispatcher.py):
    import re
    
    class Dispatcher(object):
        def __init__(self, handle404 = None):
            self.urls = dict()
            self.request_path = ''
            if handle404:
                self.handle404 = handle404
            else:
                self.handle404 = self._404
    
        def __call__(self, environ, start_response):
            self.request_path = environ.get('PATH_INFO', '')
            for url in self.urls:            
                regex = re.compile(url)
                if regex.match(self.request_path):
                    m = regex.match(self.request_path)                        
                    mod_name, func_name = self._get_mod_func(self.urls[url])                
                    try:
                        callback = getattr(__import__(mod_name, {}, {}, ['']), func_name)
                    except ImportError, e:
                        raise Exception, "Could not import %s. Error was: %s" % (mod_name, str(e))
                    except AttributeError, e:
                        raise Exception, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))                
                    args = (environ, start_response)
                    kwargs = dict()                
                    for i in regex.groupindex:
                        kwargs[i] = m.group(i)
                    # Run callback with environ, start_response and args
                    return callback(*args, **kwargs)
            # No match with the defined urls
            return self.handle404(environ, start_response)
                
        def _get_mod_func(self, callback):
            """
            Converts 'path.to.module.funtion' to ['path.to.module', 'function']
            """
            try:
                d = callback.rindex('.')
            except ValueError:
                return callback, ''
            return callback[:d], callback[d+1:]
        
        def _404(self, environ, start_response):
            start_response("404 Not Found", [('content-type', 'text/html')])
            return ['Not Found']
    
        def add(self, regex, handler):
            self.urls[regex] = handler
    

    And here is the views(views.py):
    def index(environ, start_response):
        start_response("200 Ok", [('content-type', 'text/html')])
        return ['Index']
    
    def hello(environ, start_response, username):
        start_response("200 Ok", [('content-type', 'text/html')])
        return ['Hello %s' % username]
    

    Simple eh?
    This is just a start, now we can add more features, like encapsulate the start_response method and add some kind of HttpResponse.
    I don't what do reinvent the wheel here and add another web framework to Python, just like Joe Gregorio says in this article. But to prove how trivial is to make a simple framework with WSGI and don't worry about the deployment at development phase.