Commit ca65d190 authored by 崔为之's avatar 崔为之 💪🏽

Update project

parent 21734a2e
...@@ -9,7 +9,7 @@ Database: ...@@ -9,7 +9,7 @@ Database:
Host: localhost Host: localhost
Port: 5432 Port: 5432
DB: elp DB: elp
TableName: users TableName: logs
Elasticsearch: Elasticsearch:
Host: 172.28.5.39 Host: 172.28.5.39
......
...@@ -10,5 +10,4 @@ ...@@ -10,5 +10,4 @@
# @Description : # @Description :
""" """
from .user import UserDao
from .log import LogDao from .log import LogDao
...@@ -13,10 +13,9 @@ ...@@ -13,10 +13,9 @@
from loguru import logger from loguru import logger
from application.utils import ElasticsearchUtil
from application.libs.helper import MySQLHelper from application.libs.helper import MySQLHelper
from application.utils import ParseUtil
from application.models import Log from application.models import Log
from application.utils import ElasticsearchUtil, ParseUtil
class LogDao: class LogDao:
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version : Python 3.11.4
# @Software : Sublime Text 4
# @Author : StudentCWZ
# @Email : StudentCWZ@outlook.com
# @Date : 2023/10/28 23:56
# @File : user.py
# @Description :
"""
from application.extensions.init_sqlalchemy import db
from application.models.user import User
class UserDao:
@classmethod
def get_all(cls):
return User.query.all()
@classmethod
def get_by_id(cls, user_id: int):
return User.query.get(user_id)
@classmethod
def create(cls, username: str, password: str, email: str):
new_user = User(username=username, email=email, password=password)
db.session.add(new_user)
db.session.commit()
return new_user
...@@ -42,17 +42,6 @@ def init_database(app: Flask) -> None: ...@@ -42,17 +42,6 @@ def init_database(app: Flask) -> None:
with app.app_context(): with app.app_context():
db.session.execute(text(f""" db.session.execute(text(f"""
CREATE TABLE IF NOT EXISTS {cfg.TableName} ( CREATE TABLE IF NOT EXISTS {cfg.TableName} (
id SERIAL NOT NULL,
username VARCHAR(80) NOT NULL,
email VARCHAR(120) NOT NULL,
password VARCHAR(255) NOT NULL,
active BOOLEAN,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
"""))
db.session.execute(text("""
CREATE TABLE IF NOT EXISTS logs (
id SERIAL NOT NULL, id SERIAL NOT NULL,
date_time TIMESTAMP WITH TIME ZONE NOT NULL, date_time TIMESTAMP WITH TIME ZONE NOT NULL,
uuid varchar(100) DEFAULT NULL, uuid varchar(100) DEFAULT NULL,
......
...@@ -12,7 +12,6 @@ ...@@ -12,7 +12,6 @@
import datetime import datetime
from application.extensions.init_sqlalchemy import db from application.extensions.init_sqlalchemy import db
from application.models import User
from application.libs.helper import MySQLHelper from application.libs.helper import MySQLHelper
...@@ -33,9 +32,3 @@ def task(): ...@@ -33,9 +32,3 @@ def task():
} }
with MySQLHelper(**options) as helper: with MySQLHelper(**options) as helper:
print(helper.execute(cfg.Sql)) print(helper.execute(cfg.Sql))
print("create user")
# user = User(username="CWzz", email="Stuu@outlook.com", password="qwe!2345", active=True,
# created_at=datetime.datetime.utcnow())
# user.save()
print("created user admin")
...@@ -10,5 +10,4 @@ ...@@ -10,5 +10,4 @@
# @Description : # @Description :
""" """
from .user import User
from .log import Log from .log import Log
...@@ -69,19 +69,6 @@ class Log(db.Model): ...@@ -69,19 +69,6 @@ class Log(db.Model):
_dic[key] = value _dic[key] = value
return _dic return _dic
def save(self):
partition_date = self.date_time.strftime('%Y_%m')
partition_name = f'{self.__tablename__}_{partition_date}'
with db.session.begin_nested():
db.session.execute(text(f"""
CREATE TABLE IF NOT EXISTS {partition_name} PARTITION OF {self.__tablename__}
FOR VALUES FROM ('{self.date_time.strftime('%Y-%m-01')}') TO
('{self.date_time.strftime('%Y-%m-01')}'::date + interval '1 month');
"""))
db.session.add(self)
db.session.commit()
@classmethod @classmethod
def batch_save(cls, objects): def batch_save(cls, objects):
with db.session.begin_nested(): with db.session.begin_nested():
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version : Python 3.11.4
# @Software : Sublime Text 4
# @Author : StudentCWZ
# @Email : StudentCWZ@outlook.com
# @Date : 2023/10/28 22:12
# @File : user.py
# @Description :
"""
import os
from sqlalchemy import text
from sqlalchemy.ext.hybrid import hybrid_property
from application.extensions.init_bcrypt import bcrypt
from application.extensions.init_sqlalchemy import db
class User(db.Model):
"""Basic user model"""
__tablename__ = os.environ.get('TableName', 'users')
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
_password = db.Column("password", db.String(255), nullable=False)
active = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, nullable=False)
@hybrid_property
def password(self):
return self._password
@password.setter
def password(self, password: str):
self._password = bcrypt.generate_password_hash(password).decode('utf-8')
def check_password(self, password: str):
# 判断传过来的密码是否与数据库存的密码一致
return bcrypt.check_password_hash(self._password, password)
def to_dict(self) -> dict:
"""object to dict"""
return {
'id': self.id,
'username': self.username,
'email': self.email,
}
def __repr__(self) -> str:
return f'<User {self.username}>'
def save(self):
partition_date = self.created_at.strftime('%Y_%m')
partition_name = f'{self.__tablename__}_{partition_date}'
with db.session.begin_nested():
db.session.execute(text(f"""
CREATE TABLE IF NOT EXISTS {partition_name} PARTITION OF {self.__tablename__}
FOR VALUES FROM ('{self.created_at.strftime('%Y-%m-01')}') TO
('{self.created_at.strftime('%Y-%m-01')}'::date + interval '1 month');
"""))
db.session.add(self)
db.session.commit()
...@@ -10,6 +10,4 @@ ...@@ -10,6 +10,4 @@
# @Description : # @Description :
""" """
from .user import CreateUserItem
from .user import UserSchema
from .request import ParseLogRequestItem from .request import ParseLogRequestItem
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version : Python 3.11.4
# @Software : Sublime Text 4
# @Author : StudentCWZ
# @Email : StudentCWZ@outlook.com
# @Date : 2023/10/29 00:07
# @File : user.py
# @Description :
"""
from pydantic import BaseModel, EmailStr, field_validator
from application.extensions.init_marshmallow import ma
from application.extensions.init_sqlalchemy import db
from application.models import User
from marshmallow import validates, ValidationError
class CreateUserItem(BaseModel):
username: str
password: str
email: EmailStr
@classmethod
@field_validator("username")
def name_must_contain_only_characters(cls, value):
if not value.isalpha():
raise ValueError("Username must contain only characters.")
return value
class UserSchema(ma.SQLAlchemyAutoSchema):
id = ma.Int(dump_only=True)
username = ma.Str(required=True)
password = ma.String(load_only=True, required=True)
email = ma.Email(required=True)
class Meta:
model = User
sqla_session = db.session
load_instance = True
exclude = ("_password",)
@validates('username')
def validate_username(self, username):
if len(username) < 3:
raise ValidationError('Username must be at least 3 characters.')
\ No newline at end of file
...@@ -17,12 +17,10 @@ from flask.cli import with_appcontext ...@@ -17,12 +17,10 @@ from flask.cli import with_appcontext
@click.command("init") @click.command("init")
@with_appcontext @with_appcontext
def init(): def init():
"""Create a new admin user""" """Create a new log"""
from application.extensions.init_sqlalchemy import db from application.extensions.init_sqlalchemy import db
from application.models import User
click.echo("create user") # click.echo("create log")
user = User(username="StudentCWZ", email="StudentCWZ@outlook.com", password="qwe!2345", active=True) # db.session.add(user)
db.session.add(user) # db.session.commit()
db.session.commit() # click.echo("created log")
click.echo("created user admin")
...@@ -10,5 +10,4 @@ ...@@ -10,5 +10,4 @@
# @Description : # @Description :
""" """
from .user import UserService
from .log import LogService from .log import LogService
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version : Python 3.11.4
# @Software : Sublime Text 4
# @Author : StudentCWZ
# @Email : StudentCWZ@outlook.com
# @Date : 2023/10/29 00:03
# @File : user.py
# @Description :
"""
from application.dao import UserDao
class UserService:
@classmethod
def get_all_users(cls):
return UserDao.get_all()
@classmethod
def get_user_by_id(cls, user_id: int):
return UserDao.get_by_id(user_id)
@classmethod
def create_user(cls, username: str, password: str, email: str):
return UserDao.create(username, password, email)
...@@ -12,10 +12,8 @@ ...@@ -12,10 +12,8 @@
from flask import Flask from flask import Flask
from .user import register_user_views
from .log import register_log_views from .log import register_log_views
def init_views(app: Flask) -> None: def init_views(app: Flask) -> None:
register_user_views(app)
register_log_views(app) register_log_views(app)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version : Python 3.11.4
# @Software : Sublime Text 4
# @Author : StudentCWZ
# @Email : StudentCWZ@outlook.com
# @Date : 2023/10/29 00:18
# @File : __init__.py.py
# @Description :
"""
from flask import Flask
from .user import user_api
def register_user_views(app: Flask):
app.register_blueprint(user_api)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version : Python 3.11.4
# @Software : Sublime Text 4
# @Author : StudentCWZ
# @Email : StudentCWZ@outlook.com
# @Date : 2023/10/29 00:08
# @File : user.py
# @Description :
"""
import json
from flask import Blueprint, current_app, request, jsonify
from flask_restful import Api
from application.services import UserService
from marshmallow import ValidationError
from application.schemas import UserSchema
from application.utils import ElasticsearchUtil
from application.libs.helper import ConfigHelper
user_api = Blueprint('user_api', __name__)
api_users = Api(user_api)
@user_api.route('/users', methods=['GET'])
def get_users():
users = UserService.get_all_users()
return jsonify([user.to_dict() for user in users])
@user_api.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = UserService.get_user_by_id(user_id)
if user is None:
return jsonify({'error': 'User not found'}), 404
return jsonify(user.to_dict())
@user_api.route('/users', methods=['POST'])
def create_user():
user_schema = UserSchema()
try:
data = user_schema.load(request.json)
except ValidationError as e:
return jsonify(e.messages), 400
username = data.username
password = data.password
email = data.email
user = UserService.create_user(username, password, email)
return jsonify(user_schema.dump(user)), 201
@user_api.route('/tests', methods=['POST'])
def test_user():
# data = request.get_json()
# start = data.get('start')
# end = data.get('end')
# dsl = ElasticsearchUtil.dsl(start, end)
# index = current_app.config.Elasticsearch.Index
# res = ElasticsearchUtil.search(index, dsl)
# print(len(res))
res = {
"user_name": "libai",
"user_age": 18,
}
res_json = json.dumps(res)
return res_json, 200
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment