Compare commits

..

44 Commits

Author SHA1 Message Date
b187a50878 Delete pictures_handle.cpython-311.pyc 2024-07-01 14:10:25 +08:00
826ff901cf Update .gitignore 2024-07-01 14:10:08 +08:00
66078799ff Update website.py 2024-07-01 14:08:44 +08:00
152bc9fd83 Update requirements.txt 2024-07-01 14:08:36 +08:00
1a7828a850 Update .gitignore 2024-07-01 14:08:00 +08:00
7a195da164 Update huaweitest.py 2024-04-24 17:35:21 +08:00
29a0404643 Update huaweitest.py 2024-04-15 11:34:00 +08:00
57714ddd21 Update huaweitest.py 2024-03-28 10:04:05 +08:00
8cc72f50ee Update huaweitest.py 2024-03-25 14:53:53 +08:00
fb3d7190b7 更新 huaweitest.py 2024-03-09 11:08:44 +08:00
57f7f9252f 更新 huaweitest.py 2024-03-01 18:33:59 +08:00
a7e630cd84 删除 test_main.http 2024-03-01 14:21:37 +08:00
905b3dcef8 删除 website.cpython-311.pyc 2024-02-28 17:57:34 +08:00
dab5c40e31 删除 huaweitest.cpython-311.pyc 2024-02-28 17:57:31 +08:00
e64a56e4d0 更新 .gitignore 2024-02-28 17:57:28 +08:00
c7788c409f 更新 huaweitest.py 2024-02-28 17:56:45 +08:00
fba2513b5f 创建 huaweitest.py 2024-02-19 17:15:26 +08:00
48074edc21 创建 huaweitest.cpython-311.pyc 2024-02-19 17:15:23 +08:00
5ad3062457 更新 website.cpython-311.pyc 2024-01-26 10:17:28 +08:00
d3d4b30c9a 更新 website.py 2024-01-26 10:17:26 +08:00
6f93326ba0 更新 website.py 2024-01-24 16:00:25 +08:00
fc8976efba 更新 pictures_handle.py 2024-01-24 16:00:23 +08:00
8a16672573 更新 pictures_handle.cpython-311.pyc 2024-01-24 16:00:21 +08:00
e7971b6a03 更新 website.cpython-311.pyc 2024-01-24 16:00:19 +08:00
6327c8f878 更新 website.py 2024-01-23 18:02:56 +08:00
9233f0224d 创建 pictures_handle.py 2024-01-23 18:02:54 +08:00
f82c7db414 创建 pictures_handle.cpython-311.pyc 2024-01-23 18:02:51 +08:00
953a4b22f6 更新 website.cpython-311.pyc 2024-01-23 18:02:44 +08:00
ee0762b0b1 创建 website.cpython-311.pyc 2024-01-23 16:01:27 +08:00
13d2081aff 更新 main.py 2024-01-23 16:01:25 +08:00
6e57862d26 创建 website.py 2024-01-23 16:01:22 +08:00
319b4d2c79 更新 .gitignore 2024-01-23 16:01:16 +08:00
7cb5e177fc 更新 main.py 2024-01-11 17:47:16 +08:00
406c78bf02 删除 __pycache__/main.cpython-311.pyc 2024-01-11 17:45:37 +08:00
2032d20d89 更新 main.py 2024-01-11 17:45:58 +08:00
87dc8562ab 更新 main.cpython-311.pyc 2024-01-09 18:00:57 +08:00
bf4a54d611 更新 .gitignore 2024-01-09 18:00:51 +08:00
e18b71b7fa 更新 main.py 2024-01-09 18:00:37 +08:00
8051d4a027 更新 main.py 2024-01-09 16:11:23 +08:00
c81cde9aee 更新 main.cpython-311.pyc 2024-01-09 16:11:20 +08:00
89c680d369 创建 requirements.txt 2024-01-05 19:12:57 +08:00
cae3ad3091 更新 .gitignore 2024-01-05 19:08:31 +08:00
86a6f60f78 Merge branch 'master' of https://gitea.kimgo.cn/wsy182/fastAPI 2024-01-05 19:07:58 +08:00
50414bc9e4 更新 .gitignore 2024-01-05 19:07:52 +08:00
8 changed files with 333 additions and 33 deletions

5
.gitignore vendored
View File

@@ -1,2 +1,7 @@
.idea .idea
.DS_Store .DS_Store
__pycache__
venv
__pycache__/
pictures/
*/__pycache__/

Binary file not shown.

145
huaweitest.py Normal file
View File

@@ -0,0 +1,145 @@
from fastapi import FastAPI, Query, Request, HTTPException
from datetime import datetime
import random
app = FastAPI()
@app.get("/")
async def root(request: Request):
# 获取当前时间
now = datetime.now()
# 格式化时间为 年-月-日 时:分:秒 的格式
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"请求IP地址: {request.client.host},请求时间{formatted_now},请求路径: /")
return "welcome to fastAPI!"
def random_bool():
return "true" if random.random() > 0.5 else "false"
@app.get("/script/getscriparam")
async def getscriparam(request: Request):
# 获取当前时间
now = datetime.now()
# 格式化时间为 年-月-日 时:分:秒 的格式
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"请求IP地址: {request.client.host},请求时间{formatted_now},请求路径: /script/getscriparam")
language_list = ["English (United States)", "Spanish (Mexico)", "English (United Kingdom)", "English (Australia)"]
data = {
"interaction": {"from": 20, "to": 30},
"bounceRate": {"from": 0.3, "to": 0.4},
"pagesToViewPerSession": {"from": 2, "to": 3},
"sessionsPerUser": {"from": 2, "to": 3},
"ctr": {"from": 0.03, "to": 0.05},
"shouldDoClick": "true",
"shouldExecute": "true",
"shouldBounce": "false",
"languageFullName": random.choice(language_list),
}
return data
@app.get("/script/success")
async def do_success(request: Request):
# 获取当前时间
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 获取请求者的IP地址
client_host = request.client.host
# 打印上报成功的时间和IP地址
# print(f"请求IP地址: {client_host},上报成功时间: {current_time}")
print(f"请求IP地址: {client_host},请求时间{current_time},请求路径: /script/success")
data = {}
return {
"code": 0,
"msg": "ok",
"data": data
}
@app.get("/script/failed")
async def do_failed(request: Request, reason: str = None, errortype: str = None):
# 获取当前时间
now = datetime.now()
# 格式化时间为 年-月-日 时:分:秒 的格式
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"请求IP地址: {request.client.host},请求时间{formatted_now},请求路径: /script/failed")
# 假设这里记录失败原因到日志或数据库
print(f"上报失败,Time: {formatted_now}, 失败原因: {reason},失败类型: {errortype}.") # 实际应用中应使用更专业的日志记录方式
return {
"code": 0,
"msg": "ok",
"data": {}
}
@app.get("/report/chrome/crash")
async def report_chrome_crash(id: str, timestamp: str = Query(None)):
# 获取当前时间
now = datetime.now()
# 格式化时间为 年-月-日 时:分:秒 的格式
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
# 假设这里记录失败原因到日志或数据库
print(f"Time: {formatted_now}, ID: {id}, 时间戳: {timestamp}") # 实际应用中应使用更专业的日志记录方式
return {
"code": 0,
"msg": "ok",
"data": {}
}
@app.get("/script/uploaddata")
async def upload_ads_status(impressions: str, clicks: str):
# 获取当前时间
now = datetime.now()
# 格式化时间为 年-月-日 时:分:秒 的格式
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
# 假设这里记录失败原因到日志或数据库
print(f"Time: {formatted_now}, impressions: {impressions}, clicks: {clicks}") # 实际应用中应使用更专业的日志记录方式
return {
"code": 0,
"msg": "ok",
"data": {}
}
@app.post("/api/account/")
async def get_account(request: Request):
server_token = "cT&Ur7AciCgL6P$2u!^mauI05r6jcD$A"
accounts = [
{"account": "reedavice8@gmail.com", "password": "L906lTeTlpelaq",
"auxiliary_mailbox": "tcmuffin56@mailexpire.com"},
{"account": "annist95g@gmail.com", "password": "28CUxUmygURereJ",
"auxiliary_mailbox": "b1youngster983@yahoo.ie"},
{"account": "vr8607864@gmail.com", "password": "J945YgaX", "auxiliary_mailbox": "sbqunmetal3@xtra.co.nz"},
{"account": "ShimoGuagliardo537@gmail.com", "password": "94Ss9YYx3",
"auxiliary_mailbox": "spigelmyerhalalikyzd185@yawua.us"},
]
# 从请求头中获取token
token = request.headers.get('Authorization')
# 获取当前时间
now = datetime.now()
# 格式化时间
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"请求IP地址: {request.client.host}, 请求时间: {formatted_now}, 请求token: {token}, 请求路径: /api/account/")
# 检查token是否存在且匹配
if not token or token != server_token:
# 如果token不正确返回401未授权状态
raise HTTPException(status_code=401, detail="Unauthorized")
# 随机选择一个账户信息返回
selected_account = random.choice(accounts)
return selected_account

67
main.py
View File

@@ -1,6 +1,5 @@
from fastapi import FastAPI, HTTPException, Request from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
import base64
import os import os
app = FastAPI() app = FastAPI()
@@ -8,12 +7,7 @@ app = FastAPI()
@app.get("/") @app.get("/")
async def root(): async def root():
return {"message": "Hello World"} return "welcome to fastAPI!"
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}
@app.post("/user/login") @app.post("/user/login")
@@ -23,7 +17,6 @@ async def login(request: Request):
username = data.get("username") username = data.get("username")
password = data.get("password") password = data.get("password")
print(f"username: {username},password: {password}") print(f"username: {username},password: {password}")
# Replace with your actual validation logic
if username == "1" and password == "1": if username == "1" and password == "1":
data1 = None data1 = None
return {"code": "0", "msg": "ok", "data": data1} return {"code": "0", "msg": "ok", "data": data1}
@@ -34,21 +27,21 @@ async def login(request: Request):
@app.get("/api/get-menu") @app.get("/api/get-menu")
async def get_menu(): async def get_menu():
base_url = "http://127.0.0.1:8000/api/menu-image/"
directory = "assets/images/icon"
pic_list = [ pic_list = [
{id: 1, "menu_name": "政策查询", "url": "/pages/policy/policy", "path": "assets/images/icon/政策解读.png"}, {id: 1, "menu_name": "政策查询", "url": "/pages/policy/policy", "icon_name": "政策解读.png"},
{id: 2, "menu_name": "问答", "url": "/pages/qa/qa", "path": "assets/images/icon/问答.png"}, {id: 2, "menu_name": "问答", "url": "/pages/qa/qa", "icon_name": "问答.png"},
{id: 3, "menu_name": "信息管理", "url": "/pages/assist/assist", "path": "assets/images/icon/群众信息管理.png"}, {id: 3, "menu_name": "信息管理", "url": "/pages/assist/assist", "icon_name": "群众信息管理.png"},
{id: 4, "menu_name": "招聘", "url": "/pages/recruit/recruit", "path": "assets/images/icon/招聘.png"} {id: 4, "menu_name": "招聘", "url": "/pages/recruit/recruit", "icon_name": "招聘.png"}
] ]
data = [] data = []
for item in pic_list: for item in pic_list:
with open(item['path'], "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode()
data.append({ data.append({
"id": item[id], "id": item[id],
"menu_name": item['menu_name'], "menu_name": item['menu_name'],
"url": item['url'], "url": item['url'],
"base64EncodedImage": encoded_string "image_url": base_url + item['icon_name']
}) })
return { return {
@@ -92,3 +85,47 @@ async def get_swiper_image(image_id: str):
except FileNotFoundError: except FileNotFoundError:
# 如果文件没有找到返回404错误 # 如果文件没有找到返回404错误
raise HTTPException(status_code=404, detail="Image not found") raise HTTPException(status_code=404, detail="Image not found")
@app.get("/api/menu-image/{image_name}.png")
async def get_menu_image(image_name: str):
base_image_path = "assets/images/icon"
# 构造图片文件的完整路径
image_path = f"{base_image_path}/{image_name}.png" # 假设图片格式为png根据需要修改
print(image_path)
try:
# 返回图片文件的响应
return FileResponse(image_path)
except FileNotFoundError:
# 如果文件没有找到返回404错误
raise HTTPException(status_code=404, detail="Image not found")
@app.get("/api/policy-list")
async def get_policy_list():
policy_list = [
{"title": "政策标题1", "date": "2024-01-01"},
{"title": "政策标题2", "date": "2023-01-02"},
{"title": "政策标题3", "date": "2022-01-03"},
{"title": "政策标题4", "date": "2023-01-14"},
{"title": "政策标题5", "date": "2022-01-14"},
{"title": "政策标题6", "date": "2023-01-15"},
{"title": "政策标题7", "date": "2021-01-16"},
{"title": "政策标题8", "date": "2021-01-02"},
{"title": "政策标题9", "date": "2024-02-02"},
{"title": "政策标题10", "date": "2024-03-02"},
{"title": "政策标题11", "date": "2024-04-02"},
{"title": "政策标题12", "date": "2024-01-02"},
{"title": "政策标题13", "date": "2023-01-24"},
{"title": "政策标题14", "date": "2022-01-02"},
{"title": "政策标题15", "date": "2022-12-02"},
{"title": "政策标题16", "date": "2021-04-02"},
{"title": "政策标题17", "date": "2020-02-02"}
]
return {
"code": 0,
"msg": "ok",
"data": policy_list
}

18
requirements.txt Normal file
View File

@@ -0,0 +1,18 @@
annotated-types==0.6.0
anyio==4.2.0
click==8.1.7
fastapi==0.108.0
h11==0.14.0
httptools==0.6.1
idna==3.6
pillow==10.2.0
pydantic==2.5.3
pydantic_core==2.14.6
python-dotenv==1.0.0
PyYAML==6.0.1
sniffio==1.3.0
starlette==0.32.0.post1
typing_extensions==4.9.0
uvicorn==0.25.0
watchfiles==0.21.0
websockets==12.0

View File

@@ -1,11 +0,0 @@
# Test your FastAPI endpoints
GET http://127.0.0.1:8000/
Accept: application/json
###
GET http://127.0.0.1:8000/hello/User
Accept: application/json
###

34
utils/pictures_handle.py Normal file
View File

@@ -0,0 +1,34 @@
import os
def get_pictures_info(directory, page, page_size):
pictures = []
start_index = (page - 1) * page_size
end_index = start_index + page_size
counter = 0
for filename in os.listdir(directory):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
if start_index <= counter < end_index:
file_path = os.path.join(directory, filename)
size = os.path.getsize(file_path)
size_mb = size / (1024 * 1024)
picture_info = {
"id": counter + 1,
"photo_name": filename,
"photo_size": round(size_mb, 2),
"photo_url": file_path
}
pictures.append(picture_info)
counter += 1
if counter >= end_index:
break
return pictures
def get_total_pages(directory, page_size):
total_photos = 0
for filename in os.listdir(directory):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
total_photos += 1
return (total_photos + page_size - 1) // page_size

72
website.py Normal file
View File

@@ -0,0 +1,72 @@
import os
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from utils.pictures_handle import get_pictures_info
from utils.pictures_handle import get_total_pages
app = FastAPI()
app.mount("/static", StaticFiles(directory="assets/images/pictures/"), name="static")
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"], # 允许的源列表
allow_credentials=True,
allow_methods=["*"], # 允许的方法
allow_headers=["*"], # 允许的头
)
@app.get("/")
async def root():
return "welcome to fastAPI!"
@app.get("/api/get-menu")
async def get_menu():
menu_list = [
{"id": 1, "menu_name": "首页", "url": "/", "src": "/index.svg"},
{"id": 2, "menu_name": "图片", "url": "/photos", "src": "/photo.svg"},
{"id": 3, "menu_name": "视频", "url": "/videos", "src": "/videos.svg"},
{"id": 4, "menu_name": "关于", "url": "/about", "src": "/about.svg"}
]
return {
"code": 0,
"msg": "ok",
"data": menu_list
}
@app.get("/api/get-photo-list")
async def get_photo_list(page: int = 1, page_size: int = 10):
dir_path = "assets/images/pictures"
total_pages = get_total_pages(dir_path, page_size)
photo_list = get_pictures_info(dir_path, page, page_size)
for photo in photo_list:
photo["photo_url"] = f"http://127.0.0.1:8000/static/{photo['photo_name']}"
return {
"code": 0,
"msg": "ok",
"data": photo_list,
"page_count": total_pages
}
@app.get("/static/{photo_name}")
async def get_photo(photo_name: str,request: Request):
request_path = str(request.url)
dir = "/assets/images/pictures"
file_path = os.path.join(dir, photo_name)
print(file_path)
if os.path.exists(file_path):
return FileResponse(file_path)
else:
print(f"ERROR: {request_path}")
return {
"code": -1,
"msg": "error",
"data": None
}