19. QGIS Server and Python

19.1. はじめに

To learn more about QGIS Server, read the QGIS Server Guide/Manual.

QGIS Server is three different things:

  1. QGIS Server library: a library that provides an API for creating OGC web services

  2. QGIS Server FCGI: a FCGI binary application qgis_maserv.fcgi that together with a web server implements a set of OGC services (WMS, WFS, WCS etc.) and OGC APIs (WFS3/OAPIF)

  3. QGIS Development Server: a development server binary application qgis_mapserver that implements a set of OGC 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 standalone WSGI/HTTP service

  • FILTERS → Enhance/Customize QGIS Server with filter plugins

  • SERVICES → Add a new SERVICE

  • OGC APIs → Add a new OGC API

Embedding and standalone applications require using the QGIS Server Python API directly from another Python script or application. 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.

19.2. Server API basics

The fundamental classes involved in a typical QGIS Server application are:

The QGIS Server FCGI or development server workflow can be summarized as follows:

1initialize the QgsApplication
2create the QgsServer
3the main server loop waits forever for client requests:
4    for each incoming request:
5        create a QgsServerRequest request
6        create a QgsServerResponse response
7        call QgsServer.handleRequest(request, response)
8            filter plugins may be executed
9        send the output to the client

Inside the QgsServer.handleRequest(request, response) method the filter plugins callbacks are called and QgsServerRequest and QgsServerResponse are made available to the plugins through the QgsServerInterface class.


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.

19.3. 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:

 1from qgis.core import QgsApplication
 2from qgis.server import *
 3app = QgsApplication([], False)
 5# Create the server instance, it may be a single one that
 6# is reused on multiple requests
 7server = QgsServer()
 9# Create the request by specifying the full URL and an optional body
10# (for example for POST requests)
11request = QgsBufferServerRequest(
12    'http://localhost:8081/?MAP=/qgis-server/projects/helloworld.qgs' +
13    '&SERVICE=WMS&REQUEST=GetCapabilities')
15# Create a response objects
16response = QgsBufferServerResponse()
18# Handle the request
19server.handleRequest(request, response)

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): https://github.com/qgis/QGIS/blob/release-3_16/tests/src/python/qgis_wrapped_server.py

19.4. Server plugins

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, a 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.

19.4.1. 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 QgsServerInterface:

Filter Type

Base Class

QgsServerInterface registration




Access Control





registerServerCache() I/O filters

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 (QgsRequestHandler) 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:

 1for each incoming request:
 2    create GET/POST request handler
 3    pass request to an instance of QgsServerInterface
 4    call requestReady filters
 5    if there is not a response:
 6        if SERVICE is WMS/WFS/WCS:
 7            create WMS/WFS/WCS service
 8            call service’s executeRequest
 9                possibly call sendResponse for each chunk of bytes
10                sent to the client by a streaming services (WFS)
11        call responseComplete
12        call sendResponse
13    request handler sends the response to the client

次の段落では、利用可能なコールバックを詳細に説明します。 requestReady


  • 認証/認可

  • リダイレクト

  • 特定のパラメーター(例えば、型名)を追加/除去

  • 例外を発生させる

SERVICE パラメーターを変更することでコアサービスを完全に置き換え、それによりコアサービスを完全にバイパスすることさえできるかもしれません(とはいえ、これはあまり意味がないということ)。 sendResponse

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 is needed (WFS GetFeature is one of them). In that case, instead of a single call to sendResponse(), the method might be exceptionally called multiple times before the response is complete, and in that case (and only in that case) it is also called before responseComplete().

sendResponse() is the best place for direct manipulation of core service’s output and while responseComplete() is typically also an option, sendResponse() is the only viable option in case of streaming services. responseComplete

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 called before sendResponse() except for streaming services (or other plugin filters) that might have called sendResponse() earlier.

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).

このアプローチは、基本的に動作しますが、それは非常に「パイソン的」ではありません:より良いアプローチは、Pythonコードから例外を発生し、それらがそこで処理されるためにC ++ループに湧き上がるのを見ることでしょう。 サーバー・プラグインを書く

A server plugin is a standard QGIS Python plugin as described in Pythonプラグインを開発する, that just provides an additional (or alternative) interface: a typical QGIS desktop plugin has access to QGIS application through the QgisInterface instance, a server plugin has only access to a QgsServerInterface 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.

2  HelloServer/
3    __init__.py    --> *required*
4    HelloServer.py  --> *required*
5    metadata.txt   --> *required* __init__.py

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) HelloServer.py

魔法が起こると、これは魔法がどのように見えるかであるところである:(例 HelloServer.py

A server plugin typically consists in one or more callbacks packed into instances of a QgsServerFilter.

Each 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”:

 1class HelloFilter(QgsServerFilter):
 3    def __init__(self, serverIface):
 4        super().__init__(serverIface)
 6    def requestReady(self):
 7        QgsMessageLog.logMessage("HelloFilter.requestReady")
 9    def sendResponse(self):
10        QgsMessageLog.logMessage("HelloFilter.sendResponse")
12    def responseComplete(self):
13        QgsMessageLog.logMessage("HelloFilter.responseComplete")
14        request = self.serverInterface().requestHandler()
15        params = request.parameterMap()
16        if params.get('SERVICE', '').upper() == 'HELLO':
17            request.clear()
18            request.setResponseHeader('Content-type', 'text/plain')
19            # Note that the content is of type "bytes"
20            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(serverIface), 100)

The second parameter of registerFilter() sets a priority which defines the order for the callbacks with the same name (the lower priority is invoked first).

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 through the QgsServerInterface. 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 (by using sendResponse()).

次の例は、いくつかの一般的なユースケースをカバーします: 入力を変更する

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 (already parsed) 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:

 1class ParamsFilter(QgsServerFilter):
 3    def __init__(self, serverIface):
 4        super(ParamsFilter, self).__init__(serverIface)
 6    def requestReady(self):
 7        request = self.serverInterface().requestHandler()
 8        params = request.parameterMap( )
 9        request.setParameter('TEST_NEW_PARAM', 'ParamsFilter')
11    def responseComplete(self):
12        request = self.serverInterface().requestHandler()
13        params = request.parameterMap( )
14        if params.get('TEST_NEW_PARAM') == 'ParamsFilter':
15            QgsMessageLog.logMessage("SUCCESS - ParamsFilter.responseComplete")
16        else:
17            QgsMessageLog.logMessage("FAIL    - ParamsFilter.responseComplete")


1 src/core/qgsmessagelog.cpp: 45: (logMessage) [0ms] 2014-12-12T12:39:29 plugin[0] HelloServerServer - loading filter ParamsFilter
2 src/core/qgsmessagelog.cpp: 45: (logMessage) [1ms] 2014-12-12T12:39:29 Server[0] Server plugin HelloServer loaded!
3 src/core/qgsmessagelog.cpp: 45: (logMessage) [0ms] 2014-12-12T12:39:29 Server[0] Server python plugins loaded
4 src/mapserver/qgshttprequesthandler.cpp: 547: (requestStringToParameterMap) [1ms] inserting pair SERVICE // HELLO into the parameter map
5 src/mapserver/qgsserverfilter.cpp: 42: (requestReady) [0ms] QgsServerFilter plugin default requestReady called
6 src/core/qgsmessagelog.cpp: 45: (logMessage) [0ms] 2014-12-12T12:39:29 plugin[0] SUCCESS - ParamsFilter.responseComplete


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 below).


If you really want to implement a custom service it is recommended to subclass QgsService and register your service on registerFilter() by calling its registerService(service) 出力を変更または置き換えする


 1from qgis.server import *
 2from qgis.PyQt.QtCore import *
 3from qgis.PyQt.QtGui import *
 5class WatermarkFilter(QgsServerFilter):
 7    def __init__(self, serverIface):
 8        super().__init__(serverIface)
10    def responseComplete(self):
11        request = self.serverInterface().requestHandler()
12        params = request.parameterMap( )
13        # Do some checks
14        if (params.get('SERVICE').upper() == 'WMS' \
15                and params.get('REQUEST').upper() == 'GETMAP' \
16                and not request.exceptionRaised() ):
17            QgsMessageLog.logMessage("WatermarkFilter.responseComplete: image ready %s" % request.parameter("FORMAT"))
18            # Get the image
19            img = QImage()
20            img.loadFromData(request.body())
21            # Adds the watermark
22            watermark = QImage(os.path.join(os.path.dirname(__file__), 'media/watermark.png'))
23            p = QPainter(img)
24            p.drawImage(QRect( 20, 20, 40, 40), watermark)
25            p.end()
26            ba = QByteArray()
27            buffer = QBuffer(ba)
28            buffer.open(QIODevice.WriteOnly)
29            img.save(buffer, "PNG" if "png" in request.parameter("FORMAT") else "JPG")
30            # Set the body
31            request.clearBody()
32            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:

2  MyAccessControl/
3    __init__.py    --> *required*
4    AccessControl.py  --> *required*
5    metadata.txt   --> *required* __init__.py

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) AccessControl.py
 1class AccessControlFilter(QgsAccessControlFilter):
 3    def __init__(self, server_iface):
 4        super().__init__(server_iface)
 6    def layerFilterExpression(self, layer):
 7        """ Return an additional expression filter """
 8        return super().layerFilterExpression(layer)
10    def layerFilterSubsetString(self, layer):
11        """ Return an additional subset string (typically SQL) filter """
12        return super().layerFilterSubsetString(layer)
14    def layerPermissions(self, layer):
15        """ Return the layer rights """
16        return super().layerPermissions(layer)
18    def authorizedLayerAttributes(self, layer, attributes):
19        """ Return the authorised layer attributes """
20        return super().authorizedLayerAttributes(layer, attributes)
22    def allowToEdit(self, layer, feature):
23        """ Are we authorised to modify the following geometry """
24        return super().allowToEdit(layer, feature)
26    def cacheKey(self):
27        return super().cacheKey()
29class AccessControlServer:
31   def __init__(self, serverIface):
32      """ Register AccessControlFilter """
33      serverIface.registerAccessControl(AccessControlFilter(serverIface), 100)



これらすべての方法で私達は、レイヤーごとの制限をカスタマイズできるようにするには、引数のレイヤーを持っています。 layerFilterExpression


def layerFilterExpression(self, layer):
    return "$role = 'user'"

属性の役割が「ユーザー」に等しい地物に制限するため。 layerFilterSubsetString

以前よりも同じですが、(データベース内で実行) SubsetString を使用

def layerFilterSubsetString(self, layer):
    return "role = 'user'"

属性の役割が「ユーザー」に等しい地物に制限するため。 layerPermissions


Return an object of type LayerPermissions(), which has the properties:

  • canRead to see it in the GetCapabilities and have read access.

  • canInsert to be able to insert a new feature.

  • canUpdate to be able to update a feature.

  • canDelete to be able to delete a feature.


1def layerPermissions(self, layer):
2    rights = QgsAccessControlFilter.LayerPermissions()
3    rights.canRead = True
4    rights.canInsert = rights.canUpdate = rights.canDelete = False
5    return rights

読み取り専用のアクセスのすべてを制限します。 authorizedLayerAttributes




def authorizedLayerAttributes(self, layer, attributes):
    return [a for a in attributes if a != "role"]

「role」属性を非表示にします。 allowToEdit


これは、 WFS-Transaction プロトコルで使用されています。


def allowToEdit(self, layer, feature):
    return feature.attribute('role') == 'user'

値「user」の属性「role」を持つ地物だけを編集できます。 cacheKey

QGISサーバーは、このメソッド中に役割を返すことができる役割ごとにキャッシュを持っている能力のキャッシュを維持します。または None を返し、完全にキャッシュを無効にします。

19.4.2. Custom services

In QGIS Server, core services such as WMS, WFS and WCS are implemented as subclasses of QgsService.

To implemented a new service that will be executed when the query string parameter SERVICE matches the service name, you can implemented your own QgsService and register your service on the serviceRegistry() by calling its registerService(service).

Here is an example of a custom service named CUSTOM:

 1from qgis.server import QgsService
 2from qgis.core import QgsMessageLog
 4class CustomServiceService(QgsService):
 6    def __init__(self):
 7        QgsService.__init__(self)
 9    def name(self):
10        return "CUSTOM"
12    def version(self):
13        return "1.0.0"
15    def executeRequest(self, request, response, project):
16        response.setStatusCode(200)
17        QgsMessageLog.logMessage('Custom service executeRequest')
18        response.write("Custom service executeRequest")
21class CustomService():
23    def __init__(self, serverIface):
24        serverIface.serviceRegistry().registerService(CustomServiceService())

19.4.3. Custom APIs

In QGIS Server, core OGC APIs such OAPIF (aka WFS3) are implemented as collections of QgsServerOgcApiHandler subclasses that are registered to an instance of QgsServerOgcApi (or it's parent class QgsServerApi).

To implemented a new API that will be executed when the url path matches a certain URL, you can implemented your own QgsServerOgcApiHandler instances, add them to an QgsServerOgcApi and register the API on the serviceRegistry() by calling its registerApi(api).

Here is an example of a custom API that will be executed when the URL contains /customapi:

 1import json
 2import os
 4from qgis.PyQt.QtCore import QBuffer, QIODevice, QTextStream, QRegularExpression
 5from qgis.server import (
 6    QgsServiceRegistry,
 7    QgsService,
 8    QgsServerFilter,
 9    QgsServerOgcApi,
10    QgsServerQueryStringParameter,
11    QgsServerOgcApiHandler,
14from qgis.core import (
15    QgsMessageLog,
16    QgsJsonExporter,
17    QgsCircle,
18    QgsFeature,
19    QgsPoint,
20    QgsGeometry,
24class CustomApiHandler(QgsServerOgcApiHandler):
26    def __init__(self):
27        super(CustomApiHandler, self).__init__()
28        self.setContentTypes([QgsServerOgcApi.HTML, QgsServerOgcApi.JSON])
30    def path(self):
31        return QRegularExpression("/customapi")
33    def operationId(self):
34        return "CustomApiXYCircle"
36    def summary(self):
37        return "Creates a circle around a point"
39    def description(self):
40        return "Creates a circle around a point"
42    def linkTitle(self):
43        return "Custom Api XY Circle"
45    def linkType(self):
46        return QgsServerOgcApi.data
48    def handleRequest(self, context):
49        """Simple Circle"""
51        values = self.values(context)
52        x = values['x']
53        y = values['y']
54        r = values['r']
55        f = QgsFeature()
56        f.setAttributes([x, y, r])
57        f.setGeometry(QgsCircle(QgsPoint(x, y), r).toCircularString())
58        exporter = QgsJsonExporter()
59        self.write(json.loads(exporter.exportFeature(f)), context)
61    def templatePath(self, context):
62        # The template path is used to serve HTML content
63        return os.path.join(os.path.dirname(__file__), 'circle.html')
65    def parameters(self, context):
66        return [QgsServerQueryStringParameter('x', True, QgsServerQueryStringParameter.Type.Double, 'X coordinate'),
67                QgsServerQueryStringParameter(
68                    'y', True, QgsServerQueryStringParameter.Type.Double, 'Y coordinate'),
69                QgsServerQueryStringParameter('r', True, QgsServerQueryStringParameter.Type.Double, 'radius')]
72class CustomApi():
74    def __init__(self, serverIface):
75        api = QgsServerOgcApi(serverIface, '/customapi',
76                            'custom api', 'a custom api', '1.1')
77        handler = CustomApiHandler()
78        api.registerHandler(handler)
79        serverIface.serviceRegistry().registerApi(api)