Пример #1
0
    def randomcreatedelete(self, delay):
        next_time = time.time() + delay
        while True:
            time.sleep(max(0, next_time - time.time()))
            username = ''.join([
                random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(10)
            ])
            firstname = ''.join([
                random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(20)
            ])
            lastname = ''.join([
                random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(20)
            ])
            recordtime = str(datetime.datetime.now()).split('.')[0]
            next_time += (time.time() - next_time) // delay * delay + delay
            print(username, firstname, lastname, recordtime, recordtime_dt)

            # Adding a record for every 15 secods
            if ContactModel.find_by_username(username):
                return {
                    'message':
                    "A contact with username '{}' already exists.".format(
                        username)
                }, 400
            else:
                contact = ContactModel(username, firstname, lastname,
                                       recordtime)
                try:
                    contact.save_to_db()
                    return {"message": "Contact created successfully."}, 201
                except:
                    return {
                        "message": "Error occured while inserting new contact "
                    }, 404

            #Delete a record if it is created earlier than 1 min
            contacts = {
                list(map(lambda x: x.json(), ContactModel.query.all()))
            }
            for rec in contacts:
                recordtime_dt = datetime.datetime.strptime(
                    rec["recordtime"], '%Y-%m-%d %H:%M:%S')
                timegap = int(
                    (datetime.datetime.now() - recordtime_dt).total_seconds())
                if timegap > 60:
                    contact.delete_from_db()
                    return {'message': 'contact deleted'}
Пример #2
0
 def post(self):
     data = _contact_parser.parse_args()
     if ContactModel.find_by_username(data["username"]):
         return {
             'message':
             "A contact with username '{}' already exists.".format(
                 data["username"])
         }, 400
     else:
         recordtime = str(datetime.datetime.now()).split('.')[0]
         contact = ContactModel(data["username"], data["firstname"],
                                data["lastname"], recordtime)
         try:
             contact.save_to_db()
             return {"message": "Contact created successfully."}, 201
         except:
             return {
                 "message": "Error occured while inserting new contact "
             }, 404