def init_websockets(sockets: Sockets): # ip 访问频率限制(防破解) # TODO 这个好像没用,大概是因为这边的路由并不是由 app 处理的? limiter.limit("600/day;100/hour;1/minute;1/second")(bot_bp) # 将 flask_sockets 的 blueprint 注册到 sockets 实例 sockets.register_blueprint(bot_bp)
def init_api(api_: Api): limiter.limit("666/hour;20/minute;3/second")(table_bp) # 更严格的限制 # 要将 flask-rest-api 定义的 blueprint 注册到 api_rest api_.register_blueprint(article_bp) api_.register_blueprint(comp_article_bp) api_.register_blueprint(table_bp) api_.register_blueprint(relation_bp) api_.register_blueprint(session_bp) api_.register_blueprint(user_bp)
class TokenList(Resource): decorators = [limiter.limit("5/hour", get_uid)] @verify_addr def post(self): if not request.json.get('username', None): error = { 'resource': 'Token', 'field': 'username', 'code': 'missing_field' } return {'message': 'Validation Failed', 'errors': error}, 422 if not request.json.get('password', None): error = { 'resource': 'Token', 'field': 'username', 'code': 'missing_field' } return {'message': 'Validation Failed', 'errors': error}, 422 if g.uid == -1: return {'message': 'username or password error'}, 422 s = Serializer(app.config['SECRET_KEY'], expires_in=app.config['EXPIRES']) token = s.dumps({'uid': g.uid, 'scope': g.scope.split(',')}) return { 'uid': g.uid, 'access_token': token, 'token_type': 'self', 'scope': g.scope, 'expires_in': app.config['EXPIRES'] }, 201, { 'Cache-Control': 'no-store', 'Pragma': 'no-cache' }
class VotePoemAPI(Resource): decorators = [ limiter.limit("1 per day", key_func=lambda: vote_limiter(request)) ] def post(self): content = request.get_json(silent=True) if ((u'b' in content) and (u'c' in content)): c = content.get(u'c') b = content.get(u'b') else: return { 'error': "Trying to vote for nothing. What are you? An anarchist?!" } if (('downvote' in content) and (content.get(u'downvote'))): multiplier = -1 else: multiplier = 1 if b.startswith('b') and c.startswith('c'): acab = Acab.query.filter_by(b=b, c=c).first() if acab is None: acab = Acab(b=b, c=c, vote=multiplier) db.session.add(acab) db.session.commit() else: acab.vote += 1 * multiplier db.session.commit() return {'vote': {'c': c, 'b': b}} else: return {'error': "You can't vote for that!"}
class User(Resource): decorators = [verify_token, limiter.limit("50/minute")] @verify_addr @verify_scope def get(self, user_id): user = Users.query.filter_by(id=user_id, banned=0).first() if user: return { 'id': user.id, 'username': user.username, 'scope': user.scope, 'date_created': str(user.date_created), 'date_modified': str(user.date_modified), 'banned': user.banned }, 200 else: return {}, 404 @verify_addr @verify_scope def put(self, user_id): parser = reqparse.RequestParser() parser.add_argument('scope', type=unicode, required=True, help='A scope field is require', location='json') args = parser.parse_args() # 所有权限范围 all_scope = set() for i in Scope.query.all(): all_scope.add(i.name) # 授予的权限范围 request_scope = set(request.json.get('scope', u'null').split(',')) # 求交集后的权限 u_scope = ','.join(all_scope & request_scope) db.session.query(Users).filter_by(id=user_id).update({ 'scope': u_scope, 'date_modified': arrow.now().datetime }) db.session.commit() user = Users.query.filter_by(id=user_id).first() app.config['SCOPE_USER'][user.id] = set(user.scope.split(',')) return { 'id': user.id, 'username': user.username, 'scope': user.scope, 'date_created': str(user.date_created), 'date_modified': str(user.date_modified), 'banned': user.banned }, 201
class UserList(Resource): decorators = [verify_token, limiter.limit("50/minute")] @verify_addr @verify_scope def post(self): if not request.json.get('username', None): error = { 'resource': 'Token', 'field': 'username', 'code': 'missing_field' } return {'message': 'Validation Failed', 'errors': error}, 422 if not request.json.get('password', None): error = { 'resource': 'Token', 'field': 'username', 'code': 'missing_field' } return {'message': 'Validation Failed', 'errors': error}, 422 user = Users.query.filter_by(username=request.json['username'], banned=0).first() if not user: password_hash = sha256_crypt.encrypt(request.json['password'], rounds=app.config['ROUNDS']) # 所有权限范围 all_scope = set() for i in Scope.query.all(): all_scope.add(i.name) # 授予的权限范围 request_scope = set(request.json.get('scope', u'null').split(',')) # 求交集后的权限 u_scope = ','.join(all_scope & request_scope) u = Users(username=request.json['username'], password=password_hash, scope=u_scope, banned=0) db.session.add(u) db.session.commit() return { 'id': u.id, 'username': u.username, 'scope': u.scope, 'date_created': str(u.date_created), 'date_modified': str(u.date_modified), 'banned': u.banned }, 201 else: return {'message': 'username is already esist'}, 422
class HbcApi(Resource): decorators = [limiter.limit("2400/minute"), verify_addr] @verify_addr #@verify_token def get(self, jgsj, hphm, kkdd): try: hbc = Hbc.query.filter(Hbc.date == jgsj[:10], Hbc.hphm == hphm, Hbc.jgsj == jgsj, Hbc.kkdd_id == kkdd).first() except Exception as e: logger.error(e) if hbc: return { 'id': hbc.id, 'jgsj': str(hbc.jgsj), 'hphm': hbc.hphm, 'kkdd_id': hbc.kkdd_id, 'imgpath': hbc.imgpath }, 200 else: return {}, 200
class HbcImg(Resource): decorators = [limiter.limit("2400/minute")] @verify_addr #@verify_token def get(self, date, hphm, kkdd): try: hbc = Hbc.query.filter(Hbc.date == date, Hbc.hphm == hphm, Hbc.kkdd_id.startswith(kkdd), Hbc.imgpath != '').first() except Exception as e: logger.error(e) if hbc: return { 'id': hbc.id, 'jgsj': str(hbc.jgsj), 'hphm': hbc.hphm, 'kkdd_id': hbc.kkdd_id, 'imgpath': hbc.imgpath }, 200 else: return {}, 200
class HbcList(Resource): decorators = [limiter.limit("600/minute")] @verify_addr #@verify_token def post(self): parser = reqparse.RequestParser() parser.add_argument('jgsj', type=unicode, required=True, help='A jgsj field is require', location='json') parser.add_argument('hphm', type=unicode, required=True, help='A hphm field is require', location='json') parser.add_argument('kkdd_id', type=unicode, required=True, help='A kkdd_id field is require', location='json') parser.add_argument('hpys_id', type=int, required=True, help='A hpys field is require', location='json') parser.add_argument('fxbh_id', type=int, required=True, help='A fxbh field is require', location='json') parser.add_argument('cdbh', type=int, required=True, help='A cdbh field is require', location='json') parser.add_argument('imgurl', type=unicode, required=True, help='A imgurl field is require', location='json') parser.add_argument('imgpath', type=unicode, help='A imgurl field is require', location='json') args = parser.parse_args() t = arrow.get(request.json['jgsj']).replace(hours=-8).to('local') hbc = Hbc(date=t.format('YYYY-MM-DD'), jgsj=t.datetime, hphm=request.json['hphm'], kkdd_id=request.json['kkdd_id'], hpys_id=request.json['hpys_id'], fxbh_id=request.json['fxbh_id'], cdbh=request.json['cdbh'], imgurl=request.json['imgurl'], imgpath=request.json.get('imgpath', ''), banned=0) db.session.add(hbc) db.session.commit() result = row2dict(hbc) result['jgsj'] = str(result['jgsj']) del result['date'] return result, 201