Beispiel #1
0
 def put(self, username, task_id):
     """Update an existing task given a username and task id."""
     with self.make_session() as session:
         profile = yield as_future(
             session.query(Profile).filter(
                 Profile.username == username).first)
         if profile:
             task = yield as_future(
                 session.query(Task).filter(
                     Task.profile == profile).get(task_id))
             if task:
                 self.authenticate_response(profile)
                 self.send_response({
                     'username': username,
                     'task': task.to_dict()
                 })
             else:
                 self.authenticate_response(profile)
                 self.send_response({
                     'username': username,
                     'task': None
                 },
                                    status=404)
         else:
             self.send_response(
                 {
                     'error':
                     '555You do not have permission to access this data.'
                 },
                 status=403)
Beispiel #2
0
 def delete(self, username, task_id):
     """Delete an existing task given a username and task id."""
     with self.make_session() as session:
         profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
         if profile:
             task = yield as_future(session.query(Task).filter(Task.profile == profile).get(task_id))
             if task:
                 session.delete(task)
                 session.commit()
             self.authenticate_response(profile)
             self.send_response({'username': username, 'msg': 'Deleted.'})
         else:
             self.send_response({'error': 'You do not have permission to access this data.'}, status=403)
Beispiel #3
0
 def post(self):
     """Log a user in."""
     try:
         needed = ['username', 'password']
         if all([key in self.form_data for key in needed]):
             with self.make_session() as session:
                 username = self.form_data['username'][0]
                 profile = yield as_future(
                     session.query(Profile).filter(
                         Profile.username == username).first)
                 if profile and hasher.verify(self.form_data['password'][0],
                                              profile.password):
                     self.authenticate_response(profile)
                     self.send_response(
                         {'msg': 'Login succeeded. Please proceed.'},
                         status=201)
                 else:
                     self.send_response(
                         {
                             'error':
                             'Incorrect username/password combination.'
                         },
                         status=400)
         else:
             self.send_response({'error': 'Some fields are missing'},
                                status=400)
     except Exception as e:
         self.send_response({'error': str(e)}, status=400)
Beispiel #4
0
 def put(self, username):
     """Handle incoming put request to update a specific profile."""
     with self.make_session() as session:
         profile = yield as_future(
             session.query(Profile).filter(
                 Profile.username == username).first)
         print('Profile name is ' + Profile.username +
               ' and the username is ' + username)
         if profile:
             if 'username' in self.form_data:
                 profile.username = self.form_data['username'][0]
             if 'password' in self.form_data and 'password2' in self.form_data and self.form_data['password'] == \
                     self.form_data['password2'] and self.form_data['password'][0] != '':
                 profile.password = hasher.hash(
                     self.form_data['password'][0])
             if 'email' in self.form_data:
                 profile.email = self.form_data['email'][0]
             session.add(profile)
             session.commit()
             self.authenticate_response(profile)
             self.send_response(
                 {
                     'msg': 'Profile updated.',
                     'profile': profile.to_dict(),
                     'username': profile.username
                 },
                 status=202)
         else:
             self.send_response(
                 {
                     'error':
                     '222You do not have permission to access this profile.'
                 },
                 status=403)
Beispiel #5
0
 def post(self):
     """Handle a POST request for user registration."""
     needed = ['username', 'email', 'password', 'password2']
     if all([key in self.form_data for key in needed]):
         username = self.form_data['username'][0]
         try:
             with self.make_session() as session:
                 profile = yield as_future(
                     session.query(Profile).filter(
                         Profile.username == username).first)
                 if not profile:
                     if self.form_data['password'] == self.form_data[
                             'password2']:
                         self.build_profile(session)
                         self.send_response({'msg': 'Profile created'},
                                            status=201)
                     else:
                         self.send_response(
                             {'error': "Passwords don't match"}, status=400)
                 else:
                     self.send_response(
                         {
                             'error':
                             "Profiles already exists, please login."
                         },
                         status=400)
         except Exception as e:
             print("Exception occurred: " + str(e))
             self.set_status(status_code=500,
                             reason="Backend server is down!!!")
Beispiel #6
0
 async def parse_request(cls, session, request_string: str) -> str:
     dates, temp_data, hum_data = [], [], []
     request_string += ',' * (max(3 - request_string.count(','), 0))  # Preventing unpacking error
     module_id, client_id, from_date, until_date = request_string.split(',')
     from_date = cls.__parse_date_string(from_date) or datetime(year=2000, month=1, day=1)
     until_date = cls.__parse_date_string(until_date) or datetime.now()
     query = cls._get_weekly_detailed_query() if (until_date - from_date) <= timedelta(days=7) \
         else cls._get_monthly_average_query()
     data = await asyncio.wrap_future(as_future(session.execute(query,
                                                                {'module_id': module_id, 'client_id': client_id,
                                                                 'from_date': from_date,
                                                                 'until_date': until_date + timedelta(days=1)
                                                                 }).fetchall))
     for temp, hum, date in data:
         temp_data.append(str(temp))
         hum_data.append(str(hum))
         dates.append(f'"{date}"')
     formatted = """
             {{
                 "labels":[{month_list}],
                 "datasets":[
                 {{"label":"temperature","data":[{temp_data}],"borderColor":"rgb(175,92,22)"}},
                 {{"label":"humidity","data":[{hum_data}],"borderColor":"rgb(50,50,192)"}}
                 ]
             }}
             """.format(month_list=','.join(dates), temp_data=','.join(temp_data), hum_data=','.join(hum_data))
     return formatted
Beispiel #7
0
    def post(self, username):
        """
        Creates a new task
        """

        with self.make_session() as session:

            user = yield as_future(
                session.query(User).filter(User.username == username).first)
            if user:

                try:
                    due_date = self.data['due_date'][0]
                    completed = self.data['completed'][0]
                except KeyError:
                    due_date = None
                    completed = None

                task = Task(
                    name=self.data['name'][0],
                    note=self.data['note'][0],
                    creation_date=datetime.now(),
                    due_date=datetime.strptime(due_date, '%d/%m/%Y %H:%M:%S')
                    if due_date else None,
                    completed=completed if completed else False,
                    user_id=user.id,
                    user=user)

                session.add(task)
                self.send_response(
                    {
                        'message': 'Task created',
                        'Task': task.name
                    }, status=201)
Beispiel #8
0
 def get(self):
     username = self.get_argument('username', None)
     if username:
         print('Got request for username <%s>' % username)
         # Get key for user or create record in db
         with self.make_session() as session:
             user = yield as_future(
                 session.query(User).filter(
                     User.username == username).first)
             if not user:
                 keys = generate_rsa_pair(rsa_size)
                 user = User(
                     username=username,
                     public_key=keys.get('public_key'),
                 )
                 session.add(user)
             self.send_response(
                 {
                     'username': user.username,
                     'publick_key': str(user.public_key),
                 },
                 status=201,
             )
     else:
         self.send_response('No username provided', status=400)
 def post(self):
     url = self.get_argument('url')
     # Fetch word dictionary with frequency
     word_dict = build_word_dict(url)
     # Get public key
     public_key = get_keys("public_key")
     new_dict_array = []
     with self.make_session() as session:
         # Iterate through all the word in the word_dict , create the word hash and
         # check if a word hash exists in the database
         for word, quantity in word_dict:
             new_dict = {'text': word, 'size': quantity}
             new_dict_array.append(new_dict)
             salted_hash = get_salted_hash(word)
             word_element = yield as_future(
                 session.query(Word).filter(
                     Word.word_hash == salted_hash).first)
             if not word_element:
                 # Create a word object and add to session
                 encrypted_word = encrypt_data(word, public_key)
                 session.add(
                     Word(word_hash=salted_hash,
                          word=encrypted_word,
                          count=quantity))
             else:
                 # update the word object with the frequency
                 word_element.count += quantity
             session.commit()
     self.render("base.html", word_array=json_encode(new_dict_array))
Beispiel #10
0
 def post(self, username):
     """Create a new task."""
     with self.make_session() as session:
         profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
         if profile:
             due_date = self.form_data['due_date'][0]
             try:
                 task = Task(
                     name=self.form_data['name'][0],
                     note=self.form_data['note'][0],
                     creation_date=datetime.now(),
                     due_date=datetime.strptime(due_date, '%d/%m/%Y %H:%M:%S') if due_date else None,
                     completed=self.form_data['completed'][0],
                     profile_id=profile.id,
                     profile=profile
                 )
                 session.add(task)
                 session.commit()
                 self.authenticate_response(profile)
                 self.send_response({'msg': 'posted'}, status=201)
             except KeyError:
                 self.authenticate_response(profile)
                 self.send_response({'error': 'Some fields are missing'}, 400)
         else:
             self.send_response({'error': 'You do not have permission to access this profile.'}, status=404)
Beispiel #11
0
 def delete(self, username):
     """Delete an existing task from the database."""
     with self.make_session() as session:
         profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
         session.delete(profile)
         session.commit()
         self.send_response({}, status=204)
Beispiel #12
0
    def get(self):
        with self.make_session() as session:
            session.add(User(username='******'))
            session.add(Foo(foo='foo'))
            session.add(Bar(bar='bar'))
            session.commit()
            count = yield as_future(session.query(User).count)

        self.write('{} users so far!'.format(count))
Beispiel #13
0
 def get(self, username):
     """Handle incoming get request for a specific user's profile."""
     with self.make_session() as session:
         profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
         if profile:
             self.authenticate_response(profile)
             self.send_response(profile.to_dict())
         else:
             self.send_response({'error': 'You do not have permission to access this profile.'}, status=403)
Beispiel #14
0
 def get(self, username):
     """Get all tasks for an existing user."""
     with self.make_session() as session:
         profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
         if profile:
             tasks = [task.to_dict() for task in profile.tasks]
             self.send_response({
                 'username': profile.username,
                 'tasks': tasks
             })
Beispiel #15
0
    def get(self, username):
        """
        Get all tasks for an existing user
        """

        with self.make_session() as session:
            user = yield as_future(
                session.query(User).filter(User.username == username).first)
            if user:
                tasks = [task.columns_to_dict() for task in user.tasks]
                self.send_response({'username': user.username, 'tasks': tasks})
    def test_concurrent_requests_using_yield(self):
        sessions = [db.sessionmaker() for _ in range(self.session_count)]

        for index, session in enumerate(sessions):
            session.add(User('User #{}'.format(index)))
        session.commit()

        yield [as_future(session.query(User).count) for session in sessions]

        for session in sessions:
            session.close()
Beispiel #17
0
 def post(self):
     """Handle a POST request for user registration."""
     needed = ['username', 'email', 'password', 'password2']
     if all([key in self.form_data for key in needed]):
         username = self.form_data['username'][0]
         with self.make_session() as session:
             profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
             if not profile:
                 if self.form_data['password'] == self.form_data['password2']:
                     self.build_profile(session)
                     self.send_response({'msg': 'Profile created'}, status=201)
                 else:
                     self.send_response({'error': "Passwords don't match"}, status=400)
Beispiel #18
0
 def get(self, username):
     """Get all tasks for an existing user."""
     with self.make_session() as session:
         profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
         if profile:
             tasks = [task.to_dict() for task in profile.tasks]
             self.authenticate_response(profile)
             self.send_response({
                 'username': profile.username,
                 'tasks': tasks
             })
         else:
             self.send_response({'error': 'The profile does not exist'}, status=404)
Beispiel #19
0
    def test_concurrent_requests_using_yield(self):
        factory = make_session_factory(postgres_url, pool_size=1)

        sessions = [factory.make_session() for _ in range(self.session_count)]

        yield [
            as_future(lambda: session.execute(
                'SELECT pg_sleep(:duration)',
                {'duration': self.sleep_duration},
            )) for session in sessions
        ]

        for session in sessions:
            session.close()
 def get(self):
     private_key = get_keys("private_key")
     words = []
     with self.make_session() as session:
         # Fetch all the words from the table in order of their frequency and return
         # to the front end
         word_array = yield as_future(
             session.query(Word).order_by(desc(Word.count)).all)
         for word_obj in word_array:
             word = {}
             word["count"] = word_obj.count
             # Decrypt the key before sending back to front end
             word["word"] = decrypt_data(word_obj.word, private_key)
             words.append(word)
     self.render("admin.html", words=words)
Beispiel #21
0
def post(self, username):
    """Create a new task."""
    with self.make_session() as session:
        profile = yield as_future(session.query(Profile).filter(Profile.username == username).first)
        if profile:
            due_date = self.form_data['due_date'][0]
            task = Task(
                name=self.form_data['name'][0],
                note=self.form_data['note'][0],
                creation_date=datetime.now(),
                due_date=datetime.strptime(
                    due_date, '%d/%m/%Y %H:%M:%S') if due_date else None,
                completed=self.form_data['completed'][0],
                profile_id=profile.id,
                profile=profile
            )
            session.add(task)
            self.send_response({'msg': 'posted'}, status=201)
    def get(self):
        with self.make_session() as session:
            count = yield as_future(session.query(User).count)

        self.write('{} users so far!'.format(count))
Beispiel #23
0
            def get(h_self):
                with h_self.make_session() as session:
                    count = yield as_future(session.query(User).count)

                h_self.write(str(count))
 def get_queues_async(session):
     return as_future(DeviceType.get_queues(session).all)
Beispiel #25
0
 def as_future(self, callable):
     return tsql.as_future(callable)
Beispiel #26
0
 async def _get_modules(self, session):
     return await asyncio.wrap_future(as_future(session.query(Module).all))
Beispiel #27
0
 def get_owned_devices_async(self, session):
     return as_future(self.get_owned_devices(session).all)
Beispiel #28
0
 def get_all_ro_urls_async(session):
     return as_future(DeviceQueue.get_all_ro_urls(session).all)