I have found that using cython is the best, minimal and maintainable way to go forward. Below, I have pasted some code which:
- Demonstrates using multiple files (dependencies)
- Calling the main file
- Using the static files from the storage
Background
I was building a flask application, which was intended to be consumed as an API from another service. I wanted to deploy on the server where the code is not readable, so I had to cover my Flask application into some sort of binary format.
File structure:
The following is the file structure of my project:
app.py
functions.py (used from app.py)
some_more_functions.py (used from functions.py)
resources/
| some_file_1.pkl
| some_file_2.pkl
What we want to do
The method I am going to show you will only create binary of the selected files, without touching or compiling the libraries, or any other dependencies.
When you use some other libraries like pyinstaller, it will try to compile everything, even some heavy libraries like torch and it takes time and is often error prone.
If your purpose is to hide the source code and run the file smoothly, then take this approach.
Step - 1: Create a setup.py file
This file is the main file, which will compile your source code.
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize(["app.py", "functions.py", "some_more_functions.py"]),
)
That's it.
Step - 2: Compile the files
python setup.py build_ext --inplace
The above command will create the binary versions of your mentioned files. In linux, they will be .so and in windows they will be .pyd.
We are almost done.
Step - 3: Test your files
After compiling, we can't simply run the file with python app.so we need some "app runner".
So, create a new file which will call your main app.
# new file `main_app.py`
import app # Import your compiled module
if __name__ == '__main__':
app.app.run(debug=True) # Assuming 'app' is the Flask app instance in app.so
Then call it with:
python main_app.py
👉🏻 So how is it better?
- We didn't need to compile any dependency.
- We just compiled the source code.
- No need to reset any resources path which the source code points to, they will get automatically be pointed.
- Compilation usually takes 1-2 minutes.
I hope this helps!