skip to Main Content

So I’m working on a little board game project in React, using TypeScript. I also want to create an engine that gives an evaluation for the current board state (i.e. Player 1 wins in 2 moves), but I would prefer to write it in Python.

What are some ways in which I can send the board state from my TS code to my Python code and receive a response?

I have tried using AJAX to send a request to my Python file. However, I am unsure of how to input to it through standard input, and how I would get the values that it prints to standard output (or if there is a better way to receive these values) in my current situation. Since the Python file is stored on my local file system, would I need to use a backend framework to host it on a server/api?

Thank you for your help if this is a dumb question.

2

Answers


  1. For your Python file to communicate with your front-end code, it needs to be able to recieve HTTP requests and respond with HTTP responses; therefore, it needs to be a server. You could definitely try having your terminal or stdin be the "middleman", but the far simpler approach would be to handle it all in your Python code. Luckily for you, there are many great Python backend frameworks, and if all your server needs is to handle one request I think you’ll find them all very easy to use.

    You could look into any of these:

    Login or Signup to reply.
  2. I would like to build off of what Evyatar Shafran said.

    Generally, in order for your React project (front-end) to interact with some Python code, this Python code should be running inside of a server (back-end). The front-end should then communicate with the back-end through HTTP requests, for example POST to submit data or GET to retrieve data. You can read more about the various types of HTTP requests here.

    Of the above mentioned solutions (Flask, Django, FastAPI), Flask and Django are generally used to serve web pages (that is, they handle HTTP requests, server .html pages, interact with DBs etc.).

    FastAPI is probably the closest match for what you are trying to achieve (passing messages back and forth between the React and Python projects, while the front-end logic is handled by React, not the back-end server), but I have never used it.

    Django can be configured to create REST APIs, by using Django REST Framework. Think of this as an add-on to Django, that allows it to work as an HTTP server decoupled from the front-end logic, as in your use case. Using DRF is important, as it allows you to circumvent some Django features that make sense in the context of making Fullstack projects, but not so much when setting up a REST API, for example the CSRF token feature.

    Depending on your use case and your aims for the project, it might be beneficial to use Django over FastAPI. For a more in-depth comparison see here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search