Micro-SaaS #2, Python Threading

As promised in my initial blog post, I am continuing to write about the entire development process of GhostiFi, from concept, to sketch, to pseudocode, to actual code.

In this post, I will be showing how I turned the threading pseudocode into actual Python.

Python Threading

I started off by researching how to do threading. I’ve done threading in Python a few times before. I made a GUI chatbot for PvPGN servers in PyQT4 once, and another time I wrote a script to upgrade firmware on 70+ Cisco switches.

However, I still didn’t feel that I fully understood how it works, so I started off by learning more about it.

I came across this blog post by Chris Kiehl, where he gave an example of an easier way to handle threading in Python, and it looked like a good idea.

https://chriskiehl.com/article/parallelism-in-one-line

So I decided to try it out. The code turned out to be much simpler than what I’ve done before, and it’s been working great so far for what I needed to do (spawn a new thread for each server create/destroy/rebuild).

SQLAlchemy Threading

Another topic that I researched was how to handle threading with SQLAlchemy.

The information that I found on SQLAlchemy threading was very limited, but the post below did reference using scoped_session if you are threading SQLAlchemy. Although I’ll admit I still don’t really understand it.

Multi-threaded use of SQLAlchemy
I want to make a Database Application Programming Interface written in Python and using SQLAlchemy (or any other database connectors if it is told that using SQLAlchemy for this kind of task is not...

However, I moved forward using the new threading technique and scoping SQLAlchemy sessions, and I was able to get my code working!

https://gist.githubusercontent.com/reillychase/fa64aeba34616b0e91c089b91ebb85e2/raw/2aafd00d5075f80b496c0236c5ef70923bcfaaf5/server.py

So the project is now at the point where people can purchase the VPN, and my server.py script will know that it needs to create/destroy/rebuild a server for that user. It will spawn a new thread for each user who needs one of those tasks run. Right now those functions will simply print “Created!”, “Destroyed!”, or “Rebuilt!” respectively. Next step is to write the code to actually make those things happen instead of just printing it.

Closing thoughts

If you have any feedback on how I could improve this, please let me know in the comments section!

I am also looking for feedback on the concept itself, as well as beta testers. Please sign up for the newsletter at https://ghostifi.net if you are interested.