source: subversion/sites/wms.openstreetmap.de/wms.wsgi @ 28346

Revision 28346, 5.7 KB checked in by bastik, 2 years ago (diff)

more layer options

  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3#
4# Mapscript WMS server with default request parameters for josm
5#
6# to be used in conjunction with wsgi Interface
7#
8# (c) 2009-2010 Sven Geggus <sven-osm@geggus.net>
9#
10# Released under the GNU GENERAL PUBLIC LICENSE
11# http://www.gnu.org/copyleft/gpl.html
12#
13# $Id$
14#
15
16debug = 0
17mapfile="/osm/wms/osmwms.map"
18tcopyright="copyrighted Material: OSM use only"
19
20josmdefaults={'SERVICE': 'WMS', 'VERSION': '1.1.1', 'FORMAT':'image/png', 'REQUEST':'GetMap'}
21
22import os,crypt,mapscript,sys,math,string,cgi
23from time import *
24
25# make our WMS also usable as TMS
26def TileToMeters(tx, ty, zoom):
27  initialResolution = 20037508.342789244 * 2.0 / 256.0
28  originShift = 20037508.342789244
29  tileSize = 256.0
30  zoom2 = (2.0**zoom)
31  res = initialResolution / zoom2
32  mx = (res*tileSize*(tx+1))-originShift
33  my = (res*tileSize*(zoom2-ty))-originShift
34  return mx, my
35
36# this will give the BBox Parameter from x,y,z
37def TileToBBox(x,y,z):
38  x1,y1=TileToMeters(x-1,y+1,z)
39  x2,y2=TileToMeters(x,y,z) 
40  return x1,y1,x2,y2
41
42# generate a valid XML ServiceException message text
43# from a simple textual error message
44def SException(start_response,msg,code=""):
45  xml = '<ServiceExceptionReport '
46  xml += 'xmlns=\"http://www.opengis.net/ogc\" '
47  xml += 'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance" '
48  xml += 'xsi:schemaLocation=\"http://www.opengis.net/ogc '
49  xml += 'http://schemas.opengis.net/wms/1.1.1/OGC-exception.xsd\">\n'
50  if code == "":
51    xml += '  <ServiceException>\n  ' + msg
52  else:
53    xml += '  <ServiceException code=\"' + code +'\">\n  ' + msg
54  xml += '\n  </ServiceException>\n</ServiceExceptionReport>\n'
55  status = '200 OK'
56  response_headers = [('Content-type', 'application/vnd.ogc.se_xml'),('Content-Length', str(len(xml)))]
57  start_response(status, response_headers)
58  return xml
59
60# "main"
61def application(env, start_response):
62 
63  global debug
64  global tcopyright
65
66  # read apaceh environment variables
67  content_type = "text/plain"
68  response_headers = dict([('Content-type', content_type)])
69
70  url = "http://%s%s" % \
71        (env['SERVER_NAME'],env['REQUEST_URI'])
72
73  os.chdir(env['DOCUMENT_ROOT'])
74 
75  querystr = env['QUERY_STRING']
76  try:
77    uagent = env['HTTP_USER_AGENT']
78  except:
79    uagent = ''
80 
81  qupper=querystr.upper()
82 
83  # MAP=something in request is always an error 
84  if "MAP=" in qupper:
85    return SException(start_response,'Invalid argument "MAP=..." in request')
86   
87  # if tile=something is given we are in TMS mode
88 
89   
90  # parse QUERY_STRING
91  query = cgi.parse_qsl(querystr)
92  query = dict(query)
93 
94  msreq = mapscript.OWSRequest()
95
96  query_layers=''
97  tilemode=0
98  REQUEST=''
99  # ad QUERY items into mapscript request object
100  for key, value in query.items():
101    key=key.upper()
102    if (key == "DEBUG"):
103      debug = 1
104    if (key == "REQUEST"):
105      REQUEST = value
106    if (key == "LAYERS"):
107      query_layers=value
108      if ("," in query_layers):
109        return SException(start_response,'Multiple Layers are currently unsupported')
110    if key != "TILE":
111      msreq.setParameter(key,value)
112    else:
113      xyz=value.split(',')
114      if (len(xyz) != 3):
115        return SException(start_response,'Invalid argument "TILE=%s" in request, must be TILE=x,y,z' % value)
116      try:
117        x=int(xyz[0])
118      except:
119        return SException(start_response,'Invalid argument "TILE=%s" in request, must be TILE=x,y,z' % value)
120      try:
121        y=int(xyz[1])
122      except:
123        return SException(start_response,'Invalid argument "TILE=%s" in request, must be TILE=x,y,z' % value)
124      try:
125        z=int(xyz[2])
126      except:
127        return SException(start_response,'Invalid argument "TILE=%s" in request, must be TILE=x,y,z' % value)                                                                                                                                                     
128      tilemode=1
129
130  # we are in tilemode, lets add the required keys
131  if (tilemode):
132    msreq.setParameter("srs","EPSG:900913")
133    msreq.setParameter("bbox","%f,%f,%f,%f" % TileToBBox(x,y,z))
134    msreq.setParameter("width","256")
135    msreq.setParameter("height","256")
136
137  # add default QUERY items for use with JOSM
138  # this will allow for easy to remember WMS Request-URLs
139  if ("JOSM" in uagent) or (tilemode):
140    for d in josmdefaults:
141      if d not in qupper:
142        msreq.setParameter(d,josmdefaults[d])
143
144  map = mapscript.mapObj(mapfile)
145  map.setMetaData("wms_onlineresource",url.split("?")[0])
146 
147  try:
148    layer=map.getLayerByName(query_layers)
149    cstring=layer.metadata.get('copyright')
150    wms_disabled=layer.metadata.get('-wms-disabled')
151  except:
152    cstring=tcopyright
153 
154  if wms_disabled == 'true' and not tilemode:
155    return SException(start_response,'No WMS available for this layer, try TMS.')
156 
157  clayer=map.getLayerByName("copyright")
158  cclass=clayer.getClass(0)
159  cclass.setText(cstring)
160  if (REQUEST == "GetCapabilities"):
161    map.removeLayer(clayer.index)
162 
163  # write a mapfile for debugging purposes
164  if (debug):
165    os.umask(022)
166    map.save("/tmp/topomap.map")
167
168  # write mapserver results to buffer
169  mapscript.msIO_installStdoutToBuffer()
170  try:
171    res = map.OWSDispatch(msreq)
172  except:
173     return SException(start_response,str(sys.exc_info()[1]))
174
175  # adjust content-type
176  content_type = mapscript.msIO_stripStdoutBufferContentType()
177 
178  output=mapscript.msIO_getStdoutBufferBytes()
179 
180  # set Expire header to 100 days from now
181  expire = strftime('%a, %d %b %Y %H:%M:%S %z',gmtime(time()+3600*24*100))   
182 
183  response_headers = [('Content-type', content_type),
184                      ('Expires', expire),
185                      ('Content-Length', str(len(output)))]
186  status = '200 OK'
187  start_response(status, response_headers)
188 
189  # write image data to stdout
190  return output
191
Note: See TracBrowser for help on using the repository browser.