예제 #1
0
    async def post(self, request, uid):
        try:
            u = User[uid]
        except IndexError as dn:
            return jsonify({
                "msg": "未找到用户",
            }, ensure_ascii=False, status=401)

        except Exception as e:
            return jsonify({
                "msg": "执行错误",
            }, ensure_ascii=False, status=500)
        else:
            if u:
                insert = request.json
                try:
                    validate(instance=insert, schema=Todo_Schema)
                except Exception as e:
                    return jsonify({
                        "msg": "参数错误",
                        "error": str(e)
                    }, ensure_ascii=False, status=401)
                else:
                    Todo.get(uid).append(insert)
                    return jsonify({
                        "msg": "插入成功"
                    }, ensure_ascii=False)
            else:
                return jsonify({
                    "msg": "未找到用户",
                }, ensure_ascii=False, status=401)
예제 #2
0
 async def create(self, request):
     result = await app.apg.fetchrow(
         self.table.insert().values(name=request.json['name']))
     try:
         return jsonify({'id': result['id']}, status=201)
     except Exception as e:
         return jsonify({'error': str(e)})
예제 #3
0
    async def get(self, request, uid):
        try:
            u = User[uid]
        except IndexError as dn:
            return jsonify({
                "msg": "未找到用户",
            }, ensure_ascii=False, status=401)

        except Exception as e:
            return jsonify({
                "msg": "执行错误",
            }, ensure_ascii=False, status=500)
        else:
            if u:
                if Todo.get(uid):
                    return jsonify({
                        "uid": uid,
                        "todo": Todo.get(uid)
                    },
                                   ensure_ascii=False)
                else:
                    return jsonify({
                        "msg": "未找到用户的todo列表",
                    },
                                   ensure_ascii=False,
                                   status=404)
            else:
                return jsonify({
                    "msg": "未找到用户",
                },
                               ensure_ascii=False,
                               status=401)
async def get_wordcloud(request):
    try:
        logger.info('开始进入模型,服务端获取数据')
        now_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        t1 = time.time()
        print('request', request)
        # content = request.get_json(silent=True, force=True)
        content = request.json
        print('content', content)
        text = content['word']
        # text='"life is short,you need python"'
        # res = await get_word_cloud(text)##await后面需要接协程对象,即定义成异步函数即可
        res = get_word_cloud(text)

        # content=content['data']
        logger.info('from client type content:{}'.format(
            type(content)))  # Do your processing

        logger.info('筛选出需要的字段')

        logger.info('开始调用模型')

        logger.info('模型已经计算完毕,返回结果,耗时{}s'.format(time.time() - t1))
        return jsonify(res)

    except Exception as e:
        logger.error('出错:{}\n{}'.format(e, traceback.format_exc()))

        return jsonify({'data': None, 'code': "1", 'message': "{}".format(e)})
예제 #5
0
    async def get(request):
        """查询任务"""
        _task_id = request.args.get('task_id')

        if _task_id is None:
            return jsonify(error_missing_request_params())

        resp_data = dict(id=1,
                         uuid=uuid4().hex,
                         task_name='王五',
                         task_info='task task task task')

        return jsonify(success_response(resp_data))
예제 #6
0
 async def read(self, request, db_id=False):
     if not db_id:
         result = [
             dict(r) for r in await app.apg.fetch(self.table.select())
         ]
     else:
         try:
             result = dict(await app.apg.fetchrow(
                 self.table.select(self.table.c.id == db_id)))
         except TypeError:
             return jsonify({'error': 'No matching record was found.'},
                            status=404)
     return jsonify({'result': result})
예제 #7
0
    async def post(self, request):
        insert = request.json

        try:
            validate(instance=insert, schema=User_Schema)
        except Exception as e:
            return jsonify({
                "msg": "参数错误",
                "error": str(e)
            },
                           ensure_ascii=False,
                           status=401)
        else:
            uid = User.append(insert)
            return jsonify({"msg": "插入成功", "uid": uid}, ensure_ascii=False)
예제 #8
0
async def _after_request(request, response):
    DB.close()
    if _is_sanic_static(response):
        return
    if 'args' in request and SECRET_EXTRA_INFO_KEYWORD in request['args']:
        try:
            body_dict = json.loads(response.body)
            body_dict.update({'request_info': status(request)})
            response.body = jsonify(body_dict).body
        except Exception:
            pass

    # if there is no session, delete cookie
    if 'session_id' not in request and _SESSION_COOKIE_NAME in request.cookies:
        session = Session.get('session_id', request.cookies.get(_SESSION_COOKIE_NAME, 'invalid'))
        if session is not None:
            session.delete_instance()
        debug('Deleting cookie')
        response.cookies[_SESSION_COOKIE_NAME] = ''
        response.cookies[_SESSION_COOKIE_NAME]['expires'] = 0
        response.cookies[_SESSION_COOKIE_NAME]['max-age'] = 0

    # If session id has changed
    elif request.get('session_id', False) and \
            request['session_id'] != request.cookies.get(_SESSION_COOKIE_NAME, 'invalid'):
        debug('Saving session in cookie %s', request['session_id'])
        response.cookies[_SESSION_COOKIE_NAME] = request['session_id']
        response.cookies[_SESSION_COOKIE_NAME]['expires'] = _SESSION_COOKIE_EXPIRES
        response.cookies[_SESSION_COOKIE_NAME]['httponly'] = True

    if not request.path.startswith('/status'):
        debug(f'Endpoint {request.path} ')
예제 #9
0
 def wrapper(request, *args, **kw):
     status = 200
     try:
         result = decorated(request, *args, **kw)
     except UserException as user_exception:
         log("User exception in mock: %s" % user_exception.message,
             request=request,
             exc_info=True)
         status = 500
         result = {
             'success': False,
             'result': {
                 'message': user_exception.message
             }
         }
     except json.JSONDecodeError:
         log(ERROR_INVALID_JSON, request=request, exc_info=True)
         status = 500
         result = {
             'success': False,
             'result': {
                 'message': ERROR_INVALID_JSON
             }
         }
     except Exception:
         log("Exception in mock", request=request, exc_info=True)
         status = 500
         result = {'success': False, 'result': {'message': ERROR_TEXT}}
     if 'success' not in result:
         result = {'success': True, 'result': result}
     return jsonify(result,
                    status=status,
                    headers=generate_cors_headers(request))
예제 #10
0
async def screenshot_upload(request):
    if request.headers.get("Authorization") != "[removed]":
        return response.json({"url": "Get Welcomer at https://welcomer.gg today B) I tried uploading an image but i didn't have the token"})
    i = int.from_bytes(
        base64.b64decode(
            str(uuid.uuid4()) + str(uuid.uuid4()) + str(uuid.uuid4()) + str(uuid.uuid4()) +
            str(uuid.uuid4()) + str(uuid.uuid4()).replace("-", "")),
        'big', signed=True)
    # _id = base64.urlsafe_b64encode(i.to_bytes((i.bit_length() + 8) // 8, 'big', signed=True)).decode("ascii")
    # _id = base64.b85encode(i.to_bytes((i.bit_length() + 8) // 8, 'big', signed=True)).decode("ascii")

    random.seed(i)
    _id = "".join(random.choices(a, k=8))
    _tid = (_id.encode("punycode")[-10:]).decode("ascii")

    files = request.files
    _file = files.get('file', None)

    if not _file:
        return "{success: false}", 403

    _format = imghdr.what(io.BytesIO(_file.body))
    if _format:
        _filename = _tid + "." + _format
        _fakefilename = _id + "." + _format
        path = join(cdn_path, ss_path, _filename)
        with open(path, "wb") as f:
            f.write(_file.body)
        return jsonify(
            {"success": True, "id": _filename,
             "url": f"https://cdn.welcomer.gg/imoog/{_fakefilename}"})
예제 #11
0
    async def get(self, request):
        count = len(User)
        result = {
            "description":
            "测试api,User总览",
            "user-count":
            count,
            "links": [
                {
                    "uri": "/user",
                    "method": "POST",
                    "description": "创建一个新用户"
                },
                {
                    "uri": "/user/<int:uid>",
                    "method": "GET",
                    "description": "用户号为<id>的用户信息"
                },
                {
                    "uri": "/user/<int:uid>",
                    "method": "PUT",
                    "description": "更新用户号为<id>用户信息"
                },
                {
                    "uri": "/user/<int:uid>",
                    "method": "DELETE",
                    "description": "删除用户号为<id>用户"
                },
            ]
        }

        return jsonify(result, ensure_ascii=False)
예제 #12
0
 async def snapshot(_):
     return jsonify({
         'nodes': [{
             'cpu': self.slave_registry[key]['cpu'],
             'name': key
         } for key in self.slave_registry
                   if self.slave_registry[key]['ws'].state == 1]
     })
예제 #13
0
def webJson(mystatus=RetCode.SUCCESS, data='', **kwargs):
    """jsonify自带有status参数,所以这里用mystatus避免冲突"""
    result = {
        RetCode.CODE: mystatus[1],
        RetCode.MSG: mystatus[2],
        RetCode.DATA: data
    }
    return jsonify(result, status=mystatus[0], **kwargs)
예제 #14
0
        async def get_pid_info(_, slave_name, pid):

            if slave_name not in self.slave_registry:
                return jsonify({'status': 'fail', 'message': 'Node not found'})
            current_slave_ws = self.slave_registry[slave_name]['ws']
            await current_slave_ws.send(
                '{"route": "/processinfo", "pid" : "%s"}' % pid)
            response_from_current_slave = await current_slave_ws.recv()
            return text(response_from_current_slave)
예제 #15
0
async def _version(request):
    return jsonify(
        {
            'version': version.VERSION,
            'name': version.NAME,
            'hostname': cape_frontend_settings.HOSTNAME,
            'port': cape_frontend_settings.CONFIG_SERVER['port'],
        },
        headers=generate_cors_headers(request))
예제 #16
0
def _timeout(request, exception):
    return jsonify({
        'success': False,
        'result': {
            'message': TIMEOUT_TEXT
        }
    },
                   status=500,
                   headers=generate_cors_headers(request))
예제 #17
0
def _404(request, exception):
    return jsonify({
        'success': False,
        'result': {
            'message': NOT_FOUND_TEXT
        }
    },
                   status=500,
                   headers=generate_cors_headers(request))
예제 #18
0
    async def get(self, request, uid):
        try:
            u = User[uid]
        except IndexError as dn:
            return jsonify({
                "msg": "未找到用户",
            }, ensure_ascii=False, status=401)

        except Exception as e:
            return jsonify({
                "msg": "执行错误",
            }, ensure_ascii=False, status=500)
        else:
            if u:
                return jsonify(u, ensure_ascii=False)
            else:
                return jsonify({
                    "msg": "未找到用户",
                }, ensure_ascii=False, status=401)
예제 #19
0
        async def get_info(_, name):
            if name not in self.slave_registry:
                return jsonify({'status': 'fail', 'message': 'Node not found'})
            current_slave_ws = self.slave_registry[name]['ws']
            #send the json patload to the current selected slave
            await current_slave_ws.send('{"route" : "/info"}')
            #get the response from the slave
            response_from_current_slave = await current_slave_ws.recv()
            #send back the response to the client

            return text(response_from_current_slave)
예제 #20
0
 def wrapper(request, *args, **kw):
     try:
         status = 200
         result = decorated(request, *args, **kw)
         if 'success' not in result:
             result = {'success': True, 'result': result}
     except SanicException as e:
         status = getattr(e, 'status_code', 500)
         result = {'success': False, 'message': str(e)}
     
     return jsonify(result, status=status, headers=generate_cors_headers(request))
예제 #21
0
 async def update(self, request, db_id):
     try:
         modified = False
         columns = self.related.name.split('_')[:-1]
         related_name = [n for n in columns if n != self.table.name].pop()
         related_id = request.json.pop(related_name + '_id', None)
         if related_id:
             rel_cols = [c + '_id' for c in columns]
             values = {
                 self.table.name + '_id': db_id,
                 related_name + '_id': related_id
             }
             # Update related row in a single call preserving idempotency
             # using from_select()
             select = sa.select([
                 values[rel_cols[0]], values[rel_cols[1]]
             ]).where(~sa.exists(self.related.c).where(
                 sa.and_(self.related.c[rel_cols[0]] == values[rel_cols[0]],
                         self.related.c[rel_cols[1]] == values[
                             rel_cols[1]])))
             insert = await app.apg.fetchval(
                 self.related.insert().from_select(
                     rel_cols,
                     select).returning(self.related.c[related_name + '_id'])
             )
             modified = bool(insert)
         if request.json:
             row = await app.apg.fetchval(self.table.update().values(
                 **request.json).where(self.table.c.id == db_id).returning(
                     self.table.c.id))
             if not row:
                 return jsonify({'error': 'Not found.'}, status=404)
             modified = True
         return jsonify(
             {
                 'result':
                 'Success' if modified else 'Relation already exists.'
             },
             status=200 if modified else 304)
     except asyncpg.exceptions.ForeignKeyViolationError:
         return jsonify({'error': 'Invalid ID supplied.'}, status=400)
예제 #22
0
    async def put(self, request, uid):
        try:
            u = User[uid]
        except IndexError as dn:
            return jsonify({
                "msg": "未找到用户",
            }, ensure_ascii=False, status=401)

        except Exception as e:
            return jsonify({
                "msg": "执行错误",
            }, ensure_ascii=False, status=500)
        else:
            if u:
                insert = request.json
                u.update(insert)
                return jsonify({"msg": "更新成功"}, ensure_ascii=False)
            else:
                return jsonify({
                    "msg": "未找到用户",
                },
                               ensure_ascii=False,
                               status=401)
예제 #23
0
def _500(request, exception):
    log('500', request=request, exc_info=True)
    if exception.__class__ is UserException:
        log("User exception: %s" % exception.message,
            request=request,
            exc_info=True)
        message = exception.message
        return jsonify({
            'success': False,
            'result': {
                'message': message
            }
        },
                       status=500,
                       headers=generate_cors_headers(request))
    return redirect('/500.html')
예제 #24
0
async def generate_questions(request):
    args = getattr(request, "args", None)
    logger.info(f"Got generate questions request with args {args}")
    args_dict = dict(args) if args else {}
    locale_arg = args_dict.get("locale", [])
    size_arg = args_dict.get("size", [])
    locale = locale_arg[0] if locale_arg else "en"
    size = size_arg[0] if size_arg else 20
    if "-" in locale:
        locale = locale.split("-")[0]
    if locale not in questions_by_locale:
        raise InvalidUsage(f"Invalid locale: {locale}")
    try:
        logger.info(f"Preparing set of {size} question in {locale} language")
        return jsonify({"questions": collect_questions(locale, size)},
                       ensure_ascii=False)
    except Exception as e:
        return ServerError("Couldn't prepare a set of questions")
예제 #25
0
    async def list_related(self, request, db_id):
        field_names = self.related.name.split('_')[:-1]
        field_names.remove(self.table.name)
        related_name = field_names.pop()
        tables = {
            'author': authors_table,
            'book': books_table,
            'mapping': mapping_table
        }
        related_table = tables[related_name]
        mapping = tables['mapping']

        result = await app.apg.fetch(
            sa.select([related_table.c.id, related_table.c.name]).select_from(
                related_table.join(
                    mapping, related_table.c.id ==
                    mapping.c[related_name + '_id']).join(
                        self.table, self.table.c.id == mapping.c[
                            self.table.name + '_id'])).where(
                                mapping.c[self.table.name + '_id'] == db_id))
        return jsonify({'result': [dict(r) for r in result]})
예제 #26
0
def _500(request, exception):
    error_id = secrets.token_urlsafe(32)
    if exception.__class__ is UserException:
        debug("User exception: %s" % exception.message, exc_info=True)
        message = exception.message
    elif exception.__class__ is json.JSONDecodeError:
        debug(ERROR_INVALID_JSON, exc_info=True, error_id=error_id)
        message = ERROR_INVALID_JSON
    elif exception.__class__ is InvalidUsage:
        debug(ERROR_INVALID_USAGE, exc_info=True)
        message = ERROR_INVALID_USAGE
    else:
        warning("Exception in API", exc_info=True)
        message = ERROR_TEXT
    return jsonify(
        {
            'success': False,
            'result': {
                'message': message,
                'errorId': error_id
            }
        },
        status=500,
        headers=generate_cors_headers(request))
예제 #27
0
 async def count_related(self, request, db_id):
     related_name = self.table.name + '_id'
     result = await app.apg.fetchval(
         sa.select([sa.func.count()]).select_from(
             self.related).where(self.related.c[related_name] == db_id))
     return jsonify({'result': result})
예제 #28
0
 async def delete(self, request, db_id):
     result = await app.apg.fetchval(self.table.delete().where(
         self.table.c.id == db_id).returning(self.table.c.id))
     return jsonify(
         {'result': 'Success' if result else 'No matching record found.'},
         status=200 if result else 404)
예제 #29
0
async def on_get_quote(request):
    json = request.json

    # Handle body matching
    def get(tag):
        if tag not in json:
            raise InvalidUsage('JSON is missing: \'{}\''.format(tag))
        return request.json[tag].strip().upper()

    base_currency, quote_currency, action = get('base_currency'), get(
        'quote_currency'), get('action')
    amount = float(get('amount'))
    product_id, inverted = match_product_id(base_currency, quote_currency)

    # match the type of order to the type of dataset
    book = client.get_book(product_id)
    if book is None:
        raise InvalidUsage('No data available yet!')
    if action == 'BUY':
        data = book.get_asks()
    elif action == "SELL":
        data = book.get_bids()
        if inverted:
            raise InvalidUsage(
                'Base currency and quote currency reversed for sell quote!')
    else:
        raise InvalidUsage('Unknown action type!')

    properties = products[product_id]
    weights, values = [], []
    # Find the scalar which is used to convert floats to the nearest integer for weighting
    # Precision is used in exporting result with proper number of decimals
    if inverted:
        # All cryptos seem to be fixed at 8 decimals
        precision = 8
        amount_scalar = float(properties['quote_increment'])
    else:
        # get base currency decimals
        precision = abs(properties['quote_increment'].as_tuple().exponent)
        amount_scalar = float(properties['base_min_size'] *
                              properties['quote_increment'])
    # Go through converting prices and sizes to weights and values
    for (price, size) in data:
        exchange_rate = (size * price)
        if inverted:
            weights.append(int(exchange_rate / amount_scalar))
            values.append(size)
        else:
            weights.append(int(size / amount_scalar))
            values.append(exchange_rate)
    # run knapsack algorithm
    total = knapsack(values[:50], weights[:50], amount / amount_scalar)

    # return pretty formatted json result
    return jsonify({
        'price':
        '{:.{prec}f}'.format(total / amount, prec=precision),
        'total':
        '{:.{prec}f}'.format(total, prec=precision),
        'currency':
        quote_currency
    })
예제 #30
0
 async def preflight(self, *args, **kwargs):
     return jsonify({'message': 'A workaround for browsers'})