Hi Twisted-Web devs,
I am using Twisted for a web-application. I have a resource called Data, for which variables are called in a URL string:
http://localhost:8008/data?pet=dog&breed=lab&idtag=12345
Where 'pet' is a variable name, as is 'breed' and 'idtag', etc. This all works fine, and we get a JSON object back from the query that we use in the web application.
In terms of client ease of use we want to be able to handle URL parsing, such that:
http://localhost:8008/data?pet=dog&breed=lab&idtag=12345
can be written:
http://localhost:8008/pet/dog/lab/12345
which is a nice semantic URL.
However, we also have a bunch of static files (such as jquery javascript and images) that we serve in the application, like:
http://localhost:8008/images/layout.png
- and -
http://localhost:8008/jquery/functionality.js
We want to make sure we are handling these correctly and efficiently. From twisted.web we are using the rewrite module thus:
import sys
import os
import re
from twisted.web import server, static, rewrite
from twisted.application import service, internet
root = resource.Root()
# Another file (resource.py) defines the resources Data() and Root()
root.putChild('data', resource.Data())
root.putChild('images', static.File(images_dir))
root.putChild('jquery', static.File(js_dir))
rewrite_root = rewrite.RewriterResource(root, pathToArgs)
site = server.Site(rewrite_root)
application = service.Application('My App Name')
internet.TCPServer(8008, site).setServiceParent(application)
pathToArgs is the critical function, and it is where we are currently determining how to handle these different URL strings:
def pathToArgs(request):
parts = request.uri.split('/')
if request.uri == '/':
# Do nothing - at the root level
elif 'jquery' in request.postpath:
# Handle static jquery request
elif 'images' in request.postpath:
# Handle static image request
elif len(request.postpath) == 1:
# Handle only pet type
elif len(request.postpath) == 2:
# Handle pet type and breed
elif len(request.postpath) == 3:
# Handle pet type, breed and idtag
# Imagine this up to 'n' variables.....
elif len(request.postpath) == n
# Handle n variables
We seem to have an awful lot of replicated code in trying to parse the URL based on the length of the requested.postpath and dealing with each segment (split by '/') of the URL string. I feel that what we are trying to do has probably already been accounted for in the Twisted architecture available to us. Does anyone have any input on what (if anything) I am missing or lacking? Is this the correct way to approach development in Twisted? I am working my way through the O'Reilly Twisted Network Programming Essentials and studying the Twisted docs online, but I have not seen any 'best practices' approaches to application development, especially where parsing arguments is concerned.
Thanks in advance,
- Rob