How to create Python session from PHP

I want to create a Python session and call Python API from PHP. As my Python script needs to load prebuild model and load libraries on session startup, running a new session (running a script) every time running a Python command is not a good idea. So, I want to create a Python session in the background with predefined commands, and later I can input commands at any time and get the output of Python.

For example, when I was using R, there is a package called 'reticulate' which call Python API and it keeps the Python session. So, I built Web-app with (R) shiny-server and a single session Python.

I googled all the possible keywords, but all results are 'how to run python script from php'. I am pretty sure that if I ask this question on StackOverflow, it will be marked as duplicated with those 'how to run python script from php'. So, I come here to get help. 😁 Any references or answers are appreciated. Thanks in advance.

3 comments · 60% upvoted · other discussions

comments

BlueScreenJunky

Not sure about your particular Python App, but on the client side a session is usually just a session cookie with a token that get matched on the server. So what you would do in PHP is :

  • Make an Http request to your Python App
  • Get the cookies from the http response
  • Save the cookies somewhere
  • Send the cookies with every subsequent request to stay on the same session

For example if you use Guzzle to make your request you can see the documentation about cookies here : https://docs.guzzlephp.org/en/stable/quickstart.html#cookies

Plastonick

I can't quite tell what your use case is, or what you currently have, however to authenticate between different APIs what you'd normally use is some sort of access token (such as a JWT). You could generate it in your PHP session using the relevant context from your session, send that to your Python API, which can authenticate and use that data (such as a user ID). You won't have access to your full session data, but you can pass the relevant context over securely (note the JWT payload is readable by the user, so shouldn't contain sensitive data).

Does that sound like the solution to your problem?

[deleted]

When you say “Python” and “session”, I think of Jupyter Notebook? Can you explain why you’re trying to mix Php and Python. If you want a web UI in front of Python, can you do it with Flask or Django?