예제 #1
0
def test_json_response(json_app):
    from sanic.response import json_dumps

    request, response = json_app.test_client.get("/")
    assert response.status == 200
    assert response.text == json_dumps(JSON_DATA)
    assert response.json == JSON_DATA
예제 #2
0
def test_custom_request():
    app = Sanic(name=__name__, request_class=CustomRequest)

    @app.route("/post", methods=["POST"])
    async def post_handler(request):
        return text("OK")

    @app.route("/get")
    async def get_handler(request):
        return text("OK")

    payload = {"test": "OK"}
    headers = {"content-type": "application/json"}

    request, response = app.test_client.post("/post",
                                             data=json_dumps(payload),
                                             headers=headers)

    assert isinstance(request.body_buffer, BytesIO)
    assert request.body_buffer.closed
    assert request.body == b'{"test":"OK"}'
    assert request.json.get("test") == "OK"
    assert response.text == "OK"
    assert response.status == 200

    request, response = app.test_client.get("/get")

    assert isinstance(request.body_buffer, BytesIO)
    assert request.body_buffer.closed
    assert request.body == b""
    assert response.text == "OK"
    assert response.status == 200
async def send_event(request):

    # if channel_id is None than event will be send to all subscribers
    channel_id = request.json.get("channel_id")
    logger.success(f"Message {request.json} on {channel_id}")

    # optional arguments: event_id - str, event - str, retry - int
    # data should always be str
    # also you can use sse_send_nowait for send event without waiting
    try:
        await request.app.sse_send(json_dumps(request.json),
                                   channel_id=channel_id)
    except KeyError:
        logger.error("channel not found, No subscribers found")
        return response.json({
            "error": True,
            "succes": False,
            "message": "No subscribers found"
        })

    return response.json({
        "error": False,
        "succes": True,
        "message": "subscribers found and message sent"
    })
예제 #4
0
def test_custom_request():
    app = Sanic(request_class=CustomRequest)

    @app.route("/post", methods=["POST"])
    async def post_handler(request):
        return text("OK")

    @app.route("/get")
    async def get_handler(request):
        return text("OK")

    payload = {"test": "OK"}
    headers = {"content-type": "application/json"}

    request, response = app.test_client.post(
        "/post", data=json_dumps(payload), headers=headers
    )

    assert isinstance(request.body_buffer, BytesIO)
    assert request.body_buffer.closed
    assert request.body == b'{"test":"OK"}'
    assert request.json.get("test") == "OK"
    assert response.text == "OK"
    assert response.status == 200

    request, response = app.test_client.get("/get")

    assert isinstance(request.body_buffer, BytesIO)
    assert request.body_buffer.closed
    assert request.body == b""
    assert response.text == "OK"
    assert response.status == 200
예제 #5
0
async def _contest(request):
    admin = request.ctx.session['user']['admin']
    if not admin and not in_time_open():
        return response.redirect('/')

    team_id = request.ctx.session['user']['id']

    if request.method== 'POST':
        return response.redirect('/contest')
    
    not_seen = not await app.ctx.db.fetchval("SELECT seen from seen where team_id=$1", team_id)
    latest_announcement = 0
    print("NOS", not_seen)
    if not_seen:
        latest_announcement = await app.ctx.db.fetchval("SELECT msg FROM announcements ORDER BY timestamp DESC LIMIT 1")
        print("LA", latest_announcement);
    problems = await fetch_problems(db=app.ctx.db, team_id=team_id)
    team_stats = await fetch_team_stats(db=app.ctx.db, team_id=team_id)

    print(problems[0].attempts)

    return await render_template(
        app.ctx.env,
        request,
        "opho/contest.html", 
        team_stats=team_stats, 
        latest_announcement=json_dumps(latest_announcement),
        problems=sorted(problems, 
        key=lambda x: x.number)
    )
예제 #6
0
 async def respond(self, response, cursor):
     primary = []
     included = []
     if self.single:
         response.write('{"data":')
     else:
         response.write('{"data":[')
     prev_included = False
     join = False
     unique = set()
     async for row in cursor:
         ident = (row[1], row[2])
         if ident in unique:
             continue
         unique.add(ident)
         attrs, rels = self.match_row_values(row[1], row[3])
         obj = {
             'type': row[1],
             'id': row[2],
             'attributes': attrs,
             'relationships': rels
         }
         if row[0] == 'f':
             if join:
                 response.write(',' + json_dumps(obj))
             else:
                 response.write(json_dumps(obj))
                 join = True
         else:
             if not prev_included:
                 if self.single:
                     response.write(',"included":[')
                 else:
                     response.write('],"included":[')
                 prev_included = True
                 join = False
             if join:
                 response.write(',' + json_dumps(obj))
             else:
                 response.write(json_dumps(obj))
                 join = True
     if self.single and not self.include:
         response.write('}')
     else:
         response.write(']}')
예제 #7
0
async def handler(request):
    body = nlp(request.body.decode('ASCII'))
    entstat = [{
        'text': ent.text,
        'type': ent.label_,
        'start': ent.start_char,
        'end': ent.end_char
    } for ent in body.ents]
    return sanic.response.HTTPResponse(body=json_dumps(entstat),
                                       content_type='application/json')
예제 #8
0
def set_cookies(token,cookies):
    '''
    加密cookies
    :param token:
    :param cookies:
    :return:
    '''
    f = Fernet(token)
    cookies_json = json_dumps(cookies)
    token = f.encrypt(cookies_json.encode())
    cookies_json = token.decode()
    return cookies_json
예제 #9
0
    def __init__(self, message='', errors=None, **kwargs):
        data = self.schema.load(
            dict(
                type=self.type,
                message=message,
                errors=errors,
            )).data

        kwargs.setdefault('content_type', 'application/json')
        kwargs.setdefault('status', 400)

        super().__init__(json_dumps(data), **kwargs)
예제 #10
0
파일: pcapid.py 프로젝트: lxp/pcapid
async def send_message(peer_id, message):
    print('Sent(%s): %s' % (peer_id, message))
    return await peers[peer_id].ws.send(json_dumps(message))
예제 #11
0
async def tag_git(request):

    # get profile
    profile = requests.get('{0}?token={1}&user={2}&pretty=1'.format(
        URL_GET_PROFILE, TOKEN, request.form.get('user_id')))

    if profile.status_code == 200:
        user_profile = profile.json().get('profile')

        try:
            # get text command
            text = request.form.get('text')
            text_split = text.split(' ')

            __repo = None
            __commit_hash = None
            __tag_name = None

            for ts in text_split:
                # checking start with --
                ts_des = (ts.split('--', 1)[1]).split('=')
                ts_command = ts_des[0]
                ts_val = ts_des[1]

                if ts_command not in LIST_COMMAND:
                    return json({'message': 'Invalid syntax'})

                if ts_command == 'repo':
                    __repo = ts_val

                elif ts_command == 'commit':
                    __commit_hash = ts_val

                elif ts_command == 'tag':
                    __tag_name = ts_val

            # GIT PROCESS

            # MAKE RELEASE TAGS
            if __repo != None and __commit_hash != None and __tag_name != None:

                # check tag if exist
                # GET /repos/:owner/:repo/releases/tags/:tag
                url_check_tag = '{}/repos/{}/{}/releases/tags/{}'.format(
                    URL_GIT, USER_GIT, __repo, __tag_name)
                check_tag = requests.get(url_check_tag,
                                         auth=HTTPBasicAuth(
                                             USER_GIT, PSWD_GIT))
                # if exist update tag
                if check_tag.status_code == 200:
                    existing_tag_release = check_tag.json()
                    # do update
                    # PATCH /repos/:owner/:repo/releases/:release_id
                    url_update_tag = '{}/repos/{}/{}/releases/{}'.format(
                        URL_GIT, USER_GIT, __repo,
                        existing_tag_release.get('id'))

                    data_release = {
                        "tag_name": __tag_name,
                        "target_commitish": __commit_hash,
                        "name": __tag_name,
                        "body": "Update Release to {}".format(__tag_name),
                        "draft": False,
                        "prerelease": False,
                    }

                    patch_release = requests.patch(
                        url_update_tag,
                        data=json_dumps(data_release),
                        auth=(USER_GIT, PSWD_GIT))

                    # after update tag release we must update refs commit of tag
                    # POST /repos/:owner/:repo/git/refs
                    url_ref = "{}/repos/{}/{}/git/refs/tags/{}".format(
                        URL_GIT, 'sendaljpt', 'slack-bot', __tag_name)
                    data_ref = {"sha": __commit_hash, "force": True}
                    patch_ref = requests.patch(url_ref,
                                               data=json_dumps(data_ref),
                                               auth=(USER_GIT, PSWD_GIT))

                # if not exist create new tag
                # POST /repos/:owner/:repo/releases
                elif check_tag.status_code == 404:
                    url_release = '{}/repos/{}/{}/releases'.format(
                        URL_GIT, USER_GIT, __repo)
                    data_release = {
                        "tag_name": __tag_name,
                        "target_commitish": __commit_hash,
                        "name": __tag_name,
                        "body": "Release to {}".format(__tag_name),
                        "draft": False,
                        "prerelease": False,
                    }

                    post_release = requests.post(url_release,
                                                 data=json_dumps(data_release),
                                                 auth=(USER_GIT, PSWD_GIT))

                message_slack = "{} tags {} with a commit {}".format(
                    user_profile.get('email'), __tag_name, __commit_hash)
                await send_to_slack(channel=TO_CHANNEL, text=message_slack)

                return json({'message': 'Done!'})

            return json({'message': 'Invalid syntax'})

        except SlackApiError as e:

            return json({'message': f"Failed due to {e.response['error']}"})

        except Exception as e:
            return json({'message': 'Invalid syntax'})
예제 #12
0
async def tag_menu(request):

    request_data = request.form.get('payload')
    if request_data != None:
        data_req = JSon.loads(request_data)
        __repo = data_req['submission']['repo']
        __commit_hash = data_req['submission']['commit_hash']
        __tag_name = data_req['submission']['tag_name']

        # get profile
        profile = requests.get('{0}?token={1}&user={2}&pretty=1'.format(
            URL_GET_PROFILE, TOKEN, data_req['user']['id']))
        user_profile = profile.json().get('profile')

        # check tag if exist
        # GET /repos/:owner/:repo/releases/tags/:tag
        url_check_tag = '{}/repos/{}/{}/releases/tags/{}'.format(
            URL_GIT, USER_GIT, __repo, __tag_name)
        check_tag = requests.get(url_check_tag,
                                 auth=HTTPBasicAuth(USER_GIT, PSWD_GIT))
        # if exist update tag
        if check_tag.status_code == 200:
            existing_tag_release = check_tag.json()
            # do update
            # PATCH /repos/:owner/:repo/releases/:release_id
            url_update_tag = '{}/repos/{}/{}/releases/{}'.format(
                URL_GIT, USER_GIT, __repo, existing_tag_release.get('id'))

            data_release = {
                "tag_name": __tag_name,
                "target_commitish": __commit_hash,
                "name": __tag_name,
                "body": "Update Release to {}".format(__tag_name),
                "draft": False,
                "prerelease": False,
            }

            patch_release = requests.patch(url_update_tag,
                                           data=json_dumps(data_release),
                                           auth=(USER_GIT, PSWD_GIT))

            # after update tag release we must update refs commit of tag
            # POST /repos/:owner/:repo/git/refs
            url_ref = "{}/repos/{}/{}/git/refs/tags/{}".format(
                URL_GIT, 'sendaljpt', 'slack-bot', __tag_name)
            data_ref = {"sha": __commit_hash, "force": True}
            patch_ref = requests.patch(url_ref,
                                       data=json_dumps(data_ref),
                                       auth=(USER_GIT, PSWD_GIT))

        # if not exist create new tag
        # POST /repos/:owner/:repo/releases
        elif check_tag.status_code == 404:
            url_release = '{}/repos/{}/{}/releases'.format(
                URL_GIT, USER_GIT, __repo)
            data_release = {
                "tag_name": __tag_name,
                "target_commitish": __commit_hash,
                "name": __tag_name,
                "body": "Release to {}".format(__tag_name),
                "draft": False,
                "prerelease": False,
            }

            post_release = requests.post(url_release,
                                         data=json_dumps(data_release),
                                         auth=(USER_GIT, PSWD_GIT))

        message_slack = "{} tags {} with a commit {}".format(
            user_profile.get('email'), __tag_name, __commit_hash)
        await send_to_slack(channel=TO_CHANNEL, text=message_slack)

        return json({'message': 'Done!'})

    else:
        data = {
            "callback_id":
            "ryde-46e2b0",
            "title":
            "Taging github",
            "submit_label":
            "Submit",
            "state":
            "init",
            "elements": [{
                "type": "text",
                "label": "Repository",
                "name": "repo"
            }, {
                "type": "text",
                "label": "Commit Hash",
                "name": "commit_hash"
            }, {
                "type": "text",
                "label": "Tag Name",
                "name": "tag_name"
            }],
            "trigger_id":
            request.form.get('trigger_id')
        }

        client.dialog_open(dialog=data,
                           trigger_id=request.form.get('trigger_id'))

        return json({'message': 'tag in progress'})
예제 #13
0
파일: http.py 프로젝트: olivier-m/rafter
 def body(self):
     return self._encode_body(json_dumps(self._data))
예제 #14
0
def test_json_response(json_app):
    from sanic.response import json_dumps
    request, response = json_app.test_client.get('/')
    assert response.status == 200
    assert response.text == json_dumps(JSON_DATA)
    assert response.json == JSON_DATA