コード例 #1
0
ファイル: mock.py プロジェクト: tonglei100/doo
def response(api, request: http.Request, params, **kwarg):
    params = dict(params)
    headers = dict(request.headers)
    if doc[api]['Method'] == 'POST':
        body = eval(request.body.decode('utf-8'))
    else:
        body = {}

    headers_doc = doc[api]['REQUEST']['Headers']
    for k in headers_doc:
        if headers_doc[k] != headers.get(k.lower()):
            return http.JSONResponse(f'Headers is not matching\ndoc \
            {k}:{headers_doc[k]}\nreal {k}:{headers.get(k)}',
                                     status_code=404)

    body = dict(body, **params)
    for data in doc[api]:
        if 'DATA' in data:
            result = check_body(doc[api][data]['REQUEST'], body, **kwarg)
            if result:
                if doc[api][data].get('delay'):
                    sleep(doc[api][data]['delay'])
                return http.JSONResponse(doc[api][data]['RESPONSE'], \
                status_code=doc[api][data].get('status_code', 200), headers=doc[api]['RESPONSE']['Headers'])

    return http.JSONResponse('No body data matching', status_code=404)
コード例 #2
0
def response(api, request: http.Request, params, **kwarg):
    params = dict(params)
    headers = dict(request.headers)
    if doc[api]['方法'] == 'POST':
        body = eval(request.body.decode('utf-8'))
    else:
        body = {}

    headers_doc = doc[api]['REQUEST']['Headers']
    for k in headers_doc:
        if headers_doc[k] != headers.get(k.lower()):
            return http.JSONResponse(f'Headers is not matching\ndoc \
            {k}:{headers_doc[k]}\nreal {k}:{headers.get(k)}',
                                     status_code=404)

    req_data_doc = doc[api]['REQUEST']['Data']
    res_data_doc = doc[api]['RESPONSE']['Data']
    body = dict(body, **params)
    for i in range(len(req_data_doc)):
        result = check_body(req_data_doc[i], body, **kwarg)
        if result:
            if doc[api].get('delay'):
                sleep(doc[api]['delay'][i])
            return http.JSONResponse(res_data_doc[i],
                                     status_code=doc[api]['status_code'][i],
                                     headers=doc[api]['RESPONSE']['Headers'])

    return http.JSONResponse('No body data matching', status_code=404)
コード例 #3
0
ファイル: api.py プロジェクト: stevanmilic/valis-coin
def push_transaction(transaction: Transaction) -> http.JSONResponse:
    if not validate_transaction(transaction):
        return http.JSONResponse({'status': 'Error'}, status_code=400)

    client.txns_pool.append(transaction)
    if len(client.txns_pool) == client.TXNS_POOL_SIZE:
        miner.process_txns_pool(client.txns_pool, client.blockchain.tail_block)
        client.txns_pool = []

    return http.JSONResponse({'status': 'Success'}, status_code=200)
コード例 #4
0
def delete_route(source: str) -> types.Route:
    try:
        route = {
            "source": source,
            "target": ROUTER.lookup(source),
            "settings": ROUTER.lookup_settings(source),
        }
        ROUTER.delete(source)
        return http.JSONResponse(types.Route(route), status_code=204)
    except RedisRouter.LookupNotFound:
        return http.JSONResponse(
            {"message": f"Route with source {source} doesn't exist"},
            status_code=404)
コード例 #5
0
 def drop(session: Session) -> http.JSONResponse:
     """
     Drop resource collection.
     """
     num_records = session.query(model).count()
     session.query(model).delete()
     return http.JSONResponse({'deleted': num_records}, status_code=204)
コード例 #6
0
def hello_world(accept_language: http.Header) -> http.JSONResponse:
    if 'de' in accept_language:
        data = {'text': 'Hallo, Welt!'}
    else:
        data = {'text': 'Hello, world!'}
    headers = {'Vary': 'Accept-Language'}
    return http.JSONResponse(data, status_code=200, headers=headers)
コード例 #7
0
ファイル: hooks.py プロジェクト: fellowme/star_builder
    def on_error(self, error: Exception, app: App) -> http.Response:
        """
        Handle error
        """
        code = 999
        message = None
        if error.args:
            if not isinstance(error.args[0], (tuple, list)) \
                    or len(error.args[0]) < 2:
                if isinstance(error.args[0], int):
                    code = error.args[0]
                else:
                    message = error.args[0]
            else:
                code, message = error.args[0][:2]

        code = int(code)
        # apistar不支持在on_request时打断后续执行直接返回response
        # 所以在只能通过raise异常来通过异常参数传递响应。
        if isinstance(message, http.Response):
            return message

        if message is None:
            message = self.errors.get(code, "Not configured error")

        payload = {
            "type": "normal",
            "code": code,
            "errcode": code,
            "message": message,
        }
        if app.debug:
            payload["detail"] = "".join(traceback.format_exc())
        traceback.print_exc()
        return http.JSONResponse(payload)
コード例 #8
0
ファイル: peewee.py プロジェクト: perdy/apistar-crud
 def drop(cls) -> DropOutput:
     """
     Drop resource collection.
     """
     num_records = model.delete().execute()
     return http.JSONResponse(DropOutput({"deleted": num_records}),
                              status_code=204)
コード例 #9
0
ファイル: app.py プロジェクト: wajika/ceryx
def delete_route(source: str) -> types.Route:
    try:
        route = {
            'source': source,
            'target': ROUTER.lookup(source),
            'settings': ROUTER.lookup_settings(source),
        }
        ROUTER.delete(source)
        return http.JSONResponse(
            types.Route(route),
            status_code=204,
        )
    except RedisRouter.LookupNotFound:
        return http.JSONResponse(
            {'message': f'Route with source {source} doesn\'t exist'},
            status_code=404,
        )
コード例 #10
0
        def add_item(data: cls.schema_add, obj: ActesPermissions):
            # obj.medicaments.create(**data)
            try:
                item = cls.model(ordonnance=obj, **data)
            except TypeError as exc:
                raise MapistarBadRequest("acte_id doit correspondre à une ordonnance")

            return http.JSONResponse(item.dico, status_code=201)
コード例 #11
0
 def create(cls, session: Session, element: input_type) -> output_type:
     """
     Create a new element for this resource.
     """
     record = model(**element)
     session.add(record)
     session.flush()
     return http.JSONResponse(output_type(record), status_code=201)
コード例 #12
0
 def drop(cls, session: Session) -> DropOutput:
     """
     Drop resource collection.
     """
     num_records = session.query(model).count()
     session.query(model).delete()
     return http.JSONResponse(DropOutput({"deleted": num_records}),
                              status_code=204)
コード例 #13
0
ファイル: patients.py プロジェクト: jgirardet/mapistar
def add(patient: PatientCreateSchema) -> http.JSONResponse:
    """
    Ajouter un nouveau patient

    Args:
        patient: données du nouveau patient
    """
    a = db.Patient(**patient)
    return http.JSONResponse(a.dico, status_code=201)
コード例 #14
0
def astrologer_root(astrologer: str) -> http.JSONResponse:
    if AManager.is_valid_astrologer(astrologer):
        data = {
            'message':
            "ERR0R: Sorry but " + astrologer + " is away at the moment"
        }
    else:
        data = {'message': "ERR0R: No astrologer accepted!"}
    return http.JSONResponse(data, status_code=400)
コード例 #15
0
def create_puppy(session: Session, puppy: PuppyType,
                 raise_exception: http.QueryParam) -> http.JSONResponse:
    if raise_exception:
        raise Exception

    model = PuppyModel(**puppy)
    session.add(model)
    session.flush()
    return http.JSONResponse(PuppyType(model), status_code=201)
コード例 #16
0
ファイル: api.py プロジェクト: stevanmilic/valis-coin
def add_block(block: Block) -> http.JSONResponse:
    if not verify_block(block):
        return http.JSONResponse({'status': 'Error'}, status_code=400)

    # NOTE: this is done in separete thread, hooray
    client.announce_mined_block(block)

    miner.stop_mining()
    client.update_utxo(block.txns)
    client.txns_pool = filter(
        lambda txn: any(b_txn._dict == txn._dict for b_txn in block.txns),
        client.txns_pool
    )

    client.blockchain.set_block(block.mined_hash, block)
    client.blockchain.tail_block = block

    return http.JSONResponse({'status': 'Success'}, status_code=200)
コード例 #17
0
def datain(request: http.Request) -> http.JSONResponse:
    data = DataIn(name='EventLog',
                  request_id='fd',
                  payload=request.body.decode('utf-8').strip())

    headers = {'Vary': 'Accept-Language'}
    return http.JSONResponse(data,
                             status_code=200,
                             headers=headers)
コード例 #18
0
def run(request: http.Request, words, scale=1, level='L'):
    try:
        qr = myqr.run(words, scale=int(scale), version=1, level=level)
        imgByteArr = io.BytesIO()
        qr.save(imgByteArr, format='PNG')
        return http.Response(imgByteArr.getvalue(),
                             headers={'Content-Type': 'image/png'})
    except Exception as e:
        return http.JSONResponse({'message': e.args}, status_code=400)
コード例 #19
0
        def delete(cls, session: Session,
                   element_id: str) -> typing.Dict[str, typing.Any]:
            """
            Delete an element of this resource.
            """
            if session.query(model).filter_by(id=element_id).count() == 0:
                raise NotFound

            session.query(model).filter_by(id=element_id).delete()
            return http.JSONResponse(None, status_code=204)
コード例 #20
0
ファイル: users.py プロジェクト: marceloandriolli/featuren
def create_user(userData: UserType):
    """
    Create a new user
    """

    if User.check_username(userData.username):
        msg = f"The username: {userData.username} isn't available. Please try another."
        return http.JSONResponse({"message": msg}, status_code=409)

    user = User()
    user = user.create(userData)

    msg = "User created successfully."
    log.info(f"{msg} - ID: {user.id}")

    headers = {"Content-Location": f"/users/{user.id}"}
    return http.JSONResponse({"message": msg},
                             status_code=201,
                             headers=headers)
コード例 #21
0
def astrologer_sign(astrologer: str, sign: str) -> http.JSONResponse:
    if AManager.is_valid_astrologer(astrologer):
        data = {
            'message':
            "ERR0R: Sorry but there is currently no horoscope of the " + sign +
            " readed by " + astrologer
        }
    else:
        data = {'message': "ERR0R: No astrologer accepted!"}
    return http.JSONResponse(data, status_code=400)
コード例 #22
0
ファイル: peewee.py プロジェクト: perdy/apistar-crud
        def create(cls, element: input_type) -> output_type:
            """
            Create a new element for this resource.
            """
            fields = dict(element)
            if fields.get("id") is None:
                del fields["id"]

            record = model.create(**fields)
            return http.JSONResponse(output_type(record), status_code=201)
コード例 #23
0
async def create_article(app: App, data: http.RequestData,
                         password: http.Header) -> http.JSONResponse:
    # if not is_auth(password):
    #     raise exceptions.BadRequest()
    if not data['title']:
        raise exceptions.BadRequest()

    article_id = repo.add_article({'title': data['title']})
    url = app.reverse_url('get_article', article_id=article_id)
    headers = {'Location': url}
    return http.JSONResponse({}, status_code=201, headers=headers)
コード例 #24
0
def token_login(user: schemas.TokenUser):
    from django_apistar.authentication.models import Token

    if not user:
        return http.JSONResponse({"message": "Invalid credentials."},
                                 status_code=400)

    user = authenticate(username=user['username'], password=user['password'])

    if user:
        try:
            return user.auth_token.key
        except ObjectDoesNotExist:
            token = Token(user=user)
            token.save()
            return user.auth_token.key

    else:
        return http.JSONResponse({"message": "Invalid credentials."},
                                 status_code=400)
コード例 #25
0
ファイル: patients.py プロジェクト: jgirardet/mapistar
def update(new_data: PatientUpdateSchema,
           patient_id: int) -> http.JSONResponse:
    """modify patients

    Args:
        new_data: Rien n'est requis.
        id: patient id.
    """
    to_update = get_or_404(db.Patient, patient_id)
    to_update.set(**{k: v for k, v in new_data.items() if v})
    return http.JSONResponse(to_update.dico, status_code=201)
コード例 #26
0
ファイル: peewee.py プロジェクト: perdy/apistar-crud
        def delete(cls, element_id: str) -> typing.Dict[str, typing.Any]:
            """
            Delete an element of this resource.
            """
            try:
                record = model.get_by_id(element_id)
            except DoesNotExist:
                raise NotFound

            record.delete_instance()

            return http.JSONResponse(None, status_code=204)
コード例 #27
0
def data_fetcher(accept_language: http.Header) -> http.JSONResponse:

    headers = {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    }
    # TODO: check if this Access-Control definition is the best approach, since it may leave the app insecure

    filename = "data.json"
    with open(os.path.join(BASE_DIR, filename)) as f:
        jsonarray = json.load(f)
    return http.JSONResponse(jsonarray, status_code=200, headers=headers)
コード例 #28
0
        def update(cls, session: Session, element_id: str,
                   element: input_type) -> output_type:
            """
            Update an element of this resource.
            """
            record = session.query(model).get(element_id)
            if record is None:
                raise NotFound

            for k, value in element.items():
                setattr(record, k, value)

            return http.JSONResponse(output_type(record), status_code=200)
コード例 #29
0
def welcome() -> http.JSONResponse:
    data = {
        "project": "Horoscofox",
        'author': {
            "Username": "******",
            "link": "github.com/Owanesh"
        },
        "contributor": {
            "Username": "******",
            "link": "github.com/astagi"
        }
    }
    return http.JSONResponse(data, status_code=200)
コード例 #30
0
def login(userData: UserType):
    """
    Login
    """
    user = User.where("username", userData.username).first()

    if user and user.check_password(userData.password):

        log.info(f"Login user with id: {user.id} successfully")

        payload = {
            "user_id": user.id,
            "exp":
            datetime.utcnow() + timedelta(seconds=jwt_settings.get("exp")),
        }

        token = jwt.encode(payload, jwt_settings.get("secret"),
                           jwt_settings.get("algorithm"))
        return http.JSONResponse({"token": token.decode("utf-8")})

    msg = f"Wrong credentials"
    return http.JSONResponse({"message": msg}, status_code=400)