Skip to content

Commit

Permalink
配置允许储存任意JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
xfgryujk committed Oct 13, 2019
1 parent dcbb90a commit bb1acae
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 16 deletions.
5 changes: 4 additions & 1 deletion views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ def set_default_headers(self):

def prepare(self):
if self.request.headers.get('Content-Type', '').startswith('application/json'):
self.json_args = json.loads(self.request.body)
try:
self.json_args = json.loads(self.request.body)
except json.JSONDecodeError:
self.json_args = None
else:
self.json_args = None

Expand Down
45 changes: 30 additions & 15 deletions views/config.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,35 @@
# -*- coding: utf-8 -*-

import json
import uuid

import views.base
from typing import *

configs: Dict[str, dict] = {}
MAX_CONFIG_SIZE = 100 * 1024

ALLOWED_FIELDS = (
'showDanmaku', 'showGift', 'mergeSimilarDanmaku', 'minGiftPrice', 'maxSpeed',
'maxNumber', 'blockGiftDanmaku', 'blockLevel', 'blockNewbie', 'blockNotMobileVerified',
'blockKeywords', 'blockUsers', 'blockMedalLevel', 'css'
)
configs: Dict[str, dict] = {}


# noinspection PyAbstractClass
class ConfigsHandler(views.base.ApiHandler):
async def post(self):
if not isinstance(self.json_args, dict):
self.set_status(400)
return

config = self.json_args
config_id = str(uuid.uuid4())
config = {
name: self.json_args[name] for name in ALLOWED_FIELDS
}
config['id'] = config_id
config_str = json.dumps(config)
if len(config_str) > MAX_CONFIG_SIZE:
self.set_status(413)
return

configs[config_id] = config
self.write(config_str)
self.set_status(201)
self.write(config)
self.set_header('Content-Type', 'application/json; charset=UTF-8')

if len(configs) > 10000:
for _, key in zip(range(100), configs):
Expand All @@ -34,13 +39,23 @@ async def post(self):
# noinspection PyAbstractClass
class ConfigHandler(views.base.ApiHandler):
async def put(self, config_id):
config = configs.get(config_id, None)
if config is None:
if config_id not in configs:
self.set_status(404)
return
for name in ALLOWED_FIELDS:
config[name] = self.json_args[name]
self.write(config)
if not isinstance(self.json_args, dict):
self.set_status(400)
return

config = self.json_args
config['id'] = config_id
config_str = json.dumps(config)
if len(config_str) > MAX_CONFIG_SIZE:
self.set_status(413)
return

configs[config_id] = config
self.write(config_str)
self.set_header('Content-Type', 'application/json; charset=UTF-8')

async def get(self, config_id):
config = configs.get(config_id, None)
Expand Down

0 comments on commit bb1acae

Please sign in to comment.