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

Dev #6

Merged
merged 2 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified __pycache__/fastapi_server.cpython-312.pyc
Binary file not shown.
Binary file modified app/__pycache__/main.cpython-312.pyc
Binary file not shown.
3 changes: 2 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from app.routers import http_mock
import logging

# 设置日志级别为 INFO
logging.basicConfig(level=logging.INFO)

app = FastAPI(
Expand All @@ -15,7 +16,7 @@
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 生产环境应限制允许的源
allow_origins=["http://localhost", "https://example.com"], # 根据实际需求设置允许的源
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
Expand Down
Binary file modified app/routers/__pycache__/http_mock.cpython-312.pyc
Binary file not shown.
8 changes: 7 additions & 1 deletion app/routers/http_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ async def make_request(request: Request, data: HTTPRequestSchema):
encoding=data.encoding,
)

return {
response_data = {
"status_code": response.status_code,
"text": response.text,
"headers": dict(response.headers),
"elapsed": response.elapsed.total_seconds()
}

return HTTPResponseSchema(**response_data)
except TimeoutError as e:
raise HTTPException(status_code=504, detail="Gateway Timeout")
except ConnectionError as e:
raise HTTPException(status_code=502, detail="Bad Gateway")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Binary file modified app/schemas/__pycache__/request_schema.cpython-312.pyc
Binary file not shown.
Binary file modified app/schemas/__pycache__/response_schema.cpython-312.pyc
Binary file not shown.
23 changes: 19 additions & 4 deletions app/schemas/request_schema.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# request_schema.py
from typing import Dict, Optional, Union

from pydantic import BaseModel, HttpUrl
from pydantic import BaseModel, AnyUrl

class HTTPRequestSchema(BaseModel):
"""
Expand All @@ -16,9 +16,24 @@ class HTTPRequestSchema(BaseModel):
:param encoding: 请求体的编码
"""
method: str
url: HttpUrl
params: Optional[Dict[str, str]] = None
headers: Optional[Dict[str, str]] = None
url: AnyUrl
params: Optional[Dict[str, str]] = {}
headers: Optional[Dict[str, str]] = {}
data: Optional[Union[str, Dict]] = None
json_data: Optional[Dict] = None
encoding: Optional[str] = None

class Config:
arbitrary_types_allowed = True

@classmethod
def __get_validators__(cls):
yield cls.validate

@classmethod
def validate(cls, v):
if v.params is None:
v.params = {}
if v.headers is None:
v.headers = {}
return v
Binary file modified app/utils/__pycache__/request_helper.cpython-312.pyc
Binary file not shown.
9 changes: 6 additions & 3 deletions app/utils/encoding_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ def decode_content(content, encoding):

:param content: 要解码的字节内容
:param encoding: 指定的编码格式
:return: 解码后的字符串
:return: 解码后的字符串,如果解码失败,则返回原始的字节内容
"""
if encoding:
try:
logging.info(f"Attempting to decode content with encoding: {encoding}")
logging.debug(f"Attempting to decode content with encoding: {encoding}")
return content.decode(encoding)
except UnicodeDecodeError as e:
logging.error(f"UnicodeDecodeError: {e}. Trying to decode with UTF-8 and ignore errors.")
return content.decode("utf-8", errors="ignore")
try:
return content.decode("utf-8", errors="ignore")
except UnicodeDecodeError as e:
logging.error(f"Failed to decode content with UTF-8: {e}. Returning original bytes.")
return content
4 changes: 2 additions & 2 deletions app/utils/request_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
import logging

async def send_http_request(method, url, **kwargs):
async with httpx.AsyncClient(timeout=10.0) as client: # 设置超时时间为10秒
async with httpx.AsyncClient(timeout=30.0) as client: # 设置超时时间为30秒
try:
logging.info(f"Sending {method} request to {url} with params: {kwargs}")
response = await client.request(method=method, url=url, **kwargs)
logging.info(f"Received response: {response.status_code}")
return response
except httpx.RequestError as exc:
logging.error(f"An error occurred while requesting {exc.request.url!r}.")
logging.error(f"An error occurred while requesting {exc.request.url!r}: {exc}")
raise
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
Expand Down
13 changes: 12 additions & 1 deletion fastapi_server.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
# fastapi_server.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.main import app as fastapi_app
import logging

def run_fastapi():
import uvicorn
try:
logging.info("Starting FastAPI server...")
uvicorn.run(fastapi_app, host="127.0.0.1", port=8015)
uvicorn.run(fastapi_app, host="0.0.0.0", port=8015) # 允许所有IP访问
except Exception as e:
logging.error(f"An error occurred while running the FastAPI server: {e}")

if __name__ == "__main__":
# 添加 CORS 中间件
fastapi_app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:8501"], # 允许访问的域名
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)

run_fastapi()
30 changes: 17 additions & 13 deletions run.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
# run.py

from multiprocessing import Process
from fastapi_server import run_fastapi # 从 fastapi_server 模块导入 run_fastapi 函数
from ui.app import run_ui # 从 ui.app 模块导入 run_ui 函数
from fastapi_server import run_fastapi
from ui.app import run_ui
import logging

def run_streamlit():
run_ui() # 调用 run_ui 函数启动 Streamlit 应用
run_ui()

if __name__ == "__main__":
# 创建两个进程,一个运行 FastAPI 服务器,一个运行 Streamlit UI 应用
fastapi_process = Process(target=run_fastapi)
streamlit_process = Process(target=run_streamlit)
try:
# 创建两个进程,一个运行 FastAPI 服务器,一个运行 Streamlit UI 应用
fastapi_process = Process(target=run_fastapi)
streamlit_process = Process(target=run_streamlit)

# 启动两个进程
fastapi_process.start()
streamlit_process.start()

# 启动两个进程
fastapi_process.start()
streamlit_process.start()
# 等待两个进程结束
fastapi_process.join()
streamlit_process.join()

# 等待两个进程结束
fastapi_process.join()
streamlit_process.join()
except Exception as e:
logging.error(f"An error occurred: {e}")
Binary file modified ui/__pycache__/app.cpython-312.pyc
Binary file not shown.
1 change: 1 addition & 0 deletions ui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import logging

# 设置日志级别为 INFO
logging.basicConfig(level=logging.INFO)

def get_params(param_type, key_prefix, value_prefix):
Expand Down