Python mapscript
From DreamsteepWiki
PYTHON MAPSCRIPTING
TO INSTALL JUST EXCRACT mapscript-5.2.1.win32.zip in cgi-bin dir mapscript.pyc, etc
#!c:\python25\python.exe -u
import mapscript
import cgi
import cgitb; cgitb.enable();
import random
# path defaults
#
#map_path = "/ms4w/apps/test/"
#map_file = "first.map"
map_path = "/ms4w/apps/foobar/htdocs/"
map_file = "foo.map"
# Create a unique image name every time through
#
image_name = "pythonms_hello" \
+ str(random.randrange(999999)).zfill(6) \
+ ".png"
# Create a new instance of a map object
#
map = mapscript.mapObj(map_path+map_file)
# Create an image of the map and save it to disk
#
img=map.draw()
img.save("/ms4w/apps/foobar/htdocs/" + image_name)
# Output the HTML form and map image
#
print "Content-type: text/html"
print
print "<html>"
print "<header><title>Python Mapscript Hello World</title></header>"
print "<body>"
print """
<form name="hello" action="pythonms_hello.py" method="POST">
<input type="image" name="img" src="/tmp/%s">
</form>
""" % image_name
print "</body>"
print "</html>"
UNTESTED
#!/usr/bin/python
import mapscript
from cgi import parse_qsl
import os
import Image
from cStringIO import StringIO
BUFFER_PCT = 0.1
MAPFILE = 'soil.map'
########################################################
MAPFILE = os.path.join(os.path.dirname(__file__), MAPFILE)
def application(environ, start_response):
winput = dict(parse_qsl(environ['QUERY_STRING']))
format = winput.get('FORMAT', 'image/png')
start_response('200 OK', [('Content-Type', format)])
extension = format[format.find('/') + 1:]
wms = mapscript.mapObj(MAPFILE)
req = mapscript.OWSRequest()
for k,v in winput.items():
req.setParameter(k, v)
buffer = BUFFER_PCT/2
bbox = map(float, winput['BBOX'].split(","))
rangex = bbox[2] - bbox[0]
rangey = bbox[3] - bbox[1]
w = int(winput['WIDTH'])
h = int(winput['HEIGHT'])
xdelta = int(round(w * buffer)) # e.g add 13px on each side
ydelta = int(round(h * buffer)) # for 256x256 image
bbox[0] -= rangex * buffer # extend the
bbox[1] -= rangey * buffer # bbox in
bbox[2] += rangex * buffer # all
bbox[3] += rangey * buffer # directions
# http://trac.osgeo.org/mapserver/ticket/2299
req.setParameter('WIDTH', str(w + 2 * xdelta)) # and adjust the
req.setParameter('HEIGHT', str(h + 2 * ydelta)) # h, w by the same
req.setParameter('BBOX', ",".join(map(str,bbox))) # amount
req.setParameter("STYLES", "")
req.setParameter("REQUEST", "GetMap")
# PIL doesnt like interlace.
wms.outputformat.setOption('FORMATOPTIONS', 'INTERLACE=OFF')
wms.loadOWSParameters(req)
im = Image.open(StringIO(wms.draw().getBytes()))
if im is None: return ['']
# crop the image back to the requested w, h
im = im.crop((xdelta, ydelta, w + xdelta, h + ydelta))
buffer = StringIO()
im.save(buffer, extension)
buffer.seek(0)
data = buffer.read()
return [ data ]

