コード例 #1
0
def update_book(book_id):
  """this function handles updating the title of an existing book"""
  if book_id < len(books):
    book_title = request.forms.get('title')
    books[book_id] = book_title
    redirect('/books/%i' % book_id)
  abort(404)
コード例 #2
0
def general_information():
    username = request.get_cookie("account", secret=SECRET)

    if username:
        engine_count = len(load_engine_db(DB_PATH)['engine'])
        try:
            running_project = "text-primary|" + send_request("%s/listprojects.json" % scrapyd_api_url)['projects'][0]
            running_spider = "text-primary|" + send_request("%s/listspiders.json?project=%s" % \
                                                            (scrapyd_api_url, running_project.split('|')[1]))[
                'spiders'][0]
            project_version = "text-primary|" + send_request("%s/listversions.json?project=%s" % \
                                                             (scrapyd_api_url, running_project.split('|')[1]))[
                'versions'][0]
        except requests.ConnectionError:
            running_project = "text-danger|CRAWLER SERVER IS DOWN"
            running_spider = "text-danger|CRAWLER SERVER IS DOWN"
            project_version = "text-danger|CRAWLER SERVER IS DOWN"
        except IndexError:
            running_project = "text-danger|NO CRAWLER PROJECT RUNNING"
            running_spider = "text-danger|NO CRAWLER PROJECT RUNNING"
            project_version = "text-danger|NO CRAWLER PROJECT RUNNING"
        return template('_layout/layout.html', title=APP_NAME, name=username, page='informations', \
                        running_project=running_project, running_spider=running_spider, project_version=project_version, \
                        engine_count=engine_count)
    else:
        redirect('/login')
コード例 #3
0
def add_engine():
    username = request.get_cookie("account", secret=SECRET)

    if username:
        return template('_layout/layout.html', title=APP_NAME, name=username, page='add_engine')
    else:
        redirect('/login')
コード例 #4
0
ファイル: blog.py プロジェクト: joshprewitt/m101p
def post_new_comment():
    name = bottle.request.forms.get("commentName")
    email = bottle.request.forms.get("commentEmail")
    body = bottle.request.forms.get("commentBody")
    permalink = bottle.request.forms.get("permalink")

    post = posts.get_post_by_permalink(permalink)
    cookie = bottle.request.get_cookie("session")

    username = sessions.get_username(cookie)

    # if post not found, redirect to post not found error
    if post is None:
        bottle.redirect("/post_not_found")
        return

    # if values not good, redirect to view with errors

    if name == "" or body == "":
        # user did not fill in enough information

        # init comment for web form
        comment = {"name": name, "email": email, "body": body}

        errors = "Post must contain your name and an actual comment."
        return bottle.template("entry_template", dict(post=post, username=username, errors=errors, comment=comment))

    else:

        # it all looks good, insert the comment into the blog post and redirect back to the post viewer
        posts.add_comment(permalink, name, email, body)

        bottle.redirect("/post/" + permalink)
コード例 #5
0
def engine_list():
    username = request.get_cookie("account", secret=SECRET)

    if username:
        engine_config = load_engine_db(DB_PATH)
        engines = engine_config['engine']
        try:
            post_to_lintas = engine_config['post_to_lintas']
        except KeyError:
            post_to_lintas = "No"
        engine_count = len(engines)
        engine_list = AutoVivification()
        for engine in engines:
            engine_list[engine]['status'] = "ACTIVE" if is_engine_activated(engine.lower()) else "INACTIVE"
            engine_list[engine]['cmd'] = engines[engine]['cmd']
            engine_list[engine]['minute_run_at'] = engines[engine]['run_at'][0]
            engine_list[engine]['hour_run_at'] = engines[engine]['run_at'][1]
        try:
            running_project = "text-primary|" + send_request("%s/listprojects.json" % scrapyd_api_url)['projects'][0]
            running_spider = "text-primary|" + send_request("%s/listspiders.json?project=%s" % (scrapyd_api_url, running_project.split('|')[1]))['spiders'][0]
            project_version = "text-primary|" + send_request("%s/listversions.json?project=%s" % (scrapyd_api_url, running_project.split('|')[1]))['versions'][0]
        except requests.ConnectionError:
            running_project = "text-danger|CRAWLER SERVER IS DOWN"
            running_spider = "text-danger|CRAWLER SERVER IS DOWN"
            project_version = "text-danger|CRAWLER SERVER IS DOWN"
        except IndexError:
            running_project = "text-danger|NO CRAWLER PROJECT RUNNING"
            running_spider = "text-danger|NO CRAWLER PROJECT RUNNING"
            project_version = "text-danger|NO CRAWLER PROJECT RUNNING"

        return template('_layout/layout.html', title=APP_NAME, name=username, page='main', running_project=running_project, running_spider=running_spider, project_version=project_version, engine_count=engine_count, engines=engine_list, post_to_lintas=post_to_lintas)
    else:
        redirect("/login")
コード例 #6
0
        def wrapper(*args, **kwargs):
            (language, redirect) = self.get_language()

            if redirect:
                from tools import utils
                from bottle import redirect
                url = request.urlparts
                new_url = []
                new_url.append("/" + language[0])
                new_url.append(request.fullpath)
                if url.query:
                    new_url.append("?")
                    new_url.append(url.query)
                redirect("".join(new_url))
                return

            # Setup Gettext
            k = ','.join(language)
            if self.cache.has_key(k):
                gt = self.cache[k]
            else:
                gt = gettext.translation(self.domain, localedir=self.localedir, languages=language)
                self.cache[k] = gt
            gt.install(unicode=1)

            # Add the language as a keyword argument.
            kwargs[keyword] = language

            return callback(*args, **kwargs)
コード例 #7
0
def activate_deactivate_engine(engine_name, minute, hour, cmd):
    cmd_string = 'sh %s/shell/set_cron.sh %s %s %s %s' % \
                 (CONSOLE_ROOT_DIR, minute, '*/%s' % hour, engine_name, 'APPEND' if cmd == 'activate' else 'REMOVE')
    cmd_exec = subprocess.Popen(cmd_string.split(), stdout=subprocess.PIPE)

    if str(cmd_exec.stdout.read()) == "":
        redirect("/home")
コード例 #8
0
    def save_config(self, screen):

        # Flag to indicate whether params have changed
        change_params = False

        # Get the new params from the web form
        try:
            params = json.loads(request.forms.get("params"))
        except ValueError:
            return "INVALID JSON"
        else:
            # Let's check if the params have changed

            # Build the path to our config file
            conffile = os.path.join(self.folder, "screens", screen, "conf.json")

            # Open the file and load the config
            with open(conffile, "r") as cfg_file:
                conf = json.load(cfg_file)

            # Check if the form is the same as the old one
            if conf.get("params", dict()) != params:

                # If not, we need to update
                change_params = True

            if change_params:
                # Submit the new params to the API
                r = requests.post("{}{}/configure".format(self.api,
                                                          screen), json=params)

            redirect("/")
コード例 #9
0
ファイル: server.py プロジェクト: prgreen/zeitgeist
def submit_upvote():
    #TODO Check IP address for limitation
    sentence = html_unescape(request.forms.get('sentence'))
    if len(sentence) <= 140 and sentence != '':
        if r.zscore(SENTENCES_KEY, sentence) != None:
            r.zincrby(SENTENCES_KEY, sentence)
    redirect('/')
コード例 #10
0
ファイル: circushttpd.py プロジェクト: MPOWER4RU/circus
def switch(name):
    url = request.query.get('redirect', '/')
    try:
        client.switch_status(name)
        redirect(url)
    except CallError, e:
        redirect(url + '?msg=' + str(e))
コード例 #11
0
ファイル: circushttpd.py プロジェクト: MPOWER4RU/circus
def disconnect():
    global client

    if client is not None:
        client.stop()
        client = None
        redirect('/?msg=disconnected')
コード例 #12
0
def do_save():
	Config.set('player', 'server', request.forms.get('server'))
	Config.set('player', 'channel', request.forms.get('channel'))
	cfgfile = open(configfile,'w+')
	Config.write(cfgfile)
	cfgfile.close()
	redirect('/')
コード例 #13
0
ファイル: statistic.py プロジェクト: OlafRadicke/tuxerjoch
    def statistic_get(self):
        '''This controller show the statistic'''
        authenticated = controls.auth.authenticated_check( self.couchDB )
        if authenticated == None:
            bottle.redirect("/login")

        global_config_data = json.loads( self.couchDB.getDocValue( "global_config" ).text, 'utf8')
        # check session
        authenticated = bottle.request.get_cookie("authenticated", secret = global_config_data["cookie_secret_key"])

        if os.path.isfile( global_config_data["statistic_report"] ):
            with open( global_config_data["statistic_report"] ) as html_statistic:
                html_statistic_data = html_statistic.read()
                html_statistic.close()

        else:
            logging.error( "Can not open " + global_config_data["statistic_report"])


            html_out = bottle.template(
                'skeleton',
                uri_prefix="../",
                title="Statistik",
                flashed_message="Can not open " + global_config_data["statistic_report"],
                flashed_level="danger",
                authenticated=authenticated)
            return html_out


        return html_statistic_data
コード例 #14
0
ファイル: blog.py プロジェクト: carlan/m101p
def process_login():

    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")

    print "user submitted ", username, "pass ", password

    user_record = users.validate_login(username, password)
    if user_record:
        # username is stored in the user collection in the _id key
        session_id = sessions.start_session(user_record['_id'])

        if session_id is None:
            bottle.redirect("/internal_error")

        cookie = session_id

        # Warning, if you are running into a problem whereby the cookie being set here is
        # not getting set on the redirect, you are probably using the experimental version of bottle (.12).
        # revert to .11 to solve the problem.
        bottle.response.set_cookie("session", cookie)

        bottle.redirect("/welcome")

    else:
        return bottle.template("login",
                               dict(username=cgi.escape(username), password="",
                                    login_error="Invalid Login"))
コード例 #15
0
ファイル: pyload_app.py プロジェクト: tetratec/shareacc
def login():
    # set mobilecookie to reduce is_mobile check-time
    response.set_cookie("mobile", str(is_mobile()))
    if not PYLOAD and SETUP:
        redirect("/setup")
    else:
        return render_to_response("login.html", proc=[pre_processor])
コード例 #16
0
ファイル: routes.py プロジェクト: nels-o/citer
def prototype():
    md5     = request.forms.md5
    bib     = request.forms.bib
    notes   = request.forms.notes
    tags    = request.forms.tags.split(',')
    if md5:
        doc = Document.select().where(Document.md5 == md5).get()
        if doc:
            if notes:
                doc.notes = notes
            if bib:
                try:
                    bibtexparser.loads(bib)
                    doc.bib = bib.strip()
                except:
                    session()['msg'] = "Invalid bibtex."
                    return redirect('/annotate/'+md5)
            if tags:
                with db.atomic():
                    Tag.delete().where(Tag.document == doc).execute()
                    for tag in tags:
                        try:
                            Tag.insert(document=doc, value=tag).execute()
                        except Exception:
                            pass
            doc.save()
            session()['msg'] = " Success"
            return redirect('/annotate/'+md5)
    else:
        session()['msg'] = "Invalid request. No document specified."
        return redirect('/annotate/'+md5)

    session()['msg'] = "You missed a field, or something went wrong."
    return redirect('/annotate/'+md5)
コード例 #17
0
ファイル: routes.py プロジェクト: nels-o/citer
def prototype(name="Default"):
    r = Review.select().where(Review.name==name).count()
    if r > 0:
        session()['curr_review'] = name
        return redirect('/annotate')
    session()['msg'] = 'Invalid review'
    return redirect('/')
コード例 #18
0
ファイル: app.py プロジェクト: wightman/speakeasy
 def _check_auth(*args,**kwargs):
   sess = Session(bottle.request,bottle.response)
   if not sess.is_new():
     user =  User.find_by_id(sess['id'])
     if user:
       return handler(user,*args,**kwargs)
   bottle.redirect('/login')
コード例 #19
0
ファイル: app.py プロジェクト: wightman/speakeasy
def delete(user, page, id):
  post = Post(int(id))
  if post.user == user:
    user.delete(id)
    bottle.redirect('/'+page)
  else:
    bottle.redirect('/'+page)
コード例 #20
0
ファイル: blog.py プロジェクト: drozas/mongodb
def process_signup():

    connection = pymongo.Connection(connection_string, safe=True)

    email = bottle.request.forms.get("email")
    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")
    verify = bottle.request.forms.get("verify")

    # set these up in case we have an error case
    errors = {'username':cgi.escape(username), 'email':cgi.escape(email)}
    if (user.validate_signup(username, password, verify, email, errors)):
        if (not user.newuser(connection, username, password, email)):
            # this was a duplicate
            errors['username_error'] = "Username already in use. Please choose another"
            return bottle.template("signup", errors)
            
        session_id = user.start_session(connection, username)
        print session_id
        cookie= user.make_secure_val(session_id)
        bottle.response.set_cookie("session",cookie)
        bottle.redirect("/welcome")
    else:
        print "user did not validate"
        return bottle.template("signup", errors)
コード例 #21
0
ファイル: hotel.py プロジェクト: matves/opb-hotelirji
def login_post():
    """Obdelaj izpolnjeno formo za prijavo"""
    # Uporabniško ime, ki ga je uporabnik vpisal v formo
    uporabnisko_ime = bottle.request.forms.uporabnisko_ime
    geslo = bottle.request.forms.geslo
    # Izračunamo MD5 hash gesla, ki ga bomo spravili
    geslo = password_md5(bottle.request.forms.geslo)
    (rekkap, rektip, rekcena)=reklama_login()

    # Preverimo, ali se je uporabnik pravilno prijavil: daj mi tega, ki ima ta username in password
    cur = baza.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT 1 FROM oseba WHERE uporabnisko_ime=%s AND geslo=%s",[uporabnisko_ime, geslo])
    #mi da prvi rezultat, če je to none, se ni prijavil pravilno
    if cur.fetchone() is None:
        # Username in geslo se ne ujemata
        return bottle.template("login.html",
                               napaka="Nepravilna prijava.",
                               uporabnisko_ime=uporabnisko_ime,
                               rekkap=rekkap,
                               rektip=rektip,
                               rekcena=rekcena)
          #username mu vpišemo nazaj, gesla mu seveda ne bomo nazaj poslali
    else:
        # Vse je v redu, nastavimo cookie in preusmerimo na glavno stran
        ##cookie: ime cookieja, ime vrednosti, kje je veljaven, kako je zakodiran (nekaj naključnega)
        bottle.response.set_cookie('uporabnisko_ime', uporabnisko_ime, path='/', secret=secret)
        bottle.redirect("/")
        ##pošljemo ga na glavno stran in če bo rpavilno delovala, bo vidla njegov cookie
    cur.close()
コード例 #22
0
ファイル: blog.py プロジェクト: drozas/mongodb
def post_newpost():
    title = bottle.request.forms.get("subject")
    post = bottle.request.forms.get("body")
    tags = bottle.request.forms.get("tags")

    username = login_check()  # see if user is logged in
    if (username is None):
        bottle.redirect("/login")        
    
    if (title == "" or post == ""):
        errors="Post must contain a title and blog entry"
        return bottle.template("newpost_template", dict(subject=cgi.escape(title, quote=True), username=username,
                                                 body=cgi.escape(post, quote=True), tags=tags, errors=errors))

    # extract tags
    tags = cgi.escape(tags)
    tags_array = extract_tags(tags)
    
    # looks like a good entry, insert it escaped
    escaped_post = cgi.escape(post, quote=True)

    # substitute some <p> for the paragraph breaks
    newline = re.compile('\r?\n')
    formatted_post = newline.sub("<p>",escaped_post)
    
    permalink=insert_entry(title, formatted_post, tags_array, username)

    # now bottle.redirect to the blog permalink
    bottle.redirect("/post/" + permalink)
コード例 #23
0
ファイル: core.py プロジェクト: Jamschnei/social_network
def requireAuth():
	if bottle.request.get_cookie('_aok_'):
		renewAuth()
	elif bottle.request.get_cookie('_aep_'):
		bottle.redirect('/')
	else:
		bottle.redirect('/authrequired')
コード例 #24
0
ファイル: app.py プロジェクト: rSimulate/Cosmosium
def submit_log_in():
    uid = request.forms.get('userid')
    pw = request.forms.get('password')
    rem = request.forms.get('remember_me')
    _user = USERS.getUserByName(uid)
    set_login_cookie(_user, uid, pw, rem)
    redirect('/play')
コード例 #25
0
ファイル: app.py プロジェクト: rSimulate/Cosmosium
def login_success():
    token = request.forms.get('token')
    session = rauth.OAuth2Session(config.GOOGLE_CLIENT_ID, config.GOOGLE_CLIENT_SECRET, token)
    json = session.get('https://www.googleapis.com/oauth2/v1/userinfo').json()
    if json is None:
        return

    def convert(inputt):
        if isinstance(inputt, dict):
            return {convert(key): convert(value) for key, value in inputt.iteritems()}
        elif isinstance(inputt, list):
            return [convert(element) for element in inputt]
        elif isinstance(inputt, unicode):
            return inputt.encode('utf-8')
        else:
            return input
    json = convert(json)
    name = json['name'].replace(" ", "_")
    user = User(name, json['picture'], "NASA", "For the Benefit of All")
    gameToken = user.name
    gameToken = gameToken.replace(" ", "_")
    USERS.addUser(user, gameToken)
    response.set_cookie("cosmosium_login", gameToken, max_age=60 * 60 * 5)
    loginTokens.append({'name': user.name, 'social_token': token, 'game_token': gameToken})

    # now that we're logged in, send the user where they were trying to go, else to main page
    target = request.query.target or '/play'
    redirect(target)
コード例 #26
0
ファイル: webserver.py プロジェクト: bjolseth/spiderpig
def delete(term):
    termObj = dictionary.searchExact(term)
    if not termObj:
        errorPage("Error saving " + term)

    dictionary.deleteTerm(termObj)
    redirect('/')
コード例 #27
0
ファイル: admin.py プロジェクト: danwinkler/dtext
def admin(mongodb):
    user = helper.get_user(mongodb)

    if not user or "admin" not in user.get("roles", []):
        redirect("/")

    return helper.template("admin/admin", user=user)
コード例 #28
0
ファイル: blog.py プロジェクト: drozas/mongodb
def get_newpost():

    username = login_check()  # see if user is logged in
    if (username == None):
        bottle.redirect("/login")        

    return bottle.template("newpost_template", dict(subject="", body="",errors="", tags="", username=username))
コード例 #29
0
ファイル: blog.py プロジェクト: sithu/pymongo-in-bottle
def post_newcomment():
    name = bottle.request.forms.get("commentName")
    email = bottle.request.forms.get("commentEmail")
    body = bottle.request.forms.get("commentBody")
    permalink = bottle.request.forms.get("permalink")

    # look up the post in question
    connection = pymongo.Connection(connection_string, safe=True)
    db = connection.blog
    posts = db.posts

    username = login_check()  # see if user is logged in
    permalink = cgi.escape(permalink)

    post = posts.find_one({"permalink": permalink})
    # if post not found, redirct to post not found error
    if post == None:
        bottle.redirect("/post_not_found")

    # if values not good, redirect to view with errors
    errors = ""
    if name == "" or body == "":

        # fix up date
        post["date"] = post["date"].strftime("%A, %B %d %Y at %I:%M%p")

        # init comment
        comment = {}
        comment["name"] = name
        comment["email"] = email
        comment["body"] = body

        errors = "Post must contain your name and an actual comment."
        print "newcomment: comment contained error..returning form with errors"
        return bottle.template("entry_template", dict(post=post, username=username, errors=errors, comment=comment))

    else:

        # it all looks good, insert the comment into the blog post and redirect back to the post viewer
        comment = {}
        comment["author"] = name
        if email != "":
            comment["email"] = email
        comment["body"] = body

        try:
            last_error = posts.update(
                {"permalink": permalink}, {"$push": {"comments": comment}}, upsert=False, manipulate=False, safe=True
            )

            print "about to update a blog post with a comment"

            # print "num documents updated" + last_error['n']
        except:
            print "Could not update the collection, error"
            print "Unexpected error:", sys.exc_info()[0]

        print "newcomment: added the comment....redirecting to post"

        bottle.redirect("/post/" + permalink)
コード例 #30
0
ファイル: blog.py プロジェクト: drozas/mongodb
def process_login():

    connection = pymongo.Connection(connection_string, safe=True)

    username = bottle.request.forms.get("username")
    password = bottle.request.forms.get("password")

    print "user submitted ", username, "pass ", password

    userRecord = {}
    if (user.validate_login(connection, username, password, userRecord)):
        session_id = user.start_session(connection, username)
        if (session_id == -1):
            bottle.redirect("/internal_error")

        cookie = user.make_secure_val(session_id)

        # Warning, if you are running into a problem whereby the cookie being set here is 
        # not getting set on the redirct, you are probably using the experimental version of bottle (.12). 
        # revert to .11 to solve the problem.
        bottle.response.set_cookie("session", cookie)
        
        bottle.redirect("/welcome")

    else:
        return bottle.template("login", 
                           dict(username=cgi.escape(username), password="", 
                                login_error="Invalid Login"))
コード例 #31
0
def domakeZipPrompt(account, loc):
    email = request.forms.get('email')
    redirect('/mkzip/' + account + '/' + loc + '/' + email)
コード例 #32
0
def status():
    name = request.COOKIES.get('name', '')
    password = request.COOKIES.get('password', '')
    status = request.forms.get('status')
    (status2, message) = DB_SERVER.setStatus(name, password, status)
    redirect('/')
コード例 #33
0
def do_login(db):
    username = request.forms.get('username')
    password = request.forms.get('password')
    error = None
    user = get_user(db, username)
    print(user)

    if (request.forms.get("login")):
        if user is None:
            response.status = 401
            error = "{} is not registered.".format(username)

        #for this elif statement, we change password to be the hashed/salted
        #version of the plain text password. We do this by using the hash_pbkdf2
        #function from hash.py using the plain text password and the
        #random_salt assigned to the user. This allows us to throw an error
        #if the hash of the password used to login does not match the hash of
        #the password used to register.
        elif user.password != hash_pbkdf2(password, user.random_salt):
            response.status = 401
            error = "Wrong password for {}.".format(username)
        else:
            pass  # Successful login

    elif (request.forms.get("register")):
        if user is not None:
            response.status = 401
            error = "{} is already taken.".format(username)

        #Within this block of code, we first load in the breaches. Then we have
        #several if statements -- the first checks if the username trying to log
        #in is in the plain text breach. If it is, it checks if the entered
        #password matches the password in the breach -- if it does, it blocks
        #the registration and throws an error. If it does not, no error is
        #thrown and the next if statement is checked. The same process is
        #repeated for the next two if statements (one for the hashed breach and
        #one for the salted breach). All 3 of these if statements will be
        #executed -- this accounts for cases where a username might be present
        #in more than 1 of the breaches. If no errors are thrown, the username
        #and password are approved/created.
        #To test, we took a username from the plain text breach and tested it
        #with the password from the breach -- it was rejected. When we tested
        #with a random password, it was approved. We did the same for the
        #hashed breach by converting one of the hashes into a plain text
        #password -- same results. We also did the same thing for the salted
        #breach, using the password we outputed in brute.py -- same results.
        #This confirmed that our system catches dangerous pairs from all
        #breaches.
        else:
            load_breaches(db)
            breaches = get_breaches(db, username)

            if len(breaches[0]) != 0:
                if password == breaches[0][0].password:
                    response.status = 401
                    error = "This is a dangerous username-password pair. Please choose a different password for {}".format(
                        username)
            if len(breaches[1]) != 0:
                pw_hash = hash_sha256(password)
                if pw_hash == breaches[1][0].hashed_password:
                    response.status = 401
                    error = "This is a dangerous username-password pair. Please choose a different password for {}".format(
                        username)
            if len(breaches[2]) != 0:
                pw_salt = hash_pbkdf2(password, breaches[2][0].salt)
                if pw_salt == breaches[2][0].salted_password:
                    response.status = 401
                    error = "This is a dangerous username-password pair. Please choose a different password for {}".format(
                        username)
            if error == None:
                create_user(db, username, password)

    else:
        response.status = 400
        error = "Submission error."

    if error is None:  # Perform login
        existing_session = get_session_by_username(db, username)
        if existing_session is not None:
            delete_session(db, existing_session)
        session = create_session(db, username)
        response.set_cookie("session", str(session.get_id()))
        return redirect("/{}".format(username))
    return template("login", error=error)
コード例 #34
0
def do_logout(db, session):
    delete_session(db, session)
    response.delete_cookie("session")
    return redirect("/login")
コード例 #35
0
ファイル: bottle_example.py プロジェクト: imfht/flaskapps
from bottle import run, route, request, get, post, static_file, redirect
from gluino import wrapper, DAL, Field, SQLFORM, cache, IS_NOT_EMPTY
import time

# configure the gluino wrapper
wrapper.debug = True
wrapper.redirect = lambda status, url: redirect(url)

# create database and table
db = DAL('sqlite://storage.sqlite')
db.define_table('person', Field('name', requires=IS_NOT_EMPTY()))


# define action
@get('/index')
@post('/index')
@wrapper(view='templates/index.html', dbs=[db])
def index():
    vars = wrapper.extract_vars(request.forms)
    form = SQLFORM(db.person)
    if form.accepts(vars):
        message = 'hello %s' % form.vars.name
    else:
        message = 'hello anonymous'
    people = db(db.person).select()
    now = cache.ram('time', lambda: time.ctime(), 10)
    return locals()


# handle static files
@route('/static/<filename>')
コード例 #36
0
def checkAccess():
    global access
    if not access:
        redirect('/noaccess')
コード例 #37
0
def logout():
    global loggedIn, loc
    loggedIn = ''
    loc = ''
    redirect('/')
コード例 #38
0
def get_post_details(id):
    pid = getLoginId()
    if pid is not None:
        return serve_pages("post_details.html")
    else:
        redirect('/login')
コード例 #39
0
def get_exercises():
    pid = getLoginId()
    if pid is not None:
        return serve_pages("problem.html")
    else:
        redirect('/login')
コード例 #40
0
def login():
    redirect('/')
コード例 #41
0
def get_messages():
    pid = getLoginId()
    if pid is not None:
        return serve_pages("messages.html")
    else:
        return redirect('/login')
コード例 #42
0
def get_resources_download(id):
    pid = getLoginId()
    if pid is not None:
        return serve_pages("problem_details.html")
    else:
        redirect('/login')
コード例 #43
0
ファイル: picoreflowd.py プロジェクト: whatnick/picoReflow
def index():
    return bottle.redirect('/picoreflow/index.html')
コード例 #44
0
def get_personal_page():
    pid = getLoginId()
    if pid is not None:
        return serve_pages("user_details.html")
    else:
        redirect('/login')
コード例 #45
0
ファイル: server.py プロジェクト: badboy/homu
def rollup(user_gh, state, repo_label, repo_cfg, repo):
    user_repo = user_gh.repository(user_gh.user().login, repo.name)
    if user_repo is None:
        return 'You must have a fork of rust-lang/rust named rust under your user account.'  # noqa
    base_repo = user_gh.repository(repo.owner.login, repo.name)

    nums = state.get('nums', [])
    if nums:
        try:
            rollup_states = [g.states[repo_label][num] for num in nums]
        except KeyError as e:
            return 'Invalid PR number: {}'.format(e.args[0])
    else:
        rollup_states = [x for x in g.states[repo_label].values() if x.rollup]
    rollup_states = [x for x in rollup_states if x.approved_by]
    rollup_states.sort(key=lambda x: x.num)

    if not rollup_states:
        return 'No pull requests are marked as rollup'

    base_ref = rollup_states[0].base_ref

    base_sha = repo.ref('heads/' + base_ref).object.sha
    branch_name = 'rollup-' + ''.join(
        random.choice(string.digits + string.ascii_lowercase)
        for _ in range(7))
    utils.github_set_ref(
        user_repo,
        'heads/' + branch_name,
        base_sha,
        force=True,
    )

    successes = []
    failures = []

    for state in rollup_states:
        if base_ref != state.base_ref:
            failures.append(state.num)
            continue

        state.body = suppress_pings(state.body)
        state.body = suppress_ignore_block(state.body)

        merge_msg = 'Rollup merge of #{} - {}, r={}\n\n{}\n\n{}'.format(
            state.num,
            state.head_ref,
            state.approved_by,
            state.title,
            state.body,
        )

        try:
            user_repo.merge(branch_name, state.head_sha, merge_msg)
        except github3.models.GitHubError as e:
            if e.code != 409:
                raise

            failures.append(state)
        else:
            successes.append(state)

    title = 'Rollup of {} pull requests'.format(len(successes))

    body = 'Successful merges:\n\n'
    for x in successes:
        body += ' - #{} ({})\n'.format(x.num, x.title)
    body += '\nFailed merges:\n\n'
    for x in failures:
        body += ' - #{} ({})\n'.format(x.num, x.title)
    body += '\nr? @ghost\n@rustbot modify labels: rollup'

    # Set web.base_url in cfg to enable
    base_url = g.cfg['web'].get('base_url')
    if not base_url:
        # If web.base_url is not present, fall back to using web.canonical_url
        base_url = g.cfg['web'].get('canonical_url')

    if base_url:
        pr_list = ','.join(str(x.num) for x in successes)
        link = '{}/queue/{}?prs={}'.format(base_url, repo_label, pr_list)
        body += '\n'
        body += IGNORE_BLOCK_START
        body += '\n[Create a similar rollup]({})\n'.format(link)
        body += IGNORE_BLOCK_END

    try:
        pull = base_repo.create_pull(
            title,
            state.base_ref,
            user_repo.owner.login + ':' + branch_name,
            body,
        )
    except github3.models.GitHubError as e:
        return e.response.text
    else:
        redirect(pull.html_url)
コード例 #46
0
def get_admin():
    admin_cookie = request.get_cookie('atoken')
    if admin_cookie:
        return serve_pages("admin.html")
    else:
        redirect('/alogin')
コード例 #47
0
ファイル: app.py プロジェクト: ludel/ORQ2
def slash_redirection(*args):
    return redirect(request.url + '/')
コード例 #48
0
        error = excel_import(all_sqls, tmp_filename, db)
        os.remove(tmp_filename)  # 删除上传的临时文件
    else:  # 没有文件
        error = '数据格式错误[1]'

    if error:
        # 导入数据错误,进行数据恢复
        try:
            excel_import(all_sqls, os.path.join(tmp_root, BACK_FILE), db)
            print '数据恢复成功'
        except Exception, e:
            print '数据恢复错误: %s' % e
        return template('error', error=error + '    数据已恢复')
    else:
        redirect("/item")


@route("/item/export")
def item_export(db):
    tmp_root = './tmp/'
    filename = current_time("item_%Y%m%d%H%M.xls")  # 文件名
    error = ''

    if not isfile(tmp_root + filename):
        all_sqls = EXPORT_SQLS
        error = excel_export(all_sqls, tmp_root, filename, db)

    if error:
        return template('error', error=error)
    else:
コード例 #49
0
ファイル: server.py プロジェクト: zodman/anilist-torrents
def logout():
    if get_access_token():
        del request.session["access_token"]
        del request.session["refresh_token"]
        del request.session["expires"]
    redirect("/")
コード例 #50
0
ファイル: app.py プロジェクト: geonsik-yu/AnormalyDetection
def redirect_to_hello():
    redirect('/hello')
コード例 #51
0
def redirect_with_query(redirect_uri, params):
    """Return a Bottle redirect to the given target URI with query parameters
    encoded from the params dict.
    """
    return redirect(redirect_uri + '?' + urllib.parse.urlencode(params))
コード例 #52
0
ファイル: server.py プロジェクト: zodman/anilist-torrents
def impersonate(access_token, expires):
    request.session["access_token"] = access_token
    request.session["refresh_token"] = None
    request.session["expires"] = expires
    redirect("/")
コード例 #53
0
def show(show_id):
    sectionTemplate = "./templates/show.tpl"
    section_data = find_show(show_id)
    if(section_data == {}):
        redirect('/error')
    return template("./pages/index.html", version=getVersion(), sectionTemplate=sectionTemplate, sectionData=section_data)
コード例 #54
0
def account_open(db, render):
    form = forms.account_open_form()
    if not form.validates(source=request.forms):
        return render("card_open_form", form=form)
    if vcache.is_over(get_cookie("customer_id"), form.d.recharge_card):
        return render("card_open_form", form=form, msg=u"该充值卡一小时内密码输入错误超过5次,请一小时后再试")

    card = db.query(models.SlcRechargerCard).filter_by(card_number=form.d.recharge_card).first()
    check_result = check_card(card)
    if check_result['code'] > 0:
        return render('card_open_form', form=form, msg=check_result['data'])

    if utils.decrypt(card.card_passwd) != form.d.recharge_pwd:
        vcache.incr(get_cookie("customer_id"), form.d.recharge_card)
        errs = vcache.errs(get_cookie("customer_id"), form.d.recharge_card)
        return render('card_open_form', form=form, msg=u"充值卡密码错误%s次" % errs)

    vcache.clear(get_cookie("customer_id"), form.d.recharge_card)

    # start open
    accept_log = models.SlcRadAcceptLog()
    accept_log.accept_type = 'open'
    accept_log.accept_source = 'customer'
    accept_log.account_number = form.d.account_number
    accept_log.accept_time = utils.get_currtime()
    accept_log.operator_name = "customer"
    accept_log.accept_desc = u"用户自助开户:%s" % (form.d.account_number)
    db.add(accept_log)
    db.flush()
    db.refresh(accept_log)

    _datetime = utils.get_currtime()
    order_fee = 0
    balance = 0
    expire_date = utils.add_months(datetime.datetime.now(), card.months).strftime("%Y-%m-%d")
    product = db.query(models.SlcRadProduct).get(form.d.product_id)
    # 预付费包月
    if product.product_policy == PPMonth:
        order_fee = decimal.Decimal(product.fee_price) * decimal.Decimal(card.months)
        order_fee = int(order_fee.to_integral_value())
    # 买断包月,买断时长,买断流量
    elif product.product_policy in (BOMonth, BOTimes, BOFlows):
        order_fee = int(product.fee_price)
    # 预付费时长,预付费流量
    elif product.product_policy in (PPTimes, PPFlow):
        balance = card.fee_value
        expire_date = '3000-11-11'

    order = models.SlcMemberOrder()
    order.order_id = utils.gen_order_id()
    order.member_id = get_cookie("customer_id")
    order.product_id = product.id
    order.account_number = form.d.account_number
    order.order_fee = order_fee
    order.actual_fee = card.fee_value
    order.pay_status = 1
    order.accept_id = accept_log.id
    order.order_source = 'customer'
    order.create_time = _datetime
    order.order_desc = u"用户使用充值卡[ %s ]开户" % form.d.recharge_card
    db.add(order)

    account = models.SlcRadAccount()
    account.account_number = form.d.account_number
    account.ip_address = ''
    account.member_id = get_cookie("customer_id")
    account.product_id = order.product_id
    account.install_address = ''
    account.mac_addr = ''
    account.password = utils.encrypt(form.d.password)
    account.status = 1
    account.balance = balance
    account.time_length = int(product.fee_times)
    account.flow_length = int(product.fee_flows)
    account.expire_date = expire_date
    account.user_concur_number = product.concur_number
    account.bind_mac = product.bind_mac
    account.bind_vlan = product.bind_vlan
    account.vlan_id = 0
    account.vlan_id2 = 0
    account.create_time = _datetime
    account.update_time = _datetime
    db.add(account)

    clog = models.SlcRechargeLog()
    clog.member_id = get_cookie("customer_id")
    clog.card_number = card.card_number
    clog.account_number = form.d.account_number
    clog.recharge_status = 0
    clog.recharge_time = _datetime
    db.add(clog)

    card.card_status = CardUsed

    db.commit()
    redirect('/')
コード例 #55
0
def episode(show_id, ep_id):
    section_data = find_ep(show_id, ep_id)
    if(section_data == None):
        redirect('/error')
    sectionTemplate = "./templates/episode.tpl"
    return template("./pages/index.html", version=getVersion(), sectionTemplate=sectionTemplate, sectionData=section_data)
コード例 #56
0
def show_request(show_id):
    section_data = find_show(show_id)
    if(section_data == {}):
        redirect('/error')
    return template("./templates/show.tpl",  result=section_data)
コード例 #57
0
def get_source_redirect():
    """Download the source of this application."""
    redirect(ZIP_PATH)
コード例 #58
0
def episode_request(show_id, ep_id):
    section_data = find_ep(show_id, ep_id)
    if(section_data == None):
        redirect('/error')
    return template("./templates/episode.tpl",  result=section_data)
コード例 #59
0
def get_source_redirect():
    """Download the source of this application."""
    redirect("/static/index.html")
コード例 #60
0
ファイル: server.py プロジェクト: tesuji/homu
def rollup(user_gh, state, repo_label, repo_cfg, repo):
    user_repo = user_gh.repository(user_gh.user().login, repo.name)
    base_repo = user_gh.repository(repo.owner.login, repo.name)

    nums = state.get('nums', [])
    if nums:
        try:
            rollup_states = [g.states[repo_label][num] for num in nums]
        except KeyError as e:
            return 'Invalid PR number: {}'.format(e.args[0])
    else:
        rollup_states = [x for x in g.states[repo_label].values() if x.rollup]
    rollup_states = [x for x in rollup_states if x.approved_by]
    rollup_states.sort(key=lambda x: x.num)

    if not rollup_states:
        return 'No pull requests are marked as rollup'

    base_ref = rollup_states[0].base_ref

    base_sha = repo.ref('heads/' + base_ref).object.sha
    branch_name = 'rollup-' + ''.join(
        random.choice(string.digits + string.ascii_lowercase)
        for _ in range(7))
    utils.github_set_ref(
        user_repo,
        'heads/' + branch_name,
        base_sha,
        force=True,
    )

    successes = []
    failures = []

    for state in rollup_states:
        if base_ref != state.base_ref:
            failures.append(state.num)
            continue

        merge_msg = 'Rollup merge of #{} - {}, r={}\n\n{}\n\n{}'.format(
            state.num,
            state.head_ref,
            state.approved_by,
            state.title,
            state.body,
        )

        try:
            user_repo.merge(branch_name, state.head_sha, merge_msg)
        except github3.models.GitHubError as e:
            if e.code != 409:
                raise

            failures.append(state)
        else:
            successes.append(state)

    title = 'Rollup of {} pull requests'.format(len(successes))

    body = 'Successful merges:\n\n'
    for x in successes:
        body += ' - #{} ({})\n'.format(x.num, x.title)
    body += '\nFailed merges:\n\n'
    for x in failures:
        body += ' - #{} ({})\n'.format(x.num, x.title)
    body += '\nr? @ghost'

    try:
        pull = base_repo.create_pull(
            title,
            state.base_ref,
            user_repo.owner.login + ':' + branch_name,
            body,
        )
    except github3.models.GitHubError as e:
        return e.response.text
    else:
        redirect(pull.html_url)