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.
1 Answers
I have tried quickly by writing a quick QGIS Server plugin and it worked. I have followed the link you gave more or less.
Make a folder called
ServerExpressionfor instance.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=TrueIn 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()
Transfer this folder in the plugin directory on the server, reload QGIS Server if needed
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.
- 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