Exemplo n.º 1
0
    def get(self):
        if not request_wants_json():
            abort(400, message="request needs JSON")
        parser = reqparse.RequestParser()
        parser.add_argument('lon', type=float, required=True, location='args')
        parser.add_argument('lat', type=float, required=True, location='args')
        try:
            args = parser.parse_args()
        except BadRequest as e:
            return json.dumps(e.data), 400, {
                "Content-Type": "application/json"
            }

        cur = current_app.extensions['sqlalchemy'].db.session.connection()\
                .connection.cursor(cursor_factory=RealDictCursor)
        cur.execute(
            """SELECT active, nom, insee FROM "ZUPC"
            WHERE ST_Intersects(shape, ST_POINT(%s, %s)::geography)""",
            (args['lon'], args['lat']))
        to_return = []
        ZUPC = administrative_models.ZUPC
        for zupc in cur.fetchall():
            if any(map(lambda z: zupc['insee'] == z['insee'], to_return)):
                continue
            to_return.append(
                marshal(zupc,
                        ZUPC.marshall_obj(filter_id=True, level=1, api=api)))
        return {"data": to_return}, 200
Exemplo n.º 2
0
def zupc():
    if request.method != "GET":
        abort(405, message="method now allowed")
    if request_wants_json():
        abort(400, message="bad format")
    roles_accepted = set(['admin', 'mairie', 'prefecture', 'operateur'])
    if  current_user.is_anonymous() or\
            len(roles_accepted.intersection(current_user.roles)) == 0:
        abort(403)
    page = int(request.args.get('page')) if 'page' in request.args else 1
    return render_template('lists/zupc.html',
        zupc_list=administrative_models.ZUPC.query.paginate(page))
Exemplo n.º 3
0
def get_ads_list():
    if request_wants_json():
        abort(501, message="You can't ask for JSON")
    parser = reqparse.RequestParser()
    parser.add_argument('numero', type=unicode, help=u"Numero de l'ADS", required=False,
                        location='values')
    parser.add_argument('insee', type=unicode,
            help=u"Code INSEE de la commune d\'attribution de l'ADS", required=False,
                    location='values')
    args = self.parser.parse_args()
    if args["numero"] and args["insee"]:
        return ads_details(args.get("numero"), args.get("insee"))
    else:
        return ads_list()
Exemplo n.º 4
0
 def post(self):
     if 'file' in request.files:
         filename = "ads-{}-{}.csv".format(current_user.email,
                 str(datetime.now().strftime("%Y-%m-%dT%H:%M:%S:%f")))
         documents.save(request.files['file'], name=filename)
         slack = slacker()
         if slack:
             slack.chat.post_message('#taxis-internal',
             'Un nouveau fichier ADS a été envoyé par {}. {}'.format(
                 current_user.email, filename))
         return "OK"
     elif request_wants_json():
         return self.post_json()
     abort(400, message="File is not present!")
Exemplo n.º 5
0
 def post(self):
     if 'file' in request.files:
         filename = "conducteurs-{}-{}.csv".format(current_user.email,
                 str(datetime.now()))
         documents.save(request.files['file'], name=filename)
         slack = slacker()
         if slack:
             slack.chat.post_message('#taxis',
             'Un nouveau fichier conducteurs a été envoyé par {}. {}'.format(
                 current_user.email, url_for('documents.documents',
                     filename=filename, _external=True)))
         return "OK"
     if request_wants_json():
         return self.post_json()
     abort(400, message="Unable to find file")
Exemplo n.º 6
0
 def post(self):
     if 'file' in request.files:
         filename = "ads-{}-{}.csv".format(
             current_user.email,
             str(datetime.now().strftime("%Y-%m-%dT%H:%M:%S:%f")))
         documents.save(request.files['file'], name=filename)
         slack = slacker()
         if slack:
             slack.chat.post_message(
                 '#taxis-internal',
                 'Un nouveau fichier ADS a été envoyé par {}. {}'.format(
                     current_user.email, filename))
         return "OK"
     elif request_wants_json():
         return self.post_json()
     abort(400, message="File is not present!")
Exemplo n.º 7
0
 def post(self):
     if 'file' in request.files:
         filename = "conducteurs-{}-{}.csv".format(current_user.email,
                                                   str(datetime.now()))
         documents.save(request.files['file'], name=filename)
         slack = slacker()
         if slack:
             slack.chat.post_message(
                 '#taxis',
                 'Un nouveau fichier conducteurs a été envoyé par {}. {}'.
                 format(
                     current_user.email,
                     url_for('documents.documents',
                             filename=filename,
                             _external=True)))
         return "OK"
     if request_wants_json():
         return self.post_json()
     abort(400, message="Unable to find file")
Exemplo n.º 8
0
    def get(self):
        if not request_wants_json():
            abort(400, message="request needs JSON")
        parser = reqparse.RequestParser()
        parser.add_argument('lon', type=float, required=True, location='args')
        parser.add_argument('lat', type=float, required=True, location='args')
        try:
            args = parser.parse_args()
        except BadRequest as e:
            return json.dumps(e.data), 400, {"Content-Type": "application/json"}

        zupc_list = db.session.execute(
            """SELECT insee, active, nom
               FROM "ZUPC"
               WHERE ST_INTERSECTS(shape, 'POINT(:lon :lat)')
               AND parent_id = id
               ORDER BY max_distance ASC;""",
            args).fetchall()
        to_return = []
        client = influx_db.get_client(current_app.config['INFLUXDB_TAXIS_DB'])
        for zupc in zupc_list:
            if any([zupc[0] == z['insee'] for z in to_return]):
                current_app.logger.debug("ZUPC {} already added, skipping it".format(zupc[0]))
                continue
            to_return.append({"insee": zupc[0], "active": zupc[1], "nom": zupc[2]})
            if not client:
                current_app.logger.error("No influxdb client")
                continue
            request = """SELECT "value" FROM "nb_taxis_every_1" WHERE "zupc" = '{}' AND "operator" = ''  AND time > now() - 1m  fill(null) LIMIT 1;""".format(zupc['insee'])
            try:
                r = client.query(request)
            except InfluxDBClientError as e:
                current_app.logger.error(e)
                continue
            points = list(r.get_points())
            if len(points) <= 0:
                current_app.logger.debug("No stat points found, request: \"{}\"".format(request))
                continue
            to_return[-1]['nb_active'] = points[0].get('value')
        return {"data": to_return}, 200
Exemplo n.º 9
0
    def get(self):
        if not request_wants_json():
            abort(400, message="request needs JSON")
        parser = reqparse.RequestParser()
        parser.add_argument('lon', type=float, required=True, location='args')
        parser.add_argument('lat', type=float, required=True, location='args')
        try:
            args = parser.parse_args()
        except BadRequest as e:
            return json.dumps(e.data), 400, {"Content-Type": "application/json"}

        cur = current_app.extensions['sqlalchemy'].db.session.connection()\
                .connection.cursor(cursor_factory=RealDictCursor)
        cur.execute("""SELECT active, nom, insee FROM "ZUPC"
            WHERE ST_Intersects(shape, ST_POINT(%s, %s)::geography)""",
            (args['lon'], args['lat']))
        to_return = []
        ZUPC = administrative_models.ZUPC
        for zupc in cur.fetchall():
            if any(map(lambda z: zupc['insee'] == z['insee'], to_return)):
                continue
            to_return.append(marshal(zupc, ZUPC.marshall_obj(filter_id=True,
                level=1, api=api)))
        return {"data": to_return}, 200