Example #1
0
def incoming_update(request: Request):
    update = telegram.Update.de_json(request.get_json(force=True, cache=False), ccn_bot)
    log.info(request.get_json(force=True, cache=False))
    log.info(update)
    res = dispatcher.dispatcher.process(update)

    return res
Example #2
0
def res_post(uid: str):
    if know_post(uid):
        if not Request.get_json(request):
            apo_post = post_factory.post_factory(uid)
            apo_post.apothanasia()
            return Response(json.dumps(vars(apo_post)), 200)

        req = Request.get_json(request)
        tmp_post = response_post.ResponsePost(link=uid, content=req['content'],
                            password=req['password'] if 'password' in Request.get_json(request) else '',
                            lang=req['lang'] if 'lang' in Request.get_json(request) else 'und')
        tmp_post.post_contribution()

        return Response(json.dumps(vars(tmp_post)), 200)
Example #3
0
def delete_post(uid):
    if know_post(uid):
        if not Request.get_json(request):
            req = Request.get_Json(request)
            if not 'password' in req:
                abort(400)

        req = Request.get_json(request)
        tmp_post = post_factory.post_factory(uid)
        if not tmp_post.password == req['password']:
            abort(401)
        else:
            tmp_post.delete_post()
            return Response(json.dumps({'message': 'Your post deleted ;)'}), 200)
Example #4
0
def delete_post(uid):
    if exist_post(uid):
        if not Request.get_json(request):
            req = Request.get_json(request)
            if 'password' not in req:
                abort(400)

        req = Request.get_json(request)
        tmp_post = post_factory(uid)
        if not tmp_post.password == req['password']:
            abort(401)
        else:
            tmp_post.delete_post()
            return Response(json.dumps({'message': 'Your post deleted ;)'}),
                            200)
Example #5
0
def _process_request(request: flask.Request, method: str,
                     encrypt_request: bool,
                     require_verified_email: bool) -> dict[str, typing.Any]:
    """Handle authentication and encryption."""
    if method in ('GET', 'DELETE'):
        data = dict(request.args)
    elif method in ('POST', 'PATCH'):
        if encrypt_request:
            data = _decrypt_request(request.get_data())
        else:
            data = request.get_json(force=True, silent=True)
        if not isinstance(data, dict):
            raise utils.RequestError(3113)
    session_id = None
    session_token = None
    if 'session_id' in data:
        session_id = data.pop('session_id')
    if 'session_token' in data:
        session_token = data.pop('session_token')
    if bool(session_id) ^ bool(session_token):
        raise utils.RequestError(1303)
    if session_id and session_token:
        session = models.Session.validate_session_key(session_id,
                                                      session_token)
        request.session = session
        user = session.user
        if require_verified_email and not user.email_verified:
            raise utils.RequestError(1307)
        data['user'] = user
    else:
        request.session = None
    return data
Example #6
0
def familyquestion(request: Request) -> Union[Response, None]:
    if request.method == 'POST'
        request_json = request.get_json()
        textdata = request_json['context']
        id = request_json['id']

        engine = sqlalchemy.create_engine(
            sqlalchemy.engine.url.URL(
                drivername = driver_name,
                username = db_user,
                password = db_password,
                database = db_name,
                query = query_string,
            ),
            pool_size = 5,
            max_overflow = 2,
            pool_timeout = 30,
            pool_recycle = 1800
        )
        SessionClass = sessionmaker(engine) 
        session = SessionClass()
        questionadd = session.query(Question).filter(Question.id == id).first()
        questionadd.text = textdata
        session.commit()

        return make_response("201 Create", 201)
def get_user_connection_details(request: Request):
    connection = DatabaseConnection('userbase.db')
    cursor = connection.conn.cursor()
    jsondata = (request.get_json())

    if jsondata is None:
        return {'serverCode': 400}
    else:
        username = jsondata['username']
        cursor.execute('SELECT ipaddress FROM user WHERE username=?',
                       (username, ))
        ip = cursor.fetchone()
        cursor.execute('SELECT port FROM user WHERE username=?', (username, ))
        port = cursor.fetchone()
        cursor.execute('SELECT netplaymode FROM user WHERE username=?',
                       (username, ))
        mode = cursor.fetchone()

        data = {
            'ipAddress': '\'' + ip[0] + '\'',
            'port': '\'' + port[0] + '\'',
            'mode': '\'' + mode[0] + '\'',
            'serverCode': 200
        }

        return data
def get_user_info(reqeust: Request):
    connection = DatabaseConnection('userbase.db')
    cursor = connection.conn.cursor()
    jsondata = (reqeust.get_json())

    if jsondata is None:
        return {'serverCode': 400}
    else:
        username = jsondata['username']
        cursor.execute('SELECT ipaddress FROM user WHERE username=?;',
                       (username, ))
        ip = cursor.fetchone()
        cursor.execute('SELECT port FROM user WHERE username=?;', (username, ))
        port = cursor.fetchone()
        cursor.execute('SELECT mostplayedgame FROM user WHERE username=?;',
                       (username, ))
        mostplayedgame = cursor.fetchone()
        cursor.execute('SELECT mostplayedemulator FROM user WHERE username=?;',
                       (username, ))
        mostplayedemulator = cursor.fetchone()
        cursor.execute('SELECT mode FROM user WHERE username=?', (username, ))
        mode = cursor.fetchone()

        jsonlist = {
            'ipAddress': '\'' + ip[0] + '\'',
            'port': '\'' + port[0] + '\'',
            'mostPlayedGame': '\'' + mostplayedgame[0] + '\'',
            'mostPlayedEmulator': '\'' + mostplayedemulator[0] + '\'',
            'serverCode': 200,
            'mode': '\'' + mode[0] + '\''
        }

        return jsonlist
Example #9
0
def fetch_events(request: flask.Request) -> Dict[str, Any]:
    print("MDW: fetch_events() called, request: {request}")
    request_json = request.get_json(silent=True)
    request_args = request.args

    if request_json and "maxResults" in request_json:
        maxResults = int(request_json["maxResults"])
    else:
        maxResults = 10
    print(f"MDW: maxResults is: {maxResults}")

    service = build("calendar", "v3")

    now = datetime.datetime.utcnow()
    now_iso = now.isoformat() + "Z"

    # For human formatting
    anow = arrow.utcnow().to("US/Pacific")
    datestring = anow.strftime("%A, %B %-d")
    timestring = anow.strftime("%-I:%M %p")

    events_result = (
        service.events()
        .list(
            calendarId=CALENDAR,
            timeMin=now_iso,
            maxResults=maxResults,
            singleEvents=True,
            orderBy="startTime",
        )
        .execute()
    )
    events = events_result.get("items", [])

    # Parse out timestamps since CircuitPython doesn't have datetime.
    for event in events:
        event["now"] = {
            "date": datestring,
            "time": timestring,
            "dateTime": now_iso,
            "timestamp": int(now.timestamp()),
        }
        st = event["start"]["dateTime"]
        et = event["end"]["dateTime"]
        try:
            stp = datetime.datetime.strptime(st, "%Y-%m-%dT%H:%M:%S%z")
            etp = datetime.datetime.strptime(et, "%Y-%m-%dT%H:%M:%S%z")
            event["start"]["timestamp"] = int(stp.timestamp())
            event["start"]["when"] = stp.strftime("%-I:%M %p")
            until = humanize.naturaldelta(arrow.get(stp) - anow)
            event["start"]["until"] = until
            event["end"]["timestamp"] = int(etp.timestamp())
        except Exception as e:
            warning = f"Warning: {e}"
            print(warning)
            event["start"]["warning"] = warning

    if not events:
        return {"result": []}
    return {"result": events}
Example #10
0
def _is_request_valid(request: Request) -> Tuple[bool, Optional[Tuple[Response, int]]]:
    if request.method != "POST":
        return False, (jsonify({"status": "failed", "message": "Invalid method"}), 405)

    if not request.is_json:
        return False, (jsonify({"status": "failed", "message": "Invalid data"}), 422)

    request_data = request.get_json()

    if not _is_language_valid(request_data):
        return False, (jsonify({"status": "failed", "message": "Set lang parameter to pl or en"}), 422)

    lang = request_data["lang"]

    if "msisdn" not in request_data or not _check_phone_number(request_data["msisdn"]):
        return False, (jsonify({"status": "failed", "message": _get_message(MESSAGE_INVALID_PHONE_NUMBER, lang)}), 422)

    msisdn = request_data["msisdn"]

    if _is_too_many_requests_for("msisdn", msisdn, limit=INVALID_REGS_PER_MSISDN_LIMIT):
        return (
            False,
            (jsonify({"status": "failed", "message": _get_message(MESSAGE_REGISTRATION_NOT_AVAILABLE, lang)}), 429),
        )

    return True, None
Example #11
0
 def create(self, r: Request, **kwargs):
     body = r.get_json()
     transaction_request = CreateTransactionRequest(**body)
     if transaction_request.transaction_date > date.today():
         # TODO: is this desirable?
         raise InvalidRequestException(
             'cannot create a request for a future date')
Example #12
0
def request_to_post(request: flask.Request):
    try:
        json_str = request.get_json()["data"]
        post_json = json.loads(json_str, encoding="utf8")
    except Exception as e:
        print(e)
        return None
    if "body" in post_json.keys() and \
       "title" in post_json.keys() and \
       "category" in post_json.keys() and \
       "description" in post_json.keys() and \
       len(post_json["body"]) > 2 and \
       len(post_json["title"]) > 2 and \
       len(post_json["category"]) > 2 and \
       len(post_json["description"]) > 2:
        return {
            "body": post_json["body"],
            "title": post_json["title"],
            "category": post_json["category"],
            "description": post_json["description"],
            "date_posted": datetime.now(),
            "id": shortuuid.uuid(),
            "votes": 0,
            "comments": [],
        }
    return None
Example #13
0
def webhook(request: Request):
    logging.info("access_route: %s", ",".join(request.access_route))
    logging.info("args: %s", request.args)
    logging.info("data: %s", request.data)
    logging.info("form: %s", request.form)
    if request.args.get("apikey") != apikey and request.form.get("apikey") != apikey:
        return make_response("", 404)
    if "version" in request.args:
        return str(os.environ.get("X_GOOGLE_FUNCTION_VERSION")) + "\n"
    if "title" in request.form:
        return post_np(request.form["title"], request.form.get("show"))
    if request.form.get("group") in group_ids:
        pin = request.form.get("pin")
        if pin in ["true", "1"]:
            pin = True
        elif pin in ["false", "0"]:
            pin = False
        notify = True if request.form.get("notify") in ["true", "1"] else False
        forward = True if request.form.get("forward") in ["true", "1"] else False
        return post_pin(
            bot,
            request.form["group"],
            request.form.get("message"),
            pin,
            notify,
            forward,
        )
    update = Update.de_json(request.get_json(force=True), bot)
    dispatcher.process_update(update)
Example #14
0
def receiver(request: Request):
    method = request.method
    if method == "POST":
        request_json = request.get_json(force=True)
        logging.error(f"Received a POST request: {request_json}")
        update: telegram.Update = telegram.Update.de_json(
            request_json, Config.bot)
        chat_id = update.message.chat.id

        # if update.effective_message.effective_type == 'photo':
        if len(update.message.photo) != 0:
            response = Observer().get_response(update.message)
        else:
            response = Queryer().get_response(update.message)

        if response is None:
            return ok_response
        return send_message_in_https_response(chat_id, response)

    elif method == "GET":
        logging.error(f"Received a GET request")
        updater = OverallUpdater()
        updater.get_and_send_updates()

    else:
        logging.error(f"Received {method} request. I don't know what to do.")
    return make_response("Completed the request")
Example #15
0
def get_post_parameter(request: flask.Request, key: str) -> str or bool:
    """
    Extracts Parameters from a POST request.

    Parameters
    -----------
    request : flask.Request
        The request object.
    key : str
        The key to look for in the request.

    Returns
    -------
    str or bool
        Returns the value of the given key and False otherwise.

    """
    json = request.get_json(silent=True)
    args = request.args
    if json and key in json:
        return json[key]
    elif args and key in args:
        return args[key]
    else:
        return False
Example #16
0
def http(request: Request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    data = request.get_json()
    api_key = data.get('key', None)
    trigger_name = data.get('trigger', None)
    departement = data.get('departement', '75')

    if api_key is None:
        return Response('Cannot ping ifttt without API key', 404)

    if trigger_name is None:
        return Response('Cannot ping ifttt without trigger name', 404)

    run_script(api_key=api_key,
               trigger_name=trigger_name,
               departement=departement)

    return Response('OK')
Example #17
0
def pm_sensor_storage(request: Request) -> Response:
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    try:
        sensor_data = extract_sensor_data(request.get_json(silent=True))
    except RequestInvalidError as e:
        logging.warning("invalid request: %s", e)
        return Response(status=400)

    sensor_data["datetime"] = datetime.utcnow()

    client = bigquery.Client(
        location=os.getenv("BIGQUERY_REGION", "europe-west3"))
    errors = client.insert_rows(get_or_create_table(client), [sensor_data])
    if errors:
        logging.warning("failed to store data in bigquery: %s", errors)
        return Response(status=500)

    return Response(status=201)
Example #18
0
    def _handle_github_request(self, request: flask.Request) -> None:
        if not self._is_valid_github_request(request):
            raise APIException(
                'Got invalid github request',
                f'The webhook request on webhook {self.id} was not valid',
                APICodes.WEBHOOK_INVALID_REQUEST, 400)

        if request.is_json:
            data = request.get_json()
        else:
            data = json.loads(request.form['payload'])

        repo = data.get('repository', {})
        self._handle_request(
            request,
            event=request.headers.get('X-GitHub-Event', 'unknown'),
            get_data=lambda: _PartialGitCloneData(
                type='github',
                url=repo['html_url'],
                commit=data['after'],
                repository_name=repo['full_name'],
                ref=data['ref'],
                sender_username=data['sender']['login'],
                sender_name=data['sender']['login'],
                webhook_id=str(self.id),
                clone_url=repo['ssh_url'],
                event=request.headers['X-GitHub-Event'],
                default_branch=repo['default_branch']),
        )
Example #19
0
    def _handle_gitlab_request(self, request: flask.Request) -> None:
        got_token: str = request.headers.get('X-Gitlab-Token', '')
        assert self.secret
        if not hmac.compare_digest(self.secret, got_token):
            raise APIException(
                'Got invalid gitlab request',
                f'The webhook request on webhook {self.id} was not valid',
                APICodes.WEBHOOK_INVALID_REQUEST, 400)

        data = request.get_json()
        project = data.get('project', {})

        self._handle_request(
            request,
            event=data['object_kind'],
            get_data=lambda: _PartialGitCloneData(
                type='gitlab',
                url=data['repository']['homepage'],
                commit=data['checkout_sha'],
                repository_name='{namespace} / {name}'.format(**project),
                ref=data['ref'],
                sender_username=data['user_username'],
                sender_name=data['user_name'],
                webhook_id=str(self.id),
                clone_url=project['git_ssh_url'],
                event=data['object_kind'],
                default_branch=project['default_branch'],
            ),
        )
Example #20
0
def handle_deliver_emails_for_batch_email_reporting(request: Request) -> None:
    """Cloud function to deliver a batch of generated emails.
    It hits the App Engine endpoint `reporting/deliver_emails_for_batch`. It requires a JSON input containing the
    following keys:
        batch_id: (required) Identifier for this batch
        redirect_address: (optional) An email address to which all emails should
        be sent instead of to their actual recipients.
    Args:
        request: HTTP request payload containing JSON with keys as described above
    Returns:
        Nothing.
    Raises:
        Nothing. All exception raising is handled within the App Engine logic.
    """
    project_id = os.environ.get(GCP_PROJECT_ID_KEY)
    if not project_id:
        logging.error("No project id set, returning")
        return

    request_params = request.get_json()
    if not request_params:
        logging.error("No request params, returning")
        return

    batch_id = request_params.get("batch_id", '')
    redirect_address = request_params.get("redirect_address", '')
    url = _APP_ENGINE_PO_MONTHLY_REPORT_DELIVER_EMAILS_URL.format(project_id, batch_id, redirect_address)

    logging.info("Calling URL: %s", url)
    response = make_iap_request(url, IAP_CLIENT_ID[project_id])
    logging.info("The response status is %s", response.status_code)
Example #21
0
def getsqlstring(request):
    request_json = request.get_json()
    stmt = sqlalchemy.text(
        "SELECT * FROM customers LIMIT 2"
    )  #("INSERT INTO entries (guestName, content) values ('third guest', 'Also this one');")
    db = sqlalchemy.create_engine(sqlalchemy.engine.url.URL(
        drivername=driver_name,
        username=db_user,
        password=db_pass,
        database=db_name,
        query=query_string,
    ),
                                  pool_size=5,
                                  max_overflow=2,
                                  pool_timeout=30,
                                  pool_recycle=1800)
    print("Cloud SQL was successfully queried " + request_json['tablename'])
    try:
        with db.connect() as conn:
            custy = conn.execute(stmt).fetchall()
            print(type(custy[0]))
            print(custy)
    except Exception as e:
        return 'Error: {}'.format(str(e))
    # This ia an important line. This is returned by the cloud function
    return json.dumps({"sql": "SELECT * FROM customers"})
Example #22
0
def handle(req: Request):
    """handle a request to the function.

    Your response is immediately passed to the caller, unmodified.
    This allows you full control of the response, e.g. you can set
    the status code by returning a tuple (str, int). A detailed
    description of how responses are handled is found here:

    http://flask.pocoo.org/docs/1.0/quickstart/#about-responses

    Args:
        req (Request): Flask request object
    """
    # load molecule from smiles and calculate fp
    mol = Chem.MolFromSmiles(req.get_json()['smiles'])
    if mol:
        fp = Chem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048)
        fp = np.asarray(fp).reshape(1, -1)

        # predict
        data = zip(classes, model.predict_proba(fp)[0])
        predictions = pd.DataFrame(data, columns=['chembl_id', 'proba'])
        predictions = predictions.to_dict(orient='records')
    else:
        predictions = None
    return json.dumps(predictions)
Example #23
0
def calendar_api(api_request: Request):
    """Cloud function entry point

    :param api_request: http request
    """
    with app.app_context():

        # construct headers
        headers = Headers()
        for key, value in api_request.headers.items():
            headers.add(key, value)

        # prepare content
        content = {}
        if headers.get('content-type') == 'application/json':
            content['json'] = api_request.get_json(silent=True)
        else:
            content['data'] = api_request.form

        with app.test_request_context(method=api_request.method,
                                      base_url=api_request.base_url,
                                      path=api_request.path,
                                      query_string=api_request.query_string,
                                      headers=headers,
                                      **content):
            try:
                rv = app.preprocess_request()
                if rv is None:
                    rv = app.dispatch_request()
            except Exception as e:
                rv = app.handle_user_exception(e)
            response = app.make_response(rv)
            return app.process_response(response)
Example #24
0
def parse_request(request: Request, model_type: Type[T]) -> T:
    request_json = request.get_json(silent=True)
    if not request_json:
        raise BadRequestException("Request body is not a valid JSON")
    try:
        return model_type(**request_json)
    except ValidationError as e:
        raise BadRequestException(f"Bad request: {e}")
Example #25
0
 def get(self, proc):
     body_json = Request.get_json(self)
     if (proc == Url.SEARCH_TAG):
         return self.search_tag(body_json['tags'],
                                body_json['current_page'])
     elif (proc == Url.SEARCH_TITLE):
         return self.search_title(body_json['title'],
                                  body_json['current_page'])
Example #26
0
def post_content():
    if not Request.get_json(request):
        abort(400)

    req = Request.get_json(request)
    if not 'content' in req:
        abort(400)

    if len(req['content']) <= 0:
        abort(123)

    tmp_post = post.Post(content=req['content'],
                password=req['password'] if 'password' in Request.get_json(request) else '',
                lang=req['lang'] if 'lang' in Request.get_json(request) else 'und')
    tmp_post.post_contribution()

    return Response(json.dumps(vars(tmp_post)), 200)
Example #27
0
 def search(self, r: Request, **kwargs):
     body = r.get_json()
     search_type = body['searchType']
     search_id = body['searchId']
     if search_type not in ['username', 'group']:
         raise InvalidRequestException(
             f"search type '{search_type}' not supported")
     memberships = self.service.search(search_type, search_id)
     return {'memberships': [m.to_response() for m in memberships]}
Example #28
0
def receive_sensor(request: Request):
    request_json = request.get_json(silent=True)
    print(request.headers)
    print(request_json)

    publisher = pubsub_v1.PublisherClient()
    topic_path = publisher.topic_path(PROJECT_ID, TOPIC_ID)
    publisher.publish(topic_path, json.dumps(request_json).encode("utf-8"))
    return f'send temperature {request_json}!'
Example #29
0
def calculate_cost(request: Request):
    param = request.get_json()
    imo_no = param['imo_no']
    map_size = param.get("map_size", (1000, 2000))

    route_df = read_ship_voyage_data(imo_no)
    grid = HexGrid(*map_size)

    sparse_matrix = generate_layer_by_counting(route_df, grid)
    return sparse2dict(sparse_matrix), 200
Example #30
0
    def _has_valid_als_opts(request_obj: Request) -> bool:
        try:
            als_opts = request_obj.get_json()['als_opts']
        except (BadRequest, KeyError):
            return False

        required_keys = ('rank_opts', 'reg_param_opts', 'max_iter_opts')

        for key in required_keys:
            assert key in als_opts.keys()
            assert isinstance(als_opts[key], list)
Example #31
0
def res_post(uid: str):
    if exist_post(uid):
        if not Request.get_json(request):
            apo_post = post_factory(uid)
            apo_post.apothanasia()
            return Response(
                json.dumps(vars(apo_post), default=support_datetime_default),
                200)

        req = Request.get_json(request)
        tmp_post = response_post.ResponsePost(
            link=uid,
            content=req['content'],
            password=req['password']
            if 'password' in Request.get_json(request) else '',
            lang=req['lang'] if 'lang' in Request.get_json(request) else 'und')
        tmp_post.post_contribution()

        return Response(
            json.dumps(vars(tmp_post), default=support_datetime_default), 200)
Example #32
0
 def post_google_api(self, req: Request):
     # dialog_fulfillment = DialogflowRequest(req.data)
     # print(dialog_fulfillment.get_intent_name())
     # request = req.get_json()
     # responseId = request['responseId']
     # print("this is my response ID")
     # print(responseId)
     # print("this is my req to the google api ")
     # print(request)
     self.format_response()
     return jsonify({'res': req.get_json()})
Example #33
0
    def _request_json(cls, request: Request) -> dict:
        """Parse request body as JSON, or raise BadRequest error

        :param req: the HTTP request
        :return: a dict containing the parsed JSON
        :raise: BadRequest when the request mimetype isn't application/json or the request body can't be parsed as JSON
        """
        json_dict = request.get_json()
        if not json_dict:
            raise BadRequest('mimetype must be application/json and body must be parseable JSON')
        return json_dict