Exemple #1
0
 def add():
     name = request.form['name']
     price = int(request.form['price'])
     qty = int(request.form['qty'])
     good = Good(0, name, price, qty)
     db.add(db.open_db(db_url), good)
     return redirect(url_for('index'))
def signin(db):
    session = bottle.request.environ.get('beaker.session')
    username = bottle.request.forms.username.strip().lower()
    email = bottle.request.forms.email.strip().lower()
    username_re = re.compile(r'^[_0-9A-Za-z]{5,20}$')
    email_re = re.compile(r'^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$')
    password = bottle.request.forms.password
    if not username_re.match(username):
        return {'ok':False,'msg':u"Имя пользователя должно быть не менее 5 и \
не более 20 символов, и содержать латинские буквы и цифры и знак подчеркивания"}
    if not email_re.match(email):
        return {'ok':False, 'msg': u"Неправильный формат e-mail"}
    if len(password) < 6:
        return {'ok':False,'msg':u"Пароль должен содержать не менее 7 символов"}
    user = db.query(User).filter(or_(User.name==username,User.email==email)).first()
    if not user:
        new_user = User(name = username, 
                        password=hashlib.sha256(password).hexdigest(),
                        email = email)
        new_user_notebook = Notebook(name=u"Блокнот", deflt=True)
        new_user_notebook.user = new_user
        new_note = Note(text=u"Добро пожаловать в Notebook!", title=u"Первая заметка");
        new_user_notebook.notes.append(new_note);
        db.add(new_user)
        db.commit()
        session['user_id'] = new_user.id
        return {'ok':True, 'msg':u"Пользователь {0} создан.".format(new_user.name)}
    else:
        return {'ok':False,'msg':u"Пользователь с таким именем или адресом e-mail уже существует"}
Exemple #3
0
def zcn(s,id):
    '''
      查询淘宝中此商品信息,s为关键词,id为生成id,将查到的商品保存到数据库id表中并返回成功数目
      参数说明:
         s: 关键词
    '''
    global pic,name,price,deal
    pic=[];name=[];price=[];deal=[] #清零
    #将关键词转成网页编码
    s=urllib.quote(s)
    s.replace('%20','+')
    url='http://www.amazon.cn/s/field-keywords=%s'%s
    start=0 #起始位置
    text="" #查询内容
    db.create(id)
    text=requests.get(url).text#requsts经测试比urllib快
    find(text)
    s=[1,2,3,4,5,6,7]
    for i in range(len(name)): #按格式写入文件
        s[0]=name[i][1].encode('gbk');s[1]=pic[i].encode('gbk');s[2]=name[i][0].encode('gbk');
        s[3]=(price[i].encode('gbk')).replace(',','')
        s[4]=-1;s[5]=-1;s[6]='亚马逊'
        #print s
        db.add(id,s)
    return len(name)    
Exemple #4
0
def useradd():
    if not session.get('name'):
        return redirect('/login')
    if request.method == 'GET':
        return render_template('add.html', role=session.get('role'))
    if request.method == 'POST':
        l = []
        data = dict((k, v[0]) for k, v in dict(request.form).items())
        data['password'] = md5(request.form.get('password') + salt).hexdigest()

        for i in db.list('users', fields_user):
            l.append(i['name'])
        if not data['name']:
            return json.dumps({'code': 1, 'errmsg': 'name can not be null'})
        elif not data['name_cn']:
            return json.dumps({
                'code': 1,
                'errmsg': 'chinese name can not be null'
            })
        elif not data['password']:
            return json.dumps({
                'code': 1,
                'errmsg': 'password can not be null'
            })
        elif data['name'] not in l:
            conditions = ["%s='%s'" % (k, v) for k, v in data.items()]
            db.add('users', conditions)
            return json.dumps({'code': 0, 'result': 'add user success'})
        return json.dumps({'code': 1, 'errmsg': 'username is exist'})
Exemple #5
0
def lambda_handler(event, context):
    purchaseID = None
    print("event")
    print(event)
    print("context")
    print(context)

    userID = event['session']['user']['userId']

    name = extract_name(event, context)
    location = extract_lat_long(event, context)
    phoneNumber = extract_phone(event, context)
    # This is the user phone number
    productResponse = get_product_response(event, context)
    endSession = True
    if event["request"]["type"] == "LaunchRequest":
        speech = responses.start_response()
        endSession = False
    elif event["request"]["type"] == "IntentRequest":

        if event["request"]["intent"]["name"] == 'whatBuy':
            speech = responses.what_can_i_buy()
        else:
            isPurchased = productResponse['inSkillProducts'][0][
                'entitlementReason'] == 'PURCHASED'

            if isPurchased and db.get_user(userID) != None:
                restaraunt = event["request"]["intent"]["slots"]["restaraunt"][
                    "value"]
                speech, uuid, restaurantNumber = on_intent(
                    event["request"], event["session"], location, name,
                    phoneNumber)
                db.add(userID, restaraunt, location, uuid, restaurantNumber)
                echo.make_call(restaurantNumber, db.get_user(userID)['uuid'])
                db.delete(userID)

            else:
                purchaseID = productResponse['inSkillProducts'][0]['productId']
                restaraunt = event["request"]["intent"]["slots"]["restaraunt"][
                    "value"]
                dateVal = event["request"]["intent"]["slots"]["dateVal"][
                    "value"]
                timeVal = event["request"]["intent"]["slots"]["timeVal"][
                    "value"]
                speech, uuid, restaurantNumber = on_intent(
                    event["request"], event["session"], location, name,
                    phoneNumber, dateVal, timeVal)
                db.add(userID, restaraunt, location, uuid, restaurantNumber)
    else:
        echo.make_call(
            db.get_user(userID)['restaurant_number'],
            db.get_user(userID)['uuid'])
        # echo.make_call(RESTAURANT_PHONE_NUMBER, db.get_user(userID)['uuid'])
        db.delete(userID)
        speech = "We will let you know after the reservation has been made"
        send_text(
            "Reservation has been successfully placed for {}".format(name))
    x = returnSpeech(speech, product=purchaseID, endSession=endSession)
    print(x)
    return x
def getPasswd():  # Get your user and password and stores them in database.
    user = raw_input("Enter userName : "******"Enter password : ")
    if len(user) > 0 and len(passwd) > 0:
        db.add(user, passwd)
    else:
        getPasswd()
Exemple #7
0
def jobadd():
    name = session.get('name')
    id = session.get('id')
    if request.method == 'GET':
        return render_template('/job/jobadd.html',
                               info=session,
                               role=session.get('role'))
    else:
        data = dict((k, v[0]) for k, v in dict(request.form).items())
        data['apply_persion'] = name

        if not data['apply_desc']:
            return json.dumps({
                'code': 1,
                'errmsg': 'job description can not be null'
            })
        conditions = ["%s='%s'" % (k, v) for k, v in data.items()]
        db.add('ops_jobs', conditions)

        # 获取申请人email地址
        user = db.list('users', fields_user, id)
        # 从用户列表获取邮箱账号和密码
        email, passwd = user['email'], base64.b64decode(user['email_password'])
        # 发送邮件(申请人发邮件给当天值班人)
        # myMail.myMail(email,passwd,duty_email,data['apply_desc'])
        # 异步发送
        thr = Thread(target=myMail.myMail,
                     args=(email, passwd, duty_email, data['apply_desc']))
        thr.start()

        return json.dumps({'code': 0, 'result': 'apply job success'})
Exemple #8
0
def taobao(s,id):
    '''
      查询淘宝中此商品信息,s为关键词,id为生成id,将查到的商品保存到数据库id表中并返回成功数目
      参数说明:
         s: 关键词
    '''
    global pic,name,price,deal
    pic=[];name=[];price=[];deal=[] #清零
    #将关键词转成网页编码
    s=urllib.quote(s)
    s.replace('%20','+')
    url='http://s.taobao.com/search?q=%s&s='%s
    start=0 #起始位置
    text="" #查询内容
    db.create(id)
    while start==0 or find(text)!=0:
        text=requests.get(url+str(start)).text.encode('u8')#requsts经测试比urllib快
        start+=44
        if start>220:break #只抓取前5页
    s=[1,2,3,4,5,6,7]
    for i in range(len(name)): #按格式写入文件
        s[0]=name[i][1].decode('u8').encode('gbk');s[1]=pic[i];s[2]=name[i][0];s[3]=price[i][0]
        s[4]=price[i][1];s[5]=deal[i];s[6]='淘宝'
        #print s
        db.add(id,s)
    return len(name)    
Exemple #9
0
  def start(self):
    game = self.session.query(Games).order_by(Games.game_id.desc()).first()
    if  not game is None and game.result == 0:
      self.player.setHand(list(game.player_hand))
      self.dealer.setHand(list(game.dealer_hand))
      self.game.setDeck(list(game.deck))

    start(self.game,self.player,self.dealer)
    r1 = self.player.getResult(self.game) 
    r2 = self.dealer.getResult(self.game)

    if ( r1 == "" and r2 == ""):
      message = ""
      result = 0
    else:
      message = ' use start() to start a new game'
      result = 1

    if game is None or game.result == 1:
      add(self.session,self.player.hand,self.dealer.hand,self.game.deck,result)
    else:
      update(game,self.player.hand,self.dealer.hand,self.game.deck,result)

    self.session.commit()

    return "Player's hand: ", self.player.hand, "Dealer's hand: ", self.dealer.hand,'  ',r1+r2,message
Exemple #10
0
 def run(self):
     while True:
         binary_data, addr = self.sock.recvfrom(config.chunk_size)
         if binary_data:
             d = self.parsed(msgpack.unpackb(binary_data))
             db.add(d).callback(True)
             self.q.put(d, True)
Exemple #11
0
  def hit(self):
    game = self.session.query(Games).order_by(Games.game_id.desc()).first()
    if not game is None and game.result == 0:
      self.player.setHand(list(game.player_hand))
      self.dealer.setHand(list(game.dealer_hand))
      self.game.setDeck(list(game.deck))

    checkDeck(self.game,self.player,self.dealer)
    self.player.drawCard(self.game)
    points = self.player.getPoints(self.game)
    result = 1
    if (points == 21):
      message = "Player wins! " + ','.join(self.player.hand) + '  use start() to start a game'
    elif (points > 21):
      message = "Player loses! " + ','.join(self.player.hand) + '  use start() to start a game'
    else:
      result = 0
      message = self.player.hand

    if game is None or game.result == 1:
      add(self.session,self.player.hand,self.dealer.hand,self.game.deck,result)
    else:
      update(game,self.player.hand,self.dealer.hand,self.game.deck,result)

    self.session.commit()


    return message
Exemple #12
0
  def stick(self): 
    game = self.session.query(Games).order_by(Games.game_id.desc()).first()
    if  not game is None and game.result == 0:
      self.player.setHand(list(game.player_hand))
      self.dealer.setHand(list(game.dealer_hand))
      self.game.setDeck(list(game.deck))

    playerPoints = self.player.getPoints(self.game)
    dealerPoints = self.dealer.getPoints(self.game)

    if (dealerPoints > playerPoints): 
      message = " Dealer Wins! " + ','.join(self.dealer.hand) + '  use start() to start a game'  
    else:
      while(dealerPoints < 21):
        checkDeck(self.game,self.player,self.dealer)
        self.dealer.drawCard(game = self.game)
        dealerPoints = self.dealer.getPoints(self.game)
        if (dealerPoints > 21):
          message = " Player Wins!Dealer's hand: " + ','.join(self.dealer.hand) + '  use start() to start a game'
          break
        if (dealerPoints > playerPoints or dealerPoints == 21):
          message = " Dealer Wins! Dealer's hand: " + ','.join(self.dealer.hand) + '  use start() to start a game'
          break

    if game is None or game.result == 1:
      add(self.session,self.player.hand,self.dealer.hand,self.game.deck,1)
    else:
      update(game,self.player.hand,self.dealer.hand,self.game.deck,1)

    self.session.commit()



    return message,"Player's points:",playerPoints,"Dealer's points:",dealerPoints
Exemple #13
0
def serveradd():
    if request.method == 'GET':
        res = db.select('cabinet')
        cabinets = [
            dict((v, idc[k]) for k, v in enumerate(config.idc_fields))
            for idc in res
        ]
        resb = db.select('user')
        users = [
            dict((v, user[k]) for k, v in enumerate(config.user_fields))
            for user in resb
        ]
        return render_template('/server/serveradd.html',
                               cabinets=cabinets,
                               users=users,
                               role=session.get('role'))
    data = {k: v[0] for k, v in dict(request.form).items()}
    res = db.select('server', hostname=data['hostname'])
    if res:
        return json.dumps({
            'code': 0,
            'result': 'add cabinet name already exist'
        })
    db.add('server', data)
    return json.dumps({'code': 1, 'result': 'add cabinet success'})
Exemple #14
0
async def insertUser(user: User, db: Session = Depends(db.get_db)):
    userDB = DB_User(**user.dict())
    db.add(userDB)
    # db.add(user)
    db.commit()
    # db.refresh()
    return user
Exemple #15
0
def perform_update(params):
    user = kerbparse.get_kerberos()
    device = db.get_device_latest(params["id"])
    if not can_edit(user, device):
        raise Exception("no access")
    rack = db.get_rack(params["rack"])
    first, last = int(params["first"]), int(params["last"])
    assert 1 <= first <= last <= rack.height
    if not moira.is_email_valid_for_owner(params["owner"]):
        raise Exception("bad owner")
    ndevice = db.DeviceUpdates(
        id=device.id,
        name=params["devicename"],
        rack=params["rack"],
        rack_first_slot=first,
        rack_last_slot=last,
        ip=params.get("ip", ""),
        contact=params["contact"],
        owner=params["owner"],
        service_level=params.get("service", ""),
        model=params.get("model", ""),
        notes=params.get("notes", ""),
        last_updated_by=user,
    )
    db.add(ndevice)
    db.session.commit()
    send_notification(True, ndevice, user)
    print("Content-type: text/html\n")
    print(jenv.get_template("done.html").render(id=device.id).encode("utf-8"))
Exemple #16
0
def code():
    role = session.get('role')
    if request.method=='GET':
	return render_template('/code/code.html',role=role)
    else:
	data = dict((k,v[0]) for k,v in dict(request.form).items()) # message, key, project
	print data
	key = data.pop('key')
	project = data['project']
	data['update_persion'] = session.get('name')
	conditions = [ "%s='%s'" %  (k,v) for k,v in data.items()]
	if key == 'mmnn88' and data['project']:
	    try:
		localtime = time.strftime('-%Y-%m-%d-%H:%M:%S')
	        project_name = project+localtime # 例如: 'ecg-2016-12-07-10:00:37'
		zip_name = project_name+'.zip'
		print zip_name
	        svncheckout(url[project],path+project_name) # co 到 '/data/ecg-2016-12-07-10:00:37'
		os.chdir(path) # cd '/data'
	  	zip_dir(project_name,zip_name)
		for host in hosts:
		    trans(zip_name,path+zip_name,host)
		    exec_comm('/bin/bash /root/update.sh '+zip_name,host)
    		db.add('code',conditions)
    		return json.dumps({'code':0,'result':'更新成功'})
	    except Exception, e:
		errmsg = '失败信息 error: '+str(e)
    		return json.dumps({'code':1,'errmsg':errmsg})
	elif not data['project']:
	    return json.dumps({'code':1,'errmsg':errmsg})
    def handle_starttag(self, tag, attrs):
        """find out <a> tag anf href attribute in that for urls"""
        import constants
        import logging
        if tag != constants.HTML_TAG_A:
            return

        attrs = dict(attrs)
        url_path = attrs[constants.HTML_TAG_A_ATTR_HREF]

        from html import Html
        from url import InvalidUrlError

        try:
            html = Html.from_url_string(url_string=url_path)
        except InvalidUrlError as e:
            logging.debug(e)

        else:
            import db

            try:
                db.add(html)
            except db.NotUniqueError as e:
                logging.debug(e)
Exemple #18
0
def workadd():
    name = session.get('name')
    id = session.get('id')
    if request.method == 'GET':
        return render_template('/work/workadd.html',
                               info=session,
                               role=session.get('role'))
    else:
        data = dict((k, v[0]) for k, v in dict(request.form).items())
        data['des_name'] = name

        if not data['operate']:
            return json.dumps({
                'code': 1,
                'errmsg': 'work description can not be null'
            })
        conditions = ["%s='%s'" % (k, v) for k, v in data.items()]
        db.add('work', conditions)

        #	# 获取申请人email地址
        #        user = db.list('users',fields_user,id)
        #	# 从用户列表获取邮箱账号和密码(暂时没有)
        #        email,passwd = user['email'],user['password']
        #	# 发送邮件(需要发件人账号密码,密码,收件人,正文)
        #        myMail.mymail(email,passwd,localemail,data)

        return json.dumps({'code': 0, 'result': 'apply work success'})
Exemple #19
0
async def start_handler(message):
    db.add(message.chat.id)
    if message.chat.id < 0:
        return

    await bot.send_message(message.chat.id, consts.text['start'])
    await bot.send_message(message.chat.id,
                           consts.text['menu'],
                           reply_markup=keyboards.start)
Exemple #20
0
async def start_handler(message):
    db.add(message.chat.id)
    if message.chat.id < 0:
        return

    await bot.send_message(message.chat.id, bot_utils.TEXT['start'])
    await bot.send_message(message.chat.id,
                           bot_utils.TEXT['menu'],
                           reply_markup=bot_utils.keyboard_start)
Exemple #21
0
def signup():
    if request.method == "GET":
        return render_template("signup.html")
    else:
        d = {'uname': request.form['uname'], 'pword': request.form['pword']}
        if request.form['button'] == "Submit":
            db.add(d['uname'], d['pword'])
            return redirect(url_for('login'))
        else:
            return render_template("signup.html")
Exemple #22
0
 def record_add(self, name, address, zip, email, number):
     if len(self.address_book) > 5:
         return None
     elif name in self.address_book.keys():
         print("Name already exists")
     else:
         self.address_book[name] = address, zip, email, number
         db.add(name, address, zip, email, number, self.username)
         print("Successfully added " + name)
         return True
def signup():
    if request.method=="GET":
        return render_template("signup.html")
    else:
        d={'uname':request.form['uname'],'pword':request.form['pword']}
        if request.form['button']=="Submit":
            db.add(d['uname'],d['pword'])
            return redirect(url_for('login'))
        else:
            return render_template("signup.html")
Exemple #24
0
 def POST(self):
     storage = web.input(uploadFile={})
     filename = storage.uploadFile.filename  # The filename.
     content = storage.uploadFile.file.read()  # The content of the file.
     title = storage.title  # The title of the new sound.
     artist = storage.artist  # The artist of the new sound.
     db.add(midi_file=content,
            filename=filename,
            title=title,
            artist=artist)
     return
def canAddBoardToDB():
	test_name = "Database: Can add board to DB"

	try:
		database = createTestDB()
		board = createTestBoard()
		db.add(board,database,"boards")

		passTest(test_name)
	except:
		failTest(test_name, sys.exc_info()[1])
def canAddProjectToDB():
	test_name = "Database: Can add project to database"

	try:
		database = createTestDB()
		project = createTestProject()
		db.add(project, database, "projects")

		passTest(test_name)
	except:
		failTest(test_name, sys.exc_info()[1])
Exemple #27
0
def main():

    while True:
        i = int(
            input(
                " 1=> add user, 2=> view user, 3=>remove user ,4=> view all 5=> quit"
            ))
        if i == 1:
            name = input("give user name: ")
            if db.contains(name):
                print("ERROR!! user {} already exists".format(name))
            else:
                pwd = getpass.getpass("give password:"******"confirm passwd:")
                if pwd == pwd2:
                    db.add(name, pwd)
                    print("{} sucessfully added".format(name))
                    disc = input("give description:?? ")
                    db.adddisc(name, pwd, disc)
                else:
                    print("{} not added as typed password not matched".format(
                        name))
        elif i == 2:
            name = input("give user name: ")
            if db.contains(name):
                pwd = getpass.getpass("give password: "******"NAME:   ", name, '\nDISCRIPTION:   ',
                          db.discription(name, pwd))
                else:
                    print("you entered a wrong password for user".format(name))
            else:
                print("user {} does not exist".format(name))
        elif i == 3:
            name = input("give user name: ")
            if db.contains(name):
                pwd = getpass.getpass("give password: "******"you entered a wrong password for user {}".format(
                        name))
            else:
                print("user {} does not exist".format(name))
        elif i == 4:
            db.view()
        elif i == 5:
            print("thank you")
            break
        else:
            print("not a choice")
    else:
        db.close()
def canDeleteCardFromDB():
	test_name = "Database: Delete a card from the collection"

	try:
		database = createTestDB()
		card = createTestCard()
		db.add(card,database,"items")

		db.delete(card,database,"items")
		passTest(test_name)
	except:
		failTest(test_name, sys.exc_info()[1])
def canDeleteBoardFromDB():
	test_name = "Database: Delete a board from the collection"

	try:
		database = createTestDB()
		board = createTestBoard()
		db.add(board,database,"boards")

		db.delete(board,database,"boards")
		passTest(test_name)
	except:
		failTest(test_name, sys.exc_info()[1])
Exemple #30
0
def start(message):
    if db.get_id(str(message.from_user.id)) is None:
        db.add(str(message.from_user.id), str(message.from_user.first_name))

    bot.send_message(
        message.chat.id,
        "Вітаю, {0.first_name}!\nЯ - <b>{1.first_name}</b>, "
        "бот, у якому ви можете створювати власні галереї зображень ".format(
            message.from_user, bot.get_me()),
        parse_mode='html',
        reply_markup=markup1)
    print('has began to play' + str(message.from_user.id))
Exemple #31
0
def perform_add_part(params):
    user = kerbparse.get_kerberos()
    if not is_hwop(user):
        raise Exception("no access")
    part = db.Parts(sku=params["sku"],
                    description=params.get("description", ''),
                    notes=params.get("notes", ""),
                    last_updated_by=user)
    db.add(part)
    print("Content-type: text/html\n")
    print(
        jenv.get_template("done-part.html").render(
            sku=part.sku).encode("utf-8"))
Exemple #32
0
def add_song(song_name_path, artist, song, date, tags,
             format):  # returns id of the song
    """The main function for adding a song in the DB"""

    dst = 'Storage'
    try:
        copy(song_name_path, dst)
        filename = song_name_path.split('/')[1]
        db.add(filename, artist, song, date, tags, format)
    except:
        print("File already exists in Storage")

    pass
Exemple #33
0
def perform_update_stock(params):
    user = kerbparse.get_kerberos()
    if not is_hwop(user):
        raise Exception("no access")
    update = db.Inventory(sku=params["sku"],
                          new_count=int(params["count"]),
                          comment=params.get("comment", ""),
                          submitted_by=user)
    db.add(update)
    print("Content-type: text/html\n")
    print(
        jenv.get_template("done-part.html").render(
            sku=update.sku).encode("utf-8"))
Exemple #34
0
def ask_tag(message):
    print("asking tag")
    words = [message.text]
    if "%" in message.text:
        words = message.text.split()
        db.add(message.from_user.id, words[1], words[0] + ".jpg")

    with open(f"{words[0]}.jpg", 'wb') as new_file:
        new_file.write(inf.downloaded_file)

    saver.upload({f"{words[0]}.jpg"}, inf.folder)
    bot.send_message(message.chat.id, "Your meme is saved")
    os.remove(f"{words[0]}.jpg")
def canDeleteProjectFromDB():
	test_name = "Database: Delete a project from the collection"

	try:
		database = createTestDB()
		project = createTestProject()

		db.add(project, database, "projects")
		db.delete(project,database,"projects")

		passTest(test_name)

	except:
		failTest(test_name, sys.exc_info()[1])
def create_notebook(db):
    session = bottle.request.environ.get('beaker.session')
    user_id = session.get('user_id',0)
    try:
        data = bottle.request.json
        try:
            new_notebook = Notebook(user_id = user_id, name=data['name'] )
        except KeyError:
            return {}
        db.add(new_notebook)
        db.commit()
        return json.dumps(new_notebook.to_dict(), ensure_ascii=False)
    except NoResultFound:
        return {}
Exemple #37
0
def add():

    while True:
        clean()
        print("Wpisanie q przerywa dodawanie")
        code = raw_input("Wczytaj kod:")
        if code == "q": break

        print("Wczytany przedmiot:")
        if db.show(code) == 0: continue

        quantity = float(raw_input("Podaj ilości do dodania:"))
        if quantity > 1000: continue

        db.add(code, quantity)
Exemple #38
0
    def doAdd(self, table, fileds, optional, preAdd=None, postAdd=None):
        data = self.getReq(fileds, optional)
        if not data:
            raise BaseError(801)
        data["create_id"] = self.user["id"]
        # if hoscode:
        # 	data["create_hoscode"] = self.user["hospital_code"]

        #pre add callback
        if not preAdd and hasattr(self, "preAdd"):
            preAdd = self.preAdd
        if preAdd and preAdd(data) == False:
            raise BaseError(801)

        db = self.getDB(table)
        D("doAdd====>" + table)
        results = db.add(data)

        #post add callback
        if not postAdd and hasattr(self, "postAdd"):
            postAdd = self.postAdd
        if postAdd and postAdd(results, data) == False:
            raise BaseError(801)

        #D(results)
        self.response(results)
Exemple #39
0
def addstatus():
    if request.method == 'POST':
        user = "******"
        city = request.form["city"]
        state = request.form["state"]
        country = request.form["country"]
        dnsserver = request.form["dnsserver"]
        #user=request.headers.get('REMOTE_USER')
        #place the new monitored region in the DB
        coordinates = gmap.translate(city, state, country)
        location = ('"' + city + "," + state + "," + country + '"')
        results = mv.verify(dnsserver)
        if results == "Failure":
            return render_template("adderror.html")
        db.add(coordinates, location, dnsserver, user)
        return render_template("addstatus.html", location=location)
Exemple #40
0
    def do_POST(self):
        o = urlsplit(self.path)

        # Only index
        if o.path != '/':
            self.send_error(404)
            return

        postvars = self.parse_POST()
        if 'value_cold' not in postvars or 'value_hot' not in postvars:
            self.send_error(
                400,
                explain='Не найдены параметры запроса value_cold и value_hot')
            return

        try:
            value_cold = postvars.get('value_cold')[0]
            value_hot = postvars.get('value_hot')[0]
            forced = 'forced' in postvars
            try:
                value_cold = int(value_cold)
                value_hot = int(value_hot)
            except ValueError:
                self.send_error(
                    400,
                    explain=
                    'Параметры запроса value_cold и value_hot должны быть числами'
                )
                return

            # Проверка находится после open_web_page_mail, чтобы была возможность отправить письмо
            if not db.add(value_cold, value_hot, forced):
                message = 'Попытка повторной отправки показания за тот же месяц'
                text = HTML_TEMPLATE_SEND_AGAIN\
                    .replace('{{ error_message }}', message)\
                    .replace('{{ value_cold }}', str(value_cold))\
                    .replace('{{ value_hot }}', str(value_hot))

                self.send_response(200)
                self.send_header('Content-Type', 'text/html; charset=utf-8')
                self.send_header('Connection', 'close')
                self.end_headers()

                self.wfile.write(text.encode('utf-8'))
                return

            ok, err_text = open_web_page_mail(value_cold, value_hot)
            if not ok:
                db.delete_last()
                self.send_error(500, explain=err_text)

            # Redirect to index
            self.send_response(302)
            self.send_header('Location', '/')
            self.send_header('Connection', 'close')
            self.end_headers()

        except:
            text = traceback.format_exc()
            self.send_error(500, explain=text)
Exemple #41
0
def add():
    # Read details from user
    NAMES = {'first_name': 'First Name:', 'last_name': 'Last Name:',
             'email': 'Email:', 'phone': 'Phone:'}
    user_data = ui.get_input(names=NAMES)
    # User submitted the data, now validate till the fields are correct
    data = recursively_validate(validator=AddValidator, data=user_data,
                                names=NAMES)
    email = data.get('email')
    if email:
        # Call external service to get url
        data['thumbnail_path'] = fetch_gravatar_and_store(email=email)
    # Store to db
    db.add(data=data)
    # Call ui
    ui.add()
def canAddListToDB():
	test_name = "Database: Can add List to document of its board"

	try:
		database = createTestDB()
		board = createTestBoard()
		db.add(board,database,"boards")

		list = createTestList()
		list.board_name = board.name

		db.add(list,database,"boards")

		passTest(test_name)

	except:
		failTest(test_name, sys.exc_info()[1])
Exemple #43
0
def add_show():
    showForm = AddShowForm()
    if showForm.validate_on_submit():
        show_info = [showForm.showName.data,
                     showForm.showDay.data,
                     showForm.showStart.data,
                     showForm.showEnd.data,
                     showForm.host1.data,
                     showForm.host2.data,
                     showForm.host3.data,
                     showForm.host4.data,
                     ''
                     ]
        db.add(show_info)
        return redirect(url_for("add_show"))

    return render_template("add_show.html", alert=None, showForm=showForm, subheading="Adding New Show", page="add")
Exemple #44
0
def application(env, start_response):
    """
    The WSGI application
    """
    body = ''
    try:
        length = int(env.get('CONTENT_LENGTH', '0'))
    except ValueError:
        length = 0
    if length != 0:
        body = env['wsgi.input'].read(length)

    args = urlparse.parse_qs(body)

    # Add a new tickets and redirect to standard location (reload
    # won't trigger any new entries or such)
    if env['PATH_INFO'] == '/new':
        db.add(args.get("ticket")[0])
        start_response('301 Redirect', [('Location', '/')])
        return []

    # List old tickets
    oldtickets = tickets_table(db.getall(ticket_type='active'))

    if env['PATH_INFO'] == '/edit':
        # Tiny edit (inlined)
        print("Args: " + str(args))
        target, index = args.get('id')[0].split('_')
        value = args.get('value')[0]
        if target == "done":
            db.set(target, done_snowflake[value], index)
        else:
            db.set(target, value, index)
        response_body = cgi.escape(value)
    else:
        # Redraw main interface
        response_body = html % {"tickets":    str(oldtickets),
                                "finished":   finished,
                                "unfinished": unfinished}

    status = '200 OK'
    response_headers = [('Content-Type', 'text/html'),
                        ('Content-Length', str(len(response_body)))]
    start_response(status, response_headers)
    return [response_body]
def new_note(db):    
    session = bottle.request.environ.get('beaker.session')
    user_id = session.get('user_id')    
    data = bottle.request.json
    try:
        notebook_id = data['notebook_id']
    except KeyError:
        bottle.abort(400,"not enough parameters")
    try:
        notebook = db.query(Notebook).filter_by(user_id = user_id, id = notebook_id).one()
        try:
            new_note = Note(title=data['title'], text=data['text'], notebook_id=notebook.id)
        except KeyError:
            bottle.abort(400,"not enough parameters")
        db.add(new_note)
        db.commit()
        #notes = db.query(Note).filter_by(notebook_id = notebook_id).all()
        return json.dumps(new_note.to_dict(), ensure_ascii=False)
    except NoResultFound:
        bottle.abort(406,"error")
#!/usr/bin/python
# -*- coding: utf-8 -*-

import db

import utilities
from model import Ingredient

for recipe in db.all_recipes():
    found_articles = set()
    for recipe_item in db.recipe_items_by_recipe_id(recipe):

        was_type, alcohol_type = utilities.is_type(recipe_item.name.lower())
        if was_type:
            for article in db.articles_by_type(alcohol_type):
                if article not in found_articles:
                    found_articles.add(article)
                    ingredient = Ingredient(article.name, article.name2, article.type)
                    db.add(ingredient)
        else:
            for article in db.article_by_name_or_type(recipe_item.name):
                if article not in found_articles:
                    found_articles.add(article)
                    ingredient = Ingredient(article.name, article.name2, article.type)
                    db.add(ingredient)

db.commit()
Exemple #47
0
def _store(session, *args):
    db.add(session, *args)
Exemple #48
0
def add(ircsock, channel, info):
  """ Add a new ticket """
  db.add(info)
  sendmsg(ircsock, channel, "Added new ticket!")