def set_user_attended(user, event):
     if EventRegister.get_user_attended(user, event):
         Database.update("registrations", {"user": user, "event": uuid.UUID(event)}, {"$set": {"attended": "No"}},
                         upsert=True)
     else:
         Database.update("registrations", {"user": user, "event": uuid.UUID(event)}, {"$set": {"attended": "Yes"}},
                         upsert=True)
Exemple #2
0
def tester_method():

    email=request.form['email']
    print(email)
    user=User.get_by_email(email)
    Database.update("users",{"email":email},{"printdata":"no"})
    return "done"
    def calculate_portfolio(self, portfolio_id):
        finance_data = Database.find_one('financedata', {"portfolio_id": self.portfolio_id})
        if finance_data is not None:
            Database.remove('financedata', {"portfolio_id": self.portfolio_id})
        stock_data = Database.find('stockdata', {"portfolio_id": portfolio_id})
        current_value_list = []
        add_price_list = []
        qty_list = []
        for data in stock_data:
            current_price = (data['current_price'])
            add_price = (data['add_price'])
            qty = (data['qty'])
            current_value_list.append(current_price)
            add_price_list.append(add_price)
            qty_list.append(qty)
        total_qty = sum(qty_list)
        total_current_value = sum(current_value_list)
        total_add_price = sum(add_price_list)
        print(total_current_value)
        try:
            total_purchase_value = total_add_price * total_qty
            total_current_value = total_current_value * total_qty
            percent_change = (total_current_value - total_purchase_value) / total_current_value

            finance = Finance(portfolio_id=portfolio_id, percent_change=percent_change,
                              total_purchase_value=total_purchase_value, total_current_value=total_current_value)
            finance.save_to_database()
        except ZeroDivisionError:
            print("You need to add data first!")
Exemple #4
0
def update_database(genre):


    show = Show(None, None, None, None, None)
    page_no = 0
    titles = show_title(genre, page_no)
    print(titles)
    ratings=find_ratings(titles)
    #print(ratings)
    trailers=find_trailer_link(titles)
    #print(trailers)
    release_dates=show_release_date(genre,page_no)
    poster_link=show_poster_link(genre,page_no)
    i=0
    while i<30:
        show._id=i+1
        show.title=titles[i]
        show.rating=ratings[i]
        show.trailer=trailers[i]
        show.release_date=release_dates[i]
        show.poster=poster_link[i]
        show.save_to_mongo(genre)
        i=i+1
    print("Database Updated")
    Database.remove_all(genre+"_last_updated")
    def json():                                 #can be removed, just done during testing something
        d = str(datetime.date.today())
        return {
            "last_updated_date": d
        }

    Database.insert(genre+"_last_updated", json())
 def sync_to_db(self):
     if self._synced is False:
         Database.update(self.COLLECTION,
                         {'quiz_id': self._id, 'user_id': self._id},
                         {'passed': self._passed,
                          'try_number': self._try_number,
                          'last_try': self._last_try,})
    def test_one_shift_in_range_returns_none_for_other_days(self):

        user = User('*****@*****.**', 'u3', username='******', _id='u3')
        user.save_to_database()

        # USER HAS SHIFT FOT ONLY MONDAY
        start = beginning_of_week()
        end = start + timedelta(seconds=1)
        # create 1 second shift
        shift = Shift(user._id, start, end)
        shift.save_to_database()

        schedule = Schedule(user._id)

        # Monday is not None
        self.assertEqual(type(schedule.shifts[0]), type(shift))
        self.assertEqual(schedule.row[1], None)
        self.assertEqual(schedule.row[2], None)
        self.assertEqual(schedule.row[3], None)
        self.assertEqual(schedule.row[4], None)
        self.assertEqual(schedule.row[5], None)
        self.assertEqual(schedule.row[6], None)

        Database.remove('users', {'user_id': user._id})
        Database.remove('shifts', {'user_id': user._id})
Exemple #7
0
 def remove_from_db(self):
     if self._feed:
         news = [article for article in Database.find("articles", {"page_id" : uuid.UUID('{00000000-0000-0000-0000-000000000000}')})]
         for article in news:
             article = Article.get_by_id(article['_id'])
             article.remove_from_db()
     Database.remove(self.COLLECTION, {'_id': self._id})
Exemple #8
0
 def remove_room(self):
     _id = self._id
     Database.remove('pointssetting', {'_id':_id})
     Database.remove('players', {'room_id':_id})
     Database.remove('matches', {'room_id': _id})
     Database.remove('playersall', {'room_id': _id})
     Database.remove(collection='rooms', data=self.json())
     session['_id'] = None
Exemple #9
0
 def get_registered_events(user):
     events_registered_for = Database.find("registrations", {"user": user})
     if events_registered_for is not None:
         events = list()
         for event in events_registered_for:
             events.append(Database.find_one("events", {"_id": event["event"]}))
         return events
     return None
Exemple #10
0
 def get_all_attended(user):
     events_attended = Database.find("registrations", {"user": user, "attended": "Yes"})
     if events_attended is not None:
         events = list()
         for event in events_attended:
             events.append(Database.find_one("events", {"_id": event["event"]}))
         return events
     return None
    def test_default_values_returns_current_weeks_shifts_even_if_none(self):
        user = User('*****@*****.**', 'u1', username='******', _id='u1')
        user.save_to_database()

        schedule = Schedule(user._id)

        self.assertEqual(len(schedule.row), 7)

        Database.remove('users', {'user_id': user._id})
Exemple #12
0
def home(genre = 'comedy'):



    #date=Database.find_coloumn(genre+'_last_updated','last_updated_date')


    #if Database.count_all(genre+'_last_updated') > 0:
    #    if date[0]['last_updated_date']!=str(datetime.date.today()):
    #       update_database(genre)
    #else:
    #    update_database(genre)

    #update_database(genre)
    print("Site Visited")
    t=Database.find_coloumn(genre,"title")
    new_title=[None]*30
    new_trailer = [None] * 30
    new_dates=[None]*30
    new_ratings=[None]*30
    new_poster_links=[None]*30

    i=0
    for title in t:
        new_title[i]=title['title']
        i=i+1
    i=0

    trailers = Database.find_coloumn(genre,"trailer")
    for trailer in trailers:
        new_trailer[i]=trailer['trailer']
        i=i+1

    i=0
    release_dates = Database.find_coloumn(genre, "release_date")
    for date in release_dates:
        new_dates[i] = date['release_date']
        i = i + 1

    i = 0
    ratings = Database.find_coloumn(genre, "rating")
    for rating in ratings:
        new_ratings[i] = rating['rating']
        i = i + 1

    i=0
    poster_links = Database.find_coloumn(genre, "poster")
    for poster_link in poster_links:
        new_poster_links[i] = poster_link['poster']
        i = i + 1


    return render_template('list.html', g_link='https://www.google.com/search?q=',elements=new_title, trailer_links=new_trailer,
                           genres=genres, current_genre=genre,
                           release_dates=new_dates,
                           ratings=new_ratings,
                           poster_links=new_poster_links)
Exemple #13
0
    def test_save_simple_user_to_db(self):
        email = "*****@*****.**"
        user = User(email, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
        user.permissions = Permissions.default().name
        user.save_to_db()

        self.assertIsNotNone(User.find_by_email(email))

        Database.remove("users", {"email": email})
Exemple #14
0
 def sync_to_db(self):
     questions = []
     if self._questions is not None:
         for question in self._questions:
             questions.append(question.to_json())
     Database.update(self.COLLECTION,
                     {'_id': self._id},
                     {'title': self._title,
                      'questions': self._questions,
                      'points': self._points
                      })
Exemple #15
0
def upload_file():
    if request.method == 'POST':
        f = request.files['document']
        f.save('uploads/' + secure_filename(f.filename))
        Database.update("users",{"email":session['email']},{"printdata":"yes"})
        str="server.py"
        str1="uploads/"+f.filename
        print(str1)
        Popen(["nohup","python",str,str1,f.filename])

    return render_template("home.html")
Exemple #16
0
 def sync_to_db(self):
     if self._synced is False:
         self._synced = True
         Database.update('articles',
                         {'_id': self._id},
                         {'title': self._title,
                             'summary': self._summary,
                             'page_id': self._page_id,
                             'publication': self._publication,
                             'date': self._date
                         })
Exemple #17
0
def uploader_file():
    if request.method == 'POST':
        f = request.files['image']
        email=request.form['email']
        f.save('uploads/' + secure_filename(f.filename))
        Database.update("users",{"email":email},{"printdata":"yes"})
        str="server.py"
        str1="uploads/"+f.filename
        print(str1)
        Popen(["nohup","python",str,str1,f.filename])

    return jsonify({"status":"success"})
Exemple #18
0
 def get_college(university, college_to_find):
     uni = Database.find_one(COLLECTION, {"name": university})
     colleges = [college for college in uni["colleges"]]
     for college in colleges:
         if college_to_find == college["name"]:
             return college
     return False
Exemple #19
0
 def find_needing_update(cls, minutes_since_update=AlertConstants.ALERT_TIMEOUT):
     last_updated_limit = datetime.datetime.utcnow() - datetime.timedelta(minutes=minutes_since_update)
     return [cls(**elem) for elem in Database.find(AlertConstants.COLLECTION,
                                                   {"last_checked":
                                                        {"$lte": last_updated_limit},
                                               "active": True
                                                    })]
Exemple #20
0
def index():
    news = [article for article in Database.find("articles",
                                                 {"page_id": uuid.UUID('{00000000-0000-0000-0000-000000000000}')},
                                                 sort='date',
                                                 direction=pymongo.DESCENDING,
                                                 limit=3)]
    events = [event for event in Database.find("events", {}, sort='start', direction=pymongo.DESCENDING, limit=3)]

    for article in news:
        article['summary'] = Utils.clean_for_homepage(article['summary'])
    for event in events:
        event['description'] = Utils.clean_for_homepage(event['description'])

    return render_template('home.html',
                           events=events,
                           news=news)
Exemple #21
0
 def is_valid_login(username, password):
     user_data = Database.find_one(UserConstant.COLLECTION, {'username':username})
     if user_data is None:
         raise UserError.UserNotExist("User is not existing in the database")
     if not Utils.check_hashed_password(password, user_data['password']):
         raise UserError.PasswordIncorrect("Password is not correct")
     return True
Exemple #22
0
def admin_edit_profile_page(user):
    universities = University.get_uni_list()
    profile = User.find_by_email(user)
    mypermissions = User.get_user_permissions(session['email'])
    permissions = [permission_level for permission_level in Database.find(Permissions.COLLECTION, {})]
    return render_template('edit-profile.html', user=user, universities=universities, profile=profile,
                           permissions=permissions, mypermissions=mypermissions)
Exemple #23
0
 def from_mongo(cls, _id):
     blog_data = Database.find_one(collection='blogs', query={'_id': _id})
     return cls(author=blog_data['author'],
                title=blog_data['title'],
                description=blog_data['description'],
                created_date=created_date['created_date']
                _id=blog_data['_id'])
    def test_event_register(self):
        user = "******"
        event = Event(title="Test event",
                      description="Test description",
                      start=datetime.datetime.utcnow().strftime('%m/%d/%Y %I:%M %p'),
                      end=(datetime.datetime.utcnow() + datetime.timedelta(hours=1)).strftime('%m/%d/%Y %I:%M %p'),
                      event_type="action",
                      points=10)
        event.save_to_db()

        EventRegister.register_for_event(user, event.get_id())

        self.assertIsNotNone(EventRegister.check_if_registered(user, event.get_id()))

        Database.remove("registrations", {"user": user, "event": event.get_id()})
        Database.remove(Event.COLLECTION, {'_id': event.get_id()})
    def test_no_shifts_in_range_returns_none_for_each_day(self):
        user = User('*****@*****.**', 'u2', username='******', _id='u2')
        user.save_to_database()

        # USER HAS ZERO SHIFTS

        schedule = Schedule(user._id)

        self.assertEqual(schedule.row[0], None)
        self.assertEqual(schedule.row[1], None)
        self.assertEqual(schedule.row[2], None)
        self.assertEqual(schedule.row[3], None)
        self.assertEqual(schedule.row[4], None)
        self.assertEqual(schedule.row[5], None)
        self.assertEqual(schedule.row[6], None)

        Database.remove('users', {'user_id': user._id})
Exemple #26
0
 def from_mongo(cls, _id):
     post_data = Database.find_one(collection='posts', query={'_id': _id})
     return cls(blog_id=post_data['blog_id'],
                title=post_data['title'],
                content=post_data['content'],
                author=post_data['author'],
                created_date=post_data['created_date'],
                 _id=post_data['_id'])
 def calculate_total(portfolio_id):
     data = Database.find('stockdata', {"portfolio_id": portfolio_id})
     li = []
     for total in data:
         value = (data['total_price'])
         li.append(value)
     total_value = sum(li)
     return total_value
Exemple #28
0
def events_list_page():
    events = [event for event in Database.find("events", {}, sort='start', direction=pymongo.DESCENDING)]

    for event in events:
        event['description'] = Utils.clean_for_homepage(event['description'])

    return render_template('items/events-list.html',
                           events=events)
Exemple #29
0
 def login_is_valid(username, password):
     user_data = Database.find_one('user_data', {"username": username})
     if user_data is None:
         raise UserNotExistsError("Your username does not exist")
         pass
     if not Util.check_hashed_password(password, user_data['password'])
         raise IncorrectPasswordError("Your password was invalid")
     raise True
Exemple #30
0
    def check_user_awards(cls, user_points):
        awards_db = [award for award in Database.find(collection=Award.COLLECTION,
                                                      query={})]
        awards = []
        for award_db in awards_db:
            del award_db['_id']
            awards.append(cls(**award_db))

        return Award.check_awards(awards, user_points)
Exemple #31
0
 def delete_from_mongo(cls, query):
     Database.delete_one(MonitorConstants.COLLECTION, query)
Exemple #32
0
 def get_by_id(cls, _id):
     data = Database.find_one("users", {"_id": _id})
     if data is not None:
         return cls(**data)
 def get_by_id(cls,id):
     return cls(**Database.find_one(ItemConstants.TYPE_COLLECTION,{"_id":id}))
Exemple #34
0
 def find_by_email(cls, email):
     return cls(
         **Database.find_one(UserConstants.COLLECTION, {'email': email}))
Exemple #35
0
 def from_mongo(cls, id):
     blog_data = Database.find_one(collection='blogs', query={'id': id})
     return cls(**blog_data)
Exemple #36
0
 def get_by_user_id(cls, user_id):
     monitors = Database.find(MonitorConstants.COLLECTION,
                              {'user_id': user_id})
     return [cls(**monitor) for monitor in monitors]
Exemple #37
0
 def get_by_id(cls, id):
     return cls(
         **Database.find_one(MonitorConstants.COLLECTION, {'_id': id}))
 def save_to_mongo(self):
     Database.update(ItemConstants.COLLECTION, {'_id': self._id},
                     self.json())
Exemple #39
0
def init_db():
    Database.initialize()
Exemple #40
0
 def get_by_name(cls, store_name):
     return cls(**Database.find_one(StoreConstants.COLLECTION, {"name": store_name}))
Exemple #41
0
def initialize_database():
    Database.initialize()
Exemple #42
0
 def get_by_url_prefix(cls, url_prefix):
     """"
     http://www.johnlewis <- {'_id'... 'name': 'John Lewis'...}
     """
     return cls(**Database.find_one(StoreConstants.COLLECTION, {"url_prefix": {"$regex": '^{}'.format(url_prefix)}}))
Exemple #43
0
 def get_by_name(cls, name):
     data = Database.find_one("users", {"name": name})
     if data is not None:
         return cls(**data)
Exemple #44
0
 def get_by_email(cls, email):
     data = Database.find_one("users", {"email": email})
     if data is not None:
         return cls(**data)
 def get_all_types(cls):
     return [cls(**elm) for elm in Database.find(ItemConstants.TYPE_COLLECTION,{})]
Exemple #46
0
 def get_from_mongo(cls, id):
     blog_data = Database.find_one("blogs", {"_id": id})
     return cls(**blog_data)
Exemple #47
0
 def get_by_name(cls, monitor_name):
     return cls(**Database.find_one(MonitorConstants.COLLECTION,
                                    {'name': monitor_name}))
Exemple #48
0
 def save_to_mongo(self):
     Database.insert(collection='blogs', data=self.json())
 def save_to_mongo(self):
     Database.insert(ItemConstants.TYPE_COLLECTION,self.json())
Exemple #50
0
 def find_by_author_id(cls, author_id):
     blogs = Database.find(collection='blogs',
                           query={'author_id': author_id})
     return [cls(**blog) for blog in blogs]
Exemple #51
0
 def run(self):
     Database.initialize()
     while Alert.find_by_id(self.alert_id).active == True:
         Alert.turn_email_notification_on(self.alert_id)
Exemple #52
0
    def json(self):
        return {
            "_id": self._id,
            "blog_id": self.blog_id,
            "title": self.title,
            "content": self.content,
            "author": self.author,
            "created_date": self.created_date
        }

    @classmethod
    def from_mongo(cls, id):
        post_data = Database.find_one(collection='posts', query={'_id': id})
        return cls(**post_data)

    @staticmethod
    def from_blog(id):
        return [
            post for post in Database.find(collection='posts',
                                           query={'blog_id': id})
        ]


if __name__ == '__main__':
    Database.initialize()
    post = Post(blog_id="00219e9981b24c37802ac31b6338aef0",
                title="test post",
                content="test content",
                author="*****@*****.**")
    post.save_to_mongo()
Exemple #53
0
 def find_by_author_id(cls, author_id):
     blogs = Database.find("blogs", {"author_id": author_id})
     return [cls(**blog) for blog in blogs]
Exemple #54
0
 def from_blog(id):
     return [
         post for post in Database.find(collection='posts',
                                        query={'blog_id': id})
     ]
Exemple #55
0
 def get_by_id(cls, id):
     return cls(**Database.find_one(StoreConstants.COLLECTION, {"_id": id}))
Exemple #56
0
def initialise_database():
    Database.initialise()
Exemple #57
0
 def all(cls):
     return [
         cls(**elem)
         for elem in Database.find(StoreConstants.COLLECTION, {})
     ]
Exemple #58
0
 def save_to_mongo(self):
     Database.insert(StoreConstants.COLLECTION, self.json())
Exemple #59
0
 def save_to_db(self):
     Database.insert("users", self.json())
Exemple #60
0
 def from_mongo(cls, id):
     post_data = Database.find_one(collection='posts', query={'_id': id})
     return cls(**post_data)