Is there any way to use pyswip and Flask?

0

I have an python application whose interface is implemented in Flask and i have a module in backend that use pyswip library. The module works perfectly when i run it separately from the application. As i searched, it seems that pyswip is not thread safe. I get this error on consult function:

swipl_fid = PL_open_foreign_frame()
OSError: exception: access violation reading 0x00000028

I could try to use another SWI-Prolog library, but in my application i need to consult and external .pl file. Is there any way i could make it work?

Here's how i use the pyswip library:

from pyswip_alt import Prolog

class My_Prolog():
    def __init__(self, query):
        self.query = query.split()
        self.query = ', '.join(self.query)
        self.query = '['+self.query + ']'
        self.documents_path = "my/path"
        self.prolog = Prolog()
        self.prolog.consult("facts.pl")
        self.prolog_results = []
        self.final_result = ''

    def process(self):
        for res in self.prolog.query("complex_phrase("+self.query+", F)."):
            result = []
            for atom in res['F']:
                result.append(atom.value)
            self.prolog_results.append(result)

    def run(self):
        self.process()
        self.final_result = ' '.join(self.final_result)
        return self.final_result

And that's the way i use the class:

nl = My_Prolog(query)
nl_query =  nl.run()

and all of this is in a function that is run by Flask module.

python
flask
prolog
thread-safety
swi-prolog
asked on Stack Overflow Jul 25, 2020 by hb3

1 Answer

0

Simply use a lock?

from multiprocessing import Lock

prologlock = Lock()

@app.route(...)
def handle_x():
    with prologlock:
        return MyProlog.handle_x()
answered on Stack Overflow Aug 4, 2020 by kay

User contributions licensed under CC BY-SA 3.0