tanbushi commited on
Commit
f5cf708
·
1 Parent(s): 702187d

modify users, use cf db

Browse files
.gitignore CHANGED
@@ -1,2 +1,3 @@
1
  __pycache__/
2
- .env
 
 
1
  __pycache__/
2
+ .env
3
+ .DS_Store
__init__.py ADDED
File without changes
api_keys.db DELETED
Binary file (12.3 kB)
 
app.py CHANGED
@@ -1,21 +1,32 @@
1
  # uvicorn app:app --host 0.0.0.0 --port 7860 --reload
2
 
 
 
 
 
 
 
 
 
 
3
  from fastapi import FastAPI, HTTPException, Response, Depends
 
4
  # from starlette.requests import Request
5
 
6
  from routers.webtools_v1 import router as webtools_router
7
  from routers.users_v1 import router as users_router
8
  from routers.openai_v1 import router as openai_router
9
 
10
- from db import Db
11
 
12
  from dotenv import load_dotenv
13
  import os
14
 
15
-
16
- # 加载.env文件
17
  load_dotenv()
18
 
 
19
  DB_PATH = os.getenv("DB_PATH")
20
 
21
  # 依赖注入,获取 DB_PATH
@@ -43,7 +54,7 @@ CREATE TABLE api_keys (
43
  dest_api_key TEXT NOT NULL
44
  );
45
  """
46
- Db('api_keys.db').execute_query(sql)
47
 
48
  # def create_user_api_key(user_id, api_key, type, status, idx, dest_api_key):
49
  # sql = f"""
@@ -53,7 +64,22 @@ CREATE TABLE api_keys (
53
 
54
  # create_user_api_key('i_am_tanbushi', 'llm', '1', '0', 'dest_api_key')
55
 
56
- @app.get("/cur_path")
57
- def cur_path():
58
  # return "cur_path"
59
- return {"cur_path": os.getcwd()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # uvicorn app:app --host 0.0.0.0 --port 7860 --reload
2
 
3
+ from pathlib import Path
4
+ from global_state import set
5
+
6
+ # 获取当前文件的父目录的绝对路径,即:project_root
7
+ parent_dir = Path(__file__).resolve().parent
8
+ set('project_root', parent_dir)
9
+
10
+ print('\n\n\n======================')
11
+
12
  from fastapi import FastAPI, HTTPException, Response, Depends
13
+ from fastapi.responses import HTMLResponse
14
  # from starlette.requests import Request
15
 
16
  from routers.webtools_v1 import router as webtools_router
17
  from routers.users_v1 import router as users_router
18
  from routers.openai_v1 import router as openai_router
19
 
20
+ # from db import Db
21
 
22
  from dotenv import load_dotenv
23
  import os
24
 
25
+ print('\n\n\n======================')
26
+ # 当在本地使用.env 文件时加载.env文件
27
  load_dotenv()
28
 
29
+ # 获取环境变量,本地使用 load_dotenv 和 hf 里直接使用环境变量配置时,都可使用下面的语句
30
  DB_PATH = os.getenv("DB_PATH")
31
 
32
  # 依赖注入,获取 DB_PATH
 
54
  dest_api_key TEXT NOT NULL
55
  );
56
  """
57
+ # Db('api_keys.db').execute_query(sql)
58
 
59
  # def create_user_api_key(user_id, api_key, type, status, idx, dest_api_key):
60
  # sql = f"""
 
64
 
65
  # create_user_api_key('i_am_tanbushi', 'llm', '1', '0', 'dest_api_key')
66
 
67
+ @app.get("/list_files")
68
+ def list_files():
69
  # return "cur_path"
70
+ directory = os.getcwd()
71
+
72
+ # 遍历目录树
73
+ retstr="第一行\n第二行\n第三行\n"
74
+ # retstr = retstr + '1' + "\n"
75
+ # retstr = retstr + '2' + "\n"
76
+ # retstr = retstr + '3' + "\n"
77
+ print(retstr)
78
+ # for dirpath, dirnames, filenames in os.walk(directory):
79
+ # for filename in filenames:
80
+ # retstr = retstr + os.path.join(dirpath, filename) +'\\n'
81
+ # print(os.path.join(dirpath, filename))
82
+
83
+ return HTMLResponse(f"<pre>{retstr}</pre>")
84
+ return HTMLResponse(content=f"<pre>{retstr}</pre>", media_type="text/html")
85
+ return retstr
captcha.png DELETED
Binary file (11 kB)
 
db.py DELETED
@@ -1,64 +0,0 @@
1
- import sqlite3
2
- import json
3
-
4
- class Db():
5
- def __init__(self, db_path):
6
- self.db_path = db_path
7
- # print(self.db_path)
8
-
9
- def list_query(self, query):
10
- conn = sqlite3.connect(self.db_path)
11
- cursor = conn.cursor()
12
- cursor.execute(query)
13
- conn.commit()
14
-
15
- rows = cursor.fetchall()
16
- # print('results')
17
- # print(results)
18
- cursor.close()
19
- conn.close()
20
-
21
- json_rows = []
22
- # 为每一行结果创建一个字典,并添加到列表中
23
- for row in rows:
24
- # 使用cursor.description获取列名和相关信息
25
- columns = dict(zip([col[0] for col in cursor.description], row))
26
- json_rows.append(columns)
27
-
28
- return json_rows
29
-
30
- def insert_query(self, query):
31
- conn = sqlite3.connect(self.db_path)
32
- cursor = conn.cursor()
33
- cursor.execute(query)
34
- conn.commit()
35
- rowcount = cursor.rowcount
36
-
37
- return f"插入的行数: {rowcount}"
38
-
39
- def update_query(self, query):
40
- conn = sqlite3.connect(self.db_path)
41
- cursor = conn.cursor()
42
- cursor.execute(query)
43
- conn.commit()
44
- rowcount = cursor.rowcount
45
-
46
- return f"影响的行数: {rowcount}"
47
- # from fastapi import FastAPI
48
-
49
- # # 依赖注入,获取 FastAPI 应用实例
50
- # def get_app() -> FastAPI:
51
- # return FastAPI()
52
-
53
- # def execute_query(query):
54
-
55
-
56
-
57
-
58
- # CREATE TABLE api_keys (
59
- # api_key TEXT NOT NULL,
60
- # type TEXT NOT NULL,
61
- # status INTEGER NOT NULL,
62
- # idx INTEGER NOT NULL,
63
- # PRIMARY KEY (api_key, type, status, idx)
64
- # );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db/__init__.py ADDED
File without changes
db/cloudflare.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests, os
2
+ from dotenv import load_dotenv
3
+
4
+ class Cloudflare():
5
+ def __init__(self):
6
+ load_dotenv()
7
+ self.CF_ACCOOUNT_ID=os.getenv("CF_ACCOOUNT_ID")
8
+ self.DATABASE_ID=os.getenv("DATABASE_ID")
9
+ self.X_Auth_Key=os.getenv("X_Auth_Key")
10
+ self.X_Auth_Email=os.getenv("X_Auth_Email")
11
+
12
+ # print('Cloudflare init')
13
+ # print('self.CF_ACCOOUNT_ID',self.CF_ACCOOUNT_ID)
14
+ # print('self.DATABASE_ID',self.DATABASE_ID)
15
+ # print('self.X_Auth_Key',self.X_Auth_Key)
16
+ # print('self.X_Auth_Email',self.X_Auth_Email)
17
+
18
+ def execute_query(self, query):
19
+ url = f"https://api.cloudflare.com/client/v4/accounts/{self.CF_ACCOOUNT_ID}/d1/database/{self.DATABASE_ID}/query"
20
+ headers = {
21
+ "X-Auth-Key": f"{self.X_Auth_Key}",
22
+ "X-Auth-Email": f"{self.X_Auth_Email}"
23
+ }
24
+ input = {
25
+ "params": [],
26
+ "sql": query
27
+ }
28
+ response = requests.post(url, headers=headers, json=input)
29
+ resp_json = response.json()
30
+ print(resp_json)
31
+ return resp_json
32
+
db/tbs_db.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils.load_module import load_module
2
+
3
+ class TbsDb():
4
+
5
+ def __init__(self, db_module_filename, class_name):
6
+ self.db_module = load_module(db_module_filename, class_name)
7
+
8
+ def get_list(self, query):
9
+ response = self.execute_query(query)
10
+ if response['success']==False:
11
+ return response
12
+ return response['result'][0]
13
+ # return self.execute_query(query)
14
+
15
+ def add_item(self, query):
16
+ return self.execute_query(query)
17
+
18
+ def get_item(self, query):
19
+ return self.execute_query(query)
20
+
21
+ def execute_query(self, query):
22
+ return self.db_module.execute_query(query)
23
+
global_state.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # global_state.py
2
+ _state = {}
3
+
4
+ def set(key, value):
5
+ _state[key] = value
6
+
7
+ def get(key):
8
+ return _state.get(key)
9
+
routers/openai_v1.py CHANGED
@@ -1,5 +1,5 @@
1
  from fastapi import APIRouter, Request, HTTPException
2
- from db import Db
3
  from dotenv import load_dotenv
4
  import os, json
5
  from langchain_core.output_parsers import StrOutputParser
 
1
  from fastapi import APIRouter, Request, HTTPException
2
+ # from db import Db
3
  from dotenv import load_dotenv
4
  import os, json
5
  from langchain_core.output_parsers import StrOutputParser
routers/users_v1.py CHANGED
@@ -1,48 +1,42 @@
1
- from fastapi import APIRouter, Request, FastAPI, Depends
2
- from dotenv import load_dotenv
3
- import os
4
  import uuid
5
- from db import Db
6
 
7
- router = APIRouter()
8
-
9
- # 加载.env文件
10
- load_dotenv()
11
 
12
- DB_PATH = os.getenv("DB_PATH")
13
 
14
- # 依赖注入,获取 DB_PATH
15
- def get_db_path():
16
- return DB_PATH
17
 
18
  @router.get("/users")
19
- async def read_users(db_path: str = Depends(get_db_path)):
20
- # print('\n\n\n\n\n')
21
- # print(db_path)
22
- result = Db(db_path).list_query("SELECT * FROM users")
23
- return result
 
 
 
 
 
24
 
25
  @router.post("/users")
26
- async def create_user(request: Request, b_path: str = Depends(get_db_path)):
27
- request_json = await request.json()
28
- username = request_json.get('username')
29
- password = request_json.get('password')
30
- email = request_json.get('email')
31
- nikename = request_json.get('nikename')
32
  if nikename==None:
33
  nikename = ''
34
- # print(nikename)
35
  api_key = f'airs-{uuid.uuid4()}'
36
- # result = api_key
37
- # print(api_key)
38
- result = Db(b_path).insert_query(f"INSERT INTO users (username, password, email, nikename, api_key) VALUES ('{username}', '{password}', '{email}', '{nikename}', '{api_key}')")
39
- return result
40
 
41
  @router.get("/users/{id}")
42
- async def read_user(request: Request, id:int, db_path: str = Depends(get_db_path)):
43
- result = Db(db_path).list_query(f"SELECT * FROM users where id={id}")
44
- if len(result)>0:
45
- return result[0]
46
- else:
47
- return None
48
-
 
1
+ from fastapi import APIRouter
2
+ from pydantic import BaseModel
 
3
  import uuid
 
4
 
5
+ from global_state import get
6
+ from db.tbs_db import TbsDb
 
 
7
 
8
+ router = APIRouter()
9
 
10
+ db_module_filename = f"{get('project_root')}/db/cloudflare.py"
 
 
11
 
12
  @router.get("/users")
13
+ async def read_users():
14
+ query = "SELECT * FROM users"
15
+ response = TbsDb(db_module_filename, "Cloudflare").get_list(query)
16
+ return response
17
+
18
+ class User(BaseModel):
19
+ username: str
20
+ password: str
21
+ email: str
22
+ nikename: str = None
23
 
24
  @router.post("/users")
25
+ async def create_user(user: User):
26
+ username = user.username
27
+ password = user.password
28
+ email = user.email
29
+ nikename = user.nikename
 
30
  if nikename==None:
31
  nikename = ''
32
+
33
  api_key = f'airs-{uuid.uuid4()}'
34
+ query = f"INSERT INTO users (username, password, email, nikename, api_key) VALUES ('{username}', '{password}', '{email}', '{nikename}', '{api_key}')"
35
+ response = TbsDb(db_module_filename, "Cloudflare").add_item(query)
36
+ return response
 
37
 
38
  @router.get("/users/{id}")
39
+ async def read_user(id:int):
40
+ query = f"SELECT * FROM users where id={id}"
41
+ response = TbsDb(db_module_filename, "Cloudflare").get_item(query)
42
+ return response
 
 
 
routers/webtools_v1.py CHANGED
@@ -1,5 +1,5 @@
1
  from fastapi import FastAPI, APIRouter, Response, Depends
2
- # from captcha.image import ImageCaptcha
3
  from io import BytesIO
4
 
5
  router = APIRouter()
 
1
  from fastapi import FastAPI, APIRouter, Response, Depends
2
+ from captcha.image import ImageCaptcha
3
  from io import BytesIO
4
 
5
  router = APIRouter()
sql.md DELETED
@@ -1,88 +0,0 @@
1
- 当然,以下是完整的SQL语句,用于创建`api_names`、`api_keys`表,以及可选的`api_usage`表。这些表将支持存储API名称、API-KEY信息,并可选地记录API的使用情况。
2
-
3
- ### SQL 创建表的语句
4
-
5
- ```sql
6
- -- 创建 users 表
7
- DROP TABLE IF EXISTS "users";
8
- CREATE TABLE "users" (
9
- "id" INTEGER PRIMARY KEY AUTOINCREMENT,
10
- "username" TEXT NOT NULL,
11
- "password" TEXT NOT NULL,
12
- "email" TEXT NOT NULL,
13
- "nikename" TEXT,
14
- "created_at" DATETIME DEFAULT CURRENT_TIMESTAMP,
15
- "updated_at" DATETIME DEFAULT CURRENT_TIMESTAMP,
16
- UNIQUE ("username" ASC),
17
- UNIQUE ("email" ASC)
18
- );
19
-
20
- -- 创建api_groups表
21
- CREATE TABLE api_groups (
22
- id INTEGER PRIMARY KEY AUTOINCREMENT,
23
- group_name TEXT NOT NULL UNIQUE,
24
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
25
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
26
- );
27
-
28
- -- 创建api_names表
29
- CREATE TABLE api_names (
30
- id INTEGER PRIMARY KEY AUTOINCREMENT,
31
- api_name TEXT NOT NULL UNIQUE,
32
- api_group_id INTEGER,
33
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
34
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
35
- FOREIGN KEY (api_group_id) REFERENCES api_groups(id) ON DELETE SET NULL
36
- );
37
-
38
- -- 创建api_keys表
39
- CREATE TABLE api_keys (
40
- id INTEGER PRIMARY KEY AUTOINCREMENT,
41
- api_group_id INTEGER NOT NULL,
42
- api_key TEXT NOT NULL,
43
- category TEXT NOT NULL,
44
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
45
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
46
- FOREIGN KEY (api_group_id) REFERENCES api_groups(id) ON DELETE CASCADE
47
- );
48
-
49
- -- 创建user_api_keys表
50
- CREATE TABLE user_api_keys (
51
- id INTEGER PRIMARY KEY AUTOINCREMENT,
52
- user_api_key TEXT NOT NULL,
53
- user_id INTEGER,
54
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
55
- updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
56
- );
57
-
58
- -- 创建api_usage表(如果需要)
59
- CREATE TABLE api_usage (
60
- id INTEGER PRIMARY KEY AUTOINCREMENT,
61
- user_api_key_id INTEGER,
62
- api_key_id INTEGER,
63
- request_count INTEGER DEFAULT 0,
64
- last_used DATETIME DEFAULT CURRENT_TIMESTAMP,
65
- FOREIGN KEY (user_api_key_id) REFERENCES user_api_keys(id),
66
- FOREIGN KEY (api_key_id) REFERENCES api_keys(id)
67
- );
68
- ```
69
-
70
- ### 说明
71
-
72
- - **`api_names` 表**:存储唯一的API名称。
73
- - **`api_keys` 表**:存储每个API名称对应的多个API-KEY,包括分类信息。`api_names_id`作为外键,关联到`api_names`表。
74
- - **`user_api_keys` 表**:存储用户的API-KEY。
75
- - **`api_usage` 表**(可选):记录API的使用情况,包括请求次数和最后使用时间。这个表可以用来监控API的使用情况,帮助管理API-KEY的使用限额。
76
-
77
- 这些SQL语句假设你使用的是MySQL数据库。如果你使用的是其他类型的数据库(如PostgreSQL、SQLite等),可能需要对SQL语句进行适当的调整。如果有任何问题或需要进一步的帮助,请随时告诉我。
78
-
79
-
80
-
81
- ### 通过 api_name 查询 api_key 的 SQL 语句
82
- ```sql
83
- SELECT ak.api_key
84
- FROM api_keys ak
85
- JOIN api_groups ag ON ak.api_group_id = ag.id
86
- JOIN api_names an ON an.api_group_id = ag.id
87
- WHERE an.api_name = 'your_api_name';
88
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_db.py DELETED
@@ -1,22 +0,0 @@
1
- # PC上数据库的位置为:/mnt/f/微云同步目录/1913864316/dev/projects/api-mapper
2
-
3
- from db import Db
4
- from dotenv import load_dotenv
5
- import os
6
-
7
- # 加载.env文件
8
- load_dotenv()
9
-
10
- db = Db(os.getenv("DB_PATH"))
11
-
12
- results = db.execute_query("""
13
- SELECT an.api_name, ak.api_key
14
- FROM api_keys ak
15
- JOIN api_groups ag ON ak.api_group_id = ag.id
16
- JOIN api_names an ON an.api_group_id = ag.id
17
- WHERE an.api_name = 'glm-4-flash';
18
- """)
19
-
20
-
21
- for row in results:
22
- print(row)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_mysql.py DELETED
@@ -1,24 +0,0 @@
1
- import mysql.connector
2
-
3
- # 配置数据库连接参数
4
- config = {
5
- 'user': 'tanbushi', # 替换为你的MySQL用户名
6
- 'password': 'Tangeqin1968', # 替换为你的MySQL密码
7
- 'host': 'db4free.net', # 数据库主机地址,本地默认是localhost
8
- 'database': 'apimapper', # 你要连接的数据库名
9
- 'raise_on_warnings': True
10
- }
11
-
12
- # 建立连接
13
- try:
14
- cnx = mysql.connector.connect(**config)
15
- print("Connection established")
16
- except mysql.connector.Error as err:
17
- print("Error:", err)
18
-
19
- cursor = cnx.cursor()
20
- query = ("SELECT COUNT(*) FROM users") # 替换为你的表名和查询
21
- cursor.execute(query)
22
- count = cursor.fetchone()[0]
23
- print(f"表中的记录数: {count}")
24
- cursor.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
users.sql DELETED
@@ -1,41 +0,0 @@
1
- /*
2
- Navicat Premium Dump SQL
3
-
4
- Source Server : api_keys
5
- Source Server Type : SQLite
6
- Source Server Version : 3045000 (3.45.0)
7
- Source Schema : main
8
-
9
- Target Server Type : SQLite
10
- Target Server Version : 3045000 (3.45.0)
11
- File Encoding : 65001
12
-
13
- Date: 03/11/2024 20:45:36
14
- */
15
-
16
- PRAGMA foreign_keys = false;
17
-
18
- -- ----------------------------
19
- -- Table structure for users
20
- -- ----------------------------
21
- DROP TABLE IF EXISTS "users";
22
- CREATE TABLE "users" (
23
- "id" INTEGER PRIMARY KEY AUTOINCREMENT,
24
- "username" TEXT NOT NULL,
25
- "password" TEXT NOT NULL,
26
- "email" TEXT NOT NULL,
27
- "nikename" TEXT,
28
- "api_key" TEXT,
29
- "config" TEXT,
30
- "created_at" DATETIME DEFAULT CURRENT_TIMESTAMP,
31
- "updated_at" DATETIME DEFAULT CURRENT_TIMESTAMP,
32
- UNIQUE ("username" ASC),
33
- UNIQUE ("email" ASC)
34
- );
35
-
36
- -- ----------------------------
37
- -- Auto increment value for users
38
- -- ----------------------------
39
- UPDATE "sqlite_sequence" SET seq = 5 WHERE name = 'users';
40
-
41
- PRAGMA foreign_keys = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/__init_.py ADDED
File without changes
utils/globals.py ADDED
File without changes
utils/load_module.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+
3
+ def load_module(module_filename, class_name):
4
+ # 使用 spec_from_file_location 获取模块规范
5
+ spec = importlib.util.spec_from_file_location("db_module", module_filename)
6
+ # 如果 spec 是 None,说明无法加载模块
7
+ if spec is None:
8
+ raise ImportError(f"Cannot find module at {module_filename}")
9
+ # 使用 module_from_spec 创建一个新的模块对象
10
+ module = importlib.util.module_from_spec(spec)
11
+ # 执行模块
12
+ spec.loader.exec_module(module)
13
+ MyClass = getattr(module, class_name, None)
14
+ if MyClass is None:
15
+ raise ImportError(f"Cannot find class '{class_name}' in module '{module_filename}'")
16
+ return MyClass()