Commit 4bf50099 by Aeolus

接口开发

parent 129b3e6a
......@@ -40,3 +40,21 @@ LOGIN_TYPE = {
'send_code': 3,
'password': 4
}
AGENT_STATUS = {
'1': '超级管理员',
'2': '出库员',
'3': '渠道经理',
'4': '财务',
'5': '运维管理员',
'6': '推销员',
'7': '介绍人',
'8': '合伙人',
'9': '补货员',
'10': '场所',
}
ACCOUNT_STATUS = {
'on_use': 1,
'delete': 2
}
......@@ -6,6 +6,74 @@ from werkzeug.security import generate_password_hash, check_password_hash
from models.base_model import Base
class AdminAccount(Base):
__tablename__ = 'admin_account'
id = Column(INTEGER(10), primary_key=True, unique=True)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False, unique=True)
user_name = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False)
phone = Column(String(191, 'utf8mb4_unicode_ci'), nullable=False, unique=True)
level = Column(INTEGER(2), nullable=False)
parent_id = Column(INTEGER(10), nullable=False)
draw = Column(INTEGER(1), nullable=False)
rate = Column(INTEGER(1), nullable=False)
status = Column(INTEGER(1), nullable=False)
_password_hash_ = Column(String(255, 'utf8mb4_unicode_ci'))
comment = Column(String(255, 'utf8mb4_unicode_ci'))
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
@property
def password(self):
raise Exception('密码不能被读取') # 为了保持使用习惯,还是设置一个password字段用来设置密码,当然也不能被读取。
# 赋值password,则自动加密存储。
@password.setter
def password(self, value):
self._password_hash_ = generate_password_hash(value)
# 使用check_password,进行密码校验,返回True False。
def check_password(self, pasword):
return check_password_hash(self._password_hash_, pasword)
class AdminLoginRecord(Base):
__tablename__ = 'admin_login_record'
id = Column(INTEGER(10), primary_key=True)
phone = Column(VARCHAR(40), nullable=False)
platform = Column(TINYINT(4), nullable=False, server_default=text("'1'"))
ip = Column(VARCHAR(40), nullable=False)
last_login = Column(DateTime, nullable=False)
login_type = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False)
updated_at = Column(DateTime, nullable=False)
class AdminMachine(Base):
__tablename__ = 'admin_machine'
id = Column(INTEGER(11), primary_key=True)
user_id = Column(INTEGER(11), nullable=False)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
machine_no = Column(INTEGER(11), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class AdminPlace(Base):
__tablename__ = 'admin_place'
id = Column(INTEGER(11), primary_key=True)
user_id = Column(INTEGER(11), nullable=False)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
place_id = Column(INTEGER(11), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class Brand(Base):
__tablename__ = 'brand'
......@@ -356,6 +424,7 @@ class WxUser(Base):
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class Management(Base):
__tablename__ = 'management_login'
......@@ -384,6 +453,7 @@ class Management(Base):
def check_password(self, pasword):
return check_password_hash(self._password_hash_, pasword)
class TallymanPlace(Base):
__tablename__ = 'tallyman_place'
id = Column(INTEGER(11), primary_key=True, unique=True)
......
# coding: utf-8
from sqlalchemy import Column, DateTime, Index, String, TIMESTAMP, Text, text
from sqlalchemy.dialects.mysql import INTEGER, TEXT, TINYINT, VARCHAR
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class AdminAccount(Base):
__tablename__ = 'admin_account'
id = Column(INTEGER(10), primary_key=True, unique=True)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False, unique=True)
user_name = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False)
phone = Column(String(191, 'utf8mb4_unicode_ci'), nullable=False, unique=True)
level = Column(INTEGER(1), nullable=False)
parent_id = Column(INTEGER(10), nullable=False)
rate = Column(INTEGER(10), nullable=False)
status = Column(INTEGER(1), nullable=False)
_password_hash_ = Column(String(255, 'utf8mb4_unicode_ci'))
comment = Column(String(255, 'utf8mb4_unicode_ci'))
last_login = Column(DateTime)
expire_time = Column(DateTime)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class AdminLoginRecord(Base):
__tablename__ = 'admin_login_record'
id = Column(INTEGER(10), primary_key=True)
phone = Column(VARCHAR(40), nullable=False)
platform = Column(TINYINT(4), nullable=False, server_default=text("'1'"))
ip = Column(VARCHAR(40), nullable=False)
last_login = Column(DateTime, nullable=False)
login_type = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False)
updated_at = Column(DateTime, nullable=False)
class AdminMachine(Base):
__tablename__ = 'admin_machine'
id = Column(INTEGER(11), primary_key=True)
user_id = Column(INTEGER(11), nullable=False)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
machine_no = Column(INTEGER(11), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class AdminPlace(Base):
__tablename__ = 'admin_place'
id = Column(INTEGER(11), primary_key=True)
user_id = Column(INTEGER(11), nullable=False)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
place_id = Column(INTEGER(11), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class Brand(Base):
__tablename__ = 'brand'
id = Column(INTEGER(10), primary_key=True)
brand_name = Column(VARCHAR(191), nullable=False, index=True)
logo = Column(VARCHAR(191), nullable=False)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class Cate(Base):
__tablename__ = 'cate'
id = Column(INTEGER(10), primary_key=True)
brand_id = Column(INTEGER(10), nullable=False)
cate_name = Column(VARCHAR(191), nullable=False, index=True)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
catecol = Column(String(45, 'utf8mb4_unicode_ci'))
class Hatch(Base):
__tablename__ = 'hatch'
__table_args__ = (
Index('hatch_machine_UNIQUE', 'machine_no', 'hatch_no', unique=True),
)
id = Column(INTEGER(10), primary_key=True, unique=True)
machine_no = Column(String(20, 'utf8mb4_unicode_ci'), nullable=False)
hatch_no = Column(TINYINT(3), nullable=False)
production_id = Column(INTEGER(10), nullable=False)
name = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False)
title = Column(String(200, 'utf8mb4_unicode_ci'), nullable=False)
left_count = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
total_count = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
brand_id = Column(INTEGER(10), nullable=False)
brand_name = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False)
cate_id = Column(INTEGER(10), nullable=False)
cate_name = Column(String(200, 'utf8mb4_unicode_ci'), nullable=False)
price = Column(INTEGER(10), nullable=False)
original_price = Column(INTEGER(10), nullable=False)
img = Column(String(200, 'utf8mb4_unicode_ci'))
tags = Column(String(255, 'utf8mb4_unicode_ci'))
content = Column(Text(collation='utf8mb4_unicode_ci'))
summary = Column(Text(collation='utf8mb4_unicode_ci'))
status = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class Machine(Base):
__tablename__ = 'machine'
id = Column(INTEGER(10), primary_key=True)
machine_no = Column(String(20, 'utf8mb4_unicode_ci'), unique=True)
device_id = Column(String(45, 'utf8mb4_unicode_ci'), unique=True)
qrcode_no = Column(String(20, 'utf8mb4_unicode_ci'), nullable=False, unique=True)
mac = Column(String(30, 'utf8mb4_unicode_ci'))
power = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
short_address = Column(VARCHAR(45))
address = Column(String(191, 'utf8mb4_unicode_ci'))
place_id = Column(INTEGER(10), nullable=False)
mch_platform = Column(INTEGER(11), nullable=False, server_default=text("'1'"))
position = Column(String(20, 'utf8mb4_unicode_ci'))
hatch_number = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
type = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
status = Column(TINYINT(1), server_default=text("'0'"))
created_at = Column(TIMESTAMP, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
command_time = Column(INTEGER(4), nullable=False, server_default=text("'1'"))
class MachineProduction(Base):
__tablename__ = 'machine_production'
id = Column(INTEGER(10), primary_key=True)
machine_id = Column(INTEGER(10), nullable=False)
production_id = Column(INTEGER(10), nullable=False)
hatch_no = Column(INTEGER(10), nullable=False)
status = Column(TINYINT(1), nullable=False)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class ManagementLogin(Base):
__tablename__ = 'management_login'
id = Column(INTEGER(10), primary_key=True)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
user_name = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
phone = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False)
level = Column(INTEGER(1), nullable=False)
status = Column(INTEGER(1), nullable=False)
_password_hash_ = Column(String(255, 'utf8mb4_unicode_ci'))
last_login = Column(DateTime)
expire_time = Column(DateTime)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
class ManagementMachine(Base):
__tablename__ = 'management_machine'
id = Column(INTEGER(11), primary_key=True)
management_id = Column(INTEGER(255), nullable=False)
machine_no = Column(INTEGER(255), nullable=False)
level = Column(INTEGER(255), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
class ManagementTallyman(Base):
__tablename__ = 'management_tallyman'
id = Column(INTEGER(11), primary_key=True)
management_id = Column(INTEGER(255), nullable=False)
tallyman_id = Column(INTEGER(255), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
class NfcCard(Base):
__tablename__ = 'nfc_card'
id = Column(INTEGER(10), primary_key=True)
card_no = Column(String(40, 'utf8mb4_unicode_ci'))
user_id = Column(INTEGER(10))
nick_name = Column(String(40, 'utf8mb4_unicode_ci'))
phone = Column(String(40, 'utf8mb4_unicode_ci'), index=True)
money = Column(INTEGER(10), nullable=False)
mch_platform = Column(INTEGER(11), nullable=False, server_default=text("'1'"))
limit_count = Column(TINYINT(1), nullable=False, server_default=text("'-1'"))
status = Column(TINYINT(4), nullable=False)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class NfcCardPayRecord(Base):
__tablename__ = 'nfc_card_pay_record'
id = Column(INTEGER(10), primary_key=True)
card_no = Column(String(40, 'utf8mb4_unicode_ci'), index=True)
rent_no = Column(VARCHAR(40), nullable=False)
user_id = Column(INTEGER(10), nullable=False)
is_pay = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
pay_money = Column(INTEGER(10), nullable=False)
mch_platform = Column(INTEGER(11), nullable=False, server_default=text("'1'"))
prepay_id = Column(VARCHAR(191))
refund_no = Column(VARCHAR(191))
status = Column(TINYINT(4), nullable=False)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class NfcCardPayRefund(Base):
__tablename__ = 'nfc_card_pay_refund'
id = Column(INTEGER(11), primary_key=True)
refund_no = Column(VARCHAR(191), nullable=False)
rent_no = Column(VARCHAR(191), nullable=False)
fee = Column(INTEGER(11), nullable=False)
cause = Column(VARCHAR(191))
comment = Column(TEXT)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class Place(Base):
__tablename__ = 'place'
id = Column(INTEGER(10), primary_key=True)
place_name = Column(VARCHAR(191), nullable=False, index=True)
img = Column(VARCHAR(191))
logo = Column(VARCHAR(191), nullable=False)
address = Column(VARCHAR(255), nullable=False, server_default=text("''"))
position = Column(String(20, 'utf8mb4_unicode_ci'))
open_time = Column(VARCHAR(191), nullable=False)
close_time = Column(VARCHAR(191), nullable=False)
open_week = Column(VARCHAR(255), nullable=False, server_default=text("''"))
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class PlaceMachine(Base):
__tablename__ = 'place_machine'
id = Column(INTEGER(11), primary_key=True)
machine_id = Column(INTEGER(25))
place_id = Column(INTEGER(25))
status = Column(INTEGER(1))
created_at = Column(DateTime, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, server_default=text("CURRENT_TIMESTAMP"))
class Production(Base):
__tablename__ = 'production'
id = Column(INTEGER(10), primary_key=True)
name = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False, index=True)
title = Column(String(200, 'utf8mb4_unicode_ci'), nullable=False)
brand_id = Column(INTEGER(10), nullable=False)
cate_id = Column(INTEGER(10), nullable=False)
price = Column(INTEGER(10), nullable=False)
original_price = Column(INTEGER(10), nullable=False)
img = Column(String(200, 'utf8mb4_unicode_ci'))
tags = Column(String(255, 'utf8mb4_unicode_ci'))
content = Column(Text(collation='utf8mb4_unicode_ci'))
summary = Column(Text(collation='utf8mb4_unicode_ci'))
status = Column(TINYINT(1))
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class Rent(Base):
__tablename__ = 'rent'
id = Column(INTEGER(10), primary_key=True)
rent_no = Column(VARCHAR(40), nullable=False, index=True)
machine_no = Column(String(40, 'utf8mb4_unicode_ci'), nullable=False, index=True)
user_id = Column(INTEGER(10), nullable=False, index=True)
card_no = Column(String(40, 'utf8mb4_unicode_ci'), index=True)
place_id = Column(INTEGER(10), nullable=False, index=True)
total = Column(INTEGER(10), server_default=text("'0'"))
real_total = Column(INTEGER(10), server_default=text("'0'"))
agent_total = Column(INTEGER(10), server_default=text("'0'"))
back_money = Column(INTEGER(10), nullable=False, server_default=text("'0'"))
is_pay = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
rent_type = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
mch_platform = Column(INTEGER(1), nullable=False, server_default=text("'1'"))
add_time = Column(TIMESTAMP, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
pay_time = Column(TIMESTAMP)
is_over = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
is_cancel = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
refund_no = Column(VARCHAR(191))
expire_handle = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
prepay_id = Column(VARCHAR(191))
over_time = Column(TIMESTAMP)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class RentDetail(Base):
__tablename__ = 'rent_detail'
id = Column(INTEGER(10), primary_key=True, unique=True)
rent_no = Column(String(40, 'utf8mb4_unicode_ci'), nullable=False)
user_id = Column(INTEGER(10), nullable=False)
machine_no = Column(String(20, 'utf8mb4_unicode_ci'), nullable=False)
hatch_no = Column(TINYINT(3), nullable=False)
production_id = Column(INTEGER(10), nullable=False)
is_take = Column(TINYINT(3), nullable=False, server_default=text("'0'"))
name = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False)
title = Column(String(200, 'utf8mb4_unicode_ci'), nullable=False)
brand_id = Column(INTEGER(10), nullable=False)
brand_name = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False)
cate_id = Column(INTEGER(10), nullable=False)
cate_name = Column(String(200, 'utf8mb4_unicode_ci'), nullable=False)
price = Column(INTEGER(10), nullable=False)
rent_count = Column(TINYINT(3), nullable=False)
img = Column(String(200, 'utf8mb4_unicode_ci'))
tags = Column(String(255, 'utf8mb4_unicode_ci'))
content = Column(Text(collation='utf8mb4_unicode_ci'))
summary = Column(Text(collation='utf8mb4_unicode_ci'))
status = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class SalePlan(Base):
__tablename__ = 'sale_plan'
id = Column(INTEGER(10), primary_key=True)
name = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False)
title = Column(String(200, 'utf8mb4_unicode_ci'), nullable=False)
status = Column(TINYINT(1), nullable=False)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class SalePlanMachine(Base):
__tablename__ = 'sale_plan_machine'
id = Column(INTEGER(10), primary_key=True)
plan_id = Column(INTEGER(10), nullable=False)
machine_id = Column(INTEGER(10), nullable=False)
status = Column(TINYINT(1), nullable=False)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class SalePlanProduction(Base):
__tablename__ = 'sale_plan_production'
id = Column(INTEGER(10), primary_key=True)
plan_id = Column(INTEGER(10), nullable=False)
production_id = Column(INTEGER(10), nullable=False)
index = Column(INTEGER(10), nullable=False)
status = Column(TINYINT(1), nullable=False)
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class TallyRecord(Base):
__tablename__ = 'tally_record'
id = Column(INTEGER(10), primary_key=True)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False)
user_name = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False)
machine_no = Column(String(20, 'utf8mb4_unicode_ci'), nullable=False)
hatch_no = Column(TINYINT(3), nullable=False)
production_id = Column(INTEGER(10), nullable=False)
production_name = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False)
tally_count = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
status = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class TallymanAccount(Base):
__tablename__ = 'tallyman_account'
id = Column(INTEGER(10), primary_key=True, unique=True)
user_no = Column(String(25, 'utf8mb4_unicode_ci'), nullable=False, unique=True)
user_name = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False)
phone = Column(String(191, 'utf8mb4_unicode_ci'), nullable=False, unique=True)
level = Column(INTEGER(1), nullable=False)
status = Column(INTEGER(1), nullable=False)
_password_hash_ = Column(String(255, 'utf8mb4_unicode_ci'))
comment = Column(String(255, 'utf8mb4_unicode_ci'))
last_login = Column(DateTime)
expire_time = Column(DateTime)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
class TallymanLoginRecord(Base):
__tablename__ = 'tallyman_login_record'
id = Column(INTEGER(10), primary_key=True)
phone = Column(VARCHAR(255), nullable=False)
platform = Column(TINYINT(4), nullable=False, server_default=text("'2'"))
ip = Column(VARCHAR(255), nullable=False)
last_login = Column(DateTime, nullable=False)
login_type = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False)
updated_at = Column(DateTime, nullable=False)
class TallymanMachine(Base):
__tablename__ = 'tallyman_machine'
id = Column(INTEGER(11), primary_key=True)
user_id = Column(INTEGER(255), nullable=False)
machine_no = Column(INTEGER(255), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
class TallymanPlace(Base):
__tablename__ = 'tallyman_place'
id = Column(INTEGER(11), primary_key=True)
user_id = Column(INTEGER(255), nullable=False)
place_id = Column(INTEGER(255), nullable=False)
status = Column(INTEGER(1), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"))
class WxUser(Base):
__tablename__ = 'wx_user'
id = Column(INTEGER(10), primary_key=True)
openid = Column(String(40, 'utf8mb4_unicode_ci'), index=True)
unionid = Column(String(40, 'utf8mb4_unicode_ci'))
platform = Column(TINYINT(4), nullable=False, server_default=text("'0'"))
phone = Column(String(40, 'utf8mb4_unicode_ci'), index=True)
language = Column(String(40, 'utf8mb4_unicode_ci'))
nick_name = Column(String(40, 'utf8mb4_unicode_ci'))
gender = Column(TINYINT(4), nullable=False, server_default=text("'0'"))
avatar_url = Column(String(191, 'utf8mb4_unicode_ci'))
city = Column(String(45, 'utf8mb4_unicode_ci'))
province = Column(String(45, 'utf8mb4_unicode_ci'))
country = Column(String(45, 'utf8mb4_unicode_ci'))
status = Column(TINYINT(4), nullable=False)
last_login_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
created_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"))
updated_at = Column(TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2022/01/10
@file: __init__.py.py
@function:
@modify:
"""
from flask import Flask
from flask_cors import CORS
from flask_log_request_id import RequestID
from dotenv import load_dotenv
from models.base_model import db
from utils.my_redis_cache import redis_client
from utils.mylogger import set_logger
def create_app(config_name):
from config.env_path_config import env_path
load_dotenv(dotenv_path=env_path, verbose=True, override=True)
set_logger()
app = Flask("pc_management")
from config.app_config import config
app.config.from_object(config[config_name])
CORS(app)
db.init_app(app)
redis_client.init_app(app)
RequestID(app)
from utils.middlewares import jwt_authentication, log_enter_interface, log_out_interface, close_db_session, \
get_platform, all_options_pass
app.before_request(log_enter_interface)
app.before_request(all_options_pass)
app.before_request(get_platform)
app.before_request(jwt_authentication)
app.after_request(log_out_interface)
app.after_request(close_db_session)
# todo register blueprint
from myapps.pc_management.api import register_sukang_blueprint
register_sukang_blueprint(app)
return app
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2022/01/10
@file: __init__.py.py
@function:
@modify:
"""
from flask import Flask
from myapps.pc_management.api.admin_portal import admin_route
def register_sukang_blueprint(app: Flask):
prefix = "/pc_management"
app.register_blueprint(admin_route, url_prefix=prefix + "/admin")
# -*- coding: utf-8 -*-
import datetime
import logging
import time
from flask import Blueprint, jsonify, request, g
from pymongo import MongoClient, ASCENDING
from config.wechat_config import platform_config_list
from config.commen_config import LOGIN_TYPE, ACCOUNT_STATUS
from service.admin_service import AdminService
from utils.error_code import ACCOUNT_AGENT_SPOT_NULL_ERROR, ACCOUNT_NOT_EXISTS_ERROR, \
ACCOUNT_ALREADY_EXISTS_ERROR, ACCOUNT_ALREADY_DELETE_ERROR, AGNET_MODULES_ERROR, MODULES_NOT_EXISTS_ERROR, \
OPERATE_LEVEL_ERROR
from utils.error_code import PHONE_NOT_NULL_ERROR, PHONE_NOT_VALID_ERROR, TOKEN_NOT_VALID_ERROR, \
VERIFICATION_CODE_INVALID_ERROR, VERIFICATION_CODE_ERROR, PASSWORD_ERROR
from models.base_model import db
from models.models import AdminAccount, AdminLoginRecord, AdminMachine
from utils.jwt_util import verify_jwt, generate_jwt
from utils.my_response import BaseResponse
from service.sms_service import SMSService
logger = logging.getLogger(__name__)
admin_route = Blueprint('admin', __name__)
@admin_route.route('/test')
def test():
ip = request.remote_addr
return BaseResponse(**{'code': 200, 'msg': 'success!', 'data': ip})
@admin_route.route('/login', methods=['GET', 'POST'])
def user_login():
token = request.headers.get('Authorization')
platform = request.headers.get('platform')
cur_ip = request.remote_addr
json_data = request.get_json()
data = {}
phone = json_data['phone'] if 'phone' in json_data else None
code = json_data['code'] if 'code' in json_data else None
login_type = json_data['type'] if 'type' in json_data else 1 # 1.验证码登录,2.密码登录
if token:
# token登录
# "校验token"
payload = verify_jwt(token)
# "判断token的校验结果"
if not payload:
return BaseResponse(**TOKEN_NOT_VALID_ERROR)
# "获取载荷中的信息赋值"
user_id = payload.get('user_id')
if not user_id:
return BaseResponse(**TOKEN_NOT_VALID_ERROR)
user_info = AdminAccount.query.filter_by(id=user_id, status=1).first()
else:
if login_type == 1:
# 验证码登录
# 判断验证码是否正确
sms = SMSService()
res = sms.verificate(phone, code)
if res == -1:
return BaseResponse(**VERIFICATION_CODE_INVALID_ERROR)
elif res == -2:
return BaseResponse(**VERIFICATION_CODE_ERROR)
user_info = AdminAccount.query.filter_by(phone=phone, status=1).first()
if not user_info:
return BaseResponse(**PHONE_NOT_VALID_ERROR)
else:
# 密码登录
# 判断密码是否正确
user_info = AdminAccount.query.filter_by(phone=phone, status=1).first()
if not user_info:
return BaseResponse(**PHONE_NOT_VALID_ERROR)
if not user_info.check_password(pasword=code):
return jsonify(PASSWORD_ERROR)
new_token = generate_jwt(payload={"user_id": user_info.id}, expiry=time.time() + 24 * 60 * 60)
agent_log = AdminLoginRecord()
agent_log.phone = user_info.phone
agent_log.ip = cur_ip
agent_log.platform = platform_config_list.index(platform)
agent_log.last_login = datetime.datetime.now()
agent_log.login_type = LOGIN_TYPE['token_login']
agent_log.created_at = datetime.datetime.now()
agent_log.updated_at = datetime.datetime.now()
db.session.add(agent_log)
db.session.commit()
data['token'] = new_token
data['user_name'] = user_info.user_name
data['phone'] = user_info.phone
return BaseResponse(data=data)
@admin_route.route('/add_account', methods=['GET', 'POST'])
def add_user():
admin = g.user
json_data = request.get_json()
user_name = json_data['user_name']
phone = json_data['phone']
level = int(json_data['level'])
if level < admin.level:
return jsonify(OPERATE_LEVEL_ERROR)
password = json_data.get('password', "123456")
comment = json_data.get('comment', "")
parent_id = json_data.get("parent_id", 0)
draw = json_data.get("draw", 0)
rate = json_data.get("rate", 0)
machine_list = json_data.get("machine_list", [])
account = AdminAccount.query.filter_by(phone=phone).first()
if account:
if account.status != -1:
return jsonify(account)
else:
account = AdminAccount()
account.user_no = "todo"
account.user_name = user_name
account.phone = phone
account.level = level
account.draw = draw
account.rate = rate
account.parent_id = parent_id
account.status = 1
account.comment = comment
account.created_at = datetime.datetime.now()
account.updated_at = datetime.datetime.now()
if password:
account.password = password
db.session.add(account)
db.session.commit()
account.user_no = "SK" + str(account.id).zfill(6)
db.session.add(account)
db.session.commit()
if not machine_list:
return BaseResponse()
for i in machine_list:
model = AdminMachine()
model.user_id = account.id
model.user_no = account.user_no
model.machine_no = i
model.status = 1
db.session.add(model)
db.session.commit()
return BaseResponse()
@admin_route.route('/account_list', methods=["POST"])
def get_account_list():
json_data = request.get_json()
page = json_data.get("page", None)
page_size = json_data.get("pageSize", None)
keyword = json_data.get("keyword", None)
select_sql = """select agent_account.user_name, agent_account.phone, agent_account.level, agent_account.status,
agent_account.comment, agent_account.created_at, agent_account.updated_at, agent_account.last_login,
agent_account.id
"""
count_sql = "select count(agent_account.id) as total_count"
from_sql = " from agent_account where agent_account.id in ( select agent_account.id "
from_sql += " from agent_account "
from_sql += " left join agent_spot on agent_account.id = agent_spot.agent_no "
from_sql += " left join spot on spot.id = agent_spot.spot_no "
where_sql = " where 0=0 "
if keyword:
where_sql += """
and CONCAT(agent_account.user_name,agent_account.phone,spot.spotname) LIKE '%{keyword}%'
""".format(keyword=keyword)
where_sql += " ) "
order_sql = " ORDER BY agent_account.created_at ASC, agent_account.status ASC"
limit_sql = " LIMIT {offset} , {page_size} ".format(offset=(page - 1) * page_size, page_size=page_size)
count_result = db.session.execute(count_sql + from_sql + where_sql).fetchone()
if not count_result:
return BaseResponse(data={"list": [], "page": page, "pageSize": page_size, "total_count": 0})
else:
total_count = count_result.total_count
result = db.session.execute(select_sql + from_sql + where_sql + order_sql + limit_sql).fetchall()
return_data = []
for info in result:
return_data.append(
{"user_name": info.user_name, "phone": info.phone, "level": info.level, "status": info.status,
"comment": info.comment, "agent_id": info.id,
"create_time": info.created_at.strftime("%Y-%m-%d %H:%M:%S") if info.last_login else "",
"update_time": info.updated_at.strftime("%Y-%m-%d %H:%M:%S") if info.last_login else "",
"login_time": info.last_login.strftime("%Y-%m-%d %H:%M:%S") if info.last_login else ""})
return BaseResponse({"list": return_data, "page": page, "pageSize": page_size, "total_count": total_count})
@admin_route.route('/account_detail', methods=["POST"])
def get_account_detail():
json_data = request.get_json()
phone = json_data["phone"]
agent_info = AdminAccount.query.filter_by(phone=phone).first()
if not agent_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
user_info = {}
user_info["agent_no"] = agent_info.agent_no
user_info["user_name"] = agent_info.user_name
user_info["phone"] = phone
user_info["level"] = agent_info.level
user_info["status"] = ACCOUNT_STATUS['on_use']
user_info["comment"] = agent_info.comment
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent_info.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
else:
user_info["spot_list"] = []
return BaseResponse(data=user_info)
spot_list = db.session.query(Spot).filter(Spot.id.in_(spot_no_list)).all()
if spot_list:
spot_data_list = [
{"spot_name": i.spotname, "spot_id": i.id, "business_id": i.business_id, "spot_address": i.address} for i in
spot_list]
else:
spot_data_list = []
user_info["spot_list"] = spot_data_list
return BaseResponse(data=user_info)
@admin_route.route('/edit_account', methods=['GET', 'POST'])
def edit_user():
json_data = request.get_json()
old_phone = json_data['old_phone'] if 'old_phone' in json_data else ''
new_phone = json_data['new_phone'] if 'new_phone' in json_data else ''
user_name = json_data['name'] if 'name' in json_data else 'SSW'
password = json_data['password'] if 'password' in json_data else ''
comment = json_data['comment'] if 'comment' in json_data else ''
level = json_data['level'] if 'level' in json_data else ''
status = json_data['status'] if 'status' in json_data else ''
spot_list = json_data['spot_list'] if 'spot_list' in json_data else []
if not old_phone:
return BaseResponse(error_code=-1, error_message='old phone is null')
if not new_phone:
return BaseResponse(**PHONE_NOT_NULL_ERROR)
if not status:
return BaseResponse(**Param_Invalid_Error)
result = Helper.check_phone(new_phone)
if not result:
return BaseResponse(**PHONE_NOT_VALID_ERROR)
if not spot_list:
return BaseResponse(**ACCOUNT_AGENT_SPOT_NULL_ERROR)
agent_info = AdminAccount.query.filter_by(phone=old_phone).first()
if not agent_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
agent_info.user_name = user_name
agent_info.phone = new_phone
agent_info.status = status
agent_info.comment = comment
if level:
agent_info.level = int(level)
if password:
salt = AgentService.gene_salt()
agent_info.salt_pwd = salt
agent_info.password = AgentService.gene_pwd(password, salt)
db.session.add(agent_info)
agent_spot_info = AgentSpot.query.filter_by(agent_no=agent_info.id).all()
for info in agent_spot_info:
info.status = ACCOUNT_STATUS['delete']
db.session.add(info)
for i in spot_list:
cur_spot_info = AgentSpot.query.filter_by(agent_no=agent_info.id, spot_no=i).first()
if not cur_spot_info:
cur_agent_spot = AgentSpot()
cur_agent_spot.agent_no = agent_info.id
cur_agent_spot.spot_no = i
cur_agent_spot.status = ACCOUNT_STATUS['on_use']
cur_agent_spot.created_at = datetime.datetime.now()
cur_agent_spot.updated_at = datetime.datetime.now()
db.session.add(cur_agent_spot)
else:
cur_spot_info.status = ACCOUNT_STATUS['on_use']
db.session.add(cur_spot_info)
db.session.commit()
return BaseResponse()
@admin_route.route('/delete_account', methods=['GET', 'POST'])
def delete_user():
json_data = request.get_json()
phone = json_data['phone'] if 'phone' in json_data else ''
if not phone:
return BaseResponse(**PHONE_NOT_NULL_ERROR)
agent_info = AdminAccount.query.filter_by(phone=phone).first()
if not agent_info:
return BaseResponse(**ACCOUNT_NOT_EXISTS_ERROR)
agent_spot_info = AgentSpot.query.filter_by(agent_no=agent_info.id).all()
for info in agent_spot_info:
info.status = ACCOUNT_STATUS['delete']
db.session.add(info)
agent_info.status = ACCOUNT_STATUS['delete']
db.session.add(agent_info)
db.session.commit()
return BaseResponse()
@admin_route.route('/sendCode', methods=['GET', 'POST'])
def send_code():
json_data = request.get_json()
cur_ip = request.remote_addr
phone = json_data['phone'] if 'phone' in json_data else None
if not phone:
return BaseResponse(**PHONE_NOT_NULL_ERROR)
# 判断该手机号是否再数据库中,不在返回无权限登录
agent = AdminAccount.query.filter_by(phone=phone).first()
if not agent:
return BaseResponse(**PHONE_NOT_VALID_ERROR)
# 判断该账号是否已被删除
if agent.status == ACCOUNT_STATUS['delete']:
return BaseResponse(**ACCOUNT_ALREADY_DELETE_ERROR)
# result = Helper.check_phone(phone)
# if not result:
# return BaseResponse(**PHONE_NOT_VALID_ERROR)
sms = SMSService()
result = sms.phoneSendCode(phone, 520391, '灰兔智能')
logger.info(result)
agent_log = AdminLoginRecord()
agent_log.phone = phone
agent_log.ip = cur_ip
agent_log.last_login = datetime.datetime.now()
agent_log.login_type = LOGIN_TYPE['send_code']
agent_log.created_at = datetime.datetime.now()
agent_log.updated_at = datetime.datetime.now()
db.session.add(agent_log)
db.session.commit()
return BaseResponse()
@admin_route.route('/agent_module_list', methods=['GET', 'POST'])
def get_agent_module_list():
agent_id = g.user.id
platform = g.platform
if int(g.user.level) != 1:
agent_modules = AgentModules()
result = agent_modules.find_one({"agent_id": agent_id, "platform": platform})
return_data = {"agent_id": agent_id, "module_list": result["module_list"]}
if result:
return BaseResponse(data=return_data)
else:
return BaseResponse(**AGNET_MODULES_ERROR)
modules = Modules()
result = modules.collection.find({"platform": platform}).sort(
[("parent_id", ASCENDING), ("order_no", ASCENDING)])
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = list(result)
tmp_data = {}
for i in parent_module_list:
i.pop("_id")
if i["parent_id"] == 0:
i["children"] = []
tmp_data[i["id"]] = i
else:
tmp_data[i["parent_id"]]["children"].append(i)
module_list = list(tmp_data.values())
return_data = {"agent_id": agent_id, "module_list": module_list}
if result:
return BaseResponse(data=return_data)
else:
return BaseResponse(**AGNET_MODULES_ERROR)
@admin_route.route('/agent_module_list_by_agent_id', methods=['GET', 'POST'])
def get_agent_module_list_by_agent_id():
admin_user = g.user
if int(admin_user.level) != 1:
return BaseResponse(**OPERATE_LEVEL_ERROR)
platform = g.platform
json_data = request.get_json()
agent_id = json_data.get("agent_id", None)
agent_modules = AgentModules()
result = agent_modules.find_one({"agent_id": agent_id, "platform": platform})
if result:
return_data = {"agent_id": agent_id, "module_list": result["module_list"]}
else:
return_data = {"agent_id": agent_id, "module_list": []}
return BaseResponse(data=return_data)
@admin_route.route("/set_module_list", methods=['GET', 'POST'])
def set_agent_module_list():
parent_agent_id = g.user.id
platform = g.platform
platform_int = platform
json_data = request.get_json()
module_list = json_data.get("module_list", [])
agent_id = json_data.get("agent_id", None)
if not module_list or not agent_id:
return BaseResponse(**Param_Invalid_Error)
agent_modules = AgentModules()
modules = Modules()
if int(g.user.level) == 1:
result = modules.collection.find({"platform": platform}).sort(
[("parent_id", ASCENDING), ("order_no", ASCENDING)])
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = list(result)
return_data = []
tmp_data = {}
for i in parent_module_list:
i.pop("_id")
if i["id"] in module_list:
if i["parent_id"] == 0:
i["children"] = []
tmp_data[i["id"]] = i
else:
tmp_data[i["parent_id"]]["children"].append(i)
return_data = list(tmp_data.values())
else:
result = agent_modules.collection.find_one({"platform": platform_int, "agent_id": parent_agent_id})
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = result["module_list"]
return_data = []
for i in parent_module_list:
if i["id"] in module_list:
tmp_data = i
children_list = i["children"]
tmp_data["children"] = []
for j in children_list:
if j["id"] in module_list:
tmp_data["children"].append(j)
return_data.append(tmp_data)
for i in range(3):
agent_modules.collection.replace_one({'agent_id': agent_id, "platform": platform_int},
{'agent_id': agent_id, "platform": platform_int,
"module_list": return_data},
upsert=True)
result = agent_modules.collection.find_one({'agent_id': agent_id, "platform": platform_int,
"module_list": return_data})
if result:
return BaseResponse()
else:
continue
return BaseResponse(**COMMON_MONGO_ERROR)
# @admin_route.route("/set_super_user_module_list", methods=['GET', 'POST'])
def set_super_agent_module_list():
platform = g.platform
platform_int = platform
json_data = request.get_json()
module_list = json_data.get("module_list", [])
agent_id_list = json_data.get("agent_id_list", None)
if not module_list or not agent_id_list:
return BaseResponse(**Param_Invalid_Error)
agent_modules = AgentModules()
modules = Modules()
result = modules.collection.find({"platform": platform_int, "id": {"$in": module_list}}).sort(
[("parent_id", ASCENDING), ("order_no", ASCENDING)])
if not result:
return BaseResponse(**MODULES_NOT_EXISTS_ERROR)
parent_module_list = list(result)
tmp_data = {}
for i in parent_module_list:
i.pop("_id")
if i["parent_id"] == 0:
i["children"] = []
tmp_data[i["id"]] = i
else:
tmp_data[i["parent_id"]]["children"].append(i)
return_data = list(tmp_data.values())
for agent_id in agent_id_list:
for i in range(3):
agent_modules.collection.replace_one({'agent_id': agent_id, "platform": platform_int},
{'agent_id': agent_id, "platform": platform_int,
"module_list": return_data},
upsert=True)
result = agent_modules.collection.find_one({'agent_id': agent_id, "platform": platform_int,
"module_list": return_data})
if result:
break
else:
continue
return BaseResponse()
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version:
author:Aeolus
@time: 2021/08/05
@file: index_portal.py
@function:
@modify:
"""
import datetime
from flask import Blueprint, g
import logging
from sqlalchemy import func
from models.agent_model import AgentSpot
from models.base_model import db
from models.rent_models import Production
from models.spot_models import Spot
from service.index_service import IndexService
from utils.Helper import Helper
from utils.error_code.account_error import ACCOUNT_AGENT_SPOT_NOT_EXIST
from utils.my_response import BaseResponse
logger = logging.getLogger(__name__)
route_index = Blueprint('index', __name__)
@route_index.route("/day_income", methods=["GET"])
def get_today_income_data():
agent = g.user
return_data = {"today_income": None, "today_count": None, 'yesterday_income': None, 'yesterday_count': None}
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
else:
return BaseResponse(data=return_data)
today, tomorrow = Helper.get_today_date()
today_income, today_count = IndexService.get_total_production(spot_no_list, today, tomorrow)
return_data["today_income"] = today_income
return_data["today_count"] = today_count
today, yesterday = Helper.get_yesterday_date()
yesterday_income, yesterday_count = IndexService.get_total_production(spot_no_list, today, yesterday)
return_data["yesterday_income"] = yesterday_income
return_data["yesterday_count"] = yesterday_count
return BaseResponse(data=return_data)
@route_index.route("/week_income", methods=["GET"])
def get_week_income_data():
agent = g.user
return_data = {"week_income": None, "week_count": None, 'last_week_income': None, 'last_week_count': None}
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
else:
return BaseResponse(data=return_data)
monday, next_monday = Helper.get_week_date()
today_income, today_count = IndexService.get_total_production(spot_no_list, monday, next_monday)
return_data["week_income"] = today_income
return_data["week_count"] = today_count
last_monday, monday = Helper.get_last_week_date()
yesterday_income, yesterday_count = IndexService.get_total_production(spot_no_list, last_monday, monday)
return_data["last_week_income"] = yesterday_income
return_data["last_week_count"] = yesterday_count
return BaseResponse(data=return_data)
@route_index.route("/month_income", methods=["GET"])
def get_month_income_data():
agent = g.user
return_data = {"month_income": None, "month_count": None, 'last_month_income': None, 'last_month_count': None}
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
else:
return BaseResponse(data=return_data)
month, next_month = Helper.get_month_date()
today_income, today_count = IndexService.get_total_production(spot_no_list, month, next_month)
return_data["month_income"] = today_income
return_data["month_count"] = today_count
last_month, month = Helper.get_last_month_date()
yesterday_income, yesterday_count = IndexService.get_total_production(spot_no_list, last_month, month)
return_data["last_month_income"] = yesterday_income
return_data["last_month_count"] = yesterday_count
return BaseResponse(data=return_data)
@route_index.route("/history_income", methods=["GET"])
def get_history_income_data():
agent = g.user
return_data = {"history_income": None, "history_count": None}
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
else:
return BaseResponse(data=return_data)
today_income, today_count = IndexService.get_total_production(spot_no_list, start_time=None, end_time=None)
return_data["history_income"] = float(today_income)
return_data["history_count"] = today_count
return BaseResponse(data=return_data)
@route_index.route("/seven_day_count", methods=["GET"])
def get_seven_day_count_data():
agent = g.user
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
else:
return BaseResponse(data=[])
spot_list = db.session.query(Spot).filter(Spot.id.in_(spot_no_list)).all()
if spot_list:
spot_data = {}
for i in spot_list:
spot_data[i.id] = i.spotname
else:
return BaseResponse(**ACCOUNT_AGENT_SPOT_NOT_EXIST)
return_data = []
seven_day, today = Helper.get_seven_date()
filter_list = [
Production.agent_total > 0,
Production.created_at >= seven_day,
Production.created_at < today,
]
result = db.session.query(func.count(Production.id), Production.spot_id,
func.date_format(Production.created_at, "%Y-%m-%d")).filter(*filter_list).group_by(
Production.spot_id, func.day(Production.created_at)).order_by(Production.created_at.asc()).all()
tmp_data = {}
for i in result:
count = i[0]
spot_id = i[1]
created_at = i[2]
if tmp_data.get(spot_id, None):
tmp_data[spot_id].append({"date": created_at, "count": count, "spot_id": spot_id})
else:
tmp_data[spot_id] = [{"date": created_at, "count": count, }]
for k, v in tmp_data.items():
return_data.append({"spot_id": k, "spot_name": spot_data.get(k, spot_id), "count_data": v})
return BaseResponse(data=return_data)
@route_index.route("/last_seven_day_count", methods=["GET"])
def get_last_seven_day_count_data():
agent = g.user
agent_spot_list = AgentSpot.query.filter_by(agent_no=agent.id, status=1).all()
if agent_spot_list:
spot_no_list = [i.spot_no for i in agent_spot_list]
else:
return BaseResponse(data=[])
spot_list = db.session.query(Spot).filter(Spot.id.in_(spot_no_list)).all()
if spot_list:
spot_data = {}
for i in spot_list:
spot_data[i.id] = i.spotname
else:
return BaseResponse(**ACCOUNT_AGENT_SPOT_NOT_EXIST)
return_data = []
today = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
seven_day = today + datetime.timedelta(days=-7)
last_seven_day = seven_day + datetime.timedelta(days=-7)
filter_list = [
Production.agent_total > 0,
Production.created_at >= last_seven_day.strftime("%Y-%m-%d %H:%M:%S"),
Production.created_at < seven_day.strftime("%Y-%m-%d %H:%M:%S"),
]
result = db.session.query(func.count(Production.id), Production.spot_id,
func.date_format(Production.created_at, "%Y-%m-%d")).filter(*filter_list).group_by(
Production.spot_id, func.day(Production.created_at)).order_by(Production.created_at.asc()).all()
tmp_data = {}
for i in result:
count = i[0]
spot_id = i[1]
created_at = i[2]
if tmp_data.get(spot_id, None):
tmp_data[spot_id].append({"date": created_at, "count": count, "spot_id": spot_id})
else:
tmp_data[spot_id] = [{"date": created_at, "count": count, }]
for k, v in tmp_data.items():
return_data.append({"spot_id": k, "spot_name": spot_data.get(k, spot_id), "count_data": v})
return BaseResponse(data=return_data)
#!usr/bin/.env python
# -*- coding:utf-8 _*-
"""
@version:
@author:Aeolus
"""
import logging
from myapps.pc_management import create_app
logger = logging.getLogger(__name__)
app = create_app('prod')
logger.info("run server")
if __name__ == '__main__':
app.run('127.0.0.1', 8894, debug=True)
# -*- coding: utf-8 -*-
import base64
import datetime
import hashlib
import random
import string
from config.commen_config import ACCOUNT_STATUS
from models.models import AdminAccount
from models.base_model import db
from models.models import Place
# from models.user_models import AgentAccount
# from service.spot_service import SpotService
class AdminService():
@staticmethod
def gene_salt(length=16):
key_list = [random.choice((string.ascii_letters + string.digits)) for i in range(length)]
return ("".join(key_list))
@staticmethod
def gene_agent_code(agent_info, salt):
"""
:param agent_info:
:param salt:
:return:
"""
m = hashlib.md5()
str = "%s-%s-%s-%s" % (agent_info.id, agent_info.user_name, agent_info.phone, salt)
m.update(str.encode("utf-8"))
return m.hexdigest()
@staticmethod
def gene_pwd(pwd, salt):
"""
:param pwd:
:param salt:
:return:
"""
m = hashlib.md5()
str = "%s-%s" % (base64.encodebytes(pwd.encode("utf-8")), salt)
m.update(str.encode("utf-8"))
return m.hexdigest()
@staticmethod
def check_agent_token(token):
"""
:param token:
:return:
"""
token = base64.b64decode(token).decode("utf-8")
try:
agent_info = AgentAccount.query.filter_by(access_token=token).first()
except Exception as e:
return 1
if not agent_info:
return 1
s = token.split("#")
if len(s) != 2:
return 1
if AgentService.gene_agent_code(agent_info, agent_info.salt) != s[0]:
return 1
if agent_info.expire_time < datetime.datetime.now():
return 2
return agent_info
@staticmethod
def create_agent_no():
'''
生成用户编号
:return:
'''
ran_int = str(random.randint(1, 999999)).zfill(6)
return 'ssw' + ran_int
@staticmethod
def get_spot_info(agent_info):
"""
:param agent_info:
:return:
"""
spot_info = []
infos = db.session.query(AgentSpot, Spot).join(
Spot, Spot.id == AgentSpot.spot_no).filter(AgentSpot.agent_no == agent_info.id,
AgentSpot.status == ACCOUNT_STATUS['on_use']).all()
for info in infos:
cur_info = {}
cur_info['id'] = info.Spot.id
cur_info['spotname'] = info.Spot.spotname
cur_info['letter'] = SpotService.get_pinyin(info.Spot.spotname)
spot_info.append(cur_info)
return spot_info
#!usr/bin/env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @file: error_code.py """ ### 通用错误相关 Param_Invalid_Error = { "error_code": "500", "error_message": "params is invalid, 参数无效" } TOKEN_NOT_VALID_ERROR = { "error_code": "1001", "error_message": "无效的token" } TOKEN_NOT_PROVIDED_ERROR = { "error_code": "1002", "error_message": "token未提供" } TOKEN_EXPIRE_ERROR = { "error_code": "1003", "error_message": "token超时" } PHONE_NOT_BINDING_ERROR = { "error_code": "1004", "error_message": "未绑定手机号" } PHONE_NOT_NULL_ERROR = { "error_code": "1005", "error_message": "手机号为空" } PHONE_NOT_VALID_ERROR = { "error_code": "1006", "error_message": "无效的手机号" } USER_ALREADY_REGISTER_ERROR = { "error_code": "1007", "error_message": "用户已注册" } VERIFICATION_CODE_NULL_ERROR = { "error_code": "1008", "error_message": "验证码为空" } VERIFICATION_CODE_INVALID_ERROR = { "error_code": "1009", "error_message": "验证码已失效" } VERIFICATION_CODE_ERROR = { "error_code": "1010", "error_message": "验证码错误" } PASSWORD_ERROR = { "error_code": "1011", "error_message": "账号或密码错误" } ## 微信登陆相关 WX_LOGIN_DATA_ERROR = { "error_code": "3001", "error_message": "微信登录数据错误" } WX_LOGIN_CODE_ERROR = { "error_code": "3002", "error_message": "微信登录code值错误" } WX_OPENID_NOT_GET_ERROR = { "error_code": "3003", "error_message": "微信OpenId获取失败,请刷新重试" } WX_SESSION_KEY_ERROR = { "error_code": "3004", "error_message": "session key error" } ### 微信支付相关 WE_MINIAPP_PAY_FAIL = { "error_code": "3101", "error_message": "小程序下单失败" } ### 消息推送相关 WXBizMsgCrypt_OK = { "error_code": "0", "error_message": "WXBizMsgCrypt_OK" } WXBizMsgCrypt_ValidateSignature_Error = { "error_code": "4001", "error_message": "验证签名错误" } WXBizMsgCrypt_ParseXml_Error = { "error_code": "4002", "error_message": "解析xml错误" } WXBizMsgCrypt_ComputeSignature_Error = { "error_code": "4003", "error_message": "计算签名错误" } WXBizMsgCrypt_IllegalAesKey = { "error_code": "4004", "error_message": "Aes key非法错误" } WXBizMsgCrypt_ValidateAppid_Error = { "error_code": "4005", "error_message": "appid错误" } WXBizMsgCrypt_EncryptAES_Error = { "error_code": "4006", "error_message": "aes加密错误" } WXBizMsgCrypt_DecryptAES_Error = { "error_code": "4007", "error_message": "aes解密错误" } WXBizMsgCrypt_IllegalBuffer = { "error_code": "4008", "error_message": "illegal buffer" } WXBizMsgCrypt_EncodeBase64_Error = { "error_code": "4009", "error_message": "base64加密错误" } WXBizMsgCrypt_DecodeBase64_Error = { "error_code": "4010", "error_message": "base64解密错误" } WXBizMsgCrypt_GenReturnXml_Error = { "error_code": "4011", "error_message": "gen return xml error" } MACHINE_NOT_EXIST_ERROR = { "error_code": '5001', "error_message": "机柜不存在" } MACHINE_IS_USE_ERROR = { "error_code": '5002', "error_message": "已有他人正在租借中,请稍后" } MACHINE_IS_NOT_ONLINE_ERROR = { "error_code": '5003', "error_message": "机柜不在线" } MACHINE_ADD_ERROR = { "error_code": '5004', "error_message": "机柜添加失败" } MACHINE_NO_DUPLICATE_ERROR = { "error_code": '5005', "error_message": "machine_no duplicate,机柜编号重复" } MACHINE_EDIT_ERROR = { "error_code": '5006', "error_message": "machine edit error, 机柜修改错误" } HATCH_NOT_EXIST_ERROR = { "error_code": "5007", "error_message": "no hatch, 没有商品信息" } HATCH_NOT_ALL_EXIST_ERROR = { "error_code": "5008", "error_message": "no all hatch, 存在已售出商品" } HATCH_COUNT_ERROR = { "error_code": "5009", "error_message": "hatch count error, 商品数量错误,检查数量" } MACHINE_ACTIVATED_ERROR = { "error_code": '5010', "error_message": "machine activated, 机柜已激活" } ### 订单相关 RENT_ORDER_NOT_BACK_ERROR = { "error_code": '6101', "error_message": "有未归还的订单" } RENT_ORDER_NOT_TAKE_ERROR = { "error_code": '6102', "error_message": "有未取货的订单" } RENT_ORDER_NUMBER_MAX = { "error_code": '6103', "error_message": "订单数量达到上限" } TAKE_CODE_NOT_VALID = { "error_code": '6104', "error_message": "取货码错误请确认手机号及取货码是否匹配" } CODE_CANCEL_ERROR = { "error_code": '6105', "error_message": "取货码已取消" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } NO_POWER_ERROR = { "error_code": '6106', "error_message": "没有可租借设备" } NO_RENT_RECORD = { "error_code": '6107', "error_message": "订单不存在" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } RENT_ORDER_NUMBER_LIMIT = { "error_code": '6109', "error_message": "机柜只允许租借一台" } REFUND_NOT_RENT_INFO = { "error_code": "6301", "error_message": "没有该订单信息" } REFUND_BACK_TIME_ERROR = { "error_code": "6302", "error_message": "归还时间异常" } REFUND_NOT_PRODUCTION_INFO = { "error_code": "6303", "error_message": "没有该讲解器信息" } REFUND_MONEY_IS_ZERO = { "error_code": "6304", "error_message": "退款金额为零" } REFUND_NO_DUPLICATE = { "error_code": "6305", "error_message": "退款单号重复" } TALLYMAN_ACCOUNT_EXIST = { "error_code": "7001", "error_message": "tallyman account exist, 补货员账号已存在" } TALLYMAN_ACCOUNT_NOT_EXIST = { "error_code": "7002", "error_message": "tallyman account not exist, 补货员账号不存在" } NFC_CARD_NOT_EXIST = { "error_code": "8001", "error_message": "nfc card not exist, 卡号错误" } NFC_CARD_ACTIVATED_ERROR = { "error_code": "8002", "error_message": "nfc card activated, 卡片已激活" } NO_NFC_CARD_ERROR = { "error_code": "8003", "error_message": "no nfc card , 不存在卡片" } RE_NFC_CARD_ERROR = { "error_code": "8004", "error_message": "re nfc card , 卡片已存在" } NFC_PAY_LOAD_SECRET_ERROR = { "error_code": "8005", "error_message": "secret error , 身份验证失败" } NO_PLACE_ERROR = { "error_code": "9001", "error_message": "no place error,不存在场景" }
\ No newline at end of file
#!usr/bin/env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @file: error_code.py """ ### 通用错误相关 Param_Invalid_Error = { "error_code": "500", "error_message": "params is invalid, 参数无效" } TOKEN_NOT_VALID_ERROR = { "error_code": "1001", "error_message": "无效的token" } TOKEN_NOT_PROVIDED_ERROR = { "error_code": "1002", "error_message": "token未提供" } TOKEN_EXPIRE_ERROR = { "error_code": "1003", "error_message": "token超时" } PHONE_NOT_BINDING_ERROR = { "error_code": "1004", "error_message": "未绑定手机号" } PHONE_NOT_NULL_ERROR = { "error_code": "1005", "error_message": "手机号为空" } PHONE_NOT_VALID_ERROR = { "error_code": "1006", "error_message": "无效的手机号" } USER_ALREADY_REGISTER_ERROR = { "error_code": "1007", "error_message": "用户已注册" } VERIFICATION_CODE_NULL_ERROR = { "error_code": "1008", "error_message": "验证码为空" } VERIFICATION_CODE_INVALID_ERROR = { "error_code": "1009", "error_message": "验证码已失效" } VERIFICATION_CODE_ERROR = { "error_code": "1010", "error_message": "验证码错误" } PASSWORD_ERROR = { "error_code": "1011", "error_message": "账号或密码错误" } # 账号相关 12开头 ACCOUNT_ALREADY_EXISTS_ERROR = { "error_code": '1012', "error_message": "该账号已存在" } ACCOUNT_NOT_EXISTS_ERROR = { "error_code": '1013', "error_message": "账号不存在" } ACCOUNT_ALREADY_DELETE_ERROR = { "error_code": '1014', "error_message": "账号已被删除" } ACCOUNT_AGENT_SPOT_NULL_ERROR = { "error_code": '1015', "error_message": "代理商景点列表为空" } AGNET_MODULES_ERROR = { "error_code": '1016', "error_message": "用户未绑定模块" } OPERATE_TYPE_ERROR = { "error_code": '1017', "error_message": "type错误" } OPERATE_LEVEL_ERROR = { "error_code": '1018', "error_message": "权限错误" } OPERATE_ERROR = { "error_code": '1019', "error_message": "操作有误" } MODULES_NOT_EXISTS_ERROR = { "error_code": '1020', "error_message": "modules not exists,模块不存在" } ACCOUNT_AGENT_SPOT_NOT_EXIST = { "error_code": '1021', "error_message": "agent spot not exists,代理景区不存在" } AGENT_MACHINE_NOT_EXIST = { "error_code": '1022', "error_message": "agent machine not exists,代理机柜不存在" } ## 微信登陆相关 WX_LOGIN_DATA_ERROR = { "error_code": "3001", "error_message": "微信登录数据错误" } WX_LOGIN_CODE_ERROR = { "error_code": "3002", "error_message": "微信登录code值错误" } WX_OPENID_NOT_GET_ERROR = { "error_code": "3003", "error_message": "微信OpenId获取失败,请刷新重试" } WX_SESSION_KEY_ERROR = { "error_code": "3004", "error_message": "session key error" } ### 微信支付相关 WE_MINIAPP_PAY_FAIL = { "error_code": "3101", "error_message": "小程序下单失败" } ### 消息推送相关 WXBizMsgCrypt_OK = { "error_code": "0", "error_message": "WXBizMsgCrypt_OK" } WXBizMsgCrypt_ValidateSignature_Error = { "error_code": "4001", "error_message": "验证签名错误" } WXBizMsgCrypt_ParseXml_Error = { "error_code": "4002", "error_message": "解析xml错误" } WXBizMsgCrypt_ComputeSignature_Error = { "error_code": "4003", "error_message": "计算签名错误" } WXBizMsgCrypt_IllegalAesKey = { "error_code": "4004", "error_message": "Aes key非法错误" } WXBizMsgCrypt_ValidateAppid_Error = { "error_code": "4005", "error_message": "appid错误" } WXBizMsgCrypt_EncryptAES_Error = { "error_code": "4006", "error_message": "aes加密错误" } WXBizMsgCrypt_DecryptAES_Error = { "error_code": "4007", "error_message": "aes解密错误" } WXBizMsgCrypt_IllegalBuffer = { "error_code": "4008", "error_message": "illegal buffer" } WXBizMsgCrypt_EncodeBase64_Error = { "error_code": "4009", "error_message": "base64加密错误" } WXBizMsgCrypt_DecodeBase64_Error = { "error_code": "4010", "error_message": "base64解密错误" } WXBizMsgCrypt_GenReturnXml_Error = { "error_code": "4011", "error_message": "gen return xml error" } MACHINE_NOT_EXIST_ERROR = { "error_code": '5001', "error_message": "机柜不存在" } MACHINE_IS_USE_ERROR = { "error_code": '5002', "error_message": "已有他人正在租借中,请稍后" } MACHINE_IS_NOT_ONLINE_ERROR = { "error_code": '5003', "error_message": "机柜不在线" } MACHINE_ADD_ERROR = { "error_code": '5004', "error_message": "机柜添加失败" } MACHINE_NO_DUPLICATE_ERROR = { "error_code": '5005', "error_message": "machine_no duplicate,机柜编号重复" } MACHINE_EDIT_ERROR = { "error_code": '5006', "error_message": "machine edit error, 机柜修改错误" } HATCH_NOT_EXIST_ERROR = { "error_code": "5007", "error_message": "no hatch, 没有商品信息" } HATCH_NOT_ALL_EXIST_ERROR = { "error_code": "5008", "error_message": "no all hatch, 存在已售出商品" } HATCH_COUNT_ERROR = { "error_code": "5009", "error_message": "hatch count error, 商品数量错误,检查数量" } MACHINE_ACTIVATED_ERROR = { "error_code": '5010', "error_message": "machine activated, 机柜已激活" } ### 订单相关 RENT_ORDER_NOT_BACK_ERROR = { "error_code": '6101', "error_message": "有未归还的订单" } RENT_ORDER_NOT_TAKE_ERROR = { "error_code": '6102', "error_message": "有未取货的订单" } RENT_ORDER_NUMBER_MAX = { "error_code": '6103', "error_message": "订单数量达到上限" } TAKE_CODE_NOT_VALID = { "error_code": '6104', "error_message": "取货码错误请确认手机号及取货码是否匹配" } CODE_CANCEL_ERROR = { "error_code": '6105', "error_message": "取货码已取消" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } NO_POWER_ERROR = { "error_code": '6106', "error_message": "没有可租借设备" } NO_RENT_RECORD = { "error_code": '6107', "error_message": "订单不存在" } CODE_USED_ERROR = { "error_code": '6108', "error_message": "取货码已使用" } RENT_ORDER_NUMBER_LIMIT = { "error_code": '6109', "error_message": "机柜只允许租借一台" } REFUND_NOT_RENT_INFO = { "error_code": "6301", "error_message": "没有该订单信息" } REFUND_BACK_TIME_ERROR = { "error_code": "6302", "error_message": "归还时间异常" } REFUND_NOT_PRODUCTION_INFO = { "error_code": "6303", "error_message": "没有该讲解器信息" } REFUND_MONEY_IS_ZERO = { "error_code": "6304", "error_message": "退款金额为零" } REFUND_NO_DUPLICATE = { "error_code": "6305", "error_message": "退款单号重复" } TALLYMAN_ACCOUNT_EXIST = { "error_code": "7001", "error_message": "tallyman account exist, 补货员账号已存在" } TALLYMAN_ACCOUNT_NOT_EXIST = { "error_code": "7002", "error_message": "tallyman account not exist, 补货员账号不存在" } NFC_CARD_NOT_EXIST = { "error_code": "8001", "error_message": "nfc card not exist, 卡号错误" } NFC_CARD_ACTIVATED_ERROR = { "error_code": "8002", "error_message": "nfc card activated, 卡片已激活" } NO_NFC_CARD_ERROR = { "error_code": "8003", "error_message": "no nfc card , 不存在卡片" } RE_NFC_CARD_ERROR = { "error_code": "8004", "error_message": "re nfc card , 卡片已存在" } NFC_PAY_LOAD_SECRET_ERROR = { "error_code": "8005", "error_message": "secret error , 身份验证失败" } NO_PLACE_ERROR = { "error_code": "9001", "error_message": "no place error,不存在场景" }
\ No newline at end of file
......
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/30 @file: jwt_util.py @function: @modify: """ import jwt from flask import current_app def generate_jwt(payload, expiry, secret=None): """ 生成jwt :param payload: dict 载荷 :param expiry: datetime 有效期 :param secret: 密钥 :return: jwt """ _payload = {'exp': expiry} _payload.update(payload) if not secret: secret = current_app.config['SECRET_KEY'] token = jwt.encode(_payload, secret, algorithm='HS256') return token def verify_jwt(token, secret=None): """ 检验jwt :param token: jwt :param secret: 密钥 :return: dict: payload """ if not secret: secret = current_app.config['SECRET_KEY'] try: payload = jwt.decode(token, secret, algorithms=['HS256']) except jwt.PyJWTError: payload = None return payload if __name__ == '__main__': import time from config.env_path_config import env_path from dotenv import load_dotenv load_dotenv(dotenv_path=env_path, verbose=True, override=True) import os SECRET_KEY = os.getenv('SECRET_KEY') # token = generate_jwt({"user_id": 1}, time.time() + 6000, SECRET_KEY) token = generate_jwt({"user_no": 'SK000007'}, time.time() + 6000, SECRET_KEY) print(token) # for i in range(10): # result = verify_jwt(token, 'secret') # print(result) # print(time.time()) # time.sleep(1)
\ No newline at end of file
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/30 @file: jwt_util.py @function: @modify: """ import jwt from flask import current_app def generate_jwt(payload, expiry, secret=None): """ 生成jwt :param payload: dict 载荷 :param expiry: datetime 有效期 :param secret: 密钥 :return: jwt """ _payload = {'exp': expiry} _payload.update(payload) if not secret: secret = current_app.config['SECRET_KEY'] token = jwt.encode(_payload, secret, algorithm='HS256') return token def verify_jwt(token, secret=None): """ 检验jwt :param token: jwt :param secret: 密钥 :return: dict: payload """ if not secret: secret = current_app.config['SECRET_KEY'] try: payload = jwt.decode(token, secret, algorithms=['HS256']) except jwt.PyJWTError: payload = None return payload if __name__ == '__main__': import time from config.env_path_config import env_path from dotenv import load_dotenv load_dotenv(dotenv_path=env_path, verbose=True, override=True) import os SECRET_KEY = os.getenv('SECRET_KEY') token = generate_jwt({"user_id": 1}, time.time() + 6000, SECRET_KEY) # token = generate_jwt({"user_no": 'SK000007'}, time.time() + 6000, SECRET_KEY) print(token) # for i in range(10): # result = verify_jwt(token, 'secret') # print(result) # print(time.time()) # time.sleep(1)
\ No newline at end of file
......
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/26 @file: middlewares.py @function: @modify: """ import logging from flask import g, request, url_for, current_app, make_response, jsonify from config.wechat_config import platform_config_list from models.models import WxUser, TallymanAccount from utils.error_code import TOKEN_NOT_VALID_ERROR from utils.my_response import BaseResponse from utils.jwt_util import verify_jwt logger = logging.getLogger(__name__) def log_enter_interface(): """ 日志打印进入接口 :return: """ logger.info("######################### 进入 {} 接口 ################################ ".format(request.path)) def log_out_interface(environ): """ 日志打印退出接口 :return: """ logger.info("######################### 退出 {} 接口 ################################\n".format(request.path)) return environ def close_db_session(environ): from models.base_model import db db.session.close() return environ """用户认证机制==>每次请求前获取并校验token""" "@myapps.before_request 不使@调用装饰器 在 init文件直接装饰" def jwt_authentication(): """ 1.获取请求头Authorization中的token 2.判断是否以 Bearer开头 3.使用jwt模块进行校验 4.判断校验结果,成功就提取token中的载荷信息,赋值给g对象保存 """ path_list = request.path.split("/") if current_app.name == "sukang24h": NO_AUTH_CHECK_URL = [url_for('wx_auth.my_test'), url_for('wx_auth.mini_login'), url_for('rent.wx_pay_callback'), url_for('hatch.get_production_list'), url_for('tallyman.run_tallyman_login'), url_for('machine.run_get_machine_no'), url_for('nfc_card.run_nfc_card_wx_pay_callback'), url_for('nfc_card.run_nfc_card_user_pay_record'), url_for('nfc_card.run_nfc_card_load_succeed'), url_for('nfc_card.run_nfc_card_user_load_record'), ] if request.path not in NO_AUTH_CHECK_URL: token = request.headers.get('Authorization') # "校验token" payload = verify_jwt(token) # "判断token的校验结果" if payload: # "获取载荷中的信息赋值给g对象" if request.path.split("/")[2] == "tallyman": user_no = payload.get('user_no') if not user_no: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) if request.path.split("/")[2] == "machine": user_no = payload.get('user_no', None) user_id = payload.get('user_id', None) if user_no: try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) if user_id: try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) return BaseResponse(**TOKEN_NOT_VALID_ERROR) user_id = payload.get('user_id') if not user_id: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: NO_AUTH_CHECK_URL = [] return def get_platform(): """ :return: """ g.platform = request.headers.get('platform', "sukang24h") def all_options_pass(): """ :return: """ if request.method == "OPTIONS": headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , platform', } return make_response((jsonify({'error_code': 0}), 200, headers))
\ No newline at end of file
#!usr/bin/.env python # -*- coding:utf-8 _*- """ @version: author:Aeolus @time: 2021/03/26 @file: middlewares.py @function: @modify: """ import logging from flask import g, request, url_for, current_app, make_response, jsonify from config.wechat_config import platform_config_list from models.models import WxUser, TallymanAccount, AdminAccount from utils.error_code import TOKEN_NOT_VALID_ERROR from utils.my_response import BaseResponse from utils.jwt_util import verify_jwt logger = logging.getLogger(__name__) def log_enter_interface(): """ 日志打印进入接口 :return: """ logger.info("######################### 进入 {} 接口 ################################ ".format(request.path)) def log_out_interface(environ): """ 日志打印退出接口 :return: """ logger.info("######################### 退出 {} 接口 ################################\n".format(request.path)) return environ def close_db_session(environ): from models.base_model import db db.session.close() return environ """用户认证机制==>每次请求前获取并校验token""" "@myapps.before_request 不使@调用装饰器 在 init文件直接装饰" def jwt_authentication(): """ 1.获取请求头Authorization中的token 2.判断是否以 Bearer开头 3.使用jwt模块进行校验 4.判断校验结果,成功就提取token中的载荷信息,赋值给g对象保存 """ path_list = request.path.split("/") if current_app.name == "sukang24h": NO_AUTH_CHECK_URL = [url_for('wx_auth.my_test'), url_for('wx_auth.mini_login'), url_for('rent.wx_pay_callback'), url_for('hatch.get_production_list'), url_for('tallyman.run_tallyman_login'), url_for('machine.run_get_machine_no'), url_for('nfc_card.run_nfc_card_wx_pay_callback'), url_for('nfc_card.run_nfc_card_user_pay_record'), url_for('nfc_card.run_nfc_card_load_succeed'), url_for('nfc_card.run_nfc_card_user_load_record'), ] if request.path not in NO_AUTH_CHECK_URL: token = request.headers.get('Authorization') # "校验token" payload = verify_jwt(token) # "判断token的校验结果" if payload: # "获取载荷中的信息赋值给g对象" if request.path.split("/")[2] == "tallyman": user_no = payload.get('user_no') if not user_no: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) if request.path.split("/")[2] == "machine": user_no = payload.get('user_no', None) user_id = payload.get('user_id', None) if user_no: try: g.user = TallymanAccount.query.filter_by(user_no=user_no).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) if user_id: try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) return BaseResponse(**TOKEN_NOT_VALID_ERROR) user_id = payload.get('user_id') if not user_id: return BaseResponse(**TOKEN_NOT_VALID_ERROR) try: g.user = WxUser.query.filter_by(id=user_id).first() if not g.user: return BaseResponse(**TOKEN_NOT_VALID_ERROR) return except Exception as e: print(e) return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: return BaseResponse(**TOKEN_NOT_VALID_ERROR) elif current_app.name == "pc_management": NO_AUTH_CHECK_URL = [url_for("admin.user_login"), url_for("admin.send_code"), ] if request.path not in NO_AUTH_CHECK_URL: token = request.headers.get('Authorization') # "校验token" payload = verify_jwt(token) # "判断token的校验结果" if payload: # "获取载荷中的信息赋值给g对象" user_id = payload.get('user_id', None) if user_id: g.user = AdminAccount.query.filter_by(id=user_id).first() if g.user: return return BaseResponse(**TOKEN_NOT_VALID_ERROR) else: NO_AUTH_CHECK_URL = [] return def get_platform(): """ :return: """ g.platform = request.headers.get('platform', "sukang24h") def all_options_pass(): """ :return: """ if request.method == "OPTIONS": headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , platform', } return make_response((jsonify({'error_code': 0}), 200, headers))
\ No newline at end of file
......
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