banesullivan / server-thread Goto Github PK
View Code? Open in Web Editor NEW⚙️ Launch a WSGI or ASGI Application in a background thread with werkzeug or uvicorn
License: MIT License
⚙️ Launch a WSGI or ASGI Application in a background thread with werkzeug or uvicorn
License: MIT License
app = FastAPI()
# Allow all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # You can replace this with specific origins if needed
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def howdy():
return {"Howdy": "World"}
app.mount("/static", StaticFiles(directory=os.path.join(parent_dir,"static")), name="static")
def run_server():
global server
logger.debug(f"Starting server on {SERVER_HOST}:{SERVER_PORT}")
try:
server =ServerThread(app,host=SERVER_HOST,port=SERVER_PORT)
except Exception as e:
logger.exception(f"Exception in server thread!: {e}")
def main():
server_thread = Thread(name="Server", target=run_server)
server_thread.daemon = True
server_thread.start()
# run_thread(validate_or_remove_license)
# run_thread(run_cache_cleanup_later)
# Ensure the webserver is up & running by polling it
waits = 0
while waits < 10:
try:
print(f"http://{server.host}:{server.port}")
response = requests.get(f"http://{server.host}:{server.port}/")
response.raise_for_status()
except requests.RequestException as e:
logger.warning(f"Waiting for main window: {e}")
sleep(0.1 * waits)
waits += 1
else:
break
else:
logger.critical("Webserver did not start properly!")
sys.exit(2)
http://::1:24643
2023-12-14T18:28:43 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:43 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:43 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:44 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:44 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:44 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:45 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:45 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:46 WARNING Waiting for main window: Failed to parse: http://::1:24643/
http://::1:24643
2023-12-14T18:28:47 WARNING Waiting for main window: Failed to parse: http://::1:24643/
2023-12-14T18:28:48 CRITICAL Webserver did not start properly!
Ideally, this should work, but FastAPI is not a WSGIApplication, so it doesn't and has hard-to-debug (for users) errors:
from fastapi import FastAPI
import requests
from server_thread import ServerThread
app = FastAPI()
@app.get("/")
def howdy():
return {"Howdy": "World"}
# Launch app in a background thread
server = ServerThread(app)
# Perform requests against the server without blocking
requests.get(f"http://{server.host}:{server.port}/").raise_for_status()
Error on request:
Traceback (most recent call last):
File "/Users/bane/anaconda3/envs/geospatial/lib/python3.10/site-packages/werkzeug/serving.py", line 335, in run_wsgi
execute(self.server.app)
File "/Users/bane/anaconda3/envs/geospatial/lib/python3.10/site-packages/werkzeug/serving.py", line 322, in execute
application_iter = app(environ, start_response)
TypeError: FastAPI.__call__() missing 1 required positional argument: 'send'
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
Input In [34], in <cell line: 15>()
12 server = ServerThread(app)
14 # Perform requests against the server without blocking
---> 15 requests.get(f"[http://{server.host}:{server.port}/](http://%7Bserver.host%7D:{server.port}/)").raise_for_status()
File ~/anaconda3/envs/geospatial/lib/python3.10/site-packages/requests/models.py:960, in Response.raise_for_status(self)
957 http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
959 if http_error_msg:
--> 960 raise HTTPError(http_error_msg, response=self)
HTTPError: 500 Server Error: INTERNAL SERVER ERROR for url: http://127.0.0.1:63800/
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.