Ejemplo n.º 1
0
    def get(self):
        address = ""
        lat = ""
        long = ""
        id = None
        species = ""
        geohash = ""
        try:
            id = int(self.request.get("id"))
            logging.info("Got id %s", id)
        except ValueError:
            pass

        template_params = {"sighting": None}
        if id:
            template_params["sighting"] = Sighting.get_by_id(id)

        q = Sighting.all()
        all_sightings = []
        for result in q:
            all_sightings.append(result)

        template_params["all_sightings"] = all_sightings

        path = os.path.join(os.path.dirname(__file__), "templates/record_sighting_form.html")
        self.response.out.write(template.render(path, template_params))
Ejemplo n.º 2
0
def submit_edit_sighting(sighting_id):

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/user/<int:user_id>")

    sighting = Sighting.query.get_or_404(sighting_id)
    form = EditSightingForm(obj=sighting)
    user = User.query.get_or_404(g.user.id)

    if form.validate_on_submit():
        sighting.sighting_num = form.sighting_num.data
        sighting.date = form.date.data
        sighting.time = form.time.data
        sighting.latitude = form.latitude.data
        sighting.longitude = form.longitude.data
        sighting.species = form.species.data
        sighting.individuals = form.individuals.data
        user_id = f"{user.id}"

        sighting = Sighting(sighting_num=sighting.sighting_num,
                            date=sighting.date,
                            time=sighting.time,
                            latitude=sighting.latitude,
                            longitude=sighting.longitude,
                            species=sighting.species,
                            individuals=sighting.individuals,
                            user_id=user_id)

        db.session.commit()

        return redirect(f"/user/{user.id}/all")
Ejemplo n.º 3
0
def submit_sighting(user_id):

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/user/<int:user_id>")
    TO_EMAILS = [('*****@*****.**', 'Megan McManus'),
                 ('*****@*****.**', 'Megan McManus2'),
                 ('*****@*****.**', 'Neil Roper'),
                 ('*****@*****.**', 'Katie Douglas')]
    user = User.query.get_or_404(user_id)
    form = AddSightingForm()

    if form.validate_on_submit():
        sighting_num = form.sighting_num.data
        date = form.date.data
        time = form.time.data
        latitude = form.latitude.data
        longitude = form.longitude.data
        species = form.species.data
        individuals = form.individuals.data
        user_id = f"{user.id}"

        sighting = Sighting(sighting_num=sighting_num,
                            date=date,
                            time=time,
                            latitude=latitude,
                            longitude=longitude,
                            species=species,
                            individuals=individuals,
                            user_id=user_id)

        db.session.add(sighting)
        db.session.commit()

        message = Mail(
            from_email='*****@*****.**',
            to_emails=TO_EMAILS,
            is_multiple=True,
            subject=f"New Sighting Submitted by {sighting.user.user_name}",
            html_content=
            f"At {sighting.time}, {sighting.user.user_name} observed a {sighting.species} at {sighting.latitude}N, {sighting.longitude}W - Date {sighting.date}"
        )
        try:
            sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
            response = sg.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e.message)

        return redirect(f"/user/{user.id}/all")

    return render_template('new_sighting.html', form=form, user=user)
Ejemplo n.º 4
0
 def get(self):
     q = Sighting.all()
     points = []
     for result in q:
         point = {}
         if result.coords:
             point["lat"] = result.coords.lat
             point["lon"] = result.coords.lon
             point["address"] = result.address
             image = AttachedImage.gql("WHERE sighting = :1", result).get()
             if image:
                 point["thumbnail"] = "/show_image?id=%s&size=thumb" % image.key().id()
             points.append(point)
     self.response.headers["Content-Type"] = "application/json"
     self.response.out.write(simplejson.dumps(points))
Ejemplo n.º 5
0
async def sightings_post(request: Request) -> Response:
    """
    ---
    summary: Post device sighting
    description: This endpoint allows users to store sightings of devices on the local network
    tags:
    - Sightings
    produces:
    - application/json
    parameters:
    - in: body
      name: body
      schema:
        type: object
        properties:
          timestamp:
            type: integer
            format: int64
          alias:
            type: string
      description: A sighting to store in the KnockKnock backend
      required: true
    responses:
        "200":
            description: Sighting has been stored successfully, return sighting as it was persisted
        "400":
            description: Invalid ``from`` parameter or unable to parse the request body
    """
    # Try to parse the Request body.
    try:
        data = await request.json()
        sighting = Sighting(alias=data["alias"],
                            last_activity_timestamp=data["timestamp"])
    except BaseException as e:
        return Response(status=400, reason=f"Unable to parse body ({e})")

    session.add(sighting)
    session.commit()

    records = session.query(Sighting).filter(
        Sighting.id == session.query(func.max(Sighting.id)))

    return Response(status=200,
                    body=encode(records[0].to_json()),
                    content_type="application/json")
Ejemplo n.º 6
0
    def get(self):
        id = None
        try:
            id = int(self.request.get("id"))
            logging.info("Got id %s", id)
        except ValueError:
            pass
        if id:
            sighting = Sighting.get_by_id(id)
            logging.info("Got sighting %s", sighting.coords)
            images = AttachedImage.gql("WHERE sighting = :1", sighting).fetch(10, 0)

            for image in images:
                logging.info("Got image id = %s", image.key())

            template_params = {"images": images, "sighting": sighting}
        path = os.path.join(os.path.dirname(__file__), "templates/TestTemplat.html")
        self.response.out.write(template.render(path, template_params))
Ejemplo n.º 7
0
    def get(self):
        address = ""
        lat = ""
        long = ""
        id= None
        species = ""
        geohash = ""
        try:
            id = int(self.request.get('id'))
            logging.info("Got id %s", id);
        except ValueError:
            pass

        if id:
            #key = db.Key.from_path('Sighting', id)
            #logging.info("Got key %s", key);
            #logging.info("Got key id %s", key.id());
            sighting = Sighting.get_by_id(id)
            logging.info("Got sighting %s", sighting.coords);
            
            address = sighting.address
            if sighting.coords:
                lat = sighting.coords.lat
                long = sighting.coords.lon
            geohash = sighting.geohash
            logging.info("Got geohash %s", geohash);
            species = str(sighting.species)

        self.response.out.write('''
        <html>
            <head>
            <title>Record a new sighting...</title>


            </head>
            <body onload="initialize()">
            <form action = "record_sighting" enctype="multipart/form-data" method = "POST">
            Species: <input name = "species" type = "text" value = "%s"/><br>
            Address: <input name = "address" type = "text" value = "%s"/><br>
            geohash: <input disabled name = "geohash" type = "text" value = "%s"/><br>
            Lat: <input disabled name = "lat"  type = "text" value = "%s"/><br>
            long: <input disabled name = "long" type = "text" value = "%s" /><br>
            image: <input type="file" name="img"/><br>
            comment: <input type="textarea" name="comment"/><br>
            submit: <input name  = "save" type = "submit"/><br>

            </form>
         </body>
        </html>
        ''' % (species, address, geohash,lat, long))

        self.response.out.write("<table>");
        q = Sighting.all()
        points = []
        for result in q:
            point = {}
            if result.coords:
                point['lat'] = result.coords.lat
                point['lon'] = result.coords.lon
                point['address'] = result.address
                points.append(point)
                self.response.out.write("<tr><td><a href='/view_sighting?id=%s'>%s</a>(%s, %s) %s</td></tr>" % (result.key().id(),result.address, result.coords.lat, result.coords.lon, result.geohash))
        self.response.out.write("</table>");