Example #1
0
def get_non_contributors_users_jobs(queue='quaterly'):
    """Return a list of users that have never contributed to a project."""
    from sqlalchemy.sql import text
    from pybossa.model.user import User
    from pybossa.core import db
    # Second users that have created an account but never participated
    sql = text('''SELECT id FROM "user" WHERE
               NOT EXISTS (SELECT user_id FROM task_run
               WHERE task_run.user_id="user".id)''')
    results = db.slave_session.execute(sql)
    timeout = current_app.config.get('TIMEOUT')
    for row in results:
        user = User.query.get(row.id)

        if user.subscribed:
            subject = "Why don't you help us?!"
            body = render_template('/account/email/noncontributors.md',
                                   user=user.dictize(),
                                   config=current_app.config)
            html = render_template('/account/email/noncontributors.html',
                                   user=user.dictize(),
                                   config=current_app.config)
            mail_dict = dict(recipients=[user.email_addr],
                             subject=subject,
                             body=body,
                             html=html)

            job = dict(name=send_mail,
                       args=[mail_dict],
                       kwargs={},
                       timeout=timeout,
                       queue=queue)
            yield job
Example #2
0
def docheck():
    # session[] 存資料
    # session.get() 取 session 資料
    # 利用 request.form[] 取得表單欄位資料, 然後送到 template
    guess = request.form["guess"]
    session["guess"] = guess
    # 假如使用者直接執行 doCheck, 則設法轉回根方法
    if guess is None:
        redirect("/")
    # 從 session 取出 answer 對應資料, 且處理直接執行 docheck 時無法取 session 值情況
    try:
        theanswer = int(session.get('answer'))
    except:
        redirect("/")
    # 經由表單所取得的 guess 資料型別為 string
    try:
        theguess = int(guess)
    except:
        return redirect("/guessform")
    # 每執行 doCheck 一次,次數增量一次
    session["count"] += 1
    count = session.get("count")
    # 答案與所猜數字進行比對
    if theanswer < theguess:
        return render_template("toobig.html", guess=guess, answer=theanswer, count=count)
    elif theanswer > theguess:
        return render_template("toosmall.html", guess=guess, answer=theanswer, count=count)
    else:
        # 已經猜對, 從 session 取出累計猜測次數
        thecount = session.get('count')
        return "猜了 "+str(thecount)+" 次, 終於猜對了, 正確答案為 "+str(theanswer)+": <a href='/'>再猜</a>"
    return render_template("docheck.html", guess=guess)
Example #3
0
def stuffster():
    """Start page, redirects to login if there is no cookie for the user"""
    if 'username' in session:
        cats = db.get_categories(session['username'])
        note = db.get_note(session['username'])
        return render_template('template.html', categories = cats, user_note = note)
    return render_template('login.html')
Example #4
0
def m_doctor_update():
    action_type = request.values.get("action_type", None)
    if not action_type:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_doctor_list"))

    if action_type == "n":
        cs = connection.Clinic.find({'active':0}).sort('name')
        cats = connection.Category.find({'active':0}).sort('name')
        return render_template("m_doctor_new.html", clinics = cs, categories = cats)
    elif action_type in ["m", "d"]:
        id = request.values.get("id", None)
        if not id:
            flash("No doctor id supply", MESSAGE_ERROR)
            return redirect(url_for("m_doctor_list"))
        d = connection.DoctorProfile.one({'id' : int(id)})
        if action_type == "m":
            cs = connection.Clinic.find({'active':0}).sort('name')
            cats = connection.Category.find({'active':0}).sort('name')
            return render_template("m_doctor_update.html", doctor = d, clinics = cs, categories = cats)
        elif action_type == "d":
            info = d.populate()
            d.active = 1
            d.save()
            l = connection.SystemLog()
            l.uid = session['user_profile']['id']
            l.type = u'DELETE DOCTOR'
            l.content = u'%s delete the doctor profile [name : %s, id : %d]' % (session['user_profile']['name'], info['name'], d.id)
            flash("The doctor profile [%s] has been deleted successfully !" % info['name'], MESSAGE_INFO)
            return redirect(url_for("m_doctor_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))
Example #5
0
def m_clinic_update():
    action_type = request.values.get("action_type", None)
    if not action_type:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))

    if action_type == "n":
        return render_template("m_clinic_new.html")
    elif action_type in ["m", "d"]:
        id = request.values.get("id", None)
        if not id:
            flash("No clinic id supply", MESSAGE_ERROR)
            return redirect(url_for("m_clinic_list"))
        c = connection.Clinic.one({'id' : int(id)})
        if action_type == "m":
            return render_template("m_clinic_update.html", clinic = c)
        elif action_type == "d":
            c.active = 1
            c.save()
            l = connection.SystemLog()
            l.uid = session['user_profile']['id']
            l.type = u'DELETE CLINIC'
            l.content = u'%s delete the clinic [name : %s, id : %d]' % (session['user_profile']['name'], c.name, c.id)
            flash("The clinic [%s] has been deleted successfully !" % c.name, MESSAGE_INFO)
            return redirect(url_for("m_clinic_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))
Example #6
0
def login():
    # If a user is already logged in. is_authenticated is a function
    # of the User class in models.py
    if g.user.is_authenticated():
        return render_template('index.html', 
                                message='A user is already logged in.',
                                email=g.user.email,
                                listings=get_listings())

    # If the user is sending information (i.e. trying to log in),
    # checks the selected email against the users in the database.
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']

        # queries the database for a user with the email submitted
        user = session.query(User).filter(User.email == email).first()

        # if the user was in the database and the password matches,
        # logs the user in and returns a message.
        if user is not None and pwd_context.verify(password, user.password):
            login_user(user)
            return render_template('index.html',
                                    message='Login was successful.',
                                    email=user.email,
                                    listings=get_listings())

        return render_template('index.html',
                                message='Email or password invalid. Please try again.',
                                listings=get_listings())

    # returns login form if request method was GET
    return render_template('login.html')
Example #7
0
def run():
    form = GoalTimeForm(request.form)
    if request.method == "POST" and form.validate_on_submit():
        plan = generate_plan(
            form.wave.data,
            form.hours.data,
            form.minutes.data,
        )
        start_time = plan[0].strftime("%I:%M %p")
        goal_pace = "%d:%d" % (plan[1] / 60, plan[1] % 60)
        goal_finish = plan[2].strftime("%I:%M %p")
        beer_time = plan[3].strftime("%I:%M %p")
        plan_points = plan[4]
        friend_link = plan[5]
        return render_template(
            "layout.html",
            form=form,
            viewing_points=plan_points,
            start_time=start_time,
            goal_pace=goal_pace,
            goal_finish=goal_finish,
            beer_time=beer_time,
            friend_link=friend_link,
        )
    else:
        if request.args.get("wave"):
            form.wave.data = request.args.get("wave")
        form.hours.data = request.args.get("hours")
        form.minutes.data = request.args.get("minutes")
        return render_template("layout.html", form=form)
Example #8
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        results = wiki.search(form.term.data, form.ignore_case.data)
        return render_template('search.html', form=form,
                               results=results, search=form.term.data)
    return render_template('search.html', form=form, search=None)
Example #9
0
def login():
	'''Login to Matterhorn. This method will request the Matterhorn Login page
	to obtain a session which can be used for further requests.
	'''
	error = None
	if request.method == 'POST':
		# Prepare data
		data = {
				'j_username': request.form['username'],
				'j_password': request.form['password'] }
		try:
			opener = urllib2.build_opener(NoRedirection)
			u = opener.open(app.config['SECURITY_SERVICE'],
					urllib.urlencode(data))
			if u.headers.get('location'):
				if '/login.html' in u.headers.get('location'):
					return render_template('login.html',
							error='Could not log in. Incorrect credentials?')
			cookie = u.headers.get('Set-Cookie')
			u.close()

			response = redirect(url_for('home'))
			response.headers['Set-Cookie'] = cookie
			return response

		except urllib2.HTTPError as e:
			if e.code == 404:
				return render_template('login.html',
						error='Login service returned error. Please report this.')
			if e.code == 401:
				return render_template('login.html',
						error='Could not log in. Incorrect credentials?')
			raise e

	return render_template('login.html')
Example #10
0
File: app.py Project: mhkuu/pdnstat
def upload_pdn():
    if request.method == 'POST':
        error = None
        f = request.files['file']
        if not f: 
            error = 'Geen bestand geselecteerd'
        elif not allowed_file(f.filename):
            error = 'Bestand niet geaccepteerd'
        else: 
            filename = secure_filename(f.filename)
            #f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            
            collection_name = request.form['name'].lower()
            if not collection_name: 
                error = 'Geen naam opgegegeven'
            else: 
                c = Collection.query.filter_by(name=collection_name).first()
                if c: 
                    error = 'Naam is al in gebruik: verzin een andere naam!'
                else: 
                    upload_file(f, collection_name)
                    return redirect(url_for('collection', collection_name=collection_name))
        return render_template('upload.html', error=error)
    else: 
        return render_template('upload.html')
Example #11
0
def login():
    if request.method == 'GET':
        return render_template('login.html')

    facebook_id = request.form.get('facebook_id')
    facebook_token = request.form.get('facebook_token')

    if not facebook_id or not facebook_token:
        flash(u"잘못된 로그인 정보입니다.")
        return render_template('login.html'), 400

    me = facebook_auth(facebook_token)
    if not me:
        flash(u"페이스북 인증에 실패했습니다.")
        return render_template('login.html'), 400

    if me['id'] not in current_app.config['ALLOWED_FACEBOOK_USERS']:
        flash(u"허용되지 않은 사용자입니다.")
        return render_template('login.html'), 400

    user = User.query.filter_by(facebook_id=str(me['id'])).first()
    if user is None:
        user = User()
        user.name = me['name']
        user.facebook_id = facebook_id
        user.facebook_token = facebook_token
        db.session.add(user)
        db.session.commit()

    login_user(user)
    return redirect(url_for('web.item_list'))
Example #12
0
def track_book_location():
	if request.method == 'GET':
		return render_template('track-book-location.html')
	elif request.method == 'POST':
		f = request.form
		location_info = database.track_book(f['isbn'])
		return render_template('track-book-location.html', location_info = location_info)
Example #13
0
def user_home():
    dic_codes  = dict([(code.id,code.code_name) for code in Dic_code.query.all()])

    data_type = request.args.get('name')
    if data_type == 'index':
        user_data = Tab.query.outerjoin(Like, Tab.id==Like.like_id).filter(Like.uid==current_user.id)\
                    .filter(Like.like_type==1)
    elif data_type == 'tabs':
        user_data = Tab.query.filter_by(uid=current_user.id).order_by(Tab.create_time.desc())
    elif data_type == 'artists':
        user_data = Artist.query.outerjoin(Like, Artist.id==Like.like_id).filter(Like.uid==current_user.id)\
                    .filter(Like.like_type==2)
    else:
        user_data = Question.query.filter_by(uid=current_user.id).order_by(Question.create_time.desc())

    page = request.args.get('page')
    if page and int(page) >= 1:
        page      = int(page)
        user_data = user_data.paginate(page, 40, False)
        return render_template('users/likes_filter_ajax.html', user_data=user_data, dic_codes=dic_codes, data_type=data_type)
    else:
        page = 1
        user_data = user_data.paginate(page, 40, False)

    return render_template('users/user_home.html', user_data=user_data, dic_codes=dic_codes, data_type=data_type)
Example #14
0
def warn_old_project_owners():
    """E-mail the project owners not updated in the last 3 months."""
    from pybossa.core import mail, project_repo
    from pybossa.cache.projects import clean
    from flask.ext.mail import Message

    projects = get_non_updated_projects()

    with mail.connect() as conn:
        for project in projects:
            subject = ('Your %s project: %s has been inactive'
                       % (current_app.config.get('BRAND'), project.name))
            body = render_template('/account/email/inactive_project.md',
                                   project=project)
            html = render_template('/account/email/inactive_project.html',
                                   project=project)
            msg = Message(recipients=[project.owner.email_addr],
                          subject=subject,
                          body=body,
                          html=html)
            conn.send(msg)
            project.contacted = True
            project.published = False
            clean(project.id)
            project_repo.update(project)
    return True
Example #15
0
def other():
    if g.user.is_authenticated():
        return render_template('index.html',
                               username=g.user.email,
                               active='Miscellaneous')
    return render_template('index.html',
                           active='Miscellaneous')
Example #16
0
def totp_user_view():
	if not totp_user_enabled(session['username']):
		if request.method == 'GET':
			return render_template('totp_enable.html',active="user")
		elif request.method == 'POST':
			## verify the token entered
			token = request.form['totp_token']

			if totp_verify_token(session['username'],token):
				flash("Two step logon has been enabled for your account","alert-success")
				g.redis.set('totp.%s.enabled' % session['username'],"True")
			else:
				flash("Invalid code! Two step logons could not be enabled","alert-danger")
	
			return redirect(url_for('totp_user_view'))
				
	else:
		if request.method == 'GET':
			return render_template('totp_disable.html',active="user")
		elif request.method == 'POST':

			## verify the token entered
			token = request.form['totp_token']

			if totp_verify_token(session['username'],token):
				g.redis.delete('totp.%s.enabled' % session['username'])
				g.redis.delete('totp.%s.key' % session['username'])
				flash("Two step logons have been disabled for your account","alert-warning")
			else:
				flash("Invalid code! Two step logons were not disabled","alert-danger")
	
			return redirect(url_for('totp_user_view'))
Example #17
0
def edit_listing(listing_id):
    listing = session.query(Listing).get(listing_id)
    if listing is None:
        return abort(404)

    if not g.user.is_authenticated():
        return render_template('listing.html',
                                listing_id=listing_id,
                                title=listing.title,
                                description=listing.description,
                                price=listing.price,
                                image=listing.image,
                                message='You must be logged in to edit your listing.')

    if g.user.id != listing.user_id:
        return render_template('listing.html',
                                email=g.user.email,
                                listing_id=listing_id,
                                title=listing.title,
                                description=listing.description,
                                price=listing.price,
                                image=listing.image,
                                message='Only the creator of this listing may edit it.')

    if request.method == 'GET':
        return render_template('edit_listing.html',
                                listing_id=listing_id,
                                title=listing.title,
                                description=listing.description,
                                price=listing.price,
                                image=listing.image)

    elif request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        category = request.form['category']
        price = request.form['price']
        image = None
        if 'image' in request.files:
            image_file = request.files['image'].read()
            if image_file != '':
                image = buffer(image_file)
                listing.image = image


        if title != '':
            listing.title = title

        if description != '':
            listing.description = description

        if category != '':
            category_id = session.query(Category).filter(Category.name == category).first()
            listing.category_id = category_id

        if price != '' and is_number(price):
            listing.price = price

        session.commit()
        return redirect(url_for('listing', listing_id=listing_id))
Example #18
0
def register():

    # if a user is already logged in
    if g.user.is_authenticated():
        return render_template('index.html',
                                message='Please logout before attempting to create a new_account.',
                                email=g.user.email,
                                listings=get_listings())

    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        user = session.query(User).filter(User.email == email).first()
        if user is not None:
            return render_template('index.html',
                                    message='An account with that email already exists. If you have forgotten your password,'
                                    + ' go to "buy5c.com/forgot_password" to find out how to reset it.',
                                    listings=get_listings())

       # if no user with that email exists, creates one and adds it to the database
        else:
            password = pwd_context.encrypt(password)
            user = User(email, password)
            session.add(user)
            session.commit()
            return render_template('index.html',
                                    message='Account successfully created.',
                                    listings=get_listings())

    return render_template('register.html')
Example #19
0
def search_text():
    if request.method == 'POST':
        search_term = request.form['search_term']
        results = Document.query.search(search_term)
        return render_template('search_results.html', results=results, search_term=search_term)
    else:
        return render_template('search.html')
Example #20
0
def a_a():
    if g.user.is_authenticated():
        return render_template('index.html',
                               username=g.user.email,
                               active='Apparel/Accessories')
    return render_template('index.html',
                           active='Apparel/Accessories')
Example #21
0
File: lotg.py Project: tojaku/lotg
def update_account():
    form = AccountDataForm()
    user = g.user
    if request.method == 'GET':
        form.email.data = user.email
        form.language.data = user.language
        form.timezone.data = user.timezone
    elif request.method == 'POST' and form.validate_on_submit():
        if password_hash(form.old_password.data) != user.password:
            form.old_password.errors.append(_('Wrong password'))
            return render_template('update_account.html', form=form)
        if form.email.data != user.email:
            user.email = form.email.data
            user.confirmed = False
            user.confirmation_string = random_string(20)
            msg = message_confirmation(user.id, user.email, user.confirmation_string)
            mail.send(msg)
            flash(_('Confirmation message sent, check your e-mail'))
        if form.password.data:
            user.password = password_hash(form.password.data)
            flash(_('Password successfully changed'))
        user.language = form.language.data
        user.timezone = form.timezone.data
        db.session.commit()
        return redirect('update_account')

    return render_template('update_account.html', form=form)
Example #22
0
def appliances():
    if g.user.is_authenticated():
        return render_template('index.html',
                               username=g.user.email,
                               active='Appliances')
    return render_template('index.html',
                           active='Appliances')
Example #23
0
def m_nurse_update():
    action_type = request.values.get("action_type", None)
    if not action_type:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_nurse_list"))

    if action_type == "n":
        cs = connection.Clinic.find({'active':0}).sort('name')
        return render_template("m_nurse_new.html", clinics = cs)
    elif action_type in ["m", "d"]:
        id = request.values.get("id", None)
        if not id:
            flash("No nurse id supply", MESSAGE_ERROR)
            return redirect(url_for("m_nurse_list"))
        n = connection.NurseProfile.one({'id' : int(id)})
        if action_type == "m":
            cs = connection.Clinic.find({'active':0}).sort('name')
            return render_template("m_nurse_update.html", nurse = n, clinics = cs)
        elif action_type == "d":
            n.active = 1
            n.save()
            l = connection.SystemLog()
            l.uid = session['user_profile']['id']
            l.type = u'DELETE NURSE'
            l.content = u'%s delete the nurse [name : %s, id : %d]' % (session['user_profile']['name'], n.name, n.id)
            flash("The nurse [%s] has been deleted successfully !" % n.name, MESSAGE_INFO)
            return redirect(url_for("m_nurse_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_nurse_list"))
Example #24
0
def electronics():
    if g.user.is_authenticated():
        return render_template('index.html',
                               username=g.user.email,
                               active='Electronics')
    return render_template('index.html',
                           active='Electronics')
Example #25
0
def edit_comment(comment_id):
    if request.method == 'POST':

        if request.form['action'] == 'delete':
            with dbapi2.connect(flask.current_app.config['dsn']) as connection:
                cursor = connection.cursor()

                query = """DELETE FROM POST WHERE (POSTID= %s)"""
                cursor.execute(query, [comment_id])
                connection.commit()
            return redirect(url_for('site.main_page'))

        else:
            return render_template('edit_comment.html')
    else:
        with dbapi2.connect(flask.current_app.config['dsn']) as connection:
            cursor = connection.cursor()

            query = """SELECT * FROM POST WHERE POSTID = %s"""

            cursor.execute(query, [comment_id])
            post = cursor.fetchall()

            connection.commit()
        return render_template('edit_comment.html', post = post)
Example #26
0
def mmg():
    if g.user.is_authenticated():
        return render_template('index.html',
                               username=g.user.email,
                               active='Movies, Music, and Games')
    return render_template('index.html',
                           active='Movies, Music, and Games')
Example #27
0
def index():
    url_for('static', filename='logo.ico')
    if request.method == 'POST':
        #Check files that start with 'o-ide*'
        files = glob.glob("oide*")
        print(files)
        #Check if C was compiled
        if len(files) < 1:
            print("Compiling O...")
            compileO()
        #Run code
        code = request.form['code']
        input = request.form['input'].replace('\r\n', '\n')
        if input is None: input = ""
        print('Got code:', code, 'input:', input)
        print('Running O code...')
        p = Popen(['./oide', '-e', code], stdout=PIPE, stderr=PIPE, stdin=PIPE, universal_newlines=True)
        output, error = p.communicate(input)
        #Output to IDE
        if p.returncode:
            print('Output:', output, 'error:', error)
            return render_template('error.html', code=code, input=input, error=error)
        else:
            print('Output:', output, 'stack:', error)
            return render_template('code.html', code=code, input=input, output=output, stack=error or '[]')
    else:
        return render_template('primary.html')
Example #28
0
def tickets():
    if g.user.is_authenticated():
        return render_template('index.html',
                               username=g.user.email,
                               active='Tickets')
    return render_template('index.html',
                           active='Tickets')
Example #29
0
def blogedit(blogid):
    if 'logged_in' not in session:
        abort(403)
    if request.method == 'POST':
        title = request.form['title'].strip()
        text  = request.form['blogpost'].strip()

        error = 0
        if title == "":
            error = 1
            flash("You must make a title","error")
        if text == "":
            error = 1
            flash("You must make the blogpost","error")
        if 'Preview Blog' in request.form.values():
            renderedblog = render_bbcode(text)
            return render_template("blogedit.html",blogid=blogid,title=title,blogpost=text,recover=1,preview="1",renderedblog=renderedblog)
        if error:
            return render_template('blogedit.html',blogid=blogid,title=title,blogpost=text,recover=1)

        g.db.execute("""
UPDATE post SET title=?, text=?, lastedit=? WHERE id=?
""",(title,text,unixtime(),blogid))
        g.db.commit()
        flash("You successfully changed your blogpost","message")
        return redirect(url_for('blogpost',blogid=blogid))
    g.blog = query_db("""
SELECT * FROM post WHERE id=?
""", [str(blogid)], True,False)
    return render_template('blogedit.html',blogid=blogid)
Example #30
0
def xhr_sickbeard():
    try:
        url = '%s/?cmd=future&sort=date' % (sickbeard_url())
        result = urllib.urlopen(url).read()
        sickbeard = json.JSONDecoder().decode(result)

        compact_view = get_setting_value('sickbeard_compact') == '1'
        show_airdate = get_setting_value('sickbeard_airdate') == '1'

        if sickbeard['result'].rfind('success') >= 0:
            sickbeard = sickbeard['data']
            for time in sickbeard:
                for episode in sickbeard[time]:
                    episode['image'] = get_pic(episode['tvdbid'], 'banner')
    except:
        return render_template('sickbeard.html',
            sickbeard='',
        )

    return render_template('sickbeard.html',
        url=sickbeard_url_no_api(),
        sickbeard=sickbeard,
        missed=sickbeard['missed'],
        today=sickbeard['today'],
        soon=sickbeard['soon'],
        later=sickbeard['later'],
        compact_view=compact_view,
        show_airdate=show_airdate,
    )