4

I have some custom python functions I have defined in QGIS which I use in print composer. I tried copying the python folder into the QGIS Server path but they do not get propagated. I have seen the following http://osgeo-org.1560.x6.nabble.com/QGIS-Developer-Custom-python-expressions-in-QGIS-Server-td5362875.html but the answer seems vague to me. Any hints / documentation or that I could read on this anyone out there with an example that I could look at.

kartoza-geek
  • 1,161
  • 1
  • 7
  • 17

1 Answers1

7

I have tried quickly by writing a quick QGIS Server plugin and it worked. I have followed the link you gave more or less.

  1. Make a folder called ServerExpression for instance.

  2. In this folder, add a quick metadata.txt:

     [general]
     name=Server expression
     description=Expose Python expressions on QGIS Server
     about=Expose Python expressions on QGIS Server
     version=1.0
     qgisMinimumVersion=3.4
     author=Etienne Trimaille
     email=etrimaille@3liz.com
     server=True
    
  3. In this folder, add a __init__.py:

     from qgis.core import QgsMessageLog, Qgis, QgsExpression
     from qgis.utils import qgsfunction
    

    @qgsfunction( args='auto', group='Your group', usesGeometry=False, referencedColumns=[], helpText='Define the help string here') def your_expression(params, feature, parent): # UPDATE the qgsfunction above # ADD HERE THE EXPRESSION CODE THAT YOU WROTE IN QGIS. return params.upper()

    class ServerExpressionPlugin: def init(self): QgsMessageLog.logMessage('Loading expressions', 'ServerExpression', Qgis.Info) QgsExpression.registerFunction(your_expression)

    def serverClassFactory(serverIface): _ = serverIface return ServerExpressionPlugin()

  4. Transfer this folder in the plugin directory on the server, reload QGIS Server if needed

  5. If in your layout, you have a label with

     [%your_expression('hello')%]
    

You will have a PDF with HELLO.

To make things easy, I have added all the code in the __init__.py. Of course, you can make your Python files listing your expressions, to make it easier to copy paste between Desktop and Server.

etrimaille
  • 7,240
  • 34
  • 47
  • Thanks, I will try it. I am using docker to run qgis server. Yes the 3liz docker container – kartoza-geek Mar 27 '20 at 16:59
  • I have created the server plugin in QGIS plugin path but the functions do not get registered. I am using 3liz/qgis-map-server:3.10 – kartoza-geek Mar 27 '20 at 18:00
  • Do you have any server plugin already which are working? – etrimaille Mar 30 '20 at 08:13
  • @etrimaille, THANKS a lot ... you saved my day with this answer! Now I have a full functional QGIS 3.16 server on Windows 2016 serving beautiful wavy, wiggly lines - https://gis.stackexchange.com/questions/376411/custom-qgis-linestyle-expression-function-wont-work-with-multilinestrings/376503#376503 ... I owe you a BIG beer! – christoph Dec 02 '20 at 09:10