QGIS Server and Python¶
QGIS Server is three different things:
QGIS Server library: a library that provides an API for creating OGC web services
QGIS Server FCGI: a FCGI binary application
qgis_maserv.fcgithat together with a web server implements a set of OCG services (WMS, WFS, WCS etc.) and OGC APIs (WFS3/OAPIF)
QGIS Development Server: a development server binary application
qgis_mapserverthat implements a set of OCG services (WMS, WFS, WCS etc.) and OGC APIs (WFS3/OAPIF)
This chapter of the cookbook focuses on the first topic and by explaining the usage of QGIS Server API it shows how it is possible to use Python to extend, enhance or customize the server behavior or how to use the QGIS Server API to embed QGIS server into another application.
There are a few different ways you can alter the behavior of QGIS Server or extend its capabilities to offer new custom services or APIs, these are the main scenarios you may face:
EMBEDDING → Use QGIS Server API from another Python application
STANDALONE → Run QGIS Server as a standlone WSGI/HTTP service
FILTERS → Enhance/Customize QGIS Server with filter plugins
SERVICES → Add a new SERVICE
OGC APIs → Add a new OGC API
Embeding and standalone applications require using the QGIS Server Python API directly from another Python script or application while the remaining options are better suited for when you want to add custom features to a standard QGIS Server binary application (FCGI or development server): in this case you’ll need to write a Python plugin for the server application and register your custom filters, services or APIs.
Server API basics¶
The fundamental classes involved in a typical QGIS Server application are:
QgsServerthe server instance (typically a single instance for the whole application life)
QgsServerRequestthe request object (typically recreated on each request)
QgsServerResponsethe response object (typically recreated on each request)
QgsServer.handleRequest(request, response)processes the request and populates the response
The QGIS Server FCGI or development server workflow can be summarized as follows:
1 2 3 4 5 6 7 8 9
initialize the QgsApplication create the QgsServer the main server loop waits forever for client requests: for each incoming request: create a QgsServerRequest request create a QgsServerResponse response call QgsServer.handleRequest(request, response) filter plugins may be executed send the output to the client
QgsServer.handleRequest(request, response) method
the filter plugins callbacks are called and
QgsServerResponse are made available to the plugins through
QGIS server classes are not thread safe, you should always use a multiprocessing model or containers when building scalable applications based on QGIS Server API.
Standalone or embedding¶
For standalone server applications or embedding, you will need to use the above mentioned server classes directly, wrapping them up into a web server implementation that manages all the HTTP protocol interactions with the client.
A minimal example of the QGIS Server API usage (without the HTTP part) follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
from qgis.core import QgsApplication from qgis.server import * app = QgsApplication(, False) # Create the server instance, it may be a single one that # is reused on multiple requests server = QgsServer() # Create the request by specifying the full URL and an optional body # (for example for POST requests) request = QgsBufferServerRequest( 'http://localhost:8081/?MAP=/qgis-server/projects/helloworld.qgs' + '&SERVICE=WMS&REQUEST=GetCapabilities') # Create a response objects response = QgsBufferServerResponse() # Handle the request server.handleRequest(request, response) print(response.headers()) print(response.body().data().decode('utf8')) app.exitQgis()
Here is a complete standalone application example developed for the continuous integrations testing on QGIS source code repository, it showcases a wide set of different plugin filters and authentication schemes (not mean for production because they were developed for testing purposes only but still interesting for learning):
Server python plugins are loaded once when the QGIS Server application starts and can be used to register filters, services or APIs.
The structure of a server plugin is very similar to their desktop counterpart,
QgsServerInterface object is made available to
the plugins and the plugins can register one or more custom filters, services or APIs
to the corresponding registry by using one of the methods exposed by the server interface.
Server filter plugins¶
Filters come in three different flavors and they can be instanciated by subclassing
one of the classes below and by calling the corresponding method of
I/O filters can modify the server input and output (the request and the response) of the core services (WMS, WFS etc.) allowing to do any kind of manipulation of the services workflow, it is possible for example to restrict the access to selected layers, to inject an XSL stylesheet to the XML response, to add a watermark to a generated WMS image and so on.
From this point, you might find useful a quick look to the server plugins API docs.
Each filter should implement at least one of three callbacks:
All filters have access to the request/response object (
and can manipulate all its properties (input/output) and
raise exceptions (while in a quite particular way as we’ll see below).
Here is the pseudo code showing how the server handles a typical request and when the filter’s callbacks are called:
1 2 3 4 5 6 7 8 9 10 11 12 13
for each incoming request: create GET/POST request handler pass request to an instance of QgsServerInterface call requestReady filters if there is not a response: if SERVICE is WMS/WFS/WCS: create WMS/WFS/WCS service call service’s executeRequest possibly call sendResponse for each chunk of bytes sent to the client by a streaming services (WFS) call responseComplete call sendResponse request handler sends the response to the client
The following paragraphs describe the available callbacks in details.
This is called when the request is ready: incoming URL and data have been parsed and before entering the core services (WMS, WFS etc.) switch, this is the point where you can manipulate the input and perform actions like:
add/remove certain parameters (typenames for example)
You could even substitute a core service completely by changing SERVICE parameter and hence bypassing the core service completely (not that this make much sense though).
This is called whenever any output is sent to FCGI
stdout (and from there, to
the client), this is normally done after core services have finished their process
and after responseComplete hook was called, but in a few cases XML can become so
huge that a streaming XML implementation was needed (WFS GetFeature is one of them),
in this case,
called multiple times before the response
is complete (and before
responseComplete is called).
The obvious consequence
normally called once but might be exceptionally
called multiple times and in that case (and only in that case) it is also called
sendResponse is the best place
for direct manipulation of core service’s
output and while
is typically also an option,
sendResponse is the only
viable option in case of streaming services.
This is called once when core services (if hit) finish their process and the
request is ready to be sent to the client. As discussed above, this is normally
except for streaming services (or other plugin
filters) that might have called
responseComplete is the
ideal place to provide new services implementation
(WPS or custom services) and to perform direct manipulation of the output coming
from core services (for example to add a watermark upon a WMS image).
Raising exceptions from a plugin¶
Some work has still to be done on this topic: the current implementation can
distinguish between handled and unhandled exceptions by setting a
QgsRequestHandler property to an
instance of QgsMapServiceException,
this way the main C++ code can catch handled python exceptions and ignore
unhandled exceptions (or better: log them).
This approach basically works but it is not very „pythonic“: a better approach would be to raise exceptions from python code and see them bubbling up into C++ loop for being handled there.
Writing a server plugin¶
A server plugin is a standard QGIS Python plugin as described in
Developing Python Plugins, that just provides an additional (or alternative)
interface: a typical QGIS desktop plugin has access to QGIS application
QgisInterface instance, a server
plugin has only access to a
when it is executed within the QGIS Server application context.
To make QGIS Server aware that a plugin has a server interface, a special metadata entry is needed (in metadata.txt)
Only plugins that have the
server=True metadata set will be loaded and executed by QGIS Server.
The example plugin discussed here (with many more) is available on github at https://github.com/elpaso/qgis3-server-vagrant/tree/master/resources/web/plugins, a few server plugins are also published in the official QGIS plugins repository.
Here’s the directory structure of our example server plugin
1 2 3 4 5
PYTHON_PLUGINS_PATH/ HelloServer/ __init__.py --> *required* HelloServer.py --> *required* metadata.txt --> *required*
This file is required by Python’s import system. Also, QGIS Server requires that this
file contains a
serverClassFactory() function, which is called when the
plugin gets loaded into QGIS Server when the server starts. It receives reference to instance of
QgsServerInterface and must return instance
of your plugin’s class.
This is how the example plugin
__init__.py looks like
def serverClassFactory(serverIface): from .HelloServer import HelloServerServer return HelloServerServer(serverIface)
This is where the magic happens and this is how magic looks like:
A server plugin typically consists in one or more callbacks packed into instances
QgsServerFilter implements one or more
of the following callbacks:
The following example implements a minimal filter which prints HelloServer! in case the SERVICE parameter equals to “HELLO”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
class HelloFilter(QgsServerFilter): def __init__(self, serverIface): super().__init__(serverIface) def requestReady(self): QgsMessageLog.logMessage("HelloFilter.requestReady") def sendResponse(self): QgsMessageLog.logMessage("HelloFilter.sendResponse") def responseComplete(self): QgsMessageLog.logMessage("HelloFilter.responseComplete") request = self.serverInterface().requestHandler() params = request.parameterMap() if params.get('SERVICE', '').upper() == 'HELLO': request.clear() request.setResponseHeader('Content-type', 'text/plain') # Note that the content is of type "bytes" request.appendBody(b'HelloServer!')
The filters must be registered into the serverIface as in the following example:
class HelloServerServer: def __init__(self, serverIface): serverIface.registerFilter(HelloFilter(), 100)
The second parameter of
registerFilter sets a priority which
defines the order for the callbacks with the same name (the lower priority is
By using the three callbacks, plugins can manipulate the input and/or the output
of the server in many different ways. In every moment, the plugin instance has
access to the
QgsRequestHandler class has plenty of
methods that can be used to alter
the input parameters before entering the core processing of the server (by using
requestReady()) or after the request has been processed by the core services
The following examples cover some common use cases:
Modifying the input¶
The example plugin contains a test example that changes input parameters coming
from the query string, in this example a new parameter is injected into the
parameterMap, this parameter is then visible by core services
(WMS etc.), at the end of core services processing we check that the parameter
is still there:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class ParamsFilter(QgsServerFilter): def __init__(self, serverIface): super(ParamsFilter, self).__init__(serverIface) def requestReady(self): request = self.serverInterface().requestHandler() params = request.parameterMap( ) request.setParameter('TEST_NEW_PARAM', 'ParamsFilter') def responseComplete(self): request = self.serverInterface().requestHandler() params = request.parameterMap( ) if params.get('TEST_NEW_PARAM') == 'ParamsFilter': QgsMessageLog.logMessage("SUCCESS - ParamsFilter.responseComplete") else: QgsMessageLog.logMessage("FAIL - ParamsFilter.responseComplete")
This is an extract of what you see in the log file:
1 2 3 4 5 6
src/core/qgsmessagelog.cpp: 45: (logMessage) [0ms] 2014-12-12T12:39:29 plugin HelloServerServer - loading filter ParamsFilter src/core/qgsmessagelog.cpp: 45: (logMessage) [1ms] 2014-12-12T12:39:29 Server Server plugin HelloServer loaded! src/core/qgsmessagelog.cpp: 45: (logMessage) [0ms] 2014-12-12T12:39:29 Server Server python plugins loaded src/mapserver/qgshttprequesthandler.cpp: 547: (requestStringToParameterMap) [1ms] inserting pair SERVICE // HELLO into the parameter map src/mapserver/qgsserverfilter.cpp: 42: (requestReady) [0ms] QgsServerFilter plugin default requestReady called src/core/qgsmessagelog.cpp: 45: (logMessage) [0ms] 2014-12-12T12:39:29 plugin SUCCESS - ParamsFilter.responseComplete
On the highlighted line the “SUCCESS” string indicates that the plugin passed the test.
The same technique can be exploited to use a custom service instead of a core one: you could for example skip a WFS SERVICE request or any other core request just by changing the SERVICE parameter to something different and the core service will be skipped, then you can inject your custom results into the output and send them to the client (this is explained here below).
Modifying or replacing the output¶
The watermark filter example shows how to replace the WMS output with a new image obtained by adding a watermark image on the top of the WMS image generated by the WMS core service:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
from qgis.server import * from qgis.PyQt.QtCore import * from qgis.PyQt.QtGui import * class WatermarkFilter(QgsServerFilter): def __init__(self, serverIface): super().__init__(serverIface) def responseComplete(self): request = self.serverInterface().requestHandler() params = request.parameterMap( ) # Do some checks if (params.get('SERVICE').upper() == 'WMS' \ and params.get('REQUEST').upper() == 'GETMAP' \ and not request.exceptionRaised() ): QgsMessageLog.logMessage("WatermarkFilter.responseComplete: image ready %s" % request.parameter("FORMAT")) # Get the image img = QImage() img.loadFromData(request.body()) # Adds the watermark watermark = QImage(os.path.join(os.path.dirname(__file__), 'media/watermark.png')) p = QPainter(img) p.drawImage(QRect( 20, 20, 40, 40), watermark) p.end() ba = QByteArray() buffer = QBuffer(ba) buffer.open(QIODevice.WriteOnly) img.save(buffer, "PNG" if "png" in request.parameter("FORMAT") else "JPG") # Set the body request.clearBody() request.appendBody(ba)
In this example the SERVICE parameter value is checked and if the incoming request is a WMS GETMAP and no exceptions have been set by a previously executed plugin or by the core service (WMS in this case), the WMS generated image is retrieved from the output buffer and the watermark image is added. The final step is to clear the output buffer and replace it with the newly generated image. Please note that in a real-world situation we should also check for the requested image type instead of supporting PNG or JPG only.
Access control filters¶
Access control filters gives the developer a fine-grained control over which layers, features and attributes can be accessed, the following callbacks can be implemented in an access control filter:
Here’s the directory structure of our example plugin:
1 2 3 4 5
PYTHON_PLUGINS_PATH/ MyAccessControl/ __init__.py --> *required* AccessControl.py --> *required* metadata.txt --> *required*
This file is required by Python’s import system. As for all QGIS server plugins, this
file contains a
serverClassFactory() function, which is called when the
plugin gets loaded into QGIS Server at startup. It receives a reference to an instance of
QgsServerInterface and must return an instance
of your plugin’s class.
This is how the example plugin
__init__.py looks like:
def serverClassFactory(serverIface): from MyAccessControl.AccessControl import AccessControlServer return AccessControlServer(serverIface)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
class AccessControlFilter(QgsAccessControlFilter): def __init__(self, server_iface): super().__init__(server_iface) def layerFilterExpression(self, layer): """ Return an additional expression filter """ return super().layerFilterExpression(layer) def layerFilterSubsetString(self, layer): """ Return an additional subset string (typically SQL) filter """ return super().layerFilterSubsetString(layer) def layerPermissions(self, layer): """ Return the layer rights """ return super().layerPermissions(layer) def authorizedLayerAttributes(self, layer, attributes): """ Return the authorised layer attributes """ return super().authorizedLayerAttributes(layer, attributes) def allowToEdit(self, layer, feature): """ Are we authorise to modify the following geometry """ return super().allowToEdit(layer, feature) def cacheKey(self): return super().cacheKey() class AccessControlServer: def __init__(self, serverIface): """ Register AccessControlFilter """ serverIface.registerAccessControl(AccessControlFilter(self.serverIface), 100)
This example gives a full access for everybody.
It’s the role of the plugin to know who is logged on.
On all those methods we have the layer on argument to be able to customise the restriction per layer.
Used to add an Expression to limit the results, e.g.:
def layerFilterExpression(self, layer): return "$role = 'user'"
To limit on feature where the attribute role is equals to „user“.
Same than the previous but use the
SubsetString (executed in the database)
def layerFilterSubsetString(self, layer): return "role = 'user'"
To limit on feature where the attribute role is equals to „user“.
Limit the access to the layer.
Return an object of type
LayerPermissions, which has the properties:
canReadto see it in the
GetCapabilitiesand have read access.
canInsertto be able to insert a new feature.
canUpdateto be able to update a feature.
canDeleteto be able to delete a feature.
1 2 3 4 5
def layerPermissions(self, layer): rights = QgsAccessControlFilter.LayerPermissions() rights.canRead = True rights.canInsert = rights.canUpdate = rights.canDelete = False return rights
To limit everything on read only access.
This is used to limit the editing on a subset of features.
It is used in the
def allowToEdit(self, layer, feature): return feature.attribute('role') == 'user'
To be able to edit only feature that has the attribute role with the value user.
QGIS server maintain a cache of the capabilities then to have a cache
per role you can return the role in this method. Or return
to completely disable the cache.
In QGIS Server, core services such as WMS, WFS and WCS are implemented as subclasses of
To implemented a new service that will be executed when the query string parameter
matches the service name, you can implemented your own
and register your service on the
Here is an example of a custom service named CUSTOM:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
from qgis.server import QgsService from qgis.core import QgsMessageLog class CustomServiceService(QgsService): def __init__(self): QgsService.__init__(self) def name(self): return "CUSTOM" def version(self): return "1.0.0" def allowMethod(method): return True def executeRequest(self, request, response, project): response.setStatusCode(200) QgsMessageLog.logMessage('Custom service executeRequest') response.write("Custom service executeRequest") class CustomService(): def __init__(self, serverIface): serverIface.serviceRegistry().registerService(CustomServiceService())
In QGIS Server, core OGC APIs such OAPIF (aka WFS3) are implemented as collections of
QgsServerOgcApiHandler subclasses that
are registered to an instance of
(or it’s parent class
To implemented a new API that will be executed when the url path matches
a certain URL, you can implemented your own
instances, add them to an
QgsServerOgcApi and register
the API on the
Here is an example of a custom API that will be executed when the URL contains
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
import json import os from qgis.PyQt.QtCore import QBuffer, QIODevice, QTextStream, QRegularExpression from qgis.server import ( QgsServiceRegistry, QgsService, QgsServerFilter, QgsServerOgcApi, QgsServerQueryStringParameter, QgsServerOgcApiHandler, ) from qgis.core import ( QgsMessageLog, QgsJsonExporter, QgsCircle, QgsFeature, QgsPoint, QgsGeometry, ) class CustomApiHandler(QgsServerOgcApiHandler): def __init__(self): super(CustomApiHandler, self).__init__() self.setContentTypes([QgsServerOgcApi.HTML, QgsServerOgcApi.JSON]) def path(self): return QRegularExpression("/customapi") def operationId(self): return "CustomApiXYCircle" def summary(self): return "Creates a circle around a point" def description(self): return "Creates a circle around a point" def linkTitle(self): return "Custom Api XY Circle" def linkType(self): return QgsServerOgcApi.data def handleRequest(self, context): """Simple Circle""" values = self.values(context) x = values['x'] y = values['y'] r = values['r'] f = QgsFeature() f.setAttributes([x, y, r]) f.setGeometry(QgsCircle(QgsPoint(x, y), r).toCircularString()) exporter = QgsJsonExporter() self.write(json.loads(exporter.exportFeature(f)), context) def templatePath(self, context): # The template path is used to serve HTML content return os.path.join(os.path.dirname(__file__), 'circle.html') def parameters(self, context): return [QgsServerQueryStringParameter('x', True, QgsServerQueryStringParameter.Type.Double, 'X coordinate'), QgsServerQueryStringParameter( 'y', True, QgsServerQueryStringParameter.Type.Double, 'Y coordinate'), QgsServerQueryStringParameter('r', True, QgsServerQueryStringParameter.Type.Double, 'radius')] class CustomApi(): def __init__(self, serverIface): api = QgsServerOgcApi(serverIface, '/customapi', 'custom api', 'a custom api', '1.1') handler = CustomApiHandler() api.registerHandler(handler) serverIface.serviceRegistry().registerApi(api)