GithubHelp home page GithubHelp logo

banesullivan / server-thread Goto Github PK

View Code? Open in Web Editor NEW
4.0 4.0 0.0 17 KB

⚙️ Launch a WSGI or ASGI Application in a background thread with werkzeug or uvicorn

License: MIT License

Makefile 6.66% Python 93.34%
threading wsgi-server localtileserver asgi-server

server-thread's People

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

server-thread's Issues

fastapi dont work



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!

Add compatibility with FastAPI

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/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.