Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fastapi dont work #4

Open
wanghaisheng opened this issue Dec 14, 2023 · 10 comments
Open

fastapi dont work #4

wanghaisheng opened this issue Dec 14, 2023 · 10 comments

Comments

@wanghaisheng
Copy link



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!

@banesullivan
Copy link
Owner

This is an issue with using an IPv6 loopback address. Just use localhost or 127.0.0.1 instead of ::1.

The exact error you are seeing is coming from requests I think? But just use an ipv4 address.

Additional, why are you running run_server in a thread? The whole point of this package is so that you can use ServerThread without doing that.

Here's my version of your example:

import requests
from fastapi import FastAPI
from server_thread import ServerThread

SERVER_HOST = "127.0.0.1"
SERVER_PORT = 24643
app = FastAPI()


@app.get("/")
def howdy():
    return {"Howdy": "World"}


# app.mount("/static", StaticFiles(directory=os.path.join(parent_dir,"static")), name="static")

server = ServerThread(app, host=SERVER_HOST, port=SERVER_PORT)

print(f"http://{server.host}:{server.port}")
response = requests.get(f"http://{server.host}:{server.port}/")
response.raise_for_status()

@wanghaisheng
Copy link
Author

wanghaisheng commented Dec 15, 2023

I am stealing idea from some repo for build a small gui. use run_server because there is a later monitor server function

    monitor_thread = Thread(
        name="Thread monitor",
        target=monitor_threads,
        args=(server_thread,),
    )
    monitor_thread.daemon = True
    monitor_thread.start()
    


def monitor_threads(*threads):
    while True:
        for thread in threads:
            if not thread.is_alive():
                logger.critical(f"Thread: {thread} died, exiting!")
                quit_window(icon=None)
                server.stop()
                sys.exit(2)
        else:
            sleep(0.5)

@banesullivan

@banesullivan
Copy link
Owner

Okay

I'm going to consider this resolved as this should all work fine if using an IPv4 address

@wanghaisheng
Copy link
Author

wanghaisheng commented Dec 15, 2023

how to check server is alive?@banesullivan
can we just get the thread you start

@wanghaisheng
Copy link
Author

wanghaisheng commented Dec 15, 2023

I find the real bug here @banesullivan

import sys
import os
from fastapi import FastAPI
from fastapi.responses import FileResponse
from os import environ, path
from cheroot.wsgi import Server
from server_thread import ServerThread

from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from uploadergenius.log import logger

# from uploadergenius.server.api.account import router
from uploadergenius.settings.constants import (
    APP_NAME,
    ROOT_DIR,
    CLIENT_ROOT,
    CONTACTS_CACHE_DB_FILE,
    DEACTIVATE_SENTRY,
    DEBUG,
    DEBUG_SENTRY,
    FOLDER_CACHE_DB_FILE,
    SERVER_HOST,
    SERVER_PORT,
    SESSION_TOKEN,
)



from uploadergenius.server.models import db
from uploadergenius.server.models.proxy_model import ProxyModel
from uploadergenius.server.models.platform_model import PlatformModel,PLATFORM_TYPE
from uploadergenius.server.models.account_model import AccountModel,AccountRelationship
from uploadergenius.server.models.upload_setting_model import UploadSettingModel,BROWSER_TYPE,WAIT_POLICY_TYPE
from uploadergenius.server.models.youtube_video_model import YoutubeVideoModel,VIDEO_SETTINGS

from uploadergenius.server.models.task_model import TaskModel,TASK_STATUS
from uploadergenius.utils.customid import *

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"}

# https://www.starlette.io/staticfiles/
app.mount("/static", StaticFiles(packages=[('uploadergenius.server.app',"static")]), name="static")


print(path.join(ROOT_DIR, "static"),'=========')
print(f'try to start server {SERVER_HOST}:{SERVER_PORT}')

server = ServerThread(app, host=SERVER_HOST, port=SERVER_PORT)
# server.is_alive
# import requests

# print(f"http://{server.host}:{server.port}")
# response = requests.get(f"http://{server.host}:{server.port}/")
# response.raise_for_status()

print(f'start server {server.host}:{server.port}')

the same code will give me diff out

datadir D:\workspace\tiktoka\tiktoka-studio-uploader-genius\uploadergenius
parent_dir D:\workspace\tiktoka\tiktoka-studio-uploader-genius
D:\workspace\tiktoka\tiktoka-studio-uploader-genius\uploadergenius\static =========
try to start server 127.0.0.1:0
start server ::1:8694
inital supported platforms
add test datas
start server thread
test server works
import start server ::1:8694
2023-12-15T14:28:01 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:01 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:01 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:01 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:02 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:02 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:03 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:03 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:04 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:05 WARNING Waiting for main window: Failed to parse: http://::1:8694/static/index.html
2023-12-15T14:28:06 CRITICAL Webserver did not start properly!
$ python main.py
datadir D:\workspace\tiktoka\tiktoka-studio-uploader-genius\uploadergenius
parent_dir D:\workspace\tiktoka\tiktoka-studio-uploader-genius
D:\workspace\tiktoka\tiktoka-studio-uploader-genius\uploadergenius\static =========
try to start server 127.0.0.1:0
start server 127.0.0.1:8358
inital supported platforms
add test datas
start server thread
test server works
import start server 127.0.0.1:8358
server response 200

@wanghaisheng
Copy link
Author

with debug=True

$ python main.py
datadir D:\workspace\tiktoka\tiktoka-studio-uploader-genius\uploadergenius
parent_dir D:\workspace\tiktoka\tiktoka-studio-uploader-genius
D:\workspace\tiktoka\tiktoka-studio-uploader-genius\uploadergenius\static =========
try to start server 127.0.0.1:0
INFO: Started server process [28752]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://localhost:9054 (Press CTRL+C to quit)
start server ::1:9054
inital supported platforms
add test datas
start server thread
test server works
import start server ::1:9054
2023-12-15T14:33:00 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:00 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:00 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:00 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:01 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:01 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:02 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:02 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:03 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:04 WARNING Waiting for main window: Failed to parse: http://::1:9054/static/index.html
2023-12-15T14:33:05 CRITICAL Webserver did not start properly!

@banesullivan
Copy link
Owner

Please see my comment about not using ::1 as your SERVER_HOST: #4 (comment)

@wanghaisheng
Copy link
Author

no as you can see I print my host and port input first,both case input is the same

try to start server 127.0.0.1:0

@banesullivan
Copy link
Owner

Apologies, I missed that in all the logs. I wonder if this is a compatibility issue with uvicorn or werkzeug on Windows.

What if you use "localhost" instead of 127.0.0.1?

@banesullivan banesullivan reopened this Dec 18, 2023
@wanghaisheng
Copy link
Author

I can test this hypothis from my windows and mac tomorrw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants