pimoroni / phew

MIT License
204 stars 44 forks source link

Support for multiple web apps in one deployment #52

Open ccrighton opened 1 year ago

ccrighton commented 1 year ago

Hi,

I have an application that has two web apps. One for the initial AP configuration of the device and the second for the ongoing maintenance. Unfortunately, with phew the decorators store the routes in a global.

Phew could support this capability if the routes were stored as instance variables of a Phew server class. You'll see the similarity to Flask. The following tweak of the basic example demonstrates the idea:

from phew import server, connect_to_wifi

connect_to_wifi("<ssid>", "<password>")

webapp = server.Phew()

@webapp.route("/random", methods=["GET"])
def random_number(request):
  import random
  min = int(request.query.get("min", 0))
  max = int(request.query.get("max", 100))
  return str(random.randint(min, max))

@webapp.catchall()
def catchall(request):
  return "Not found", 404

webapp.run()

It would still be possible to not break existing apps by using a default instance of Phew in the case that the existing methods are called. In the implementation the server.route method etc. would apply to a default Phew instance stored in a server.py global variable.

ccrighton commented 1 year ago

I've created a pull request: Refactor Phew as a class to support multiple apps on one device running singly or concurrently #53

ccrighton commented 1 year ago

Currently, the run method takes control of the asyncio loop. That means nothing else can be added as a task. As a result, it's not possible to run anything but a web app. I've introduced a run_as_task method that doesn't ceed control of the loop. That means that Phew can be run alongside other functions such as an mqtt client, interrupt handlers and so on.