I have a python script running fine on my localhost. Its not an enterprise app or anything, just something I'm playing around with. It uses the "bottle" library. The app basically consumes an XML file (stored either locally or online) which contains elements with their own unique IDs, as well as some coordinates, eg mysite.com/23 will bring back the lat/long of element 23. I'm sure you're all familiar with REST at this stage anyway.

Now, I want to put this online, but have had trouble finding a host that supports "bottle". I have, however, found a host that has django installed.

So, my question is, how hard would it be to convert the following code from bottle to django? And can someone give me some pointers? I've tried to use common python libraries.

thanks.

from xml.dom.minidom import parseString
from bottle import route, run
import xml
import urllib

file = open('myfile.xml','r')
data = file.read()
dom = parseString(data)
@route('/:number')
def index(number="1"):
    rows = dom.getElementsByTagName("card")[0].getElementsByTagName("markers")[0].getElementsByTagName("marker")
    for row in rows:
        if row.getAttribute("number") == str(number):
             return str(xml.dumps({'long': row.getAttribute("lng"), 'lat': row.getAttribute("lat")}, sort_keys=True, indent=4))
    return "Not Found"


run(host='localhost', port=8080)
有帮助吗?

解决方案

I took your question as an opportunity to learn a bit more about Django. I used The Django Book as a reference.

Starting with an empty Django site (django-admin.py startproject testsite), I've changed urls.py to this:

from django.conf.urls.defaults import patterns, include, url
from testsite.views import index

urlpatterns = patterns('',
    url(r'^(\d+)$', index),
)

And views.py to this:

from django.http import HttpResponse
from xml.dom.minidom import parseString
import xml
import urllib

def index(request, number):
    data = open('myfile.xml', 'r').read()
    dom = parseString(data)
    rows = (dom.getElementsByTagName("card")[0]
               .getElementsByTagName("markers")[0]
               .getElementsByTagName("marker"))

    for row in rows:
        if row.getAttribute("number") == str(number):
             return HttpResponse(str(xml.dumps({'long': row.getAttribute("lng"), 
                    'lat': row.getAttribute("lat")}, sort_keys=True, indent=4)))
    return HttpResponse("Not Found")

Caveat: I've not tested the XML code, only Django-related one, which I've tested via python manage.py runserver.

The Django Book contains a lot of information, including how to deploy this on a production server.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top