Esempio n. 1
0
    def delete(self, event_handle):
        """
        Function for deleting event information. Returns 204 for
        successful delete, error responses for failed attemps.

        : param str event_handle: url base of the venue
        """

        event_item = Event.query.filter_by(url=event_handle).first()
        if event_item is None:
            return create_error_response(
                404, "Event not found",
                "The API can not find the Event requested.")

        try:
            db.session.delete(event_item)
            db.session.commit()
            return Response(status=204)
        except Exception as e:
            print(e)
            print("Event cannot be deleted. Rolling back")
            db.session.rollback()
            return create_error_response(
                400, "Database operation failed",
                "Product cannot be deleted. Rolling back.")
Esempio n. 2
0
    def put(self, event_handle):
        """
        Function for editing event information. Gets values from Request:
        name, description, startTime, organizer, venue and city.
        Returns 204 with location header for successful edit and
        error responses for failed edits.

        : param str event_handle: url base of the venue
        """

        event_item = Event.query.filter_by(url=event_handle).first()
        if event_item is None:
            return create_error_response(
                404, "Event not found",
                "The API can not find the Event requested.")

        try:
            json.loads(str(request.json).replace("\'", "\""))
        except (TypeError, ValueError) as e:
            return create_error_response(415, "Not JSON",
                                         "Request content type must be JSON")

        try:
            req = request.json
            new_name = get_value_for('name', req)
            new_description = get_value_for('description', req)
            new_time = get_value_for('startTime', req)

        except KeyError:
            return create_error_response(
                400, "Incomplete request",
                "Incomplete request - missing fields")

        event_item.name = new_name
        event_item.description = new_description
        event_item.startTime = datetime.strptime(new_time, '%Y-%m-%dT%H:%M:%S')
        event_item.set_url()

        evs = Event.query.filter_by(url=event_item.url).all()
        if evs is not None:
            for e in evs:
                print(e)
            if len(evs) > 1 or evs[0] is not event_item:
                return create_error_response(
                    409, "Event already exist",
                    "Event with same name, venue and time already exists.")

        try:
            db.session.commit()
            resp = Response(status=204)
            resp.headers['Location'] = url_for('api.eventitem',
                                               event_handle=event_item.url)
            resp.headers['Access-Control-Expose-Headers'] = 'Location'
            return resp
        except Exception as e:
            print(e)
            print("New event cannot be added to database. Rolling back.")
            db.session.rollback()
Esempio n. 3
0
    def put(self, organizer_handle):
        """
        Function for editing organizer information. Gets values from Request:
        organizer name, email and password.
        
        Returns 204 with location header for successful edit and
        error responses for failed edits.

        : param str organizer_handle: organizer name
        """

        organizer_item = Organizer.query.filter_by(
            name=organizer_handle).first()
        if organizer_item is None:
            return create_error_response(
                404, "Organizer not found",
                "The API can not find the Organizer requested.")

        try:
            json.loads(str(request.json).replace("\'", "\""))
        except (TypeError, ValueError) as e:
            return create_error_response(415, "Not JSON",
                                         "Request content type must be JSON")

        try:
            req = request.json
            new_name = get_value_for('name', req)
            new_email = get_value_for('email', req)
            new_password = get_value_for('password', req)
            oldorg = Organizer.query.filter_by(email=new_email).all()
            if len(oldorg) > 0:
                if len(oldorg) > 1 or oldorg[0] is not organizer_item:
                    return create_error_response(
                        409, "Organizer email reserved",
                        "Proposed new email already taken by another user.")

        except KeyError:
            return create_error_response(
                400, "Incomplete request",
                "Incomplete request - missing fields")

        try:
            organizer_item.name = new_name
            organizer_item.email = new_email
            organizer_item.password = new_password
            db.session.commit()
            resp = Response(status=204)
            resp.headers['Location'] = url_for(
                'api.organizeritem', organizer_handle=organizer_item.name)
            resp.headers['Access-Control-Expose-Headers'] = 'Location'
            return resp
        except Exception as e:
            print(e)
            print(
                "Organizer information cannot be updated in database. Rolling back."
            )
            db.session.rollback()
Esempio n. 4
0
    def post(self, cityhandle):
        """
        Adds a new venue to database. In real life, this requires admin token,
        which is not implemented here. Reads json information from request
        object: venuename and venueurl

        : param str cityhandle: name of the city to add venue in
        """

        city_item = City.query.filter_by(name=cityhandle).first()
        if city_item is None:
            return create_error_response(
                404, "City not found",
                "The API can not find the City requested.")

        try:
            json.loads(str(request.json).replace("\'", "\""))
        except (TypeError, ValueError) as e:
            return create_error_response(415, "Not JSON",
                                         "Request content type must be JSON")

        try:
            req = request.json
            venuename = get_value_for('name', req)
            venueurl = get_value_for('url', req)

            if Venue.query.filter_by(name=venuename,
                                     city_id=city_item.id).first() is not None:
                return create_error_response(
                    409, "Venue already exists",
                    "The venue with the given name already exists is this city."
                )

        except KeyError:
            return create_error_response(
                400, "Incomplete request",
                "Incomplete request - missing fields")

        new_venue = Venue()
        new_venue.name = venuename
        new_venue.url = venueurl
        new_venue.city_id = city_item.id
        try:
            db.session.add(new_venue)
            db.session.commit()
            resp = Response(status=201)
            resp.headers['Location'] = url_for('api.venueitem',
                                               cityhandle=city_item.name,
                                               venue_handle=new_venue.name)
            resp.headers['Access-Control-Expose-Headers'] = 'Location'
            return resp
        except Exception as e:
            print(e)
            print("New venue cannot be added to database. Rolling back.")
            db.session.rollback()
Esempio n. 5
0
    def put(self, cityhandle):
        """
        Function for editing city information. Gets values from Request,
        returns 204 with location header for successful edit and
        error messages for failed edits.

        : param str cityhandle: Handle, ie. name of the city
        """

        col = CollectionBuilder()
        col.create_collection(CITY_COLLECTION_URL)

        try:
            json.loads(str(request.json).replace("\'", "\""))
        except (TypeError, ValueError) as e:
            return create_error_response(415, "Not JSON",
                                         "Request content type must be JSON")
        #except:
        #    return create_error_response(415, "Not JSON",
        #                     "Request content type must be JSON")

        try:
            req = request.json
            cityname = get_value_for('name', req)
            city_with_same_name = City.query.filter_by(name=cityname).first()
            oldcity = City.query.filter_by(name=cityhandle).first()
            if city_with_same_name is not None and city_with_same_name is not oldcity:
                return create_error_response(
                    409, "City name exists",
                    "Trying to assign city a name that is already a name of another city."
                )
            if oldcity is None:
                return create_error_response(
                    404, "City does not exist",
                    "The API can not find the City requested.")

        except KeyError:
            return create_error_response(
                400, "Incomplete request",
                "Incomplete request - missing fields")

        try:
            oldcity.name = cityname
            db.session.commit()
            resp = Response(status=204)
            resp.headers['Location'] = url_for('api.cityitem',
                                               cityhandle=cityname)
            resp.headers['Access-Control-Expose-Headers'] = 'Location'
            return resp
        except Exception as e:
            print(e)
            print("New city cannot be added to database. Rolling back.")
            db.session.rollback()
Esempio n. 6
0
    def get(self, cityhandle):
        """
        Creates a response object for GET requests

        : param str cityhandle: Handle, ie. name of the city
        """

        col = CollectionBuilder()
        col_links = []
        col_links.append(
            col.create_link("profile", PROFILE_URL, "Link to profile"))
        col.create_collection(url_for("api.citycollection"), col_links)

        city_item = City.query.filter_by(name=cityhandle).first()
        if city_item is None:
            return create_error_response(
                404, "City not found",
                "The API can not find the City requested.")

        citydata = col.create_data("name", city_item.name, prompt="City name")
        citylinks = col.create_link(
            "venues-in",
            (url_for("api.venuecollection", cityhandle=city_item.name)),
            "Venues in City")

        col.add_item(url_for("api.cityitem", cityhandle=city_item.name),
                     [citydata], [citylinks])

        templatedata = col.create_data("name", city_item.name,
                                       "Name of the City")
        col.add_template_data(templatedata)

        return Response(json.dumps(col), 200, mimetype=MIMETYPE)
Esempio n. 7
0
    def post(self):
        """
        Adds a new city to database. In real life, this requires admin token,
        which is not implemented here. Reads json information from request
        object.
        """

        col = CollectionBuilder()
        col.create_collection(url_for("api.citycollection"))

        try:
            json.loads(str(request.json).replace("\'", "\""))
        except (TypeError, ValueError) as e:
            return create_error_response(415, "Not JSON",
                                         "Request content type must be JSON")
        #except:
        #    return create_error_response(415, "Not JSON",
        #                     "Request content type must be JSON")

        try:
            req = request.json
            cityname = get_value_for('name', req)
            if City.query.filter_by(name=cityname).first() is not None:
                return create_error_response(
                    409, "City already exists",
                    "The city name given already exists")

        except KeyError:
            return create_error_response(
                400, "Incomplete request",
                "Incomplete request - missing fields")

        new_city = City()
        new_city.name = cityname
        try:
            db.session.add(new_city)
            db.session.commit()
            resp = Response(status=201)
            resp.headers['Location'] = url_for('api.cityitem',
                                               cityhandle=new_city.name)
            resp.headers['Access-Control-Expose-Headers'] = 'Location'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            return resp
        except Exception as e:
            print(e)
            print("New city cannot be added to database. Rolling back.")
            db.session.rollback()
Esempio n. 8
0
    def get(self, cityhandle):
        """
        Creates a response object for GET requests, exposing
        venues of a given city.
        
        :param str cityhandle: name of the city
        """

        print(request.headers)

        city_item = City.query.filter_by(name=cityhandle).first()
        if city_item is None:
            return create_error_response(
                404, "City not found",
                "The API can not find the City requested.")

        col = CollectionBuilder()
        col_links = []
        col_links.append(
            col.create_link("profile", PROFILE_URL, "Link to profile"))
        col_links.append(
            col.create_link("up",
                            url_for("api.cityitem", cityhandle=city_item.name),
                            "City"))

        col.create_collection(
            url_for("api.venuecollection", cityhandle=city_item.name),
            col_links)

        print(type(Venue))
        venues = Venue.query.filter_by(city_id=city_item.id)

        for venue_item in venues:
            venuedata = []
            venuedata.append(
                col.create_data("name", venue_item.name, prompt="Venue name"))

            venuedata.append(
                col.create_data("url", venue_item.url, prompt="Venue URL"))

            venuelinks = []
            venuelinks.append(
                col.create_link(
                    "events-in",
                    url_for("api.venueevents",
                            cityhandle=city_item.name,
                            venue_handle=venue_item.name), "Events in City"))

            col.add_item(
                url_for("api.venueitem",
                        cityhandle=city_item.name,
                        venue_handle=venue_item.name), venuedata, venuelinks)

        col.add_template_data(col.create_data("name", "", "Name of the Venue"))
        col.add_template_data(col.create_data("url", "", "URI of the Venue"))

        return Response(json.dumps(col), 200, mimetype=MIMETYPE)
Esempio n. 9
0
    def get(self, organizer_handle):
        """
        Creates a response object for GET requests and error 
        responses for failed attempts.

        : param str organizer_handle: organizer name
        """

        organizer_item = Organizer.query.filter_by(
            name=organizer_handle).first()
        if organizer_item is None:
            return create_error_response(
                404, "Organizer not found",
                "The API can not find the Organizer with the given identifier."
            )

        col = CollectionBuilder()
        col_links = []
        col_links.append(
            col.create_link("profile", PROFILE_URL, "Link to profile"))
        col.create_collection(
            url_for("api.organizeritem", organizer_handle=organizer_item.name),
            col_links)

        organizerdata = []
        organizerdata.append(
            col.create_data("name", organizer_item.name, "Organizer name"))
        organizerdata.append(
            col.create_data("email", organizer_item.email, "Organizer email"))

        organizerlinks = []
        organizerlinks.append(
            col.create_link(
                "events-by",
                url_for("api.organizerevents",
                        organizer_handle=organizer_item.name),
                "Events by this organizer"))

        col.add_item(
            url_for("api.organizeritem", organizer_handle=organizer_item.name),
            organizerdata, organizerlinks)

        col.add_template_data(
            col.create_data("name", organizer_item.name, "Organizer name"))
        col.add_template_data(
            col.create_data("email", organizer_item.email, "Organizer email"))
        col.add_template_data(
            col.create_data("password", "", "Organizer password"))

        return Response(json.dumps(col), 200, mimetype=MIMETYPE)
Esempio n. 10
0
    def put(self, cityhandle, venue_handle):
        """
        Function for editing venue information. Gets values from Request:
        venue name and venue url.
        returns 204 with location header for successful edit and
        error messages for failed edits.

        : param str cityhandle: name of the city
        : param str venue_handle: name of the venue
        """

        city_item = City.query.filter_by(name=cityhandle).first()
        if city_item is None:
            return create_error_response(
                404, "City not found",
                "The API can not find the City requested.")

        try:
            json.loads(str(request.json).replace("\'", "\""))
        except (TypeError, ValueError) as e:
            return create_error_response(415, "Not JSON",
                                         "Request content type must be JSON")

        try:
            req = request.json
            new_name = get_value_for('name', req)
            new_url = get_value_for('url', req)

            venue_with_same_name = Venue.query.filter_by(
                name=new_name, city_id=city_item.id).first()
            oldvenue = Venue.query.filter_by(name=venue_handle,
                                             city_id=city_item.id).first()
            if venue_with_same_name is not None and venue_with_same_name is not oldvenue:
                return create_error_response(
                    409, "Venue name exists",
                    "Trying to assign venue a name that is already a name of another venue in the same city."
                )
            if oldvenue is None:
                return create_error_response(
                    404, "Venue does not exist",
                    "The API can not find the Venue in the City requested.")

        except KeyError:
            return create_error_response(
                400, "Incomplete request",
                "Incomplete request - missing fields")

        try:
            oldvenue.name = new_name
            oldvenue.url = new_url
            db.session.commit()
            resp = Response(status=204)
            resp.headers['Location'] = url_for('api.venueitem',
                                               cityhandle=city_item.name,
                                               venue_handle=oldvenue.name)
            resp.headers['Access-Control-Expose-Headers'] = 'Location'
            return resp
        except Exception as e:
            print(e)
            print("New venue cannot be added to database. Rolling back.")
            db.session.rollback()
Esempio n. 11
0
    def get(self, cityhandle, venue_handle):
        """
        Creates a response object for GET requests and error responses
        for failed requests.

        : param str cityhandle: name of the city
        : param str venue_handle: name of the venue
        """

        city_item = City.query.filter_by(name=cityhandle).first()
        if city_item is None:
            return create_error_response(
                404, "City not found",
                "The API can not find the City requested.")

        col = CollectionBuilder()

        col_links = []
        col_links.append(
            col.create_link("profile", PROFILE_URL, "Link to profile"))
        col_links.append(
            col.create_link(
                "up", url_for("api.venuecollection",
                              cityhandle=city_item.name), "City"))

        col.create_collection(
            url_for("api.venuecollection", cityhandle=city_item.name),
            col_links)

        venue_item = Venue.query.filter_by(name=venue_handle,
                                           city_id=city_item.id).first()
        if venue_item is None:
            return create_error_response(
                404, "Venue not found",
                "The API can not find the Venue with the given name in this city."
            )

        venuedata = []
        venuedata.append(
            col.create_data("name", venue_item.name, prompt="Venue name"))

        venuedata.append(
            col.create_data("url", venue_item.url, prompt="Venue URL"))

        venuelinks = []
        venuelinks.append(
            col.create_link(
                "events-in",
                url_for("api.venueevents",
                        cityhandle=city_item.name,
                        venue_handle=venue_item.name), "Events on this venue"))

        col.add_item(
            url_for("api.venueitem",
                    cityhandle=city_item.name,
                    venue_handle=venue_item.name), venuedata, venuelinks)

        col.add_template_data(
            col.create_data("name", venue_item.name, "Name of the Venue"))
        col.add_template_data(
            col.create_data("url", venue_item.url, "URI of the Venue"))

        return Response(json.dumps(col), 200, mimetype=MIMETYPE)
Esempio n. 12
0
    def get(self, event_handle):
        """
        Creates a response object for GET requests

        : param str event_handle: URI base of the event (autoformatted from name, venue and time)
        """

        event_item = Event.query.filter_by(url=event_handle).first()
        if event_item is None:
            return create_error_response(
                404, "Event not found",
                "The API can not find the Event with the given identifier.")

        col = CollectionBuilder()
        col_links = []
        col_links.append(
            col.create_link("profile", PROFILE_URL, "Link to profile"))
        col.create_collection(url_for("api.eventcollection"), col_links)

        eventdata = []
        eventdata.append(col.create_data("name", event_item.name,
                                         "Event name"))
        eventdata.append(
            col.create_data("description", event_item.description,
                            "Event description"))
        eventdata.append(
            col.create_data("organizer", event_item.organizer.name,
                            "Organizer of the Event"))
        eventdata.append(
            col.create_data("venue", event_item.venue.name,
                            "Venue of the Event"))
        eventdata.append(
            col.create_data("venue_url", event_item.venue.url, "Venue URL"))
        eventdata.append(
            col.create_data("startTime", event_item.startTime.isoformat(),
                            "Start time of the Event"))
        eventdata.append(
            col.create_data("category", event_item.category.name,
                            "Category of the Event"))

        eventlinks = []
        eventlinks.append(
            col.create_link("collection", url_for("api.eventcollection"),
                            "All events"))
        eventlinks.append(
            col.create_link(
                "in-venue",
                url_for("api.venueitem",
                        venue_handle=event_item.venue.name,
                        cityhandle=event_item.venue.city.name), "Venue"))
        eventlinks.append(
            col.create_link(
                "organized-by",
                url_for("api.organizerevents",
                        organizer_handle=event_item.organizer.name),
                "Organizer's other events"))
        # eventlinks.append(col.create_link("in-city", up, up_prompt))
        # eventlinks.append(col.create_link("in-category", up, up_prompt))
        # City-based Events and Categories not implemented yet

        col.add_item(url_for("api.eventitem", event_handle=event_item.url),
                     eventdata, eventlinks)

        col.add_template_data(
            col.create_data("name", event_item.name, "Event name"))
        col.add_template_data(
            col.create_data("description", event_item.description,
                            "Event description"))
        col.add_template_data(
            col.create_data("startTime", event_item.startTime.isoformat(),
                            "Start time of the Event"))
        #col.add_template_data(col.create_data("organizer", event_item.organizer.name, "Organizer of the Event"))
        #col.add_template_data(col.create_data("venue", event_item.venue.name, "Venue of the Event"))
        #col.add_template_data(col.create_data("city", event_item.venue.city.name, "City of the Event"))

        print(col)
        return Response(json.dumps(col), 200, mimetype=MIMETYPE)
Esempio n. 13
0
    def get(self, cityhandle=None, venue_handle=None, organizer_handle=None):
        """
        Creates a response object for GET requests

        :param str cityhandle: city name
        :param str venue_handle: venue name
        :param str organizer_handle: organizer name
        """

        # Initialize things in case Events for Venue are requested
        if cityhandle and venue_handle:

            city_item = City.query.filter_by(name=cityhandle).first()
            if city_item is None:
                return create_error_response(
                    404, "City not found",
                    "The API can not find the City requested.")

            venue_item = Venue.query.filter_by(name=venue_handle,
                                               city_id=city_item.id).first()
            if venue_item is None:
                return create_error_response(
                    404, "Venue not found",
                    "The API can not find the Venue in this City.")

            collection_url = url_for("api.venueevents",
                                     venue_handle=venue_item.name,
                                     cityhandle=city_item.name)
            up = url_for("api.venueitem",
                         venue_handle=venue_item.name,
                         cityhandle=city_item.name)
            up_prompt = "Venue"
            events = Event.query.filter_by(venue_id=venue_item.id)

        # Initialize things in case Events for Organizer are requested
        elif organizer_handle:
            is_organizer_collection = True

            organizer_item = Organizer.query.filter_by(
                name=organizer_handle).first()
            if organizer_item is None:
                return create_error_response(
                    404, "Organizer not found",
                    "The API can not find the Organizer requested.")

            up = url_for("api.organizeritem",
                         organizer_handle=organizer_item.name)
            collection_url = url_for("api.organizerevents",
                                     organizer_handle=organizer_item.name)
            up_prompt = "Organizer"
            events = Event.query.filter_by(organizer_id=organizer_item.id)

        # Initialize things if general Event collection is requested
        else:
            up = url_for("api.eventcollection")
            up_prompt = "All events"
            collection_url = url_for("api.eventcollection")
            events = Event.query.all()

        col = CollectionBuilder()
        col_links = []
        col_links.append(
            col.create_link("profile", PROFILE_URL, "Link to profile"))
        col_links.append(col.create_link("up", up, up_prompt))

        col.create_collection(collection_url, col_links)

        for event_item in events:
            eventdata = []
            eventdata.append(
                col.create_data("name", event_item.name, "Event name"))
            eventdata.append(
                col.create_data("description", event_item.description,
                                "Event description"))
            eventdata.append(
                col.create_data("organizer", event_item.organizer.name,
                                "Organizer of the Event"))
            eventdata.append(
                col.create_data("venue", event_item.venue.name,
                                "Venue of the Event"))
            eventdata.append(
                col.create_data("venue_url", event_item.venue.url,
                                "Venue URL"))
            eventdata.append(
                col.create_data("startTime", event_item.startTime.isoformat(),
                                "Start time of the Event"))
            eventdata.append(
                col.create_data("category", event_item.category.name,
                                "Category of the Event"))

            eventlinks = []
            eventlinks.append(col.create_link("up", up, up_prompt))

            col.add_item(url_for("api.eventitem", event_handle=event_item.url),
                         eventdata, eventlinks)

        col.add_template_data(col.create_data("name", "", "Event name"))
        col.add_template_data(
            col.create_data("description", "", "Event description"))
        col.add_template_data(
            col.create_data("startTime", "", "Start time of the Event"))
        col.add_template_data(
            col.create_data("organizer", "", "Organizer of the Event"))
        col.add_template_data(
            col.create_data("venue", "", "Venue of the Event"))
        col.add_template_data(col.create_data("city", "", "City of the Event"))

        return Response(json.dumps(col), 200, mimetype=MIMETYPE)
Esempio n. 14
0
    def post(self):
        """
        Adds a new event to database. Reads json information from request
        object: name, description, venue, city, organizer and startTime
        """

        try:
            json.loads(str(request.json).replace("\'", "\""))
        except (TypeError, ValueError) as e:
            return create_error_response(415, "Not JSON",
                                         "Request content type must be JSON")

        try:
            req = request.json
            eventname = get_value_for('name', req)
            eventdesc = get_value_for('description', req)
            venuename = get_value_for('venue', req)
            cityname = get_value_for('city', req)
            organizername = get_value_for('organizer', req)
            starttime_string = get_value_for('startTime', req)

            try:
                starttime = datetime.strptime(starttime_string,
                                              '%Y-%m-%dT%H:%M:%S')
            except ValueError:
                return create_error_response(
                    400, "Wrong time format",
                    "Time was passed in wrong format")

            # Category is not implemented. Using just on category for all
            category = Category.query.first()
            if category is None:
                return create_error_response(
                    404, "Category not found",
                    "Client is trying to add an event to Category that does not exist."
                )

            city = City.query.filter_by(name=cityname).first()
            venue = Venue.query.filter_by(name=venuename,
                                          city_id=city.id).first()
            if venue is None:
                return create_error_response(
                    404, "City or Venue not found",
                    "Client is trying to add an event to City or Venue that cannot be found."
                )

            organizer = Organizer.query.filter_by(name=organizername).first()
            if organizer is None:
                return create_error_response(
                    404, "Organizer not found",
                    "Client is trying to add Event to organizer that cannot be found."
                )

        except KeyError:
            return create_error_response(
                400, "Incomplete request",
                "Incomplete request - missing fields")

        newevent = Event()
        newevent.name = eventname
        newevent.description = eventdesc
        newevent.startTime = starttime
        newevent.venue = venue
        newevent.organizer = organizer
        newevent.category = category

        newevent.set_url()

        if Event.query.filter_by(url=newevent.url).first() is not None:
            return create_error_response(
                409, "Event already exist",
                "Event with same name, venue and time already exists.")

        try:
            db.session.add(newevent)
            db.session.commit()
            resp = Response(status=201)
            resp.headers['Location'] = url_for('api.eventitem',
                                               event_handle=newevent.url)
            resp.headers['Access-Control-Expose-Headers'] = 'Location'
            return resp
        except:
            print("Commit failed. Rolling back.")
            db.session.rollback()