Welcome to Python Diary I noticed that you are not currently signed in. Please take time and read the benefits of having an account.
These benefits include privary controls to disable your tracking via Google Analytics.

Index

  • Looking for advertising proposals

    Posted on Sunday, May 19th, 2013

    As some of you may have noticed, the AdSense bar no longer exists on my blog, this is due to Google recently revoking my AdSense account, I am quite sure it is in regards to mentioning it on a page. Currently users who have an account are able to opt'd out of either being tracked by Analytics or have no ads served to them. I will be removing this feature soon, as I am planning on self-hosting ads from prospect publishers. If you have a Python or Django related project which you would like to adverse on this blog, please contact me. Having a way to fund this website will allow me to publish more quality articles and tutorials. When a new article is posted, this blog receives over 1,000 hits in that single day. These are 1,000 prospect users which use Python and maybe Django who will see your advertisement. These can also be users who are just learning Python, so books and courses are also welcome.

    Currently the ad serving system has yet to be implemented, so at this time I am only asking prospect advertisers to provide me with a proposal on how the ads should be served to users and costs they might be willing to pay. For the record this blog has been online for well over a year now and receives many returning users due to the quality of the content which is provided. This website is also much more than a blog, as it has other features which bring users back for more.

    Thank you for your time in reading this.

  • DVD Collection source code now available

    Posted on Sunday, May 19th, 2013
    0 comments

    For those who were wanting a copy of the DVD Collection software made in Python, I have now open sourced it and it is live on BitBucket!

    DVD Collection software

  • Python Script to encode Django templates

    Posted on Sunday, May 19th, 2013
    3 comments

    Do you need to display raw Django template code in your Django <1.4 project? Look no further than this script! It's rather crude, but gets the job done. I haven't yet updated a few Django websites to Django 1.5, which has a new template tag to do this for you, so I created this script to use in legacy Django sites, and it works like a charm!

    #!/usr/bin/python
    
    import sys
    
    try:
      filename = sys.argv[1]
    except IndexError:
      print "This command needs exactly 1 parameter!"
      sys.exit()
    
    data = open(filename, 'r').read()
    data = data.replace('{%', '{! templatetag openblock !}').replace('%}', '{! templatetag closeblock !}')
    data = data.replace('{{', '{% templatetag openvariable %}').replace('}}', '{% templatetag closevariable %}')
    
    print data.replace('{!', '{%').replace('!}', '%}')
    

    You should Pygments to highlight the syntax like I do on this blog of course. If you are using Django 1.5 or greater, you should use the verbatim template tag over this.

  • Building a set of indie community focused Django apps

    Posted on Friday, May 10th, 2013
    0 comments

    Today I have just started work on an set of Django pluggable apps which can either be used independently or as a whole. The main focus is to provide Indie developers with an entire website framework which can be used to host a database of indie downloads, manage assets, support developer blogs and vlogs, and much more. I am building this as an open source project from the start, and it is hosted on BitBucket with the discussion hosted on Uarica.

    The first prototype of the website is done for anyone that's curious on how it currently looks, it can be accessed here.

    Uarica Project page
    BitBucket page

  • A birthday present for a friend made in Django

    Posted on Friday, April 19th, 2013
    5 comments

    I have a friend whom is a huge, and I really mean huge movie buff. He has the largest movie collection that I know of, and one the largest TVs I have seen. He was previously managing his collection using another website someone built, which I think is personally not very well done and my friend deserves much better!

    First I used the standard Python XML libraries to parse and extract all the movies he has on the old website, as I didn't want to re-enter all those movies, and I'm sure he wouldn't either. After it was all extracted and I was able to parse it easily through Python, I created the Django project and models for which the movie titles will live in. I created the first part of the website, including the importing of all his movies in just a mere 4.5 hours(according to my Subversion timestamp). I was truly amazed at what a full featured web application I could create in such little time, I could barely sleep last night as I wanted to continue work and add new features.

    Now, the website is nearing completion and I thought I'd share it here with all my loyal readers. This web application has full IMDb integration, which still has a few bugs here and there that need to be ironed out. I am currently debating if I should open source this creation or not...

    You can check this application at Cinema-Nick.com.

  • Will be taking another look at web2py

    Posted on Wednesday, April 10th, 2013
    3 comments

    My last encounter with Web2py was with version 2.0, this was back in October of 2012, of which I have a review for that version. Reviewing their changelog, I can see that this framework has evolved a great amount in just a few short months. There were many features which I praised about the framework, but there were still some things holding me back from using it over Django for my next project. So, with that, I am planning on diving back into web2py, and should have a new review up with the latest version. I have a project, I am thinking I may convert over to web2py and see how that goes. If development becomes quicker, then I will consider web2py for future projects as well.

    If you haven't already, I would recommend taking a look at web2py and see what it can offer your project. Both Django and web2py are similar, but at the same time they are very different. They both took the Ruby on Rails idea in their own direction. One thing to note, is that apps in web2py are not like apps in Django. This also makes working with web2py a little difficult at times, as it's not easy for apps to talk to each other, not as easy as it is in Django that is. However, in web2py, it's not an apps purpose to extend the frameworks functionality, it is the job of a plugin. That being said, web2py has grown a large amount since I last used it, so all my hardships I experienced last time around might be resolved.

  • Django 1.5 review is up

    Posted on Sunday, April 7th, 2013
    0 comments

    For those interested in Django to see if it's right for your next project, or if you are upgrading from an earlier version, this review is for you.

  • Source code released for my Django PIM suite

    Posted on Friday, April 5th, 2013
    0 comments

    Not sure how many of you were following my previous blog post about a bunch of Django apps I built for my own personal use. I have finally released the source code into BitBucket. Here's a short copy and paste recap of what you can find:

    PCBank AKA myFinance
    This is a personal budgeting system which I have created, it has matured a lot throughout the past few months. I originally created it in October of 2011, as using a spreadsheet to keep track of all my expenses grew tedious. It can also manage roommates, and split bills accordingly. This is my most used app out of all of the apps I created. It also has an RSS and JSON interface for third party applications to fetch data. I use the RSS for a Live Bookmark to easily access all my online banking websites from my browser toolbar. I use the JSON interface with a mobile app I created so that I can easily check my bank balances on the go without needing to actually sign into my online bank website on an insecure wireless network.
    myProjects
    This app was created in recent months to keep track of my many projects I do. It keeps track of individual projects, which I can jot down notes about each one. I can create goals under each project and assign a due date for them. This makes seeing all my workload and upcoming goals easy to browse, and add personal notes to.
    myServers
    Sort of an extension to myProjects above, as it keeps track of my various servers I run and operate. It sorts the servers by hosting provider. Then under each server, I can list the various applications which the server runs. Makes it easy to know where everything is located in my infrastructure.
    django-pim Source code

    Let me know what you think, all of these use Bootstrap for theming and some of them have APIs such as iCalendar, RSS, and JSON. PCBank was developed a very long ago, and some of the programming practices in there need some updating. I have included an svnlog.txt file in each app's directory so you can see just how each project grow since 2011. Yes, you heard me... 2011 was one of the early commits.

  • Using Pyjamas with Bootstrap

    Posted on Thursday, April 4th, 2013
    0 comments

    For a just for fun experiment, I attempted to re-create the standard Bootstrap, from Twitter theme using Pyjamas. It turned out pretty good too. Here is the source code to compile to JavaScript:

    from pyjamas.ui.RootPanel import RootPanel
    from pyjamas.ui.Button import Button
    from pyjamas import DOM
    from pyjamas.ui.Hyperlink import Hyperlink
    from pyjamas.ui.SimplePanel import SimplePanel
    from pyjamas.ui.ComplexPanel import ComplexPanel
    from pyjamas.ui.FlexTable import FlexTable
    
    class CustomPanel(ComplexPanel):
        def __init__(self, Element=None, **kwargs):
            if Element is None:
                Element = DOM.createDiv()
            self.setElement(Element)
            ComplexPanel.__init__(self, **kwargs)
    
    class NavItems(CustomPanel):
        def __init__(self, nav_list=None, **kwargs):
            CustomPanel.__init__(self, Element=DOM.createElement("ul"))
            self.addStyleName("nav")
            self.items = []
            if nav_list == None:
                nav_list = {'Home': self.onClick, 'About': self.onClick, 'Contact': self.onClick}
            for item in nav_list:
                tmp = Hyperlink(item, Element=DOM.createElement("li"))
                tmp.addClickListener(nav_list[item])
                self.items.append(tmp)
            for item in self.items:
                self.add(item)
        def clearActive(self):
            for item in self.items:
                item.removeStyleName("active")
        def onClick(self, sender):
            self.clearActive()
            sender.addStyleName("active")
        def setActive(self, item_id):
            self.clearActive()
            self.items[item_id].addStyleName("active")
    
    class NavBar(SimplePanel):
        def __init__(self, brand="Project name", nav=None, **kwargs):
            SimplePanel.__init__(self, **kwargs)
            self.addStyleName("navbar")
            self.addStyleName("navbar-inverse")
            self.addStyleName("navbar-fixed-top")
            self.setWidget(SimplePanel())
            self.getWidget().addStyleName("navbar-inner")
            self.container = CustomPanel()
            self.getWidget().setWidget(self.container)
            self.container.addStyleName("container")
            self.brand = Hyperlink(brand)
            self.brand.setElement(self.brand.anchorElem)
            self.brand.addStyleName("brand")
            self.container.add(self.brand)
            if nav == None:
                self.nav = NavItems()
            elif isinstance(nav, dict):
                self.nav = NavItems(nav)
            self.container.add(self.nav)
            self.nav.setActive(0)
        def setBrand(self, text):
            self.brand.setText(text)
        def setActive(self, item):
            self.nav.setActive(item)
    
    navbar = NavBar()
    state = 0
    
    def alter_brand(sender):
        global state
        navbar.setActive(1)
        if state == 0:
            navbar.removeStyleName("navbar-inverse")
            state = 1
        else:
            navbar.addStyleName("navbar-inverse")
            state = 0
    
    btn = Button("Hello Bootstrap!", alter_brand)
    btn.setStyleName("btn btn-primary")
    
    container = CustomPanel()
    container.addStyleName("container")
    container.add(btn)
    
    RootPanel().add(navbar)
    RootPanel().add(container)
    
    tbl = FlexTable()
    tbl.addStyleName("table")
    tbl.setText(0, 0, "Hello World!")
    tbl.setText(1,0,"Python rocks")
    tbl.setText(0,1,"Coding in my Pyjamas is awesome!")
    tbl.setText(1,1,"Bootstrap works with Pyjamas!")
    tbl.addStyleName("table-striped")
    
    container.add(tbl)
    

    This code requires the latest version of Pyjamas, version 0.8.1a as of this writing. It won't work in 0.8, which I'm curious on why. You can see a full working demo here.

  • Full map of Django 1.5 generic class views

    Posted on Wednesday, April 3rd, 2013
    1 comment

    Something which I have had yet to see anywhere online is an Epydoc of Django's class-based views. Without further adieu, I provide the Python community with a generated epydoc of Django 1.5's class-based views in all it's glory!

    Django 1.5 class views Epydoc

    On this note, I plan on adding additional Epydocs as well of other packages which seem interesting but are under-documented. Hopefully this first Epydoc helps a bunch of you out there. Enjoy!

  • Idea Collaboration in spirit of GitHub

    Posted on Wednesday, April 3rd, 2013
    1 comment

    Do you sometimes have too many ideas and no time to implement them? Or would you like some collaborative input on these ideas? How about the ability for you to fork someone else's idea, or for someone to be-able to fork yours into a new direction? Most idea collaboration software is closed, where only a small team can collaborate and grow this idea into something. These existing software suites do not provide a means for public collaboration. Forums are the closest you have for idea collaboration, however forums do not allow you to easily take over an idea and send it off in a new direction. My latest idea was to create an idea collaboration software suite, something with features that will appeal to the open source community, with features like forking of ideas into new branches to enhance collaboration. It was also a priority to enable easily access to analytical data, where you can easily see what other similar projects are using to develop their ideas or see what projects are using the same tools as you are. Having this type of data at your disposal can help grow ideas quicker, as cross-references between ideas can be made. If your seeking help on a specific tool, you can easily and effortlessly see who else is using that tool and seek assistance from them or from their open source code directly.

    This collaboration suite is not only for open source projects, but it can be used to collaborate on almost any type of idea you can dream of. If you have an interesting idea and want to see how much interest it may spark, plant the idea here and see if it grows. There is no commitment to maintain the idea you plant yourself, as someone more specialized in the field can easily fork it and grow it themselves. Each branch is tracked and can be easily cross-referenced to see the differences in one direction from another.

    Uarica: Idea Collaboration will see many new features in the near future. Currently the main features are available for public consumption, such as Forking, general notes, idea asset management(used for analytical data), user profiles, ability to follow users, like ideas, and more. This website was build using Django in roughly 1 day, and is a testament on how rapidly something can be built using Django. It is currently deployed on RedHat OpenShift platform.

    Future features will include full GitHub and BitBucket project integration for open source projects. You will be-able to access both the Issues and full source code repo. BitBucket's API is very nice, and supports both of these features. I haven't yet played with GitHub's API, and I am hoping I can do the same with it. User profiles currently include the ability to link to both websites via a standard link. Ideas can also link to both sites as well.

    Another feature which should be added shortly is a Twitter feed for each user profile and idea, so all of your tweets will appear in your profile and in the ideas page. This will allow people to easily see what you have been up to. Feeds for GitHub and BitBucket are also planned.

    Currently closed door ideas are not available, but are supported in the backend. These types of ideas will be made available to the general public once the site gains enough open door ideas, and once more features that compete with existing project management suites are added.

    I also hope to look into APIs that can help accelerate ideas and implement them. There are a vast amount of resources on the Internet, and being able to use them easily in a single collaboration suite would be very nice to have. For example, the ability to turn an idea into a Kickstarter project with the click of a button comes to mind. Perhaps integration with existing project management software such as BaseCamp. Google Drive integration is already planned, as it provides a nice cloud whiteboard for easily collaboration and document storage.

    The latest feature I just added(in about an hour of coding) is a petition add-on. This allows you to effortlessly create a petition attached to your idea. It supports a goal, a closing date, and user liking. Petitions are especially useful when attempting to get your idea out there, especially in front of political parties or large companies. There is an example petition on the Uarica idea, which closes at the end of this month with a goal of only 50 signatures. Petitions are available to anybody to view, but in order to place your signature on it, you will need to be signed-in. When forking an idea, petitions don't go with it for obvious reasons. I may add the ability to copy over completed petitions, if there is demand for it.

    Let me know what you think of this idea in the comments below.

  • Why DRY programming is so important

    Posted on Wednesday, April 3rd, 2013
    2 comments

    With the introduction of DRY(Don't Repeat Yourself) programming model, lots of existing programming languages and their associated frameworks have been jumping on broad. Some frameworks such as Ruby on Rails and Django were built from the ground up to use DRY. Django includes so many DRY helpers that creating a full featured application takes no longer than a couple days of work. With the introduction to DRY programming, it's hard to believe why so many developers still choose to use tools which include so much manual labor... Why are these programmers reinventing the wheel every single day? One of the most common tasks done in web development and design is building a data-driven form. I recently downloaded a plugin from the wordpress website to see just exactly how far this framework has progressed over the years in terms of developer friendliness and DRY principals. I was truly disappointed to see a simple Contact form require so much code. The code itself is a total of 90.6KB, a whopping 1,280 lines(with comments and blank lines). This code also contains the front-end layer for the admin interface in Wordpress along with how it's suppose to integrate with the website. In comparsion, here is the Django DRY version of a contact form(easily extendable to include new fields and includes Captcha as well):

    # contact_form.py
    from django import forms
    from django.views.generic.edit import FormView
    from django.core.mail import mail_admins
    from django.contrib import messages
    from django.template.loader import render_to_string
    from captcha.fields import ReCaptchaField
    
    class ContactForm(forms.Form):
        your_name = forms.CharField()
        your_email = forms.EmailField()
        message = forms.CharField(widget=forms.Textarea)
        captcha = ReCaptchaField()
        def send_email(self, ipaddr):
            body = render_to_string('contact.txt', {'name':self.cleaned_data['your_name'],
                                                    'email':self.cleaned_data['your_email'],
                                                    'ipaddr':ipaddr,
                                                    'message':self.cleaned_data['message']})
            mail_admins('Website contact form', body)
    
    class ContactView(FormView):
        template_name = 'contact_form.html'
        form_class = ContactForm
        success_url = '/'
        def form_valid(self, form):
            form.send_email(self.request.META['REMOTE_ADDR'])
            messages.success(self.request, "Your message has been sent!")
            return super(ContactView, self).form_valid(form)
        def form_invalid(self, form):
            messages.error(self.request, "There was an error submitting the form, please review and try again.")
            return super(ContactView, self).form_invalid(form)
    

    That's really it, I added some extra functionality to it, and it's easy to add new fields. The best part is, when adding new fields, you don't even need to touch the HTML code, it's all inclusive. You can see this exact form live on this website. Here is the most basic template without all the bootstrap magic:

              <form action="{% url 'contact-form' %}" method="post">{% csrf_token %}
                  <legend>Contact form</legend>
                  {{form.as_p}}
                  <button type="submit">Send Message</button>
              </form>
    

    There are a few different form formatters you can use, table, p, and ul. You can also make your own and include that into any template with a form. Here is one for bootstrap:

    {% for field in form %}
    <div class="control-group{% if field.errors %} error{% endif %}">
      <label class="control-label" for="{{field.id_for_label}}">{{field.label}}</label>
      <div class="controls">
        {{field}}
        {% if field.errors %}<span class="help-inline">{% for err in field.errors %}{{err}}{% endfor %}</span>
        {% else %}{% if field.help_text %}<span class="help-inline">{{field.help_text}}</span>{% endif %}{% endif %}
      </div>
    </div>
    {% endfor %}
    

    All the error messages are provided by their respective FormFields, if the email address entered isn't really an email address, then the user will automatically see an appropriate error message. I only needed to write the user facing HTML code once for the bootstrap look and feel. Then for each form on the website you see there, I merely include this bootstrap look and feel, the Django forms system takes care of the rest regardless of what fields the form has. If you create an account and use the website a bit, you see some dynamic forms controlled using jQuery, still using that same template above, just a different Django form field or widget. My consulting website's Quote form has a form that uses TinyMCE and a jQuery UI date dropdown. All of this was added to these websites in way under 1,000 lines of code. Django takes care of all the repetitive details for me. This is also why I don't charge an arm and a leg for a web development job, as the job with Django compared to some other frameworks out there is super easy! With the bootstrap-ajax jQuery plugin, you can effortlessly submit forms over AJAX. Their example code is made in Django by the way(This definitely shows the growing popularity of Django).

    Now, I normally don't do comparisons on this website, but after peeking at a wordpress plugin and seeing how not DRY it was, I needed to show prospect Django developers what they will be in for, if they plan on moving to a DRY framework. I do hope to add some tutorials and other articles soon showing how to create full applications using Django with less code than competing frameworks out there. Once you go Django, you seriously won't go back. I never did, and now I am a very proud Django web developer who advocates not re-inventing the wheel. Other fun DRY features of Django besides forms and forms based on database tables, is:

    Pagination
    Pagination is widely used in web applications, and Django includes both a low-level Paginator class that can be used with almost any data types. This class is the basis for the pagination used in the generic views for paginating database tables.
    Built-in role-based permission system
    Controlling access to resources couldn't be easier than in Django. You can easily restrict users based on either what group they are in or what fine-grained permissions they have on a particular database table. The permissions themselves are assigned and managed easily through an automatically generated interface. The API to check for permissions is very easy to use and can be used in either the Python source code or the HTML templates.
    Validators
    With custom easy to create validators, you can extend your database table and forms to only accept specifically formatted data from the user. Existing validators exist for Email addresses, IP addresses, URLs, and number ranges. A custom validator can effortlessly be attached to a data model, such a database field or form.
    Signals
    Signals are used to run specific functions when a specific event in the application occurs. It can be used to uncache something which was recently modified for example. You can even build your own signals, which is normally used in 3rd party apps to allow developers an easy API to watch and react to specific application events.
    Caching
    With caching support and a set of pluggable backends, you can easily cache data in your application for a variety of purposes. Caching can occur at any level, you can cache every single page request, cache specific URLs, only cache anonymous requests, specific blocks in a template, or even Python objects at the lowest level. Mastering this component will speed up your application and prevent any unneeded database queries. If you cache page requests, you can even use a supporting web server to serve the cached item and bypass Django entirely for some requests, speeding up your application even more.

    Since all of these components are shared with an entire Django project, each app, both yours and 3rd party ones are free to communicate with one another with little effort. You can easily create related database fields to a 3rd party app, such as a blog, forum, eShop, etc... All these apps will share the same user information, allowing your users to use a single identity throughout. Since all the data easily relatable, analytics couldn't be easier. You can more easily create a unified product, where users on your forum can easily link a post to a discussion about an item in the eShop. The forum post can contain most, if not all the metadata from the item being sold for easy reference. Users of the website can like an eShop item and this information can be displayed in the forum with little work required. The users can also have a unified profile, where it contains a list of their forum posts, their eShop likes, recent purchases, and reviews on products. Why should a user need to have 2 or more accounts on a single website? I see this a lot, and I absolutely hate it. This is why DRY is so important! It's not only beneficial for the developer, but it can also help the end user's experience as well.

  • Deployed Uarica on OpenShift

    Posted on Tuesday, April 2nd, 2013
    2 comments

    You may have heard of a cloud hosting provider called RedHat OpenShift. I just spend a few hours moving a Django app from my Rackspace Cloud server over there. It was a website I recently deployed, so no data needed to be migrated. First, I needed to move the source code into a GIT repository, which was very easy for the most part. I also needed to change the settings.py and create a setup.py file, easy enough. Once I ran git push, the site was online fairly quickly... Except for the static files. I spend a couple hours attempting to get static files to work with RedHat's OpenShift platform, with no success. I went through their documentation, the forums, and finally their IRC channel. There was no hope in sight. In the end, I used the Django-cumulus package to copy all the static files to my Rackspace CloudFiles account and pointed the STATIC_URL there and was done with it.

    So after much frustration with static files, the site is now live and working under RedHat's service. You can see it live here: Uarica.com. I plan on putting out a tutorial for deploying a Django app using their service, my current tutorial doesn't show enough on how to get it working right, especially with static files, which is the most trickiest part of hosting a Django app it seems.

  • Rethinking my hosting options...

    Posted on Tuesday, April 2nd, 2013
    6 comments

    I have recently deployed a new web application using Django, into my Rackspace Cloud server. This server doesn't seem to have enough resources to host as many apps as I currently have deployed. This is leading the uWSGI instance to throttle down lesser used instances. Since this new app is new, and there is currently not much traffic going to it, each time it's not used for an hour, the instance goes idle. Then the next request after the idle takes about 1-2 minutes to spin up the instance. If I plan on advertising this app, I'd rather have an app that functional on each request. If too many apps are up and the server runs low on memory, then nginx returns a Bad Gateway error, which I saw a few times after deploying the app. So far, it seems PythonDiary is unaffected, as it has a large amount of hourly traffic to keep the instance from idling.

    If I plan on upgrading my Rackspace Cloud server, it will cost a little more than I would currently like to spend in my budget for hosting at this time. This has lead me to rethink my hosting options...

    So far I am really eyeballing PythonAnywhere, as they are very affordable, and Python centric. With the hosting plan offered by them, it allows up to 10 domain names, which is perfect. I don't quiet have that many just yet, but I am nearing that amount. I also looked at RedHat OpenShift, which is free at first. Currently, I do not think I want to spend the time and effort moving everything to a new platform, so I am thinking of just moving my latest asset to RedHat's offering and see where this new asset goes first. This will remove the pressure that my other apps have been experiencing under my current server. I am also thinking of looking into Google App Engine for my personal profile page, but the lack of a relational database still scares me. A large amount of Django's ORM features depend on a solid relational database.

    What hosting provider do you currently prefer for hosting your Python web application?

  • Layering SSL over the XMLRPCServer

    Posted on Wednesday, March 27th, 2013

    I really enjoy how simple it is to use xmlrpclib over other APIs such as REST. I also understand that it's insecure, as it does not support authentication as REST APIs do. Although there should technically be a way to implement an authentication layer over XML-RPC. The SimpleXMLRPCServer class which ships in Python's standard library doesn't natively support SSL socket encryption. For private XML-RPC Services, which I do not want otherwise exposed, especially over plain text, SSL encryption is required. I also prefer a stand-alone server over piggybacking on an SSL enabled web-server. This enables me to choose a random port, and create services which can otherwise monitor the web service remotely. How can you monitor a web service using a web service, if the web service is having trouble... Also since the xmlrpclib module ships in the Python standard library, and supports SSL/HTTPS servers, it makes it a great light-weight protocol to use anywhere Python can be installed. I have Python installed on my Symbian smartphone, and both my Android phone and tablet. Running a quick script from my home screen yields quick results from my XML-RPC service. Anyways, enough of my rambling and justifications for using XML-RPC over a more popular protocol... Here's the class you came here to steal from my blog:

    from SocketServer import TCPServer
    import ssl
    from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCDispatcher, SimpleXMLRPCRequestHandler
    try:
        import fcntl
    except ImportError:
        fcntl = None
    
    CERT_FILE = '/home/kveroneau/cert.pem'
    
    class SSLServer(TCPServer):
        def get_request(self):
            newsocket, fromaddr = self.socket.accept()
            connstream = ssl.wrap_socket(newsocket, server_side=True,
                                         certfile=CERT_FILE, keyfile=CERT_FILE,
                                         ssl_version=ssl.PROTOCOL_SSLv23)
            return (connstream, fromaddr)
    
    class SimpleXMLRPCServer(SSLServer,
                             SimpleXMLRPCDispatcher):
        """Simple XML-RPC server.
    
        Simple XML-RPC server that allows functions and a single instance
        to be installed to handle requests. The default implementation
        attempts to dispatch XML-RPC calls to the functions or instance
        installed in the server. Override the _dispatch method inhereted
        from SimpleXMLRPCDispatcher to change this behavior.
        """
    
        allow_reuse_address = True
    
        # Warning: this is for debugging purposes only! Never set this to True in
        # production code, as will be sending out sensitive information (exception
        # and stack trace details) when exceptions are raised inside
        # SimpleXMLRPCRequestHandler.do_POST
        _send_traceback_header = False
    
        def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
                     logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
            self.logRequests = logRequests
    
            SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
            SSLServer.__init__(self, addr, requestHandler, bind_and_activate)
    
            # [Bug #1222790] If possible, set close-on-exec flag; if a
            # method spawns a subprocess, the subprocess shouldn't have
            # the listening socket open.
            if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
                flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
                flags |= fcntl.FD_CLOEXEC
                fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
    
    if __name__ == '__main__':
        print 'Running XML-RPC server on port 8000'
        server = SimpleXMLRPCServer(("localhost", 8000))
        server.register_function(pow)
        server.register_function(lambda x,y: x+y, 'add')
        server.serve_forever()
    

    There must be a more elegant way of doing this, but I was unsuccessful with creating a Mixin that could simply overwrite TCPServer.get_request(). If you know of a better way of implementing this code, please send it my way, and I will update this post and credit you for your assistance. To generate the PEM file mentioned above, use this command-line:

    kveroneau@sys1:~$ openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
    Generating a 1024 bit RSA private key
    ...++++++
    ..................................++++++
    writing new private key to 'cert.pem'
    -----
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [AU]:CA
    State or Province Name (full name) [Some-State]:Manitoba
    Locality Name (eg, city) []:Winnipeg
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Veroneau.net
    Organizational Unit Name (eg, section) []:I.T.
    Common Name (eg, YOUR name) []:Kevin
    Email Address []:***HIDDEN***
    

    A bonus of this, is that you can use SSLServer class to replace any TCPServer class and add SSL to any existing program that uses TCPServer. For non-light weight programs, consider using Twisted, it is a much more featureful Python package for creating and deploying networked applications.

About Me

My Photo
Names Kevin, hugely into UNIX technologies, not just Linux. I've dabbled with the demons, played with the Sun, and now with the Penguins.




Kevin Veroneau Consulting Services
Do you require the services of a Django contractor? Do you need both a website and hosting services? Perhaps I can help.
Python Powered | © 2012 Kevin Veroneau