Example #1
0
def edit_item(category_name, item_name):
	# Allowes logged user to edit an item they own

	item = get_item_with_name(item_name)
	category = item.category

	if request.method == "GET":
		return render_template("edit_item.html", category = category, item = item)

	# Processing Post Request
	name = request.form.get("name") 
	description = request.form.get("description")

	validation_result = validate_edit("Item", item, name)
	valid = validation_result[0]
	message = validation_result[1]
	flash(message)

	if valid:
		item.name = name if name else item.name
		item.description = description if description else item.description
		session.add(item)
		session.commit()		
		return redirect("/catalog/{0}".format(category.name))
	else:
		return render_template("edit_item.html", category = category, item = item)
Example #2
0
def new_item(category_name):
	# Allows a logged in user to add a new item, with him as its owner
	categories = session.query(Category).all()
	category = get_category_with_name(category_name)
	
	if request.method == "GET":
		return render_template("add_item.html", category = category)

	# Processing Post Request
	name = request.form.get("name")
	description = request.form.get("description")

	validation_result = validate_creation("Item", name, category.id)
	valid = validation_result[0]
	message = validation_result[1]
	flash(message)	

	if valid:
		item = Item(name = name, description = description, category_id = category.id, \
								user_id = login_session["user_id"])
		session.add(item)
		session.commit()		
		return redirect("/catalog/{0}".format(category.name))
	else:
		return render_template("add_item.html", category = category)
Example #3
0
def import_facebook_friends():
    try:
        api = facebook.create_api()
        me = api.get('me')

        friends = api.get('me/friends')['data']
        friends.append(me)

        for friend in friends:
            with db.transaction as session:
                contact = current_user.find_facebook_contact(friend['id'])
                if not contact:
                    contact = FacebookContact()
                    contact.name = friend['name']
                    contact.facebook_id = friend['id']
                    contact.user = current_user
                    contact.belongs_to_user = friend['id'] == me['id']
                    session.add(contact)
                else:
                    contact.name = friend['name']

        return redirect(url_for('contacts'))

    except (facebook.ConnectionError, facebook.OAuthError):
        return redirect(facebook.create_authorize_url(
            action_url=url_for('import_facebook_friends'),
            error_url=url_for('contacts')
        ))
Example #4
0
def editItem(item):
	"""This page will be for editing the selected item"""
	error=None
	login_already=current_user.is_authenticated()
	if login_already:
		i = session.query(Item).filter_by(id=item).one()
		if request.method == "POST":
			"""Update the infomation of the item. Item's id is used for index the url.
			   And it won't change."""
			error=vacant_input("photo")
			# Check if there is any empty input except photo.
			if not error:
				# go on input database if no empty imput. If there any, 
				# reload and labels of the empty form will turn red.
				i.name= request.form['name']
				i.discription= request.form['discription']
				i.category= request.form['category']
				if request.files['photo']:
					i.photo=upload_image(i.id)
					# the photo file will not be change if no file upload.
				session.add(i)
				session.commit()
				return redirect("/item/%s" %item)
			c = session.query(Category).all()
			return render_template("add.html", c=c, login_already=login_already, error=error)
		i=session.query(Item).filter_by(id=item).one()
		c=session.query(Category).all()
		return render_template("edit.html", c=c, item=i, login_already=login_already, error=error)
	else:
		return redirect("/")
Example #5
0
def signup():
    form = ReusableForm(request.form)
    if request.method == 'POST':
        #Creating session for user registration to send form data to database
        Session = sessionmaker(bind=engine)
        session = Session()
        name=request.form['name']
        password=request.form['password']
        email=request.form['email']
        role = 'enduser'
        #Pass the form data to user database
        user = User(name,password,email,role)
        #Add user to the session
        session.add(user)
        if form.validate():
            #Commit user data to database and rolls back and logs on exception 
            try:
                session.commit()                
            except Exception as e:
                session.rollback()
                print(e)
            finally:
                return sendEmail(name,password,email)
        else:
            #display error message in case of incorrect form data
            flash('Error: All the form fields are required OR Enter correct email address ')
    return render_template('signup.html', form=form)
Example #6
0
def add_user(name):
    admin_role = Role(name=name)
    # db.session.add(admin_role)
    session = DBSession()
    session.add(admin_role)
    ret = {'ret': 'ok'}
    return jsonify(ret)
def receiveloop(name,radio):
	radio.startListening()
	data = []
	x_old = 0
	t_old = 0
	global power, kwh, timestamp
	timestamp = datetime.datetime.utcnow()
	while True:
		if (radio.available()):
			t_new = time.time()
			timestamp = datetime.datetime.utcnow()
			radio.read(data)
			text = u''
			try:
				for i in data:
					text += unichr(i)
				x_new = int(text[:11])
			except:
				print("Some error has occurred, waiting for next pulse.")
			else:
				power = int(7200*(x_new-x_old)/(t_new-t_old))
				kwh = x_new/500
				x_old = x_new
				t_old = t_new
				new_power = Power(timestamp, x_new, power, kwh)
				session.add(new_power)
				session.commit()
				print("New counter value received: "+str(x_new))
Example #8
0
def load_locations(session):

    """
    populates locations table from seed file.
    seed file is using these fields:
    Region|Country|State or Province|County|Beach Name|MSW_ID used|msw id exists for this location?|
    Beach Name of closest MSW data|lat|lon|
    """

    with open("db_seed_data/seed_locations") as f:

        reader = csv.reader(f, delimiter="|")
        for row in reader:
            id, region, country, state_or_prov, county, beach_name, msw_id, msw_unique_id_exists, msw_beach_name, lat, long = row

            # convert string to Boolean:
            if msw_unique_id_exists == "T":
                msw_unique_id_exists = True
            else:
                msw_unique_id_exists = False

            m = model.Location(
                id=id, region=region, country=country, state_or_prov=state_or_prov,
                county=county, beach_name = beach_name, 
                msw_id=msw_id, msw_unique_id_exists=msw_unique_id_exists, msw_beach_name=msw_beach_name,
                lat=lat, long=long
                )
            session.add(m)

        session.commit()
        print "locations table seeded."
Example #9
0
def createUser(login_session):
    newUser = User(name=login_session['username'], email=login_session[
                   'email'], picture=login_session['picture'])
    session.add(newUser)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id
Example #10
0
def task():
    j = sanitize_post_task(request.get_json(force=True,silent=True))
    if not j:
        example = { "id":"123",
            "task_description":"Is company mentioned positive/neutral/negative in the following paragraph?",
            "task_text":"lorem ipsum ...",
            "answer_possibilities":["yes","no","neutral"],
            "callback_link":"http://localhost:5000/webook",
            "price":12.34 }
        return json.dumps({ 'error': 'provide a valid json body!', 'example': example }), 400

    with db.session_scope() as session:
        tid = j['id']
        if session.query(db.OpenTask).filter(db.OpenTask.id == tid).count() != 0:
            return json.dumps({ 'error': 'id already exists' }), 400

        answers = j['answer_possibilities']
        answer = None
        if type(answers) is type([]):
            answer = "|".join(answers)
        elif answers == 'text':
            answer = "text"
        else:
            return json.dumps({ 'error': 'answer_possibilities must either be of type list ["yes","no",...] or "text"' }), 400

        open_task = db.OpenTask(j['id'], j['task_description'], j['task_text'], answer, j['callback_link'], j['price'])
        session.add(open_task)
        session.commit()

        result = { 'error': None, 'success': True }

        return json.dumps(result)
Example #11
0
	def create_case(self, user, case_name, conf_builder, project_name, flow_name, properties=None, start=True):
		case = Case(
					owner_id=user.id,
					name=case_name,
					project_name=project_name,
					flow_name=flow_name,
					conf=conf_builder.get_conf(),
					properties=Data.element(properties))

		session = db.Session()
		session.add(case)
		session.commit()

		engine_case_name = "{}-{}".format(user.nick, case_name)
		#while self.engine.exists_case(engine_case_name):
		#	engine_case_name = "{}-{}".format(user.nick, uuid4().hex[-6:])

		engine_case = self.engine.create_case(engine_case_name, conf_builder, project_name, flow_name, engine_case_name)

		case.created = engine_case.created
		case.engine_name = engine_case_name
		session.commit()

		if start:
			engine_case.start()

		return case
Example #12
0
def oauthCallback():
	"""Handle the data send back by facebook."""
	# Check if login alwaydy, if yes, redirect to home page
	if not current_user.is_anonymous():
		return redirect("/")

	oauth=FacebookSignUp()
	social_id, email=oauth.callback()
	# If face book send nothing back, redirect to home page
	if social_id is None:
		flash("Authentication failed.")
		return redirect("/")

	# Check if the user already signup in our database
	try:
		user = session.query(FUser).filter_by(social_id=str(social_id)).one()
	except:
		user = None
	# If user is not in database, put it in
	if not user:
		user = FUser(social_id=str(social_id), email=email)
		session.add(user)
		session.commit()
	# Get the user login
	login_user(user, True)
	return redirect("/")
Example #13
0
def newItem():
	"""This page will be for adding a new item."""
	error=None
	login_already=current_user.is_authenticated()
	#   This function will return to homepage if it found user is not login. 
	#  	There are same setting in pages below which are able to edit the database. 
	if login_already:
		if request.method == "POST":
			error = vacant_input()
			if not error:
				"""go on input database if no empty imput. If there any, 
				   reload and labels of the empty form will turn red."""
				time_now=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
				""" Get currunt time and insert to create_time. 
				 	This will use for index items display order"""
				i = Item(create_time=time_now, 
						 name=request.form['name'], 
						 discription=request.form['discription'], 
						 category=request.form['category'])
				session.add(i)
				session.flush()
				i.photo=upload_image(i.id)
				session.commit()
				return redirect("/")
			c = session.query(Category).all()
			return render_template("add.html", c=c, login_already=login_already, error=error)
		c = session.query(Category).all()
		return render_template("add.html", c=c, login_already=login_already, error=error)
	else:
		return redirect("/")
Example #14
0
def get_or_create(session, model, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
    else:
        instance = model(**kwargs)
        session.add(instance)
        session.commit()
        return instance
def add_event_create():
    title = request.args.get("title")
    date = request.args.get("date")
    description = request.args.get("description")
    user_id = request.args.get("user_id")
    e = Event(title=title, date=date, description=description, user_id=user_id)
    session.add(e)
    session.commit()
    return "Succesfully added event for student!!"    
Example #16
0
File: admin.py Project: vipsql/paas
def addApp():
    "添加应用"
    if request.method == "GET":
        g.add=True
        g.obj={}
        
        sql="select * from paas_account where status != 3"
        dao=db.execute(sql)
        g.users=map(objToDict,dao.fetchall())
        dao.close()
        
        return render_template("admin/addApp.html")
    else:
        uid=request.form.get("uid",None)
        title=request.form.get("title",None)
        description=request.form.get("description",None)
        language=request.form.get("language",None)
        host=request.form.get("host",None)
        gitUrl=request.form.get("gitUrl",None)
        #处理git地址,防止注入恶意代码
        gitUrl=gitUrl.replace(" ","")
        
        #添加应用信息
        session=Session()
        obj=AppModel(title,description,uid,language,host,gitUrl,-1)
        session.add(obj)
        session.commit()
        
        #记录应用路径,用户,用户组
        appUser,appGroup,appPath=client.getAppMessage(obj.id,sqlDeal(language))
        sql="update paas_app set appAccount = '%s' , appGroup = '%s',appPath = '%s' where id = %d"%(appUser,appGroup,appPath,obj.id)
        dao=db.execute(sql)
        dao.close()
        
        #为应用创建一个数据库,但是静态环境不需要数据库
        if language != "static":
            dbName=hashlib.md5(str(time.time())).hexdigest()
            username=hashlib.md5(uid+str(time.time())).hexdigest()[8:-8]
            password=hashlib.md5(title.encode("UTF-8")+str(time.time())).hexdigest()
            #建立数据库
            buildDb(dbName,username,password)
        
            sql="insert into paas_db(uid,aid,dbName,username,password,host,port) values('%s','%s','%s','%s','%s','%s','%s')"%(sqlDeal(uid),str(obj.id),dbName,username,password,config.MYSQL_HOST,config.MYSQL_PORT)
            dao=db.execute(sql)
            dao.close()
        
        #初始化应用
        client.buildApp(obj.id,sqlDeal(host),sqlDeal(language))
        
        #生成apiKey和secretKey
        apiKey=hashlib.md5("apiKey_"+str(time.time())).hexdigest()
        secretKey=hashlib.md5("secretKey_"+str(time.time())).hexdigest()
        sql="insert into paas_app_token(aid,apiKey,secretKey) values('%s','%s','%s')"%(str(obj.id),apiKey,secretKey)
        dao=db.execute(sql)
        dao.close()
        
        return redirect("/admin/appManager")   
Example #17
0
def edit_view(rid):


    #debug
    if(request.form.has_key('subbtn')):
	subbtn = request.form['subbtn']
	app.logger.debug("subbtn = %s" % subbtn)
    else:
	app.logger.debug("no subbtn key")
	subbtn=None


    rec = session.query(Records).filter(Records.id == rid).first()
    form = EditForm(request.form, obj=rec)

    # set choices
    l = Records.getValuesFromField('phase')
    form.phase.choices = listToChoices(l)
    form.final_action.choices = listToChoices(Records.getValuesFromField('final_action'))

    if form.validate_on_submit():
	val = True
    else:
	val = False

    if subbtn:
	if subbtn == form.cancel:
	    app.logger.debug("cancel")
	    flash("Changes canceled")
	    return redirect('/select/')
	else:
	    app.logger.debug("saving record")
	    #form.populate_obj(rec)  # f***s up boolean nulls
	    data = form.data
	    for d in data:
		print "ghetto populate: %s -> %s" % (d, data[d])
		setattr(rec,d,data[d])
	    if val and not subbtn==form.saveselect:
		rec.status ="%s-done" % session.query(User).filter(id=uid).first().initials
	    session.add(rec)
	    session.commit()
	if subbtn == form.savenext:
	    rec.checkin(current_user.id)
	    n = getNextRecord()
	    msg = record.checkout(current_user.id)
	    flash(msg)
	    return redirect('/edit/%d' % n.id)
	elif subbtn==form.saveselect:
	    flash("Record saved but not checked in")
	    return redirect('/select/')
	    
	if form.errors:
	    app.logger.debug("oh shit:")
	    app.logger.debug(form.errors)
	flash("error")
	app.logger.debug("edit form validation failed")
    return render_template('records/edit.html', form=form, rec=rec, idx=AutoIncrement() ) 
Example #18
0
    def create_unique(cls, session, id):
        # if the site user was cached, manually upgrade it to a local user
        if SEUser.query.get(id) is not None:
            session.execute(cls.__table__.insert().values(id=id))
            return cls.query.get(id)

        o = cls(id=id)
        session.add(o)
        return o
Example #19
0
def load_entries(session):

    """
    populates entries table from seed file.

    seed file is using these fields:

    user_id|datetime start|loc_id|spot_name|go_out|
    swell1_ht|swell1_per|swell1_dir_deg|swell1_arrow_deg|swell1_dir_comp|
    wind_speed|wind_gusts|wind_dir_deg|wind_arrow_deg|
    board_id|board_pref|board_notes|buddy|gen_notes
    rate_wave_challenge|rate_wave_fun|rate_crowd_den|rate_crowd_vibe|rate_overall_fun

    (using msw api data collected for past dates from another app, only rounded degress available)
    """
    
    with open("db_seed_data/seed_entries") as f:
        reader = csv.reader(f, delimiter="|")
        for row in reader:

            print row

            (user_id, datetime_start, loc_id, spot_name, go_out,
            swell1_ht, swell1_per, swell1_dir_deg_global, swell1_arrow_deg, swell1_dir_comp, 
            wind_speed, wind_gust, wind_dir_deg, wind_arrow_deg,
            board_id, board_pref, board_notes, buddy_name, gen_notes,
            rate_wave_challenge, rate_wave_fun, rate_crowd_den, rate_crowd_vibe,
            rate_overall_fun) = row
            
            ## convert string to datetime
            date_time_start = datetime.strptime(datetime_start, "%Y-%m-%d %H:%M")
            ## temp using same start and end time. 
            date_time_end = date_time_start

            swell1_dir_deg_global = float(swell1_dir_deg_global)
            ## convert from global deg back to deg as msw would provide
            swell1_dir_deg_msw = (swell1_dir_deg_global - 180)%360
            print "swell1_dir_deg_global: ", swell1_dir_deg_global
            print "swell1_dir_deg_msw: ", swell1_dir_deg_msw


            u = model.Entry(user_id=user_id, date_time_start=date_time_start, date_time_end=date_time_end, 
                            loc_id=loc_id, spot_name=spot_name, go_out=go_out,
                            swell1_ht=swell1_ht, swell1_per=swell1_per, swell1_dir_deg_global=swell1_dir_deg_global,
                            swell1_dir_deg_msw=swell1_dir_deg_msw, swell1_arrow_deg=swell1_arrow_deg, swell1_dir_comp=swell1_dir_comp,
                            wind_speed=wind_speed, wind_gust=wind_gust,
                            wind_dir_deg = wind_dir_deg, wind_arrow_deg=wind_arrow_deg, 
                            board_id=board_id, board_pref=board_pref, board_notes=board_notes,
                            buddy_name=buddy_name, gen_notes=gen_notes,
                            rate_wave_challenge=rate_wave_challenge, rate_wave_fun=rate_wave_fun,
                            rate_crowd_den=rate_crowd_den, rate_crowd_vibe=rate_crowd_vibe,
                            rate_overall_fun=rate_overall_fun)
            session.add(u)
        
        
        session.commit()
        print "entries table seeded." 
Example #20
0
    def test_read_committee_attribute(self):

        session.add(committee(name="AttrTest", chamber="House"))
        session.commit()

        query = session.query(committee).filter(committee.name == "AttrTest").first()

        assert query is not None
        assert query.chamber == "House"
Example #21
0
    def test_read_bill_attribute2(self):

        session.add(bill(name="AttrTest2", house_status="Failed"))
        session.commit()

        query = session.query(bill).filter_by(name="AttrTest2").first()

        assert query is not None
        assert query.house_status == "Failed"
Example #22
0
    def test_read_legislator_attribute(self):

        session.add(legislator(last_name="TESTATTR", party="Republican"))
        session.commit()

        query = session.query(legislator).filter(legislator.last_name == "TESTATTR").first()

        assert query is not None
        assert query.party == "Republican"
Example #23
0
def newDevice():
	if request.method == 'POST':
		post = request.get_json()
		device = F5Device(hostName = post.get('hostName'), ipAddress = post.get('ipAddress'), details = post.get('details'), apiUserName = post.get('apiUserName'), apiPassword = post.get('apiPassword'))
		session.add(device)
		session.commit()
		flash("Added New Device - %s" %device.hostName)
		return redirect(url_for('deviceList'))
	else:
		return render_template('newdevice.html')
Example #24
0
def confirm_reg():
	user_info = simplejson.load(gh_proxy('user'))

	db = get_db()
	user = User(name=request.values('name'),
		        email=request.values('email'),
		        username=user_info['login'])

	session.add(user)
	session.commit()
Example #25
0
def create_user(name, email, picture):
	# Creates a new user
	if(get_user_with_email(email)):
		print("Email already in use")
		return False
	else:
		user = User(name=name, email = email, picture = picture)
		session.add(user)
		session.commit()
		return user
Example #26
0
def login():
    form = LoginForm(csrf_enabled=False)
    if form.validate_on_submit():
  	user = User(name = form.name)
	# add user to db
        session.add(user)
        session.commit()
        flash('Processing...')
        return redirect('/')
    return render_template('login.html', form = form)
Example #27
0
    def test_write_votes(self):
        query = session.query(vote).all()
        startSize = len(query)

        session.add(vote(legislator_id=1, bill_id=2))
        res = session.query(vote).all()
        endSize = len(res)

        self.assertEqual(startSize + 1, endSize)
        query = session.query(vote).filter(vote.legislator_id == 1).first()
        session.delete(query)
Example #28
0
    def test_write_bill_committees(self):
        query = session.query(bill_committee).all()
        startSize = len(query)

        session.add(bill_committee(bill_id=7, committee_id=5))
        res = session.query(bill_committee).all()
        endSize = len(res)

        self.assertEqual(startSize + 1, endSize)
        query = session.query(bill_committee).filter(bill_committee.bill_id == 7).first()
        session.delete(query)
def add_student_create():
    name = request.args.get("name")
    email = request.args.get("email")
    password = request.args.get("password")
    title_company = request.args.get("title_company")
    hb_class = request.args.get("hb_class")
    headshot_img_url = request.args.get("headshot_img_url")
    s = Student(name=name, email=email, password=password, title_company=title_company, hb_class=hb_class, headshot_img_url=headshot_img_url)
    session.add(s)
    session.commit()
    return "Succesfully added student!!"
def index():
    session = Session()
    if request.method == 'POST':
        task = Task(name=request.form['name'])
        if task.name != "":
            session.add(task)
            session.commit()
        return redirect('/')
    else:
        tasks = session.query(Task).all()
        return render_template('index.html', tasks=tasks)
Example #31
0
File: api.py Project: pksebben/Aaru
def create_chunk(author, text, parentid=0, title=None, children=None):
    # If parentid is special value 0, that means the chunk is a root node
    if parentid == 0:
        parent = None
        title = title
    else:
        parent = session.query(Chunk).get(parentid)
    try:
        chunk = Chunk(text=text, author=author,
                      title=title)  # should author be author.id?
        if parent:
            parent.children.append(chunk)
        session.add(chunk)
        session.commit()
        return chunk.id
    except IntegrityError as err:
        session.rollback()
        raise err.orig
Example #32
0
def do_register():
    c = json.loads(request.form['values'])
    name = c['name']
    fullname = c['fullname']
    password = c['password']
    username = c['username']


    user = entities.User(
        username=username,
        name=name,
        fullname=fullname,
        password=password
    )
    session = db.getSession(engine)
    session.add(user)
    session.commit()
    return 'Created User'
Example #33
0
def create_messages_data():
    #    msg = json.loads(request.data[])
    c = json.loads(request.data)
    #    format = '%d/%m/%Y' # The format
    #    datetime_str = datetime.datetime.strptime(c['sent_on'], format)
    #    print(datetime_str)
    message = entities.Message(
        content=c['content'],
        #        sent_on=datetime_str,
        user_from_id=c['user_from_id'],
        user_to_id=c['user_to_id'])
    session = db.getSession(engine)
    session.add(message)
    session.commit()
    session.close()
    r_msg = {'msg': 'Message Created!'}
    json_msg = json.dumps(r_msg)
    return Response(json_msg, status=201)
Example #34
0
def register():
    data = request.json
    user = models.User(username=data["username"],
                       email=data["email"],
                       password=data["password"],
                       userdescription=["userdescription"])
    if models.User.username is None or models.User.password is None:
        abort(400)  # missing arguments
    if session.query(models.User).filter_by(
            username=models.User.username).first() is not None:
        abort(400)  # existing user
    user.hash_password(models.User.password)
    session.add(user)
    session.commit()
    #when user registers, I want it to return User with location for all of User's cocktails, but there will be none if new User
    return jsonify({"username": user.username}), 201, {
        "Location": url_for("get_cocktails", id=user.id, _external=True)
    }
Example #35
0
def import_google_contacts():
    try:
        api = google.create_api(google.ContactsClient)

        group_id = None
        feed = api.GetGroups()
        for entry in feed.entry:
            if entry.title.text == 'System Group: My Contacts':
                group_id = entry.id.text

        query = ContactsQuery()
        query.max_results = 10000
        if group_id:
            query.group = group_id
        feed = api.GetContacts(q=query)

        my_emails = current_user.emails

        for entry in feed.entry:
            with db.transaction as session:
                for email in entry.email:
                    if not entry.name or not entry.name.full_name:
                        continue
                    contact = current_user.find_email_contact(email.address)
                    if not contact:
                        contact = create_email_contact(email.address)
                        contact.name = entry.name.full_name.text
                        contact.email = email.address
                        contact.user = current_user
                        contact.belongs_to_user = email.address in my_emails
                        session.add(contact)
                    else:
                        contact.name = entry.name.full_name.text

        return redirect(url_for('contacts'))

    except (google.ConnectionError, google.UnauthorizedError):
        return redirect(
            google.create_authorize_url(
                action_url=url_for('import_google_contacts'),
                error_url=url_for('contacts'),
                scope=
                'https://www.google.com/calendar/feeds/ https://www.google.com/m8/feeds/'
            ))
Example #36
0
def editRestaurant(restaurant_id):
    if 'username' not in login_session:
        return redirect('/login')
    edititem = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if getUserId(login_session['email']) == edititem.user_id:
        if request.method == 'POST':
            if request.form['name']:
                edititem.name = request.form['name']
            session.add(edititem)
            session.commit()
            flash(" Restaurant edited!")
            return redirect(url_for('showRestaurants'))
        else:
            #return "<Script>alert('Sorry!! Cannot edit other user's restaurant.')</Script>"
            #else:
            return render_template('editRestaurant.html', i=edititem)

    #return ("This page will be for editing restaurant"+restaurant_id)
    return render_template("editRestaurant.html")
Example #37
0
def objeto_agregar():
    codigo = request.form['cod_objeto']
    nom_objeto = str(request.form['nom_objeto'])
    categoria = str(request.form['categoria'])
    marca = str(request.form['marca'])
    estado = str(request.form['estado'])
    fecha_hallado = request.form['fecha_hallado']
    fecha_dev = request.form['fecha_dev']
    lugar = str(request.form['lugar'])
    nro_anaquel = request.form['nro_anaquel']
    caract_esp = str(request.form['caract_esp'])
    cod_usu_entrega = request.form['cod_usu_entrega']
    print(cod_usu_entrega)
    #conn = engine.connect()
    status = 200
    session = session_db()
    stmt = Objeto(cod_objeto=codigo,
                  nom_objeto=nom_objeto,
                  categoria=categoria,
                  marca=marca,
                  estado=estado,
                  fecha_hallado=fecha_hallado,
                  fecha_dev=fecha_dev,
                  lugar=lugar,
                  nro_anaquel=nro_anaquel,
                  caract_esp=caract_esp,
                  cod_usu_entrega=cod_usu_entrega)
    session.add(stmt)
    session.flush()
    print('1 ++++++++++++++++++++++++')
    session.commit()
    print('2 ++++++++++++++++++++++++')
    #users.insert().values({"name": "some name"})

    #conn.execute(stmt)
    rpta = {
        'tipo_mensaje': 'success',
        'mensaje': ['Se ha registrado los cambios en los items del subtítulo']
    }

    #return  json.dumps(rpta),status
    return redirect('/register')
    '''
Example #38
0
def home():
    engine = create_engine("sqlite:///blog.db", echo=True)
    Session = sessionmaker(bind=engine)
    Base.metadata.create_all(engine)
    session = Session()

    if request.method == "POST":
        username = request.form.get("name")
        usercomment = request.form.get("comment")
        user = User(name=username, comment=usercomment)
        session.add(user)
        session.commit()
        blogComments = session.query(User)
        session.close()
        return render_template("/home.html", comments=blogComments)
    else:
        blogComments = session.query(User)
        session.close()
        return render_template("/home.html", comments=blogComments)
Example #39
0
def create_newproposal():
    errors = Proposal.validate(request.json)

    if len(errors) == 0:
        user_proposed_from = g.user.id
        request_id = request.json.get('request_id')

        req = session.query(Request).filter_by(id=request_id).first()
        if req is None:
            return jsonify({'errors': 'Request is not exist'})
        else:
            user_proposed_to = req.user_id
            proposal = Proposal(request_id = request_id, \
                                user_proposed_from = user_proposed_from, user_proposed_to=user_proposed_to )
            session.add(proposal)
            session.commit()
            return jsonify({'response': True}), 201
    else:
        return jsonify({'errors': errors})
Example #40
0
def sign_up():
    username = request.args.get('username').lower()
    email = request.args.get('email').lower()
    password = request.args.get('password').lower()
    session = db_session.create_session()
    if session.query(User).filter(User.username == username).first():
        return jsonify(error='Сіз жазған логин тіркелген')
    if session.query(User).filter(User.email == email).first():
        return jsonify(error="Бұл e-mail тіркелген")
    generated_id = id_generator("User")
    user = User(email=email,
                username=username,
                password=generate_password_hash(password),
                generated_id=generated_id)
    session.add(user)
    session.commit()
    mkdir('users', generated_id)
    print('You were successfully logged in')
    return jsonify(error="No error")
Example #41
0
    def post(self):
        if (request.headers.get('Authorization')):
            content = request.get_json()
            errors = create_ManageLineControllers_schema.load(content)
            if errors:
                numberline = content.get("line2")
                customer_dentification_card = content.get("personID")
                print(customer_dentification_card)
                state = content.get("state")
                trademark = content.get("tradeMark")
                line_bdvali = session.query(Lines).filter_by(
                    numberline=numberline).first()
                if not line_bdvali:
                    idcustomer = session.query(Customer).filter_by(
                        customerIdentification=customer_dentification_card
                    ).first()
                    print(idcustomer)
                    if not idcustomer:
                        return jsonify({"Status": "No existe este usuario"})
                    manage_bd = Lines(
                        numberline=numberline,
                        customerIdentification=customer_dentification_card,
                        state=state,
                        trademark=trademark,
                    )
                    session.add(manage_bd)
                    session.commit()
                    for x in range(5):
                        manage_bd = Bill(
                            value=32000,
                            collectionDay='2020-09-22',
                            customerIdentification=customer_dentification_card,
                            numberLine=numberline)

                        session.add(manage_bd)
                        x = randint(0, 20)
                    return jsonify({
                        "Status": "Register line successfully",
                    }), 200
                return jsonify({
                    "Status": "Ya existe esta linea",
                }), 200
        return jsonify({"Status": 'no envio un token'}), 400
Example #42
0
def post_medication():
    brand = request.form['med_brand_name']
    drug = request.form['med_drug']
    dosis = request.form['med_dosis']
    prescribed_by = request.form['med_prescribed_by']
    diagnosis = request.form['med_diagnosis']
    quantity = request.form['med_quantity']
    medication = entities.Medication(med_brand_name=brand,
                                     med_drug=drug,
                                     med_dosis=dosis,
                                     med_prescribed_by=prescribed_by,
                                     med_diagnosis=diagnosis,
                                     med_quantity=quantity)
    if not med_brand_name == "":
        session = db.getSession(engine)
        session.add(medication)
        session.commit()
        return 'Create New Medication'
    return render_template("fail.html")
Example #43
0
    def add_to_cart(id):
        product = session.query(Product).get(id)
        cart = session.query(Cart).filter(Cart.user_id == current_user.id).first()
        old_cart_product = session.query(Cart_Product).filter(Cart_Product.cart_id == cart.id, Cart_Product.product_id == product.id).first()
        if not old_cart_product:
            cart_product = Cart_Product(
                product_id=product.id,
                cart_id=cart.id,
                count=1,
                one_price=product.price,
                full_price=product.price
            )
            session.add(cart_product)
            session.commit()
            address = '/product/' + str(id)

        else:
            address = '/cart'
        return redirect(address)
Example #44
0
def problem(theme, problem_id):
    session = db_session.create_session()
    form = SubmitForm()
    params = base_params("Fak me", 1)
    params["statement"] = f"problems/{problem_id}/statement.html"
    params["problem"] = session.query(Problem).filter(Problem.id == problem_id, Problem.theme == theme).first()
    params["title"] = params["problem"].title
    params["form"] = form
    params["goBack_href"] = f"/practice/{params['problem'].theme}"
    params["active_tab_id"] = 0
    if form.validate_on_submit():
        code = request.form["code_area"]
        if code == "":
            params["message"] = "You can't submit empty code"
            return render_template('problem.html', **params)
        if not current_user.is_authenticated:
            params["message"] = "You must sign in to submit code"
            return render_template('problem.html', **params)
        submission_id = 1
        if session.query(Submission).first():
            submission_id = session.query(sqlalchemy_func.max(Submission.id)).one()[0] + 1
        submission_folder = f'data/testing_system/submissions/{submission_id}'
        os.mkdir(f'data/testing_system/submissions/{submission_id}')
        language = request.form["language"]
        if language == "cpp":
            open(f"{submission_folder}/solution.cpp", "wb").writelines(
                [line.rstrip('\n').encode(encoding='UTF-8', errors='strict') for line in code])
        if language == "py":
            open(f"{submission_folder}/solution.py", "wb").writelines(
                [line.rstrip('\n').encode(encoding='UTF-8', errors='strict') for line in code])
        submission = Submission(
            id=submission_id,
            user_id=current_user.id,
            problem_id=problem_id,
            status="In queue",
            running_time=0,
            language=language
        )
        session.add(submission)
        session.commit()
        sleep(.5)
        return redirect(f'/practice/{theme}/problems/{problem_id}/my_submissions')
    return render_template('problem.html', **params)
Example #45
0
def update_item(item_id):
    item = MenuItem.get_by_id(item_id)
    if item is None:
        raise ApiError("item is not exist")

    if request.method == 'DELETE':
        session.delete(item)
        session.commit()
        return jsonify(success=True)

    dict = request.json.get('properties')
    print(dict)
    print(str(dict))
    item.properties = str(dict)

    session.add(item)
    session.commit()

    return jsonify(item.serialize)
 def create_recall_trial(participant_id, recall_trial_pixels, recall_trial_thinking_start_time,
                         recall_trial_thinking_end_time, recall_trial_drawing_start_time,
                         recall_trial_drawing_end_time):
     recall_trialInfo=recall_trial(recallTrialPixels=recall_trial_pixels,
                                   recallTrialThinkingStartTime=recall_trial_thinking_start_time,
                                   recallTrialThinkingEndTime=recall_trial_thinking_end_time,
                                   recallTrialDrawingStartTime=recall_trial_drawing_start_time,
                                   recallTrialDrawingEndTime=recall_trial_drawing_end_time)
     session.add(recall_trialInfo)
     session.flush()
     inserted_id = recall_trialInfo.recallTrialID
     session.commit()
     print("Recall Trial has been created with ID:"+str(inserted_id))
     tempArr = trialsData[participant_id].split(',')
     staff_id = tempArr[2]
     copy_trial_id = tempArr[0]
     trial_start_time = tempArr[1]
     create_trials(participant_id, staff_id, copy_trial_id, inserted_id, trial_start_time,
                   recall_trial_drawing_end_time)
Example #47
0
def new_movie(title, director, distributor, rating):
    if movie.query.filter_by(
            title=title).first():  # if there is a movie by that title
        return "That movie already exists! Go back to the home page!"
    else:  # If not, we will create this movie and add it to our database
        director = get_or_create_director(director)
        distributor = get_or_create_distibutor(distributor)
        rating = get_or_create_rating(title, rating)
        newmo = movie(title=title,
                      Director_id=director.id,
                      Distributor_id=distributor.id,
                      rating_id=rating.id)
        session.add(newmo)
        session.commit()
        return render_template('new_movie.html',
                               new_movie=newmo.title,
                               new_director=newmo.Director_id,
                               new_distributor=newmo.Distributor_id,
                               new_rating=newmo.rating_id)
Example #48
0
def createEvent():
    if request.method == 'POST':
        time = str(request.form['time']).split(':')
        time = datetime.time(int(time[0]), int(time[1]))
        date = str(request.form['date']).split('-')
        date = datetime.date(int(date[0]), int(date[1]), int(date[2]))
        events = Events(name=request.form['name'],
                        fee=request.form['fee'],
                        date=date,
                        time=time,
                        location=request.form['location'],
                        organisers=request.form['organisers'],
                        description=request.form['description'],
                        category=request.form['category'],
                        privacy=request.form['privacy'])
        session.add(events)
        session.commit()
        return render_template('landing.html')
    return render_template('createEvent.html')
Example #49
0
def add_student():
    #----------------------------------
    if not (auth.if_auth()):
        return redirect(url_for('login'))
    #----------------------------------
    student = Student()
    form = StudentForm(obj=student)
    if form.validate():
        session = db.Session()
        form.populate_obj(student)
        user_id = auth.get_user_id()
        student.user_id = user_id
        session.add(student)
        session.commit()
        return redirect(url_for('groups'))
    params = dict()
    params['form'] = form
    params['username'] = auth.get_user_name()
    return render_template('students/edit_student.html', params=params)
Example #50
0
def newItem():
    if 'username' not in login_session:
        return redirect('/login')
    print ('inside new item')
    categories = session.query(Category)
    if request.method == 'POST':
        category_name = request.form['category_name']
        category_id = session.query(Category).filter_by(
            name=category_name).one()
        new_Item = CategoryItem(title=request.form['title'],
                                description=request.form['description'],
                                category_id=category_id.id,
                                user_id=login_session['user_id'])
        session.add(new_Item)
        session.commit()
        flash("New Item %s Created successfully" % new_Item.title)
        return redirect(url_for('showCatalog'))
    else:
        return render_template('newItem.html', categories=categories)
Example #51
0
def index(
):  ## When the main route is accessed, the program checks if there are any movies in the database. If none, it will import data from a csv file
    ## Import movie data from existing csv file
    with open("movies_clean.csv", "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        data = []
        for i in reader:
            data.append(i)
    if len(Movie.query.all()) == 0:  ## If there are no movies at all
        for row in range(1, len(data)):
            director = get_or_create_director(data[row][12])
            rating = create_rating(data[row][14])
            movie = Movie(title=data[row][0],
                          director_id=director.id,
                          ratings_id=rating.id)
            session.add(movie)
            session.commit()

    return 'This is the main page. <br><a href="http://localhost:5000/allmovies">Click here to see the complete collection of movies. <br><a href="http://localhost:5000/alldirectors">Click here to see a complete list of directors. <br><a href = "http://localhost:5000/newmovie">Click here to add a new movie. <br><a href = "http://localhost:5000/director">Click here to search for the works of a specific director.'
Example #52
0
def addstudent():
    session = DBSession()
    name = request.form['name']
    no = request.form['studentno']
    phone = request.form['phonenumber']
    email = request.form['studentemail']
    address = request.form['address']
    try:
        student = Student(name, no, phone, email, address)
        session.add(student)
        return ResponseBody(0, None)()
        # return redirect(url_for('showstudents', pageindex=1))
    except Exception as e:
        logging.info(e)
        print e
        return ResponseBody(1, None)()
    finally:
        session.commit()
        session.close()
Example #53
0
def newMenuItem(restaurant_id):
    if 'username' not in login_session:
        return redirect('/login')

    if request.method == 'POST':
        newItem = MenuItem(name=request.form['name'],
                           description=request.form['description'],
                           price=request.form['price'],
                           course=request.form['course'],
                           picture=request.form['picture'],
                           restaurant_id=restaurant_id,
                           user_id=login_session['user_id'])
        session.add(newItem)
        session.commit()
        flash("New Item %s has been created" % request.form['name'])
        return redirect(url_for('showCatalogs'))
    else:
        restaurants = session.query(Restaurant).all()
        return render_template('newmenuitem.html', restaurants=restaurants)
Example #54
0
def crearnota(id, curso):
    data = request.form
    session = db.getSession(engine)
    user = session.query(entities.User).filter_by(id=id).first()
    curso = session.query(entities.Curso).filter(
        entities.Curso.name == curso, entities.Curso.user_id == id).first()
    nota = entities.Nota(variable=data['variable'],
                         nota=data['nota'],
                         porcentaje=data['porcentaje'],
                         curso_id=curso.id)
    session.add(nota)
    session.commit()
    resultado = 0
    for nota in curso.notas:
        resultado += nota.nota * nota.porcentaje / 100
    return render_template("Notas.html",
                           user=user,
                           curso=curso,
                           resultado="{0:.2f}".format(resultado))
Example #55
0
def do_sign_up():
	Session = sessionmaker(bind=engine)
	session = Session()
	USERNAME_NEW = str(request.form['new_username'])
	PASS_NEW = str(request.form['new_pass'])
	STATE=0
	IDLEFT=0
	FIRST=str(request.form['first'])
	LAST=str(request.form['last'])
	Session = sessionmaker(bind=engine)
	s = Session()
	obj = s.query(User).filter_by(username=USERNAME_NEW).first()
	if obj is None:
		user = User(USERNAME_NEW,PASS_NEW,STATE,IDLEFT,FIRST,LAST)
		session.add(user)
		session.commit()
		return render_template("signed_up.html")
	else:
		return render_template("username_exists.html")
Example #56
0
def edit_repo(repo_id):
    session = request.db_session
    if not request.user.can_manage:
        return abort(403)
    if repo_id is not None:
        repo = session.query(Repository).get(repo_id)
    else:
        repo = None

    errors = []
    if request.method == 'POST':
        secret = request.form.get('repo_secret', '')
        clone_url = request.form.get('repo_clone_url', '')
        repo_name = request.form.get('repo_name', '').strip()
        ref_whitelist = request.form.get('repo_ref_whitelist', '')
        if len(repo_name) < 3 or repo_name.count('/') != 1:
            errors.append('Invalid repository name. Format must be owner/repo')
        if not clone_url:
            errors.append('No clone URL specified')
        other = session.query(Repository).filter_by(
            name=repo_name).one_or_none()
        if (other and not repo) or (other and other.id != repo.id):
            errors.append('Repository {!r} already exists'.format(repo_name))
        if not errors:
            if not repo:
                repo = Repository(name=repo_name,
                                  clone_url=clone_url,
                                  secret=secret,
                                  build_count=0,
                                  ref_whitelist=ref_whitelist)
            else:
                repo.name = repo_name
                repo.clone_url = clone_url
                repo.secret = secret
                repo.ref_whitelist = ref_whitelist
            session.add(repo)
            session.commit()
            return redirect(repo.url())

    return render_template('edit_repo.html',
                           user=request.user,
                           repo=repo,
                           errors=errors)
def get_and_write_parks(pname, ptype, plocation, pdescription, pvalue):
    p = National_Park.query.filter_by(name=pname.decode('utf-8'),
                                      type=ptype.decode('utf-8'),
                                      location=plocation.decode('utf-8'),
                                      description=pdescription.decode('utf-8'),
                                      value=pvalue.decode('utf-8')).first()
    if p:
        return p
    else:
        ty = get_and_write_types(ptype)
        p = National_Park(name=pname.decode('utf-8'),
                          type=ptype.decode('utf-8'),
                          location=plocation.decode('utf-8'),
                          description=pdescription.decode('utf-8'),
                          value=pvalue.decode('utf-8'),
                          type_id=ty.id)
        session.add(p)
        session.commit()
        return p
Example #58
0
def result_form1():
    if request.method == "GET":
        print(
            request.args
        )  # Check out your Terminal window where you're running this... to see
        if len(request.args) > 0:
            for k in request.args:
                poss_type = request.args.get(
                    k, "None")  # in two steps for clarity
                veh = Vehicle.query.filter_by(type=poss_type).first()
                if not veh:
                    veh = Vehicle(type=request.args.get(k, "None"),
                                  number_owned=0)  # start
                    session.add(veh)
                    session.commit()
                veh.number_owned += 1
                session.add(veh)
                session.commit()
            return "Vehicles (or lack thereof) successfully noted. <br><br> <a href='http://localhost:5000/'>Go to the main page</a>"
Example #59
0
def getLog():
    """ Get the entries of logged events between a specific time interval.

    .. :quickref: Get logged events; Get logged events within time frame

    :param: timeLogStart: (Integer) start timestamp
    :param: timeLogEnd: (Integer) end timestamp


    :returns: List of event entries (strings) inside the requested time interval

    """
    processRequest = request.get_json()
    if not 'timeLogEnd' in processRequest:
        raise InvalidUsage("End time not provided", status_code=400)
    if not 'timeLogStart' in processRequest:
        raise InvalidUsage("Start time not provided", status_code=400)
    if not 'reqid' in processRequest:
        raise InvalidUsage("Unique request identifier not provided",
                           status_code=400)
    unique = str(uuid.uuid1().hex)
    scoped = daqbrokerSettings.getScoped()
    session = scoped()
    emptyIndex = next(i for i, val in enumerate(current_app.config['workers'])
                      if val == -1)
    current_app.config['workers'][emptyIndex] = 0
    newJob = daqbrokerSettings.jobs(clock=time.time() * 1000,
                                    jobid=unique,
                                    type=0,
                                    username=current_user.username,
                                    status=0,
                                    data=emptyIndex,
                                    reqid=processRequest["reqid"])
    session.add(newJob)
    session.commit()
    daqbrokerSettings.workerpool.submit(getLogEntries,
                                        int(processRequest['timeLogStart']),
                                        int(processRequest['timeLogEnd']),
                                        str(unique),
                                        current_app.config['workers'],
                                        emptyIndex, base_dir)
    return json.dumps({'id': str(unique), 'type': 'log entry'})
Example #60
0
def edit_actor(actor_id=None):
    form = ActorForm()
    session = db.session()
    if not current_user.is_authenticated() or not current_user.is_admin():
        return redirect('/')
    if actor_id:
        actor = session.query(Actor).filter_by(Id=actor_id).first()
    else:
        actor_id = None
        actor = Actor()
    if form.validate_on_submit():
        actor.Name = request.form.get('name')
        actor.Dob = request.form.get('dob')
        actor.Biography = request.form.get('biography')
        actor.ImdbId = request.form.get('imdbId')
        actor.BirthPlace = request.form.get('birthPlace')
        actor.ImageUrl = request.form.get('imageUrl')
        if not actor_id:
            session.add(actor)
        try:
            session.commit()
        except:
            flash("Database error!")
            traceback.print_exc(file=sys.stdout)
            session.rollback()
            return redirect('/')
        print('return pro')
        if not actor_id:
            flash(actor.Name + " is Added!")
        else:
            flash(actor.Name + " is Saved!")
        return redirect('actor/' + str(actor.Id))
    form.name.data = actor.Name
    form.dob.data = actor.Dob
    form.biography.data = actor.Biography
    form.birthPlace.data = actor.BirthPlace
    form.imdbId.data = actor.ImdbId
    form.imageUrl.data = actor.ImageUrl
    return render_template("publish_actor.html",
                           title='ACTOR',
                           actor_id=actor_id,
                           form=form)