Beispiel #1
0
def get_api_doppelganger(album):
    clusters = Photo.get_similar_photos(current_user, album)
    similar = []
    for cluster in clusters:
        for p in cluster:
            photo = Photo.get(current_user, p['id'])
            similar.append(photo.__dict__)
    return json.dumps(similar)
    def get(self):

        photo_query = Photo.query()
        photos = photo_query.fetch()
        photo_list = []

        for photo in photos:
            url = photo.url
            lat = photo.lat
            lon = photo.lon
            stream_id = photo.stream_id

            geopoint = search.GeoPoint(lat, lon)
            search_index = search.Document(doc_id=url,
                                           fields=[
                                               search.TextField(name='url',
                                                                value=url),
                                               search.TextField(
                                                   name='stream_id',
                                                   value=str(stream_id)),
                                               search.GeoField(name='geopoint',
                                                               value=geopoint)
                                           ])
            result = search.Index(name='photo').put(search_index)
            photo_list.append({
                'stream_id': stream_id,
                'url': url,
                'lat': lat,
                'lon': lon
            })

        self.response.out.write(json.dumps(photo_list))
Beispiel #3
0
    def get(self):
        stream_id = int(self.request.get('id'))
        min_date = int(self.request.get('min'))
        max_date = int(self.request.get('max'))

        days_to_subtract = 365 - max_date
        formatted_date_max = datetime.today() - timedelta(
            days=days_to_subtract)

        days_to_subtract = 365 - min_date
        formatted_date_min = datetime.today() - timedelta(
            days=days_to_subtract)

        self.response.headers['Content-Type'] = 'application/json'
        photos = Photo.query(Photo.stream_id == stream_id,
                             Photo.date <= formatted_date_max,
                             Photo.date >= formatted_date_min).fetch()

        photos_data = []
        if photos != None:
            for photo in photos:
                photo_data = {
                    'url': photo.get_url(),
                    'lat': photo.get_lat(),
                    'lon': photo.get_lon()
                }
                photos_data.append(photo_data)

        else:
            photos_data = None

        self.response.out.write(json.dumps(photos_data))
Beispiel #4
0
    def get(self):
        stream_id = int(self.request.get('id'))
        offset = int(self.request.get('offset'))
        limit = int(self.request.get('limit'))

        self.response.headers['Content-Type'] = 'application/json'
        stream = Stream.get_by_id(stream_id)
        photos = Photo.query(Photo.stream_id == stream_id)
        now = datetime.datetime.now()

        if stream != None and photos != None:
            if not stream.views:
                stream.views = 0

            if not stream.views_list:
                stream.views_list = []

            stream.views = stream.views + 1
            stream.views_list.insert(0, now)
            stream.put()
            photos_urls = []
            for photo in photos.fetch(limit, offset=offset):
                photos_urls.append(photo.get_url())
            stream_data = {
                'id': stream.key.id(),
                'name': stream.name,
                'cover_url': stream.cover_url,
                'tags': stream.tags,
                'photos': photos_urls
            }
        else:
            stream_data = {'id': None}

        self.response.out.write(json.dumps(stream_data))
Beispiel #5
0
    def setUp(self):
        self.europe = Continent("Europe", 2)
        self.scotland = Country("Scotland", self.europe, 1)
        self.iceland = Country("Iceland", self.europe, 3)

        self.glencoe = Location("Glencoe",
                                "This is stunning location, i need to see it",
                                False, self.scotland, 1)
        self.godafoss = Location(
            "Godafoss", "The most amazing waterfall i have ever seen", True,
            self.iceland, 2)

        self.glencoe_photo = Photo("devils_pulpit.jpg", True, self.glencoe, 1)
        self.godafoss_photo_01 = Photo("marina_sands01.jpg", True,
                                       self.godafoss, 2)
        self.godafoss_photo_02 = Photo("marina_sands01.jpg", True,
                                       self.godafoss)
Beispiel #6
0
def post_api_photos():
    photo = Photo.create(current_user, request.json['album'],
                         request.json['hash'], request.json['filename'],
                         request.json['exif_datetime'])
    file_name, file_extension = os.path.splitext(request.json['filename'])
    new_object = str(current_user.id) + "/original/" + request.json[
        'hash'][:2] + "/" + request.json['hash'] + file_extension
    q.enqueue(process_photo, FOTRINO_MINIO_BUCKET, new_object, photo.id)
    return json.dumps(photo.__dict__)
Beispiel #7
0
def get_api_photos_shared(album_uuid):
    try:
        photos = Photo.get_shared_photos(album_uuid)
    except ValueError as error:
        return error.args[0], 400
    return json.dumps([i.__dict__ for i in photos],
                      indent=4,
                      sort_keys=True,
                      default=str)
Beispiel #8
0
def put_api_photos():
    for new_photo in request.json:
        photo = Photo.get(current_user, new_photo['id'])
        try:
            photo = photo.update(current_user, new_photo['album'],
                                 new_photo['flag'], new_photo['exif_datetime'])
        except ValueError as error:
            return error.args[0], 400
    return json.dumps(photo.__dict__)
Beispiel #9
0
    def get(self):
        restid = request.args.get('id')
        rests = Rest.get_rest_object(restid)
        pics = Photo.get_rest_pics(restid)
        reviews = Review.get_rest_reviews(restid)

        for review in reviews:
            review.menu = Course.get_courses(review.revid)

        return render_template('rest_index.html', pics=pics, reviews=reviews, rests=rests)
def select(id):
    # create sql query without values
    sql = "SELECT * FROM photos WHERE id = %s"
    # create list with values required by sql query
    values = [id]
    # execute sql query
    result = run_sql(sql, values)[0]
    # convert return which is a single element list of dictionaries into a continent object
    photo = Photo(result["filename"], result["mine"], location_repository.select(result['location_id']),result["id"]) 
    # return the result 
    return photo
Beispiel #11
0
def put_api_photos_preupload():
    presigned_put_url = None
    description = None
    allowed = Photo.allowed_file(request.json['filename'])
    if not allowed:
        description = "Unsupported file type."
    if allowed:
        exists = Photo.exists(current_user, request.json['hash'])
        if exists:
            description = "Previously uploaded"
    filtered = (not allowed or exists)
    if not filtered:
        presigned_put_url = Photo.get_presigned_put_url(
            current_user, request.json['hash'], request.json['filename'])
    return json.dumps({
        "filename": request.json['filename'],
        "hash": request.json['hash'],
        "valid": not filtered,
        "description": description,
        "presigned_put_url": presigned_put_url
    })
Beispiel #12
0
    def valid(self):
        errors = []

        if not self.name:
            errors.append("recipe name cannot be blank")
        if len(self.name) > 128:
            errors.append("recipe name is too long")
        if len(self.servings) > 128:
            errors.append("servings text is too long")
        if len(self.preparation_time) > 128:
            errors.append("preparation time text is too long")

        if self.upload_file.filename and not Photo.allowed_file(self.upload_file):
            errors.append("image must be .png .jpg or .jpeg")

        for category_name in self.category_names:
            if not category_name:
                errors.append("all category names should be set")
            if len(category_name) > 128:
                errors.append("category name is too long")

        for ingredient in self.ingredients:
            if len(ingredient.name) == 0:
                errors.append("ingredient name cannot be blank")
            elif len(ingredient.name) > 128:
                errors.append("ingredient name is too long")
            if len(ingredient.quantity) > 128:
                errors.append("ingredient quantity is too long")
            if len(ingredient.unit) > 128:
                errors.append("ingredient unit is too long")
            if len(ingredient.comment) > 128:
                errors.append("ingredient comment is too long")

        if len(self.ingredients) == 0:
            errors.append("must have at least one ingredient")

        for step in self.steps:
            if len(step.instructions) == 0:
                errors.append("instructions cannot be blank")
            elif len(step.instructions) > 500:
                errors.append("instructions of a single step are too long")

        if len(self.steps) == 0:
            errors.append("must have at least one instruction step")

        errors = list(set(errors))
        if len(errors) > 0:
            self.error_message = ", ".join(errors)
        else:
            self.error_message = ""

        return len(errors) == 0
Beispiel #13
0
    def post(self):

        json_string = self.request.body
        dict_object = json.loads(json_string)

        url = dict_object['url']
        stream_id = dict_object['stream_id']
        lat = dict_object['lat']
        lon = dict_object['lon']

        photo_result = Photo.from_url(url)
        
        if not photo_result: 
	        photo = Photo(url=url, stream_id=stream_id, lat=lat, lon=lon)
	        photo_key = photo.put()

        geopoint = search.GeoPoint(lat, lon)
        search_index = search.Document(
            doc_id= str(stream_id),
            fields=[search.TextField(name='url', value=url),
            search.GeoField(name='geopoint', value=geopoint) ])
        result = search.Index(name='photo').put(search_index)
def select_all():
     # set return variable as empty list
    photos = []
    # create sql query without values
    sql = "SELECT * FROM photos"
    # execute sql query
    results = run_sql(sql)
    # convert return which is a single element list of dictionaries into list of countries objects
    for result in results:        
        photo = Photo(result["filename"], result["mine"], location_repository.select(result['location_id']),result["id"]) 
        photos.append(photo)
    # return the result 
    return photos
Beispiel #15
0
async def create_dog(dog: DogSchema):
    local = next(get_db())
    length_dog = local.query(Dog).count()
    length_sight = local.query(Sighting).count()
    length_photo = local.query(Photo).count()
    sighting = Sighting(
        sighting_id=length_sight + 1,
        dog_id=length_dog + 1,
        latitude=dog.location[0],
        longitude=dog.location[1],
    )
    dog_model = Dog(
        dog_id=length_dog + 1,
        breed=dog.breed,
        description=dog.description,
        status=dog.status,
    )
    local.add(dog_model)
    local.add(sighting)
    if dog.url:
        photo = Photo(photo_id=length_photo + 1,
                      subject_id=length_dog + 1,
                      photo_url=dog.url)
        local.add(photo)
        local.commit()
        local.refresh(photo)
    else:
        url = "./images/PUPFINDER.png"
        photo = Photo(photo_id=length_photo + 1,
                      subject_id=length_dog + 1,
                      photo_url=url)
        local.add(photo)
        local.commit()
    local.refresh(dog_model)
    local.refresh(sighting)
    return {"dog": dog_model, "sight": sighting}
Beispiel #16
0
def photos(aid):
    if 'uid' in session:
        if 'file' not in request.files:
            return abort(401)
        file = request.files['file']
        if file.filename == '':
            return abort(400)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            a = services.serviceSettings.a.findByAid(aid)
            if a == None:
                abort(404)
            if a.user != services.serviceSettings.u.findByUid(session['uid']):
                abort(403)
            a.photos = [Photo(image=app.config['UPLOAD_FOLDER']+filename, content=request.form['content'], created_at=datetime.utcnow())]
            services.serviceSettings.a.addAlbum(a)
            return Response(status=201)
    else:
        abort(401)
Beispiel #17
0
    def save(self, existing_categories, existing_ingredients):
        connection = engine.connect()
        transaction = connection.begin()
        try:
            # upload photo
            if not self.upload_file.filename:
                self.photo_file = Photo.DEFAULT_IMAGE
            else:
                self.photo_file = Photo.upload_photo(self.upload_file)

            connection.execute(
                """
                INSERT INTO recipes (name, servings, preparation_time, nutritional_info, photo_file, creator_id, created_at)
                VALUES (%s,%s,%s,%s,%s,%s,%s)""",
                (
                    self.name,
                    self.servings,
                    self.preparation_time,
                    self.nutritional_info,
                    self.photo_file,
                    self.creator_id,
                    BaseModel.timestamp_to_db(datetime.datetime.now()),
                ),
            )

            # get recipe_id
            results = connection.execute("SELECT id FROM recipes ORDER BY id DESC LIMIT 1;")
            recipe_id = None
            for result in results:
                recipe_id = result[0]

            # create categories
            for category_name in self.category_names:
                if category_name not in existing_categories:
                    connection.execute("INSERT INTO categories (name) VALUES (%s)", category_name)
                connection.execute(
                    "INSERT INTO categories_recipes (recipe_id, category_name) VALUES (%s,%s)",
                    (recipe_id, category_name),
                )

            # create ingredients
            for ingredient in self.ingredients:
                if ingredient.name not in existing_ingredients:
                    connection.execute("INSERT INTO ingredients (name) VALUES (%s)", ingredient.name)
                connection.execute(
                    """
                    INSERT INTO ingredients_recipes (ingredient_name, recipe_id, quantity, unit, comment)
                    VALUES (%s,%s,%s,%s,%s)""",
                    (ingredient.name, recipe_id, ingredient.quantity, ingredient.unit, ingredient.comment),
                )

            # create steps
            for step in self.steps:
                connection.execute(
                    """
                    INSERT INTO steps (recipe_id, number, instructions)
                    VALUES (%s,%s,%s)""",
                    (recipe_id, step.number, step.instructions),
                )

            transaction.commit()
        except Exception as e:
            transaction.rollback()
            self.error_message = e.message
            return False

        return True
Beispiel #18
0
def db_seed3():
    random.seed(1)

    conn = db_connect()
    cur = conn.cursor()
    # create the main user
    user = {
        'email' : "*****@*****.**",
        'first_name': "Anthony",
        'last_name': "Bourdain",
        'hashed_password':User.hash_password("qwerty"),
        'icon_code':1,
        'created_at' : BaseModel.timestamp_to_db(datetime.now()),
        'last_login_at' : BaseModel.timestamp_to_db(datetime.now())
    }

    cur.execute("""INSERT INTO users (email, first_name, last_name, 
                                       hashed_password, icon_code, created_at, last_login_at)
                VALUES (%(email)s, %(first_name)s, %(last_name)s, %(hashed_password)s, %(icon_code)s, 
                        %(created_at)s, %(last_login_at)s)""", user)
    cur.execute("SELECT id FROM users  WHERE email=%(email)s", {'email':user['email']})
    user_id = cur.fetchone()

    
    # Create other users 
    engine.execute("""
        INSERT INTO 
            users (email, first_name, last_name, hashed_password, icon_code, created_at, last_login_at) 
        VALUES
            ('*****@*****.**', 'Abc', 'Xyz', 'GrYOEQ1BqarF4w0IbEkIGb/jRhs4x2uWAv6WhqoKo9KMY8lqEBnjeIxAoU9CkuUP', 0, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Franklin', 'Roosevelt', '36f104ac393b8431b57e78670c350359059f5bac353ef3ce620ee7c8ccf38928', 1, '2015-10-09 12:00:00', '2015-10-09 12:00:00'),
            ('*****@*****.**', 'George', 'Washington', '1bd918318467b5edf3243b90633427d2facaf630747d2d33bce137638a8719d4', 2, '2015-10-10 12:00:00', '2015-10-10 12:00:00'),
            ('*****@*****.**', 'George', 'Bush', '1bd918318467b5edf3243b90633427d2facaf630747d2d33bce137638a8719d4', 0, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Bill', 'Clinton', '237cef09c18de58503d79d9dd966c73c9736a8a9b8def484ba08f4d97bd2d3aa', 1, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Theodore', 'Roosevelt', 'a8979eec0be4e79b40e969c701e012c56dc3dbec3ba63611e597f605fe26eac8', 2, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Richard', 'Nixon', '5f872912d9b2b6f312711902991ac83fd854c746a8922e36715ff3aff18574b1', 3, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Thomas', 'Jefferson', '62660e10f69dcf92334c3bcae6330673947c2863982a9e8af92f141ad9587ce2', 0, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'John', 'Kennedy', '9c4b7a6b4af91b44be8d9bb66d41e82589f01974702d3bf1d9b4407a55593c3c', 1, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Harry', 'Truman', '79ff9c4d2fe456cc3015d157cf941fa51a4b2c51629d73b057629cdbb9801416', 2, '2015-10-08 12:00:00', '2015-10-08 12:00:00');
        """)
    results = engine.execute("SELECT id from users;")
    all_user_ids = [tup[0] for tup in results]

    print "CHEF ID: ", user_id
    with open('data/recipe_data.json' ,'r') as f:
        data = json.loads(f.read())

    # load all of the ingredients
    print "INSERTING ALL INGREDIENTS"
    unique_ingredients = list(set([first_lower(i['name']) for d in data for i in d['ingredients']]))
    ingredients = [{'name':i} for i in unique_ingredients]
    cur.executemany("""INSERT INTO ingredients (name) VALUES (%(name)s)""", ingredients)
    
    # load all of the categories
    print "INSERTING ALL CATEGORIES"
    unique_categories = list(set([ t['name'] for d in data for t in d['tags']]))
    categories = [{'name':i} for i in unique_categories]
    cur.executemany("""INSERT INTO categories (name) VALUES (%(name)s)""", categories)

    # for each recipe, load it, get its id, then load its steps, ingredients, and categories
    recipe_ids = []
    recipe_count = len(data)
    for j,r in enumerate(data):
        recipe = {
            'name': r['name'],
            'servings': r['yield'],
            'preparation_time': r['preparation_time'],
            'photo_file': Photo.download_photo(r['photo_url']),
            'nutritional_info': r['description'],#get_random_nutritional_info(),
            'creator_id': user_id,
            'created_at': BaseModel.timestamp_to_db(datetime.now() - timedelta(minutes=(recipe_count - j)))
        }
        cur.execute("""INSERT INTO recipes (name, servings, preparation_time, photo_file, nutritional_info, creator_id, created_at)
                       VALUES (%(name)s, %(servings)s, %(preparation_time)s, %(photo_file)s,
                               %(nutritional_info)s, %(creator_id)s, %(created_at)s)""", recipe)
        cur.execute("SELECT id FROM recipes ORDER BY id DESC LIMIT 1;")
        recipe_id = cur.fetchone()
        recipe_ids.append(recipe_id[0])
        print "RECIPE NUM: ", recipe_id[0]

        categories = [{'recipe_id':recipe_id, 'category_name':t['name']} for t in r['tags']]
        cur.executemany("""INSERT INTO categories_recipes (recipe_id, category_name)
                           VALUES (%(recipe_id)s, %(category_name)s)""", categories)
        
        steps = [ {'id':recipe_id, 'n':s['number'], 'instructions':s['instructions']} for s in r['steps'] ]
        cur.executemany("""INSERT INTO steps (recipe_id, number, instructions)
                           VALUES (%(id)s, %(n)s, %(instructions)s)""", steps)

        ingredients = [{'name':first_lower(i['name']), 'id':recipe_id, 'q':i['quantity'], 'u':i['unit'],\
                        'comment':i['comment']} for i in r['ingredients'] ]
        cur.executemany("""INSERT INTO ingredients_recipes (ingredient_name, recipe_id, quantity, unit, comment)
                           VALUES (%(name)s, %(id)s, %(q)s, %(u)s, %(comment)s)""", ingredients)

    conn.commit()
    conn.close()
    print "INSERTING RATINGS AND COMMENTS"
    for recipe_id in recipe_ids:
        # for each recipe, use a Bernoulli do define if the recipe should be rated/favorited or not
        if random.uniform(0,10) >= 2:
            # randomly select target expected rating
            target_rating = random.randint(1,5)
            offset = target_rating - 3

            # select how many users are going to rate thsi recipe
            rating_count = random.randint(3,len(all_user_ids))

            # select which users are going to rate this recipe
            rating_user_ids = random.sample(all_user_ids, rating_count)

            # for each user, randomly select and create rating
            for ruid in rating_user_ids:
                rating = random.randint(1,5) + offset
                if rating < 1:
                    rating = 1
                elif rating > 5:
                    rating = 5
                engine.execute("INSERT INTO ratings (user_id, recipe_id, rating) VALUES (%s,%s,%s)", (ruid, recipe_id, int(rating)))

                # each user that rated has 1/3 chance of favoriting the recipe
                if random.randint(1,3) == 1:
                    engine.execute("INSERT INTO saved (user_id, recipe_id, saved_at) VALUES (%s,%s,%s)", (
                        ruid,
                        recipe_id,
                        BaseModel.timestamp_to_db(datetime.now())
                    ))

            # select how many users are going to comment (max is rating count)
            comment_count = random.randint(1,rating_count)
            comments = get_comments(comment_count)

            # select which users are going to comment in this recipe
            comment_user_ids = random.sample(rating_user_ids, comment_count)

            # for each user, randomly select and create comment
            for i, cuid in enumerate(comment_user_ids):
                engine.execute("INSERT INTO comments (user_id, recipe_id, text, created_at, updated_at) VALUES (%s,%s,%s,%s,%s)", 
                    (cuid, recipe_id, comments[i], 
                        BaseModel.timestamp_to_db(datetime.now()-timedelta(minutes=(comment_count - i))), 
                        BaseModel.timestamp_to_db(datetime.now()-timedelta(minutes=(comment_count - i)))
                    ))
    



    print "DONE"
Beispiel #19
0
from models.photo import Photo

list_photos = [
    Photo(
        url=
        "https://images.squarespace-cdn.com/content/v1/5e9d994b2f1c2d4970c8acdb/1587389963053-73XU5GRBB3G5MV5LXRMY/ke17ZwdGBToddI8pDm48kIkgHTxUnlW7VysxtwKs7v57gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0ivq7Q1ckvJa8MA8qNUlEObOCsMVUGH9o4TViecrUGpmccNK2aHmPI1EqrJ3R2V6NQ/DSC_5828.jpg?format=1500w",
        caption="Junior World Champion Hannah Slaney eyes up the next hold",
        user_id=4),
    Photo(
        url=
        "https://images.squarespace-cdn.com/content/v1/5e9d994b2f1c2d4970c8acdb/1587387546125-9XVQR4EEFCOILIYCY3AZ/ke17ZwdGBToddI8pDm48kNiEM88mrzHRsd1mQ3bxVct7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0s0XaMNjCqAzRibjnE_wBlkZ2axuMlPfqFLWy-3Tjp4nKScCHg1XF4aLsQJlo6oYbA/IMG_6815.jpg?format=1000w",
        caption=
        "Two sisters share a special moment before the wedding ceremony",
        user_id=4),
    Photo(
        url=
        "https://images.squarespace-cdn.com/content/v1/5e9d994b2f1c2d4970c8acdb/1587388874581-3ICCJC5DUB00ZEVLFMWK/ke17ZwdGBToddI8pDm48kKErbpWhp7vl1zMeCVdM4Ld7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0lCYWGxfdB_uf1_ERfebHZ7UL1AJZpeUglh-dzBN3nU2Mw6gPXzsdsst52ojjUXzvA/DSC_0867.jpg?format=1000w",
        caption=
        "The hills of Italy, as viewed from just over the Slovakian border",
        user_id=4),
    Photo(
        url=
        "https://images.squarespace-cdn.com/content/v1/5e9d994b2f1c2d4970c8acdb/1587391639128-1B50U4O03IXYBP2TA8Z5/ke17ZwdGBToddI8pDm48kLR2rgEg1jPu1GtjV4K1vZ97gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0scl71iiVnMuLeEyTFSXT3qwhEKW1IfUKL5GUNLdDa9MjuPXcXiDenG_NSvE-2lGCg/DSC_9731+%281%29-2.jpg?format=750w",
        caption=
        "Climbers on the Vallée Blanche with the Grand Jorasses in the background",
        user_id=4),
    Photo(
        url=
        "https://images.squarespace-cdn.com/content/v1/5e9d994b2f1c2d4970c8acdb/1587556035572-Z57N685K43LUNM7M2MUQ/ke17ZwdGBToddI8pDm48kKg9gHUxzC8TFjTv4MbkSwl7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0prfa1Z6IeUrCPboCAmmHZkq_ORj1s9iZK8iaWQvAxQZ3OpNqQjmR1zGWZGBfK589Q/DSC_0796.jpg?format=1500w",
        caption=
        "Time for a tea break by the lake on a motorcycle trip through Switzerland",
Beispiel #20
0
def get_api_photos_exif(id):
    return json.dumps(Photo.get_exif(current_user, id))
Beispiel #21
0
def create(record):
    db.session.add(record)
    db.session.commit()


# Create admin user
from models.users import Users
from models.photo import Photo
if not Users.query.filter_by(username='******').first():
    create(Users(username='******', email='*****@*****.**'))
    create(Users(username='******', email='*****@*****.**'))
if not Photo.query.filter_by(name='photo1').first():
    with open(
            "/Users/tojo/Personel/easy_photo_share/static/images/portfolio/1.jpg",
            "rb") as image_file:
        create(Photo(name='photo1',
                     base64=base64.b64encode(image_file.read())))
    with open(
            "/Users/tojo/Personel/easy_photo_share/static/images/portfolio/2.jpg",
            "rb") as image_file:
        create(Photo(name='photo2',
                     base64=base64.b64encode(image_file.read())))
    with open(
            "/Users/tojo/Personel/easy_photo_share/static/images/portfolio/3.jpg",
            "rb") as image_file:
        create(Photo(name='photo3',
                     base64=base64.b64encode(image_file.read())))

if __name__ == "__main__":
    app.run()
Beispiel #22
0
def get_api_photos(id):
    photos = Photo.get_photos(current_user, id)
    return json.dumps([i.__dict__ for i in photos],
                      indent=4,
                      sort_keys=True,
                      default=str)
Beispiel #23
0
def delete_api_photos(id):
    try:
        Photo.delete(current_user, id)
    except ValueError as error:
        return error.args[0], 400
    return json.dumps(True)
Beispiel #24
0
location_repository.save(marina_bay_gardens)
location_repository.save(devils_pulpit)

# populates locations table with to be visited places
bluelagoon = Location("Blue Lagoon", "Amazing thermal pools", False, iceland)
sentosa = Location("Sentosa", "Some entertainment there", False, singapore)
alps = Location("Alps", "Excellent glacier photo oportunity", False, austria)
namibia_dunes = Location("Namibia Dunes", "Excellent dunes photo oportunity",
                         False, namibia)

location_repository.save(bluelagoon)
location_repository.save(sentosa)
location_repository.save(alps)
location_repository.save(namibia_dunes)

photo_repository.save(Photo("Clark01.jpg", True, clark_quay))
photo_repository.save(Photo("Godafoss02.jpg", True, godafoss))
photo_repository.save(Photo("MarinaGardens01.jpg", True, marina_bay_gardens))
photo_repository.save(Photo("Glencoe01.jpg", True, glencoe))
photo_repository.save(Photo("Lava field.jpg", True, lava_field))
photo_repository.save(Photo("MarinaGardens02.jpg", True, marina_bay_gardens))
photo_repository.save(Photo("Glencoe02.jpg", True, glencoe))
photo_repository.save(Photo("Marina01.jpg", True, marina_sands_bay))
photo_repository.save(Photo("devils_pulpit.jpg", True, devils_pulpit))
photo_repository.save(Photo("Glencoe03.jpg", True, glencoe))
photo_repository.save(Photo("Marina02.jpg", True, marina_sands_bay))
photo_repository.save(Photo("marina_sands01.jpg", True, marina_sands_bay))
photo_repository.save(Photo("Glenfinnan01.jpg", True, glenfinnan))
photo_repository.save(Photo("Marina03.jpg", True, marina_sands_bay))
photo_repository.save(Photo("Godafoss01.jpg", True, godafoss))
photo_repository.save(Photo("Marina04.jpg", True, marina_sands_bay))