Example #1
0
 def POST(self, pid, cid=0):
     if session.userid == -1:
         raise web.seeother('/')
     i = web.input()
     problemid = i.get("ProblemID", 0)
     language = i.get("SubmitLanguage", None)
     code = i.get("SubmitCode", None)
     contestid = i.get("ContestID", 0)
     try:
         contestid = int(contestid)
     except:
         contestid = 0
     lang = db.Member.GetLastLanguage(session.userid)
     if not language:
         return render.Submit(problemid, contestid, lang, 'Must select a language')
     if not code:
         return render.Submit(problemid, contestid, lang, 'Must submit some code')
     if not problemid or not db.Problem.Exist(int(problemid)):
         return render.Submit(problemid, contestid, lang, 'Problem Does Not Exist')
     if contestid != 0 and db.Contest.GetStatusByID(contestid) != 2:
         return render.Submit(problemid, contestid, lang, 'Contest is not LIVE')
     if db.Contest.IsProblemNotDone(problemid, int(contestid)):
         return render.Submit(problemid, contestid, lang, 'Problem Does Not Exist or Hidden')
     db.Status.Submit(problemid, contestid, session.userid, language, code)
     raise web.seeother('/status/')
Example #2
0
	def GET(self):
		if not base.logged():
			raise web.seeother('/')

		input = web.input()
		if not input.cid.isdigit():
			return base.code("<script language='javascript'>alert('参数错误 !');window.history.back(-1);</script>")
			
		if not input: raise web.seeother('/citylist') 
		if input.action == 'mc':
			if web.ctx.session.privilege == 0:
				return base.code("<script language='javascript'>alert('您没有足够的权限,拒绝访问 !');window.history.back(-1);</script>")
			city_info = models.getOneCity(input.cid)
			return render.modify_city(city_info[0])

		elif input.action == 'vc':
			city_info = models.getOneCity(input.cid)
			return render.view_city(city_info[0])
				
		elif input.action == 'dc':
			if web.ctx.session.privilege == 0:
				return base.code("<script language='javascript'>alert('您没有足够的权限,拒绝访问 !');window.history.back(-1);</script>")
			
			# Save to history
			c = models.getOneCity(input.cid)[0]
			content = "INSERT INTO city VALUE (%s, '%s', '%s')" % (c['cid'], c['city'], c['other'])
			description = u"<b>城市:</b>"+ c['city']
			delman = web.ctx.session.username
			deltime = int(time.time())
			models.addHistory(content,description,delman,deltime)

			models.delCity(input.cid)
			raise web.seeother('/citylist')
		else:
			return base.code("<script language='javascript'>alert('参数错误 !');window.history.back(-1);</script>")
Example #3
0
def login_hook(handler):
    path_info = web.ctx.env['PATH_INFO']
    if path_info != '/login' and not session.login:
        uri = web.ctx.env['REQUEST_URI']
        web.seeother('/login?return_url=' + web.urlquote(uri))
    else:
        return handler()
Example #4
0
    def POST(self, arg):
        if session.userid != -1:
            raise web.seeother('/')
        i = web.input()
        username = i.get('Username', None)
        password = i.get('Password', None)
        repassword = i.get('RePassword', None)
        email = i.get('Email', None)
        if not password or not repassword or not password == repassword:
            return render.Register("Passwords don't match")
        if not username or not vname.match(username):
            return render.Register('UserName must be between 4 to 50 characters')
        if not vpwd.match(password):
            return render.Register('Password must be more than 4 characters')
        if not email or not vemail.match(email):
            return render.Register('Invaild Email address')

        email = email.lower()
        userid = db.Member.Add(username, password, email)
        if userid:
            session.userid = userid
            session.username = username
            session.gravatar = db.Utility.MD5(email)
            raise web.seeother('/')
        else:
            return render.Register('['+username+'] or ['+email+'] exists')
Example #5
0
	def GET(self):
		if not base.logged():
			raise web.seeother('/')
		if web.ctx.session.privilege == 0:
			return base.code("<script language='javascript'>alert('您没有足够的权限,拒绝访问 !');window.history.back(-1);</script>")
		history = models.getHistory()		
		history = list(history)		
		for h in history:
			ltime = time.localtime(int(h['deltime']))
			deltime = time.strftime("%Y-%m-%d %H:%M:%S",ltime)
			h['deltime'] = deltime
		
		input = web.input(action=None,hid=None)

		if not input.action:	
			return render.history(history)
		else:
			# Remove history
			if input.action == 'dh':
				models.delOneHistory(input.hid)
				raise web.seeother('/history')
			# Resotre history
			elif input.action == 'rh':
			 	if models.restoreHistory(input.hid):
					models.delOneHistory(input.hid)
					return base.code("<script language='javascript'>alert('恢复成功 !');window.location.href='/history'; </script>")
				else:
					return base.code("<script language='javascript'>alert('恢复失败,此记录可能已存在,请检查!');window.history.back(-1);</script>")
				
			else:
				return base.code("<script language='javascript'>alert('参数错误 !');window.history.back(-1);</script>")
Example #6
0
 def POST(self):
     data = web.input()
     if white.check_validate(data):
         white.add(data)
         web.seeother('/white/view?ip=%s' % data.get('ip'))
     else:
         web.seeother('/white/home?ret=1&info=no validate')
Example #7
0
    def GET(self):
        global ftoken_db
        i = web.input(author_key=[], language=[], first_publish_year=[], publisher_facet=[], subject_facet=[], person_facet=[], place_facet=[], time_facet=[])
        if i.get('ftokens', None) and ',' not in i.ftokens:
            token = i.ftokens
            if ftoken_db is None:
                ftoken_db = dbm.open('/olsystem/ftokens', 'r')
            if ftoken_db.get(token, None):
                raise web.seeother('/subjects/' + ftoken_db[token].decode('utf-8').lower().replace(' ', '_'))

        self.redirect_if_needed(i)

        if 'isbn' in i and all(not v for k, v in i.items() if k != 'isbn'):
            self.isbn_redirect(i.isbn)

        q_list = []
        q = i.get('q', '').strip()
        if q:
            m = re_olid.match(q)
            if m:
                raise web.seeother('/%s/%s' % (olid_urls[m.group(1)], q))
            m = re_isbn_field.match(q)
            if m:
                self.isbn_redirect(m.group(1))
            q_list.append(q)
        for k in ('title', 'author', 'isbn', 'subject', 'place', 'person', 'publisher'):
            if k in i:
                q_list.append(k + ':' + i[k].replace(':', '\\:').strip())

        return render.work_search(i, ' '.join(q_list), do_search, get_doc)
Example #8
0
 def Result(self, url='') :
     if self.IsFail() :
         return self.GetRetMsg()
         #return config.render.ErrMsg(msg=self.GetRetMsg())
     else :
         #return config.render.Msg(msg=self.GetRetMsg(), url = url)
         web.seeother(url)
def auth_user(global_config, desired_path='/home'):
    auth = web.ctx.env.get('HTTP_AUTHORIZATION')
    authreq = False
    
    if auth is None:
        authreq = True
    else:
        auth = re.sub('^Basic ','',auth)
        username,password = base64.decodestring(auth).split(':')
        
        if logged_out_users.has_key(username):
            del logged_out_users[username]
        else:
            session = DbSession.open_db_session(global_config['users_db_name'] + global_config['this_season'])
            user = UsersDataModel.getUser(session, username)
            session.remove()
            if user:
                if user.state == 'Disabled':
                    raise web.seeother('/accountdisabled')
                #if (username,password) in allowed:
                if user.check_password(password) == True:
                    raise web.seeother(desired_path)
        authreq = True
    if authreq:
        web.header('WWW-Authenticate','Basic realm="FRC1073 ScoutingAppCentral"')
        web.ctx.status = '401 Unauthorized'
        return
Example #10
0
    def POST(self, work_id):
        user = accounts.get_current_user()
        i = web.input(edition_id=None, action="add", redir=False, bookshelf_id=None)
        key = i.edition_id if i.edition_id else ('/works/OL%sW' % work_id)

        if not user:
            raise web.seeother('/account/login?redirect=%s' % key)

        username = user.key.split('/')[2]
        current_status = models.Bookshelves.get_users_read_status_of_work(username, work_id)

        try:
            bookshelf_id = int(i.bookshelf_id)
            if bookshelf_id not in models.Bookshelves.PRESET_BOOKSHELVES.values():
                raise ValueError
        except ValueError:
            return delegate.RawText(simplejson.dumps({
                'error': 'Invalid bookshelf'
            }), content_type="application/json")

        if bookshelf_id == current_status:
            work_bookshelf = models.Bookshelves.remove(
                username=username, work_id=work_id, bookshelf_id=i.bookshelf_id)

        else:
            edition_id = int(i.edition_id.split('/')[2][2:-1]) if i.edition_id else None
            work_bookshelf = models.Bookshelves.add(
                username=username, bookshelf_id=bookshelf_id,
                work_id=work_id, edition_id=edition_id)

        if i.redir:
            raise web.seeother(key)
        return delegate.RawText(simplejson.dumps({
            'bookshelves_affected': work_bookshelf
        }), content_type="application/json")
Example #11
0
    def POST(self):
        web.header('Content-Type', 'text/html')
        f = login_form()
        if not f.validates():
            raise web.seeother('/')

        authOptions = [am for am in web.config.auth.methods if am.can_handle_user(f.d.username)]
        if len(authOptions) == 0:
            raise web.internalerror("No appropriate login method available")

        for ao in authOptions:
            try:
                success, res = ao.login(f.d.username, f.d.password, web.config)
                if success == True:
                    web.config.session.loggedin = True
                    web.config.session.userid = res['userid']
                    web.config.session.userfullname = res['userfullname']
                    web.config.session.userrights = res['rights']
                    raise web.seeother("/")
            except RequireRegistrationException, info:
                web.config.session.showIdentifierRegistration = True
                web.config.session.userid = info.username
                web.config.session.userfullname = info.userfullname
                web.config.session.userrights = "none"
                raise web.seeother('/register')
Example #12
0
	def GET(self):
		data = web.input()
		contype = data['type']
		content = data['content']
		if contype=="tvshow":
			tvopen = open(tvfile,"a")
			tvread = tvopen.write(content+"\n")
			tvopen.close()
			tvShowSearchWeb()
			raise web.seeother('/')
		elif contype=="movie":
			movieopen = open(moviefile,"a")
			movieread = movieopen.write(content+"\n")
			movieopen.close()
			movieSearchWeb()
			raise web.seeother('/')
		elif contype=="music":
			musicopen = open(musicfile,"a")
			musicread = musicopen.write(content+"\n")
			musicopen.close()
			musicSearchWeb()
			raise web.seeother('/')
		elif contype=="picture":
			pictureopen = open(picturefile,"a")
			pictureread = pictureopen.write(content+"\n")
			pictureopen.close()
			photoSearchWeb()
			raise web.seeother('/')
Example #13
0
File: do.py Project: vixiaoan/Jask
	def GET(self):
		userid = web.ctx.session.userid
		if userid:
			raise web.seeother('/show')
			
		else:
			raise web.seeother('/login')
Example #14
0
  def POST( self, get_string='' ):
    log.loggit( 'delete.POST()' )

    # Catch the cancel button
    if  web.input().has_key('cancel'):
      raise web.seeother('../')

    # Validate the form
    f = delete_confirmation_form()
    if not f.validates():
      return { 'status' : 'error',
               'message' : 'Verify all information has been provided correctly.',
               'form' : f }

    if f.d['username'] == 'admin':
      return { 'status' : 'error',
               'message' : 'You cannot delete the administration account.' }

    # update the account in the database
    adb = accountdb.AccountDB();
    try:
      row = adb.delete_account( f.d['username'] )
    except:
      return { 'status' : 'error',
               'message' : 'An error occurred deleting the account.' }

    raise web.seeother('../')
Example #15
0
  def POST( self, get_string='' ):
    log.loggit( 'update.POST()' )

    # Must be a matching user or administrator to update
    wputil.must_match_username_or_admin( web.input()['username'] )

    # Catch the cancel button
    if  web.input().has_key('cancel'):
      if wputil.is_admin():
        raise web.seeother('../')
      else:
        raise web.seeother('../../')

    # Validate the form
    if wputil.is_admin():
      f = admin_account_form()
    else:
      f = account_form()
    if not f.validates():
      return { 'status' : 'error',
               'message' : 'Verify all information has been provided correctly.',
               'form' : f }

    # update the account in the database
    adb = accountdb.AccountDB()
    try:
      account = adb.update_account( f.d )
    except:
      return { 'status' : 'error',
               'message' : 'An error occurred updating the account.',
               'form' : f }

    raise web.seeother( '../review/%s' % (account['username']) )
Example #16
0
 def GET(self):
     prevUrl = memcache.get(MEMC_ADV_ID)
     if prevUrl in (AdvShare.__url__, AdvUrlFilter.__url__, AdvWhiteList.__url__, AdvImport.__url__):
         raise web.seeother(prevUrl)
     else:
         memcache.set(MEMC_ADV_ID, AdvWhiteList.__url__, 86400)
         raise web.seeother(AdvWhiteList.__url__)
Example #17
0
    def profile(self, domain, mail, accountType='user'):
        self.mail = web.safestr(mail)
        self.domain = self.mail.split('@', 1)[-1]

        if self.domain != domain:
            return web.seeother('/domains?msg=PERMISSION_DENIED')

        self.filter = '(&(objectClass=mailUser)(mail=%s))' % (self.mail,)
        if accountType == 'catchall':
            self.filter = '(&(objectClass=mailUser)(mail=@%s))' % (self.mail,)
        else:
            if not self.mail.endswith('@' + self.domain):
                return web.seeother('/domains?msg=PERMISSION_DENIED')

        if attrs.RDN_USER == 'mail':
            self.searchdn = ldaputils.convKeywordToDN(self.mail, accountType=accountType)
            self.scope = ldap.SCOPE_BASE
        else:
            self.searchdn = attrs.DN_BETWEEN_USER_AND_DOMAIN + ldaputils.convKeywordToDN(self.domain, accountType='domain')
            self.scope = ldap.SCOPE_SUBTREE

        try:
            self.user_profile = self.conn.search_s(
                self.searchdn,
                self.scope,
                self.filter,
                attrs.USER_ATTRS_ALL,
            )
            return (True, self.user_profile)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Example #18
0
	def GET(self):
		tips = "请输入邮箱地址和密码。"

		if session.login == 1:#是否登录
			web.seeother(r'/')
		else:
			return jjenv.get_template("login.html").render(nickname='',title='Login',tips=tips)
Example #19
0
 def POST(self):
     import opml
     x = web.input(importfile={})
     memcache.set(MEMC_ADV_ID, self.__url__, 86400)
     if 'importfile' in x:
         user = self.getcurrentuser()
         try:
             rsslist = opml.from_string(x.importfile.file.read())
         except Exception as e:
             return self.GET(str(e))
         
         for o in self.walkOutline(rsslist):
             title, url, isfulltext = o.text, urllib.unquote_plus(o.xmlUrl), o.isFulltext #isFulltext为非标准属性
             isfulltext = bool(isfulltext.lower() in ('true', '1'))
             if title and url:
                 rss = Feed.all().filter('book = ', user.ownfeeds).filter("url = ", url).get() #查询是否有重复的
                 if rss:
                     rss.title = title
                     rss.isfulltext = isfulltext
                     rss.put()
                 else:
                     Feed(title=title,url=url,book=user.ownfeeds,isfulltext=isfulltext,
                         time=datetime.datetime.utcnow()).put()
                         
         memcache.delete('%d.feedscount'%user.ownfeeds.key().id())
         raise web.seeother('/my')
     else:
         raise web.seeother('')
Example #20
0
File: mgr.py Project: yegle/cves
 def POST(self, chid):
     userid = web.config.db.select(
         'channels', what='user', where='id = $ch',
         vars={'ch': int(chid)})[0]['user']
     web.config.db.delete(
         'readed', where='channel = $ch', vars={'ch': int(chid)})
     web.seeother('/user/%d' % userid)
Example #21
0
File: ospi.py Project: cwalv/OSPi
 def GET(self):
     qdict = web.input()
     approve_pwd(qdict)
     if qdict.has_key('rsn') and qdict['rsn'] == '1':
         stop_stations()    
         raise web.seeother('/')
         return
     if qdict.has_key('en') and qdict['en'] == '':
         qdict['en'] = '1' #default
     elif qdict.has_key('en') and qdict['en'] == '0':
         gv.srvals = [0]*(gv.sd['nst']) # turn off all stations
         set_output()
     if qdict.has_key('mm') and qdict['mm'] == '0': clear_mm()
     if qdict.has_key('rd') and qdict['rd'] != '0' and qdict['rd'] != '':
         gv.sd['rdst'] = (gv.now+(int(qdict['rd'])*3600))
         stop_onrain()
     elif qdict.has_key('rd') and qdict['rd'] == '0': gv.sd['rdst'] = 0   
     if qdict.has_key('rbt') and qdict['rbt'] == '1':
         jsave(gv.sd, 'sd')
         gv.srvals = [0]*(gv.sd['nst'])
         set_output()
         os.system('reboot')
         raise web.seeother('/')
     for key in qdict.keys():
         try:
             gv.sd[key] = int(qdict[key])
         except:
             pass
     jsave(gv.sd, 'sd')
     raise web.seeother('/')# Send browser back to home page
     return
Example #22
0
 def GET(self):
     # 第一次登陆时如果没有管理员帐号,
     # 则增加一个管理员帐号admin,密码admin,后续可以修改密码
     tips = ''
     u = KeUser.all().filter("name = ", 'admin').get()
     if not u:
         myfeeds = Book(title=MY_FEEDS_TITLE,description=MY_FEEDS_DESC,
                 builtin=False,keep_image=True)
         myfeeds.put()
         au = KeUser(name='admin',passwd=hashlib.md5('admin').hexdigest())
         au.kindle_email = ''
         au.enable_send = False
         au.send_time = 8
         au.timezone = TIMEZONE
         au.book_type = "mobi"
         au.expires = None
         au.ownfeeds = myfeeds
         au.put()
         tips = u"初次登陆请使用用户名'admin'/密码'admin'登陆。 "
     else:
         tips = u"请输入正确的用户名和密码登陆进入系统。 "
     
     if session.login == 1:
         web.seeother(r'/')
     else:
         return jjenv.get_template("login.html").render(nickname='',title='Login',tips=tips)
Example #23
0
	def POST(self):
		form = web.input(action=None)
		
		if form.action and session.room:
			if '*' in session.room.paths:
				if form.action != session.room.num and form.action not in self.commands:
					session.room.guess -= 1
					session.room.output = "..." % session.room.guess
					if session.room.guess == 0:
						session.room = session.room.go('*')
				elif form.action == session.room.num:
					session.room = session.room.go('x')
			else:
				transition = session.room.go(form.action)
				if transition == None:
					session.room.output = "You cannot do that."
				elif transition != None:
					session.room = transition
				else:
					session.room.output = "Please enter a command."
					
		if form.action in self.commands:
			self.commands[form.action]()
			
		web.seeother('/game')
Example #24
0
    def GET(self):
        # 第一次登陆时如果没有管理员帐号,
        # 则增加一个管理员帐号admin,密码admin,后续可以修改密码
        tips = ""
        u = KeUser.all().filter("name = ", "admin").get()
        if not u:
            myfeeds = Book(title=MY_FEEDS_TITLE, description=MY_FEEDS_DESC, builtin=False, keep_image=True)
            myfeeds.put()
            au = KeUser(
                name="admin",
                passwd=hashlib.md5("admin").hexdigest(),
                kindle_email="",
                enable_send=False,
                send_time=8,
                timezone=TIMEZONE,
                book_type="mobi",
                expires=None,
                ownfeeds=myfeeds,
                oldest_article=7,
            )
            au.put()
            tips = _("Please use admin/admin to login at first time.")
        else:
            tips = _("Please input username and password.")

        if session.login == 1:
            web.seeother(r"/")
        else:
            return self.render("login.html", "Login", tips=tips)
Example #25
0
    def POST(self, _n=None):
        self.login_required()
        name = web.input().get("u")
        if name and (session.username == "admin" or session.username == name):
            u = KeUser.all().filter("name = ", name).get()
            if not u:
                tips = _("The username '%s' not exist!") % name
            else:
                if u.ownfeeds:
                    u.ownfeeds.delete()
                u.delete()

                # 要删掉数据库中订阅记录
                for book in Book.all():
                    if book.users and name in book.users:
                        book.users.remove(name)
                        book.put()

                if session.username == name:
                    raise web.seeother("/logout")
                else:
                    raise web.seeother("/admin")
        else:
            tips = _("The username is empty or you dont have right to delete it!")
        return self.render("delaccount.html", "Delete account", tips=tips, username=name)
Example #26
0
    def _store(self, uri, i):
        """
        Store a record
        """
        status = required(i, 'status')
        if status is None:
            return False

        if not self.validstatus.match(status):
            return self._badrequest("Bad value for status: '%s'" % status)

        tags = unpack_tags(getattr(i, 'tags', []))
        pairs = unpack_pairs(getattr(i, 'pairs', {}))
        location = getattr(i, 'location', None)
        known = get_known()
        unknown = get_unknown()

        try:
            u = get_manager().register(
                uri,
                int(status),
                tags = tags,
                pairs = pairs,
                location = location
                )

            known[u.id] = u
            if u.id in unknown:
                del unknown[u.id]

            web.seeother("%s/%s" % (web.ctx.home, u.id))
            return

        except URIError, e:
            return self._badrequest(e)
Example #27
0
 def POST(self):
     try:
         args = web.input(xlsfile={}) 
     except ValueError:
         return "File too large. Maximum file size is 50MB"
         
     if 'xlsfile' not in args:
         web.seeother('/')
     
     #Cleanup the file path  
     filepath = args.xlsfile.filename.replace('\\','/')
     filename = filepath.split('/')[-1]
     
     if not filename.lower().endswith('xls'):
         raise web.seeother('/?e=Only xls files are accepted')
     
     #Generate a unique folder to store the uploaded file in    
     ID = str(int(random.random()*1000000000000))
     os.mkdir(upload_dir+ID)  
     
     #Store the uploaded xls 
     fout = open(upload_dir+ID+'/'+filename,'w') 
     fout.write(args.xlsfile.file.read())
     fout.close()
     
     #Remove any expired uploads
     self.cleanup_files(upload_dir)
     
     #Convert the file. Report any errors, or offer the id of the
     #folder to download from
     try:
         download_ID = convert.convert(upload_dir +'/'+ID+'/'+filename)
     except:
         raise web.seeother('/?e='+ str(sys.exc_info()[1]))
     raise web.seeother('/?id=' + download_ID)
Example #28
0
    def POST(self):
        form = login_form()
        if not form.validates():
            return render.login(form=form)
        data = web.input()
        errcode, user = authenticate(data.username, data.password)
        req = web.ctx.req
        if errcode != ERR_OK:
            if errcode == ERR_USER_NOTEXISTS:
                req.err(u'用户未注册')
            elif errcode == ERR_PASSWORD_NOTCORRECT:
                req.err(u'密码错误')

            if 'redirect_to' in data:
                redirect_url = data.redirect_to
            req.update({
                'form': form,
                'redirect_url': redirect_url,
                })
            return render.login(**req)
        auth_login(user)
        redirect_url = data.redirect_to
        if redirect_url:
            raise web.seeother(redirect_url)
        else:
            raise web.seeother('/', True)
Example #29
0
 def GET(self):
     qdict = web.input()
     approve_pwd(qdict)
     if qdict.has_key("rsn") and qdict["rsn"] == "1":
         stop_stations()
         raise web.seeother("/")
         return
     if qdict.has_key("en") and qdict["en"] == "":
         qdict["en"] = "1"  # default
     elif qdict.has_key("en") and qdict["en"] == "0":
         gv.srvals = [0] * (gv.sd["nst"])  # turn off all stations
         set_output()
     if qdict.has_key("mm") and qdict["mm"] == "0":
         clear_mm()
     if qdict.has_key("rd") and qdict["rd"] != "0" and qdict["rd"] != "":
         gv.sd["rdst"] = gv.now + (int(qdict["rd"]) * 3600)
         stop_onrain()
     elif qdict.has_key("rd") and qdict["rd"] == "0":
         gv.sd["rdst"] = 0
     if qdict.has_key("rbt") and qdict["rbt"] == "1":
         jsave(gv.sd, "sd")
         gv.srvals = [0] * (gv.sd["nst"])
         set_output()
         os.system("reboot")
         raise web.seeother("/")
     for key in qdict.keys():
         try:
             gv.sd[key] = int(qdict[key])
         except:
             pass
     jsave(gv.sd, "sd")
     raise web.seeother("/")  # Send browser back to home page
     return
Example #30
0
def results_post(session):
    form = web.input().group
    if form is not None:
        session.studid = form
        raise web.seeother('/studedit/' + session.studid)
        #raise web.seeother('/cart')
    raise web.seeother('/search')
Example #31
0
 def POST_AUTH(self, *args, **kwargs):
     raise web.seeother("/mycourses")
Example #32
0
 def POST(self):
     table=alltable['project']
     form=web.input()
     model.new_item(table,form)
     raise web.seeother('/index_project')
Example #33
0
 def POST(self, id):
     model.del_post(int(id))
     raise web.seeother('/')
Example #34
0
 def POST(self):
     form = self.form()
     if not form.validates():
         return render.new(form)
     model.new_post(form.d.title, form.d.content)
     raise web.seeother('/')
Example #35
0
	def POST(self):
        return web.seeother('/upload')
Example #36
0
    def POST(self):
        plugin_options.web_update(web.input())  ### update options from web ###

        if sender is not None:
            sender.update()
        raise web.seeother(plugin_url(settings_page), True)
Example #37
0
 def POST_AUTH(self, *args, **kwargs):
     self.user_manager.disconnect_user()
     raise web.seeother("/courselist")
Example #38
0
 def work_edition_match(self, edition):
     raise web.seeother(edition.url("/edit?mode=found"))
Example #39
0
 def GET(self):
     if notLogdeIn():
         raise web.seeother('/login')
     else:
         return render.settings()
Example #40
0
 def GET(self):
     return web.seeother('/static/pierre.png')
Example #41
0
 def GET(self):
     if session.get('loggedin', False) == True:
         return render_template('profile.html', username = session.get('username', None))
     return web.seeother('/500')
Example #42
0
 def POST(self):
     text = web.input()
     print(text)
     raise web.seeother('/')
Example #43
0
    def GET(self):
        vid = ''
        width = ''
        height = ''
        br = ''
        sid = ''
        path = ''
        orig_file = ''

        request_file = web.ctx.path
        #print request_file
        r_cache.incr(request_file)

        cnt = request_file.count('_')

        value = r_cache.incr('overall_request_number')
        print "total requests:", value

        if cnt == 4:
            [vid, width, height, br, sid,
             orig_file] = get_trans_params(request_file)
            path = '/home/guanyu/Public/me/static/' + vid + request_file

            if os.path.exists(path):
                raise web.seeother('/static/' + vid + request_file)
            else:
                orig_file = '/home/guanyu/Public/me/static/' + vid + '/' + orig_file
                print 'requested file:' + request_file
                print 'original file:' + orig_file
                print 'segment id:' + sid
                print 'width:' + width
                print 'height:' + height
                print 'bitrate:' + br

                value = r_cache.get("trans_queue")
                value = int(value)
                print 'current transcoding size', value

                if value >= 2:
                    print 'offloading'
                    self.offloading(orig_file, width, height, br, path)
                else:
                    print 'online transcoding'
                    r_cache.incr("trans_queue")
                    cmd = "ffmpeg -i " + orig_file + " -s " \
                            + width + "x" + height + " " + path
                    os.system(cmd)
                    r_cache.decr("trans_queue")

                r_cache.incr('overall_transcoding_number')
                t = time.time()
                r_cache.sadd('transcoding_times', t)
                raise web.seeother('/static/' + vid + request_file)

        #the original bitrate file
        elif cnt == 1:
            vid = request_file.split('_')[0]
            path = '/home/guanyu/Public/me/static' + vid + request_file
            if os.path.exists(path):
                raise web.seeother('/static' + vid + request_file)
            else:
                raise web.notfound()
        else:
            raise web.notfound()
Example #44
0
 def GET(self):
     if notLogdeIn():
         raise web.seeother('/login')
     else:
         return db.getSensorsDataJSON()
Example #45
0
 def mGET(self):
     web.seeother("/")
Example #46
0
 def GET(self):
     raise web.seeother('/findauction')
Example #47
0
 def GET(self):
     raise web.seeother('/static/map.html?presentationMode=1')
Example #48
0
 def GET(self):
     raise web.seeother('/')
Example #49
0
 def GET(self):
     session.kill()
     raise web.seeother('/')
Example #50
0
 def mPOST(self):
     self.session.kill()
     web.seeother("/")
Example #51
0
 def POST(self):
     i = web.input()
     raise web.seeother('/')
Example #52
0
def start():
    global __server
    global session

    ##############################
    #### web.py setup         ####
    ##############################
    web.config.debug = False  # Improves page load speed', ]

    #### SSL for https #### http://www.8bitavenue.com/2015/05/webpy-ssl-support/
    ssl_patch = '././ssl/'
    if options.use_ssl:
        try:
            if os.path.isfile(ssl_patch +
                              'server.crt') and os.path.isfile(ssl_patch +
                                                               'server.key'):
                print 'SSL certificate OK starting HTTPS.'
                from web.wsgiserver import CherryPyWSGIServer
                CherryPyWSGIServer.ssl_certificate = "././ssl/server.crt"
                CherryPyWSGIServer.ssl_private_key = "././ssl/server.key"

        except:
            print 'SSL certificate not found.'
            pass
    #############################

    from ospy.urls import urls
    app = web.application(urls, globals())
    app.notfound = lambda: web.seeother('/', True)

    wsgifunc = app.wsgifunc()
    wsgifunc = web.httpserver.StaticMiddleware(wsgifunc)
    wsgifunc = PluginStaticMiddleware(wsgifunc)
    wsgifunc = DebugLogMiddleware(wsgifunc)
    wsgifunc = reverse_proxied(wsgifunc)

    __server = web.httpserver.WSGIServer(("0.0.0.0", options.web_port),
                                         wsgifunc)
    __server.timeout = 1  # Speed-up restarting

    sessions = shelve.open(os.path.join('ospy', 'data', 'sessions.db'))
    session = web.session.Session(app,
                                  web.session.ShelfStore(sessions),
                                  initializer={
                                      'validated': False,
                                      'pages': []
                                  })

    import atexit
    atexit.register(sessions.close)

    def exit_msg():
        print 'OSPy is closing, saving sessions.'

    atexit.register(exit_msg)

    scheduler.start()
    plugins.start_enabled_plugins()

    try:
        __server.start()
    except (KeyboardInterrupt, SystemExit):
        stop()
Example #53
0
 def GET(self):
     with io.open(u"./data/log.json", u"w") as f:
         f.write(u"")
     raise web.seeother(u"/vl")
Example #54
0
 def POST(self):
     form = self.form()
     if not form.validates():
         return render.post(form)
     raise web.seeother('/')
Example #55
0
    def GET(self):
        qdict = web.input()
        if u"opw" in qdict and qdict[u"opw"] != u"":
            try:
                if password_hash(qdict[u"opw"]) == gv.sd[u"passphrase"]:
                    if qdict[u"npw"] == u"":
                        raise web.seeother(u"/vo?errorCode=pw_blank")
                    elif qdict[u"cpw"] != u"" and qdict[u"cpw"] == qdict[
                            u"npw"]:
                        gv.sd[
                            u"passphrase"] = password_hash(  #  Set new passphrase.
                                qdict[u"npw"])
                    else:
                        raise web.seeother(u"/vo?errorCode=pw_mismatch")
                else:
                    raise web.seeother(u"/vo?errorCode=pw_wrong")
            except KeyError:
                pass

        for f in [u"name"]:
            if u"o" + f in qdict:
                gv.sd[f] = qdict[u"o" + f]

        for f in [u"loc", u"lang"]:
            if u"o" + f in qdict:
                if f not in gv.sd or gv.sd[f] != qdict[u"o" + f]:
                    qdict[u"rstrt"] = u"1"  # force restart with change
                gv.sd[f] = qdict[u"o" + f]

        if u"onbrd" in qdict:
            if int(qdict[u"onbrd"]) + 1 != gv.sd[u"nbrd"]:
                self.update_scount(qdict)
            gv.sd[u"nbrd"] = int(qdict[u"onbrd"]) + 1
            gv.sd[u"nst"] = gv.sd[u"nbrd"] * 8
            self.update_prog_lists(u"nbrd")

        if u"ohtp" in qdict:
            if u"htp" not in gv.sd or gv.sd[u"htp"] != int(qdict[u"ohtp"]):
                qdict[u"rstrt"] = u"1"  # force restart with change in htp
            gv.sd[u"htp"] = int(qdict[u"ohtp"])

        if u"oidd" in qdict:
            idd_int = 1
        else:
            idd_int = 0
        if idd_int != gv.sd[u"idd"]:
            gv.sd[u"idd"] = idd_int
            self.update_prog_lists(u"idd")

        if u"ohtip" in qdict:
            if u"htip" not in gv.sd or gv.sd[u"htip"] != qdict[u"ohtip"]:
                qdict[u"rstrt"] = u"1"  # force restart with change in htip
            gv.sd[u"htip"] = qdict[u"ohtip"]

        for f in [u"sdt", u"mas", u"mton", u"mtoff", u"wl", u"lr", u"tz"]:
            if u"o" + f in qdict:
                if (f == u"mton" and int(qdict[u"o" + f]) <
                        0):  # handle values less than zero (temp fix)
                    raise web.seeother(u"/vo?errorCode=mton_minus")
                gv.sd[f] = int(qdict[u"o" + f])

        for f in [
                u"upas",
                u"tf",
                u"urs",
                u"seq",
                u"rst",
                u"lg",
                u"pigpio",
                u"alr",
        ]:
            if u"o" + f in qdict and (qdict[u"o" + f] == u"on"
                                      or qdict[u"o" + f] == u"1"):
                gv.sd[f] = 1
            else:
                gv.sd[f] = 0

        jsave(gv.sd, u"sd")
        report_option_change()
        if u"rbt" in qdict and qdict[u"rbt"] == u"1":
            gv.srvals = [0] * (gv.sd[u"nst"])
            set_output()
            report_rebooted()
            reboot()

        if u"rstrt" in qdict and qdict[u"rstrt"] == u"1":
            restart(2)
            raise web.seeother(u"/restart")
        raise web.seeother(u"/")
Example #56
0
 def POST(self):
     db.update('actions', where="1 = 1", Torun=0, status=None)
     raise web.seeother('/reset')
Example #57
0
 def GET(self):
     olid = lending.get_random_available_ia_edition()
     if olid:
         raise web.seeother('/books/%s' % olid)
     raise web.seeother("/")
Example #58
0
 def GET(self):
     qdict = web.input()
     gv.pd[int(qdict[u"pid"])][u"enabled"] = int(qdict[u"enable"])
     jsave(gv.pd, u"programData")
     report_program_toggle()
     raise web.seeother(u"/vp")
Example #59
0
 def GET(self):
     return web.seeother('/')
Example #60
0
 def GET(self):
     web.config._session.user = u"anonymous"
     web.session.Session.kill(web.config._session)
     raise web.seeother(u"/")