Skip to content

Commit

Permalink
feat: add model
Browse files Browse the repository at this point in the history
  • Loading branch information
lloydzhou committed Dec 28, 2023
1 parent d155e8a commit 45602e9
Show file tree
Hide file tree
Showing 8 changed files with 255 additions and 35 deletions.
102 changes: 101 additions & 1 deletion pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ dependencies = [
"python-dotenv>=1.0.0",
"ca-lark-oauth==0.0.5",
"ca-lark-webhook>=0.0.3",
"flask-sqlalchemy>=3.1.1",
"flask-cors>=4.0.0",
]
requires-python = ">=3.10"
readme = "README.md"
Expand Down
8 changes: 6 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ certifi==2023.11.17
click==8.1.7
colorama==0.4.6; platform_system == "Windows"
exceptiongroup==1.2.0; python_version < "3.11"
flask==3.0.0
Flask==3.0.0
flask-cors==4.0.0
flask-sqlalchemy==3.1.1
greenlet==3.0.3; platform_machine == "win32" or platform_machine == "WIN32" or platform_machine == "AMD64" or platform_machine == "amd64" or platform_machine == "x86_64" or platform_machine == "ppc64le" or platform_machine == "aarch64"
h11==0.14.0
httpcore==1.0.2
httpx==0.26.0
Expand All @@ -21,5 +24,6 @@ MarkupSafe==2.1.3
pycryptodome==3.19.1
python-dotenv==1.0.0
sniffio==1.3.0
typing-extensions==4.9.0; python_version < "3.11"
sqlalchemy==2.0.23
typing-extensions==4.9.0
Werkzeug==3.0.1
41 changes: 9 additions & 32 deletions server/app.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,16 @@
import os

from connectai.lark.oauth import Server as OauthServer
from connectai.lark.sdk import Bot, MarketBot
from connectai.lark.webhook import LarkServer
from flask import Flask, session
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.secret_key = (os.environ.get("SECRET_KEY"),)

hook = LarkServer(prefix="/api/feishu/hook")
oauth = OauthServer(prefix="/api/feishu/oauth")

bot = Bot(
app_id=os.environ.get("APP_ID"),
app_secret=os.environ.get("APP_SECRET"),
encrypt_key=os.environ.get("ENCRYPT_KEY"),
verification_token=os.environ.get("VERIFICATION_TOKEN"),
app.secret_key = os.environ.get("SECRET_KEY")
db = SQLAlchemy(app, engine_options={"isolation_level": "AUTOCOMMIT"})
CORS(
app, allow_headers=["Authorization", "X-Requested-With"], supports_credentials=True
)


@hook.on_bot_message(message_type="text", bot=bot)
def on_text_message(bot, message_id, content, *args, **kwargs):
text = content["text"]
print("reply_text", message_id, text)
bot.reply_text(message_id, "reply: " + text)


@oauth.on_bot_event(event_type="oauth:user_info", bot=bot)
def on_oauth_user_info(bot, event_id, user_info, *args, **kwargs):
# oauth user_info
print("oauth", user_info)
# TODO
session["user_id"] = user_info["union_id"]
return user_info


app.register_blueprint(oauth.get_blueprint())
app.register_blueprint(hook.get_blueprint())
gunicorn_logger = logging.getLogger("gunicorn.error")
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
86 changes: 86 additions & 0 deletions server/model/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import json
import logging
from datetime import datetime

import bson
from app import db
from sqlalchemy import BINARY, String, text


class ObjID(BINARY):
"""基于bson.ObjectId用于mysql主键的自定义类型"""

def bind_processor(self, dialect):
def processor(value):
return (
bson.ObjectId(value).binary if bson.ObjectId.is_valid(value) else value
)

return processor

def result_processor(self, dialect, coltype):
def processor(value):
if not isinstance(value, bytes):
value = bytes(value)
return str(bson.ObjectId(value)) if bson.ObjectId.is_valid(value) else value

return processor

@staticmethod
def new_id():
return str(bson.ObjectId())

@staticmethod
def is_valid(value):
return bson.ObjectId.is_valid(value)


class JSONStr(String):
"""自动转换 str 和 dict 的自定义类型"""

def bind_processor(self, dialect):
def processor(value):
try:
if isinstance(value, str) and (value[0] == "%" or value[-1] == "%"):
# 使用like筛选的情况
return value
return json.dumps(value, ensure_ascii=False)
except Exception as e:
logging.exception(e)
return value

return processor

def result_processor(self, dialect, coltype):
def processor(value):
try:
return json.loads(value)
except Exception as e:
logging.exception(e)
return value

return processor

@staticmethod
def is_valid(value):
try:
json.loads(value)
return True
except Exception as e:
logging.exception(e)
return False


class User(db.Model):
__tablename__ = "user"
id = db.Column(ObjID(12), primary_key=True)
openid = db.Column(db.String(128), nullable=True, comment="外部用户ID")
name = db.Column(db.String(128), nullable=True, comment="用户名")
extra = db.Column(
JSONStr(1024), nullable=True, server_default=text("'{}'"), comment="用户其他字段"
)
status = db.Column(db.Integer, nullable=True, default=0, server_default=text("0"))
created = db.Column(db.TIMESTAMP, nullable=False, default=datetime.utcnow)
modified = db.Column(
db.TIMESTAMP, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow
)
1 change: 1 addition & 0 deletions server/routes/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .lark import *
49 changes: 49 additions & 0 deletions server/routes/lark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import os

from app import app
from connectai.lark.oauth import Server as OauthServerBase
from connectai.lark.sdk import Bot, MarketBot
from connectai.lark.webhook import LarkServer as LarkServerBase

bot = Bot(
app_id=os.environ.get("APP_ID"),
app_secret=os.environ.get("APP_SECRET"),
encrypt_key=os.environ.get("ENCRYPT_KEY"),
verification_token=os.environ.get("VERIFICATION_TOKEN"),
)


class LarkServer(LarkServerBase):
def get_bot(self, app_id):
# TODO search in database and create Bot()
return bot


class OauthServer(OauthServerBase):
def get_bot(self, app_id):
# TODO search in database and create Bot()
return bot


hook = LarkServer(prefix="/api/feishu/hook")
oauth = OauthServer(prefix="/api/feishu/oauth")


@hook.on_bot_message(message_type="text", bot=bot)
def on_text_message(bot, message_id, content, *args, **kwargs):
text = content["text"]
print("reply_text", message_id, text)
bot.reply_text(message_id, "reply: " + text)


@oauth.on_bot_event(event_type="oauth:user_info", bot=bot)
def on_oauth_user_info(bot, event_id, user_info, *args, **kwargs):
# oauth user_info
print("oauth", user_info)
# TODO
session["user_id"] = user_info["union_id"]
return user_info


app.register_blueprint(oauth.get_blueprint())
app.register_blueprint(hook.get_blueprint())
1 change: 1 addition & 0 deletions server/server.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os

import env
import routes
from app import app

if __name__ == "__main__":
Expand Down

0 comments on commit 45602e9

Please sign in to comment.