https://learninghub.kx.com/forums/topic/pykx-could-not-establish-an-ipc-connection-in-the-flask-app
I'm trying to make a connection from a Flask app, but it shows a QError: .pykx.i.isw
.
I tried the same function without a Flask app, and it can make a connection. Please find attached.
Can you please take a look on it.
We added some functionality in version 2.3.0
https://code.kx.com/pykx/2.4/release-notes/changelog.html#pykx-230
If you enable beta features as well as pykx threading all calls into q from any python thread will be run as if they were calling from the main thread which allows python multithreaded programs to use IPC connections in licensed mode.
You can enable this functionality like this:
import os
os.environ['PYKX_THREADING'] = '1'
os.environ['PYKX_BETA_FEATURES'] = '1'
import pykx as kx
You will also want to ensure that kx.shutdown_thread() is called when the script finishes. The safest way to do this is within a try - finally block like this.
if __name__ == '__main__':
try:
main()
finally:
kx.shutdown_thread()
More information about this functionality and an example can be found within our documentation:
https://code.kx.com/pykx/2.4/examples/threaded_execution/threading.html
Flask is spawning new processes - for nested processes to use PyKX the reimporter must be used: https://code.kx.com/pykx/3.1/api/reimporting.html
Place app.run inside 'with kx.PyKXReimport()'
from flask import Flask
import json as j
import os
os.environ['PYKX_THREADING'] = '1'
import pykx as kx
app = Flask(name)
@app.route(“/”)
def hello_kx():
qcon = kx.QConnection(host=‘localhost’, port=5000)
tables = qcon(“tables”).py()
return j.dumps(tables)
def main():
with kx.PyKXReimport(): #This is the key change
app.run(host=‘127.0.0.1’, debug=True, port=8100)
if name == ‘main’:
try:
main()
finally:
kx.shutdown_thread()