def collect_job(user_id, job_id): sql = 'select id from collect_job where user = %s and job = %s' % (user_id, job_id) if _db.query_one(sql) is None: _db.insert('collect_job', {'user': user_id, 'job': job_id}) _db.execute('update job set collect = collect + 1 where id = %s' % job_id) return True return False
def check_defaults(): cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) sql = "select * from defaults where ending > '%s' or ending is null;" % cur_time defaults = db.special_select(sql) for default in defaults: if check_time(default['starting'], default['cycle']): record = dict() record['name'] = default['name'] record['be_from'] = default['be_from'] record['be_to'] = default['be_to'] record['amt'] = default['amt'] record['tag'] = default['tag'] record['time'] = default['time'] record['remark'] = default['remark'] record['aid'] = default['aid'] reids = db.select(conn, 'records', ['reid'], dict()) reids = [t['reid'] for t in reids] record['reid'] = ''.join( random.choice(letters + numbers) for j in range(10)) while record['reid'] in reids: record['reid'] = ''.join( random.choice(letters + numbers) for j in range(10)) db.insert(conn, 'records', record)
def POST(self): if (web.config._session.roleid != 1): raise web.seeother('/') pdata = web.input(item=None, action=None, picture={}, category_id=None) if pdata.action == "create": fullpath=None if 'picture' in pdata:#what I added for storing the picture if len(pdata.picture.filename)>0: filedir='./static' filepath=pdata.picture.filename.replace('\\','/') filename=filepath.split('/')[-1] fullpath=filedir+'/'+filename fout=open(fullpath,'wb') fout.write(pdata.picture.file.read()) fout.close() create_item(pdata.item, pdata.description, pdata.price,fullpath) elif pdata.action == 'delete': if len(pdata.picture)>0: os.remove(pdata.picture) delete_item(pdata.item) elif pdata.action == 'hide': set_status(pdata.item, False) elif pdata.action == 'show': set_status(pdata.item, True) elif pdata.action == 'update': db.update('MenuItems', where='id=$pdata.item', vars=locals(), price=pdata.price) elif pdata.action == 'category': db.insert('Item_Categories', item_id = pdata.item, category_id = pdata.category_id) elif pdata.action == 'delete_category': db.delete('Item_Categories', vars=locals(), where= 'item_id = $pdata.item and category_id = $pdata.category_id') raise web.seeother('/menu_editor')
def POST(self): i = web.input() cookie = web.cookies() timestamp = time.strftime("%Y-%m-%d %I:%M:%S %p") db.insert('data', timestamp=timestamp, content=i.content, user=cookie.user)
def POST(self): auth() data = web.input(title='', contents='',tag='') ''' update tag ''' for tag in data.tag.split(';'): db.query('select name from tag') res = db.fetchAllRows() if len(tag) == 0: continue if (tag,) not in res: db.insert('insert into tag (name, num) values ("%s",1)'%tag) else: db.query('select id,num from tag where name="%s"'%tag) res = db.fetchOneRow() print res db.update('update tag set num=%d where id=%d'%((res[1]+1),res[0])) ''' update article ''' db.query('select * from article where title="%s"'%data.title) res = db.fetchOneRow() if res == None: res = db.insert('insert into article (title, content, tag, posttime) values ("%s", "%s", "%s", "%s")'%(data.title, data.contents, data.tag, time.strftime('%Y-%m-%d %H:%M:%S'))) if not res: web.redirect('/edit') return 'success' return 'repeated title'
def shippers(group_id, first_id: int, second_id: int, time: float): db.insert(TABLE='shippers', OR=REPLACE, group_id=group_id, id_first=first_id, id_scond=second_id, time=time)
def __init__(self): self.maxUsers = 10 # LIMITED TO 30 USERS/COLORS clients = db.select('user', what='count(*) as count')[0] if clients.count >= self.maxUsers: raise web.seeother('/data/warning') try: cookie = web.cookies() if cookie.user == '' and cookie.color == '': Color = self.color() User = self.name() web.setcookie('color', Color, 604800) web.setcookie('user', User, 604800) timestamp = time.strftime("%Y-%m-%d %I:%M:%S %p") db.insert('user', user=User, color=Color, timestamp=timestamp) else: data = db.select('user', where='user="******"'.format(cookie.user)) if not data: x except BaseException as ex: print ex web.setcookie('user', '', 3600) web.setcookie('color', '', 3600) raise web.seeother('/')
def sign_up(): data = { 'username': request.form.get("username"), 'password': request.form.get("password"), 'email': request.form.get("email") } aids = db.select(conn, 'account', ['aid'], dict()) aids = set([t['aid'] for t in aids]) data['aid'] = ''.join(random.choice(letters + numbers) for j in range(10)) while data['aid'] in aids: data['aid'] = ''.join( random.choice(letters + numbers) for j in range(10)) res = db.insert(conn, 'account', data) if res is True: sids = db.select(conn, "stocks", "*", dict()) random.seed(time.time()) rec_stk = random.sample(sids, 10) for stk in rec_stk: db.insert(conn, "rec_stk", {'aid': data['aid'], 'sid': stk['sid']}) resp = make_response(redirect(url_for("homepage.all_records"))) resp.set_cookie('aid', data['aid']) return resp else: return render_template('/login/SignUp.html', msg="name or email duplicate")
def buy_stock(): aid = request.cookies.get('aid') if aid is None or aid == "": return redirect(url_for("login.sign_in")) data = { 'aid': aid, 'sid': request.form.get('sid'), 'num': request.form.get('num'), 'price': float(request.form.get('price')) } if data['num'] == "": return redirect(url_for(".stock_market")) else: data['num'] = int(data['num']) tmp = db.select(conn, 'own_stk', "*", {'sid': data['sid'], 'aid': aid}) if len(tmp) == 0: db.insert(conn, 'own_stk', data) else: new_num = int(tmp[0]['num']) + data['num'] new_price = (float(tmp[0]['price']) * int(tmp[0]['num']) + data['num'] * data['price']) / new_num db.update(conn, 'own_stk', {"=": { 'price': new_price, 'num': new_num }}, { 'sid': data['sid'], 'aid': aid }) return redirect(url_for(".own_stock"))
def xwords(words: Union[str, list]): if isinstance(words, str): words = [words] for word in words: for _word in bad_words_variator(word): db.insert(TABLE='xwords', OR=IGNORE, word=_word)
def post_user(): if auth.username() != 'admin': abort_msg(400, 'Access denied, admin needed!') if not request.json: abort_msg(400, 'Expected JSON parameters') if 'user' not in request.json: abort_msg(400, 'Value for "user" not defined') user = request.json['user'] passwd = '' if 'password' in request.json: passwd = request.json['password'] if user == 'admin': abort_msg(400, 'Can\'t create admin') _db = db.connect(settings.settings()) res = db.select(_db, 'users', where='name=\'%s\'' % user) if res: abort_msg(400, 'User \"%s\" already exists' % user) if not passwd: passwd = utils.generatePassword(20) db.insert(_db, 'users', [user, passwd, utils.generateApiKey()]) data = {'user': request.json['user'], 'password': passwd} return jsonify(data)
def sign_in(): data = { 'name': request.form.get("username"), 'pwd': request.form.get("password") } res = db.select(conn, 'account', ['aid'], data) if res is not None and len(res) != 0: log = dict() lids = db.select(conn, 'logs', ['lid'], dict()) lids = set([t['lid'] for t in lids]) log['lid'] = ''.join( random.choice(letters + numbers) for j in range(10)) while log['lid'] in lids: log['lid'] = ''.join( random.choice(letters + numbers) for j in range(10)) log['if_log_in'] = True log['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) log['aid'] = res[0]['aid'] db.insert(conn, 'logs', log) resp = make_response(redirect(url_for("homepage.all_records"))) resp.set_cookie(key='aid', value=res[0]['aid'], expires=None) return resp else: return render_template('/login/SignIn.html', msg="error user name or password")
def register_user(phone, password): token = util.generate_access_token(password) salt = util.generate_salt() db.execute('update user set token = "%s", password = "******", salt = "%s", pass = 1 where phone = "%s"' % (token, util.bcrypt_password(password + salt), salt, phone)) uid = db.query_one('select id from user where phone = %s' % phone)['id'] db.insert('user_settings', {'user': uid}) db.insert('user_info', {'user': uid, 'nick': phone})
def submit_question(): form = request.form question = form['question'] answer = form['answer'] date = form['date'] tags = form['tags'].split(' ') db.insert(question, answer, date, tags) db.commit() return redirect(url_for("qaform"))
def POST(self): if (web.config._session.roleid != 1): raise web.seeother('/') pdata = web.input(category=None) db.insert('Categories', category = pdata.category) items = get_menu_items() tags = db.select('Categories').list() menu_table = render.menu_editor(items, tags) return render_page(menu_table)
def apply_job(user_id, job_id): sql = 'select id from apply_job where user = %s and job = %s' % (user_id, job_id) if _db.query_one(sql) is None: _db.insert('apply_job', {'user': user_id, 'job': job_id}) _db.execute('update job set apply = apply + 1 where id = %s' % job_id) r = _db.query_one('select company from job where id = %s' % job_id) _db.execute('update company_info set apply = apply + 1 where company = %s' % r['company']) return True return False
def before_request(): setup.create_db() _db = db.connect(settings.settings()) res = db.select(_db, 'users', ['pass'], 'name=\'%s\'' % ('admin')) if res is None or not res: admin_pass = utils.generatePassword(20) db.insert(_db, 'users', ['admin', admin_pass, utils.generateApiKey()]) print('Password for admin: "%s", keep this in safe place!\n' % (admin_pass))
def put(self): entry = json.loads(request.form["entry"]) question = entry.get("question", "") answer = entry.get("answer", "") date = entry.get("date", "") tags = entry.get("tags", "") db.insert(question, answer, date, tags) db.commit() return "", 200
def make_rec_stk(): aids = db.select(conn, "account", ["aid"], dict()) aids = [t['aid'] for t in aids] for user in aids: db.delete(conn, 'rec_stk', {'aid': user}) sids = db.select(conn, "stocks", "*", dict()) random.seed(time.time()) rec_stk = random.sample(sids, 10) for stk in rec_stk: db.insert(conn, "rec_stk", {'aid': user, 'sid': stk['sid']})
def register_company(email, password): salt = util.generate_salt() _db.insert( 'company', { 'email': email, 'password': util.bcrypt_password(password + salt), 'salt': salt }) cid = _db.query_one('select id from company where email = %s' % email) _db.insert('company_info', {'company': cid}) return True
def setUp(self): db.delete('Orders', where='1=1') db.delete('OrderedItems', where='1=1') db.delete("MenuItems", where='1=1') db.insert('MenuItems', id=1, name='Chicken', description='Chicken', price=20) self.torders = new_order() self.titems = new_item() self.tquant = new_quantity() self.config_mock = MagicMock() self.config = patch('web.config', new=self.config_mock) self.config_mock._session.roleid = 2
def todayId(self): """ Returns id in date table of date matching todays date. If no record is found a new record is created. """ wherestr = 'year=%s and month=%s and day=%s'%(self.year, self.month, self.day) today = db().select('date', cols='id', where=wherestr) if today == "": db.insert('date', {'day':self.day, 'month':self.month, 'year': self.year}) today = db().select('date', cols='id', where=wherestr) return today
def adduser(self, user, token, typed): dic = dict() dic['user'] = user dic['token'] = token dic['type'] = typed try: db.insert('users', dic) return True except BaseException: return False
def clientthread(conn): qe = QueryEngine() #Sending message to connected client #conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string #infinite loop so that function do not terminate and thread do not end. while True: #Receiving from client reply = '' data = conn.recv(1024) #print data params = qe.deserialize(data) param_type = params[0] print param_type print 'PARAMS', params if param_type == QueryType.SELECT: reply = db.select(msToSec(params[1]), params[2]) elif param_type == QueryType.INSERT: if params[2]=='': pass else: db.insert(msToSec(params[1]),params[2], params[3]) reply = "inserting " + data #reply = db.insert(params[1:]) elif param_type == QueryType.UPDATE: reply = "updating" #reply = db.update(params[1:]) elif param_type == QueryType.SELECTRANGE: #dbResponse = list(db.selectRangeForDisplay(msToSec(params[1]), msToSec(params[2]), params[3])) dbResponse = list(db.selectRangeAndInterval(msToSec(params[1]), msToSec(params[2]), params[3],params[4])) dbResponse.insert(0, QueryType.SERVER_REPLY) reply = qe.serialize(dbResponse) elif param_type == QueryType.INC_AVG: reply = db.getRunningAverage(params[1]); elif param_type == QueryType.INC_COUNT: reply = db.getAggregateCountInRange(msToSec(params[1]), msToSec(params[2]), params[3]) elif param_type == QueryType.INC_VAR: reply = db.getRunningVariance(params[1]); else: # throw exception reply = "Invalid arguments, should be start with SELECT, INSERT, or UPDATE" print reply conn.sendall(reply) #conn.close() conn.close()
def setup_admin(show_passwd=False): _db = db.connect(settings.settings()) res = db.select(_db, 'users', ['pass'], 'name=\'%s\'' % ('admin')) if res is None or not res: admin_pass = utils.generatePassword(20) db.insert(_db, 'users', ['admin', admin_pass, utils.generateApiKey()]) print ('Password for admin: "%s", keep this in safe place!' % (admin_pass)) elif show_passwd: print ('Admin password: %s' % (res[0])) else: print ('Admin already set up')
def crawl_nk(): url = config.link["nk"] pages = config.page["nk"] data = {} shop = config.main_shop["nk"] for page in pages: response = requests.get(url + str(page), headers=config.headers) soup = BeautifulSoup(response.content, "html.parser") try: product_list = soup.find("div", id="pagination_contents").find_all("div", class_="item nk-fgp-items " "nk-new-layout-product-grid") except: print(f"{url + str(page)} has no data!") continue for product in product_list: try: id = product.attrs["id"] main_item = product.find("div", class_="nk-product-desc") label = main_item.find("p", class_="label").find("span").text price_item = main_item.find("div", class_="price-details") now_price = re.sub('[^0-9]', '', price_item.find("div", class_="price-now").find("span").text) link = product.find("a").attrs["href"] except Exception as e: continue try: input = product.find("input") brand = input.attrs["data-brand"] currency = input.attrs["data-currency"] description = input.attrs["data-description"] old_price = re.sub('[^0-9]', '', price_item.find("p", class_="price-old").find("span").text) except: brand = "" currency = "" description = "" old_price = now_price if id not in data.keys(): data[id] = {"id": id, "label": label, "now_price": now_price, "old_price": old_price, "brand": brand, "currency": currency, "description": description, "link": link} insert(shop, label, now_price, old_price, link) with open('../data/nk.json', 'w', encoding='utf8') as json_file: json.dump(data, json_file, ensure_ascii=False) return 0
def add_plans(): aid = request.cookies.get('aid') if aid is None or aid == "": return redirect(url_for("login.sign_in")) plan = { 'aid': aid, 'starting': to_valid_time(request.form.get("starting")), 'ending': to_valid_time(request.form.get("ending")), 'cycle': request.form.get("cycle"), 'budget': request.form.get("budget") } if plan['budget'] == "": return render_template("/plans/AddingPlan.html", msg="illegal value") pids = db.select(conn, 'plans', ['pid'], dict()) pids = set([t['pid'] for t in pids]) plan['pid'] = ''.join(random.choice(letters + numbers) for j in range(10)) while plan['pid'] in pids: plan['pid'] = ''.join( random.choice(letters + numbers) for j in range(10)) begin, end = find_current_period(plan['starting'], plan['cycle']) sql = """select SUM(amt) as total from records where aid = '%s' and time is not null and time >= '%s' and time <= '%s';""" % ( aid, begin, end) existed_amt = db.special_select(sql)[0]['total'] plan['credit'] = float(plan['budget']) - float(existed_amt) res = db.insert(conn, 'plans', plan) if res is True: return redirect(url_for(".own_plans")) else: return render_template("/plans/AddingPlan.html", msg="illegal value")
def test_successful_insertion(rethink_connect): data = { 'name': 'A Star is Born', 'year': 2018, 'runtime': 135, 'categories': ['drama', 'music', 'romance'], 'release-date': '2018-09-07', 'director': 'Bradley Cooper', 'writer': ['Lady Gaga', 'Bradley Cooper', 'Sam Elliot'], 'actors': [ 'Eric Roth', 'Bradley Cooper', 'Will Fetters', 'William A. Wellman', 'Robert Carson' ], 'storyline': "Seasoned musician Jackson Maine (Bradley Cooper) " "discovers-and falls in love with-struggling artist " "Ally (Gaga). She has just about given up on her " "dream to make it big as a singer - until Jack coaxes " "her into the spotlight. But even as Ally's career " "takes off, the personal side of their relationship is " "breaking down, as Jack fights an ongoing battle with " "his own internal demons. Written by Warner Bros." } result = insert(database, table, data, rethink_connect) assert result is not None assert result['inserted'] is 1
def test_delete_item(self): itemid = db.insert('MenuItems', name= 'Chicken', description='Desc', price=20) delete_item(itemid) ret = db.select('MenuItems', where='name="Chicken"') with self.assertRaises(IndexError): mitem = ret[0]
def test_unsuccessful_insertion(rethink_connect): global unique_id data = { 'name': 'The Dark Knight Rises', 'year': 2012, 'runtime': 163, 'categories': ['adventure', 'thriller'], 'release-date': '2012-07-20', 'director': 'Christopher Nolan', 'writer': ['Jonathan Nolan', 'David S. Goyer', 'Christopher Nolan', 'Bob Kane'], 'actors': ['Christian Bale', 'Tom Hardy', 'Anne Hathway'], 'storyline': 'Eight years after the Joker\'s reign of anarchy,' ' the Dark Knight, with the help of the enigmatic' ' Catwoman, is forced from his imposed exile to save' ' Gotham City, now on the edge of total annihilation,' ' from the brutal guerrilla terrorist Bane.' } data.update({'id': unique_id}) result = insert(database, table, data, rethink_connect) assert result is not None assert len(result) is 0
def test_unsuccessful_insertion(rethink_connect): global unique_id data = { "name": "The Dark Knight Rises", "year": 2012, "runtime": 163, "categories": ["adventure", "thriller"], "release-date": "2012-07-20", "director": "Christopher Nolan", "writer": ["Jonathan Nolan", "David S. Goyer", "Christopher Nolan", "Bob Kane"], "actors": ["Christian Bale", "Tom Hardy", "Anne Hathway"], "storyline": "Eight years after the Joker's reign of anarchy," " the Dark Knight, with the help of the enigmatic" " Catwoman, is forced from his imposed exile to save" " Gotham City, now on the edge of total annihilation," " from the brutal guerrilla terrorist Bane.", } data.update({"id": unique_id}) result = insert(database, table, data, rethink_connect) assert result is not None assert len(result) == 0
def new(self, **kwargs): _dirty_fields = [] _values = [] for k, v in kwargs.iteritems(): _dirty_fields.append(k) if k in self.__time_fields and v: v = datetime.fromtimestamp( v ) kwargs[k] = v _values.append(v) self.__dict__.update(kwargs) _sql = 'INSERT INTO %s (' % self.table + ','.join(_dirty_fields) + ') VALUES (' \ + ','.join(['%s'] * len(_values)) + ')' res = yield db.insert(_sql, _values) if self.table == 'tb_character': if res > 1000000: db.execute('DELETE FROM {0} WHERE id={1};'.format(self.table, res)) log.error('insert error. res:{0}, _values:{1}.'.format( res, _values )) raise AttributeError('Attribute: insert new character id error') new_res = kwargs.get('sid', 1001)*1000000 + res db.execute('UPDATE {0} SET id={1} WHERE id={2};'.format(self.table, new_res, res)) self.__uid = new_res log.error('For Test. table:{0}, res:{1}, new_res:{2}.'.format( self.table, res, new_res )) else: self.__uid = res defer.returnValue(self.__uid)
def save_audit(identifier, request_type, payload, time): try: connection = configure_database(ReDB_HOST, ReDB_PORT, ReDB_AUDIT_DB, ReDB_USER, ReDB_PASS) audit_data = { "identifier": identifier, "type": request_type, "payload": payload, "time": time, } result = insert(ReDB_AUDIT_DB, ReDB_AUDIT_TABLE, audit_data, connection) if result == {}: raise Exception(f"[ERROR] Error trying to insert data. " f"Verify the logs for the full traceback. " f"The data was not inserted!") else: logging.info(f"[INFO] Audit data saved into Rethink DB!\n" f"Saved payload: {audit_data}\nRethink output" f": {result}") disconnect_database(connection) return True except Exception as err: if connection: disconnect_database(connection) raise err except KeyboardInterrupt as err: disconnect_database(connection) raise err except ConnectionClosed as err: disconnect_database(connection) raise err except CancelledError as err: disconnect_database(connection) raise err
def new(self, **kwargs): _dirty_fields = [] _values = [] for k, v in kwargs.iteritems(): _dirty_fields.append(k) if k in self.__time_fields and v: v = datetime.fromtimestamp(v) kwargs[k] = v _values.append(v) self.__dict__.update(kwargs) _sql = 'INSERT INTO %s (' % self.table + ','.join(_dirty_fields) + ') VALUES (' \ + ','.join(['%s'] * len(_values)) + ')' res = yield db.insert(_sql, _values) if self.table == 'tb_character': if res > 1000000: db.execute('DELETE FROM {0} WHERE id={1};'.format( self.table, res)) log.error('insert error. res:{0}, _values:{1}.'.format( res, _values)) raise AttributeError( 'Attribute: insert new character id error') new_res = kwargs.get('sid', 1001) * 1000000 + res db.execute('UPDATE {0} SET id={1} WHERE id={2};'.format( self.table, new_res, res)) self.__uid = new_res log.error('For Test. table:{0}, res:{1}, new_res:{2}.'.format( self.table, res, new_res)) else: self.__uid = res defer.returnValue(self.__uid)
def add_defaults(): aid = request.cookies.get('aid') if aid is None or aid == "": return redirect(url_for("login.sign_in")) default = { 'aid': aid, 'name': request.form.get("name"), 'be_from': request.form.get("be_from"), 'be_to': request.form.get("be_to"), 'starting': to_valid_time(request.form.get("starting")), 'ending': to_valid_time(request.form.get("ending")), 'cycle': request.form.get("cycle"), 'amt': request.form.get("amt"), 'remark': request.form.get("remark"), 'tag': request.form.get("tag") } dids = db.select(conn, 'defaults', ['did'], dict()) dids = set([t['did'] for t in dids]) default['did'] = ''.join( random.choice(letters + numbers) for j in range(10)) while default['did'] in dids: default['did'] = ''.join( random.choice(letters + numbers) for j in range(10)) res = db.insert(conn, 'defaults', default) if res is True: return redirect(url_for(".own_defaults")) else: return render_template("/defaults/AddingDefaults.html", msg="illegal value")
def test_set_status(self): itemid = db.insert('MenuItems', name= 'Chicken', description='Desc', price=20) set_status(itemid, False) ret = db.select('MenuItems', where='name="Chicken"') mitem = ret[0] self.assertFalse(mitem.available)
def writelogs(self, token, ip, message): try: user = self.getuser(token) except BaseException as e: raise e user = user[0] if user else 'NULL' dic = dict() dic['time'] = time_() dic['user'] = user dic['ip'] = ip dic['message'] = message try: db.insert('logs', dic) return True except BaseException: return False
def _index(): if not request.values.get("song"): return redirect("/?song=0") page = int(request.values.get("song")) if request.method == "POST": song = request.files.getlist('song[]') for song in song: name = song.filename if not name.endswith(".mp3"): return "Only MP3 files are supported." name = uuid.uuid4().hex+".mp3" with open("static/songs/"+name, 'wb') as file: file.write(song.read()) obj = Reader("static/songs/"+name) title = obj.getValue("title") if not title: title = song.filename.split(".mp3")[0] artist = obj.getValue("performer") if not artist: artist = "Unknown" year = obj.getValue("year") url = "../static/songs/"+name if not db.find("songs", {"title":title}): db.insert("songs", {"title":title, "artist":artist, "year":year, "url":url}) else: os.remove("static/songs/"+name) songs = db.find("songs", "all") playlists = db.find("playlists", "all") if songs: try: first = songs[page] except IndexError: return redirect("/") else: first = [] if not playlists: playlists = [] if not songs: songs = [] if page > 0: autoplay = {"autoplay":"autoplay", "play":"pause"} else: autoplay = {"autoplay":"", "play":"play"} return render_template("index.html", autoplay=autoplay, page=page, first=first, songs=songs, playlists=playlists)
def users(request): if request.method == 'POST': user = db.insert('users', request.data) return JSONResponse(user, status=HTTP_CREATED) data = db.get('users') return JSONResponse(data=data)
def register_user(username, password, email): password, salt = gen_password(password) return db.insert( 'users', **{ 'username': username, 'password': password, 'email': email, 'salt': salt, 'create_time': web.SQLLiteral("unix_timestamp(NOW())")} )
def test_change_pass(self): uid = db.insert('Users', uname='kevin', role=1, password=self.passwd) users.change_pass(uid, 'newpassword') ret = db.select('Users', where="uname='kevin'") user = ret[0] phash = str(user.password); expected = bcrypt.hashpw('newpassword', phash) self.assertEquals(expected, phash)
def post_machine(): if not request.json: abort_msg(400, 'Expected JSON input') # TODO: quota per user res = { 'memory': 256 * 1024, # FIXME some reasonable default 'cpus': 1, 'name': utils.generateID(), 'net': '', 'image': '', 'size': '', 'cdrom': '', } if 'mem' in request.json: res['memory'] = request.json['mem'] if 'memory' in request.json: res['memory'] = request.json['memory'] if 'size' in request.json: res['size'] = request.json['size'] if 'cpus' in request.json: try: res['cpus'] = int(request.json['cpus']) except: pass if 'image' in request.json: res['image'] = request.json['image'] if 'cdrom' in request.json: res['cdrom'] = request.json['cdrom'] if 'name' in request.json: res['name'] = request.json['name'] _db = db.connect(settings.settings()) db.insert(_db, 'machines', [res['name'], '', '', auth.username(), '']) act = actions.provider(settings.settings()) act.sendActionNow({'createMachine': res}, None) data = { 'uri': url_for('machine_id', machine_id=res['name'], _external=True), 'id': res['name'] } return jsonify(data)
def sign_out(): resp = make_response(redirect(url_for(".sign_in"))) aid = request.cookies.get('aid') resp.delete_cookie('aid') log = dict() lids = db.select(conn, 'logs', ['lid'], dict()) lids = set([t['lid'] for t in lids]) log['lid'] = ''.join(random.choice(letters + numbers) for j in range(10)) while log['lid'] in lids: log['lid'] = ''.join( random.choice(letters + numbers) for j in range(10)) log['if_log_in'] = False log['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) log['aid'] = aid db.insert(conn, 'logs', log) return resp
def setUp(self): self.passwd = "$2a$12$CyLyLDPA5NFTY48o3fANQOEsni38JgHBk3FNwdUFd1OwYMBZxN146" db.delete('Users', where='id > 0') self.uid = db.insert('Users', uname='kevin', role=1, password=self.passwd) self.input_mock = MagicMock() self.winput = patch('web.input') self.config_mock = MagicMock() self.config = patch('web.config', new=self.config_mock) self.login_web = login() self.logout_web = logout()
def configure_database(): connection = connect(ReDB_HOST, ReDB_PORT, user=ReDB_USER, password=ReDB_PASS) create_table(database, empty_table, connection) delete_all(database, table, connection) data = [{ 'name': 'The Dark Knight Rises', 'year': 2012, 'runtime': 163, 'categories': ['adventure', 'thriller'], 'release-date': '2012-07-20', 'director': 'Christopher Nolan', 'writer': ['Jonathan Nolan', 'David S. Goyer', 'Christopher Nolan', 'Bob Kane'], 'actors': ['Christian Bale', 'Tom Hardy', 'Anne Hathway'], 'storyline': 'Eight years after the Joker\'s reign of anarchy,' ' the Dark Knight, with the help of the enigmatic' ' Catwoman, is forced from his imposed exile to save' ' Gotham City, now on the edge of total annihilation,' ' from the brutal guerrilla terrorist Bane.' }, { 'name': 'Avengers: Infinity War', 'year': 2018, 'runtime': 149, 'categories': ['Action', 'Adventure', 'Fantasy'], 'release-date': '2018-04-27', 'director': ['Anthony Russo', 'Joe Russo'], 'writer': ['Christopher Markus', 'Stephen McFeely'], 'actors': [ 'Robert Downey Jr.', 'Chris Hemsworth', 'Mark Ruffalo', 'Chris Evans', 'Scarlett Johansson', 'Benedict Cumberbatch' ], 'storyline': 'The Avengers and their allies must be willing to' ' sacrifice all in an attempt to defeat the' ' powerful Thanos before his blitz of devastation' ' and ruin puts an end to the universe.' }] result = insert(database, table, data, connection) global unique_id unique_id = result['generated_keys'][0]
def modify_post(**kwargs): action = kwargs.get('action', 'create') if action == 'create': kwargs['author_id'] = web.config.get('_session').user_id kwargs['create_time'] = kwargs['update_time'] = time.mktime( datetime.utcnow().timetuple()) return db.insert('articals', **kwargs) elif action == 'update': artical_id = kwargs.pop('artical_id') #kwargs['update_time'] = time.mktime( return db.update('articals', **kwargs)
def test_web_hide_item(self): itemid = db.insert('MenuItems', name= 'Chicken', description='Desc', price=20) with self.winput as info: self.input_mock.action = 'hide' self.input_mock.item = itemid info.return_value = self.input_mock with self.config: with self.assertRaises(Exception): self.menued.POST() ret = db.select('MenuItems', where='id=$itemid', vars=locals()) mitem = ret[0] self.assertFalse(mitem.available)
def test_web_delete_item(self): itemid = db.insert('MenuItems', name= 'Chicken', description='Desc', price=20) with self.winput as info: self.input_mock.action = 'delete' self.input_mock.item = itemid info.return_value = self.input_mock with self.config: with self.assertRaises(Exception): self.menued.POST() ret = db.select('MenuItems', where='1=1') with self.assertRaises(IndexError): mitem = ret[0]
def test_delete_user(self): uid = db.insert('Users', uname='kevin', role=1, password=self.passwd) users.del_user('kevin') ret = db.select('Users', where="id=$uid", vars=locals()) with self.assertRaises(IndexError): print ret[0]
def setUp(self): self.oid = db.insert('Orders', waiter = 2)
# coding=utf-8
def add_user(uname, utype, passwd): db.insert('Users', uname=uname, role=utype, password=bcrypt.hashpw(str(passwd), bcrypt.gensalt()) )
def create_item( item, desc, price, picPath=None): db.insert('MenuItems', name=item, description=desc, price=price, picture=picPath)
def post_complaint(self, complaint, order=None): wid = None if order: od = db.select('Orders', what='waiter', where='id='+order) wid = od[0].waiter db.insert('Complaints', waiter_id=wid, complaint=complaint)
def save(self,update=False): if update == False: db.insert(table, username=self.username, password=self.encrypt_passwd, **self.opts) else: db.update(table, where="username=$username", vars={'username':self.username}, password=self.encrypt_passwd, **self.opts)
def setUp(self): self.passwd = "$2a$12$CyLyLDPA5NFTY48o3fANQOEsni38JgHBk3FNwdUFd1OwYMBZxN146" db.delete('Users', where='id > 0') self.uid = db.insert('Users', uname='kevin', role=1, password=self.passwd) self.uinfo = users.user_info()
def setUp(self): self.olist = range(0,5) for x in xrange(0,5): self.olist[x] = db.insert('Orders', waiter = 2)