def POST(self): """ post the piece """ super(new,self).GET() from model import piece from urlparse import urlparse post = web.input(_method="post",share=[]) if self.cur_user: # get cur_user cur_user = self.cur_user # set user_id user_id = cur_user["id"] # set link if "link" in post: link = post["link"] url_parsed = urlparse(link) if not url_parsed.netloc: #相当于host link = None else: link = None # set private private = "private" in post # set content content = post["content"] if content.strip() == "": error = "内容不能为空" return render.new(error) if "pics" in post: pics = post["pics"] else: pics = None # insert piece_id = piece.add(user_id=user_id,content=content,link=link,private=private,pics=pics) # share if not private: share = post["share"] content = sliceContent(content) share_content = u"「" + content + u"」" + " http://" + web.ctx.host + "/piece/" + str(piece_id) if "weibo" in share: client = oauth.createClientWithName("weibo",cur_user) client.post(share_content) if "douban" in share: client = oauth.createClientWithName("douban",cur_user) client.post(share_content) # redirect web.redirect("/people/"+str(user_id)) else: return render.new()
def GET(self): """ write new piece """ super(new,self).GET() if not self.cur_user: web.redirect("/login") else: return render.new()
def POST(self, req_path): req_path = cgi.escape(req_path) inputs = web.input() action = inputs.get("action") if (not action) or (action not in ("update", "rename")): raise web.BadRequest() new_content = inputs.get("content") new_content = web.utils.safestr(new_content) if action == "update": if (req_path in consts.g_special_paths) or (req_path in consts.g_redirect_paths) or req_path.endswith("/"): raise web.BadRequest() return page.wp_update_post(config_agent=config_agent, req_path=req_path, new_content=new_content) elif action == "rename": new_path = inputs.get("new_path") if (req_path in consts.g_special_paths) or (req_path in consts.g_redirect_paths) or (not new_path): raise web.BadRequest() return page.wp_rename_post( config_agent=config_agent, tpl_render=tpl_render, req_path=req_path, new_path=new_path ) url = os.path.join("/", req_path) web.redirect(url) return
def show(self, input, error): if not session.loggedin: web.redirect("/login?out=1") else: channels = db.select('channels', what="id,name", where="active=true", vars=locals()) grps = db.select('users_grp', what="id,name", where="active=true", vars=locals()) return render.main(u'Add user', render.adduser(input, error, channels, grps),session)
def POST(self): user=web.input().user passwd=md5str(web.input().passwd) if cmp(web.session.Session.yzm.upper(),web.input().yzm.upper()): f='Wrong! auth code is wrong!' color='red' return render.login(f,color,imgs=authidentcode(),b=web.session.Session.yzm) else: pass if checkpass(user,passwd): web.session.Session.user=user web.session.Session.uuid=md5str(user+config.mi_key) session_add('client_ip','0.0.0.0') session_add('user_info','') web.session.Session.user_info=user_persion_info(web.session.Session.user).list()[0] web.session.Session.client_ip=web.ctx.env.get('REMOTE_ADDR') n_time=str(nowtime()) login_logs(user,n_time,web.session.Session.client_ip) session_add('login_time','') web.session.Session.login_time=n_time web.redirect('/admin/manager/') else: f='Fail,username or passwd wrong!' color='red' return render.login(f,color,imgs=authidentcode(),b=web.session.Session.yzm)
def POST(self): ''' 接收指令 :return: ''' input = web.input(delay=None) delay = input.delay if not delay: return 'failed' delay = int(delay) if delay > 0: username = Common.getLoginUsername() # 获得登录用户名 if not username: # 不存在则返回重定向 return web.redirect('/404') r, data = ApiManager.getDeviceInfo(username) # 获取设备信息 if r == 'fail': # 获取设备信息失败 if data == errors.NOT_BIND: # 如果未绑定 则进入绑定页 url = '/bind?username='******'/404') else: # 成功获取信息 if delay > 15: ApiManager.sendOrder(data['id'], orders.REFRESH_RATE_REST) # 发送S_X指令'F_' + str(delay) else: ApiManager.sendOrder(data['id'], orders.REFRESH_RATE_HIGH) # 发送S_X指令'F_' + str(delay) return 'success' return 'fail'
def POST(self): frm = new_feed_form() if not frm.validates(): return render.newfeed(frm) selectors = frm['selector'].value.splitlines() selectors = [s.strip() for s in selectors] selectors = filter(None, selectors) feed = model.find_feed(frm['url'].value, selectors) if feed: return web.redirect('/%s' % feed['id']) res = htmlproc.get_prepared_html(frm['url'].value, selectors) if 'error' in res: frm.note = res['error'] return render.newfeed(frm) # TODO: limit document size url = res['url'] feed = model.find_feed(url, selectors) if feed: return web.redirect('/%s' % feed['id']) frm['url'].value = url feed_name = res['title'] or url if 'do_preview' in web.input(): return render.newfeed(frm, page_preview=res['txt'], feed_name=feed_name) else: title = res['title'] feedid = model.create_feed(url=url, name=feed_name, selectors=selectors, favicon=utils.get_favicon(url), update_interval=DEFAULT_UPDATE_INTERVAL, content=res['txt']) return web.redirect('/%s' % feedid)
def POST(self): if (session.loggedIn == False): web.redirect(serverConfig.baseURI + "admin") form = web.input() sequenceID = webDB.insert("posts", title=form['title'], content=form['content'], datetime=time.time(), username=session.username) return renderAdmin.adminPost(session, True)
def POST(self): if not session.loggedin: web.redirect("/login?out=1") else: user = web.input() try: mac_addr = user.mac if hwaddrp(mac_addr) is False: mac_addr = '00:00:00:00:00:00' if not ipaddrp(user.get('ip','')): raise ValueError db.update('users', where='id=$user.id', realname=user.realname, groups=int(user.grps), ip=user.ip, mac=user.mac, limit_sites=user.limitsites, channel=int(user.channel), bw_up=int(user.bw_up), bw_down=int(user.bw_down), vars=locals() ) config_dhcp() web.redirect("/") except ValueError: return self.show(user, True)
def POST(self, node_type): page = self.page form = _form_node(node_type, page.user.roles.keys()) # checks if this node_type exists too checkaccess(page.user, ''.join(('create ',node_type,' content'))) if form.validates(): node = form.d node.time_now = int(time.time()) node.uid = page.user.uid # Get publishing settings. options = mod[node_type].defaults # Insert main entry in 'node' table node.nid = web.insert('node',uid=page.user.uid,created=node.time_now, changed=node.time_now, title=node.title, type=node_type, **options) # Do module specific insertions. if hasattr(mod[node_type], 'node_insert'): mod[node_type].node_insert(node) web.redirect('/node/'+str(node.nid)) content = '<form method="post" name="new_node">' content += form.render() content += '<input type="submit" /></form>' web.render('generic.html')
def GET(self): if web.input().get('out', '0') == '1': session.kill() if not session.loggedin: return render.main(u'Logging in', render.login(), session) else: web.redirect('/')
def POST(self): if not session.loggedin: web.redirect("/login?out=1") else: user = web.input() try: if not ipaddrp(user.ipaddr): raise ValueError user_ip = user.get('ipaddr') user_mac = user.get('hwaddr') if hwaddrp(user_mac) is False: user_mac = '00:00:00:00:00:00' qq = db.select('users', what='COUNT(id) AS num', where='ip=$user_ip', vars=locals() )[0] if qq.num !=0: raise ValueError; else: db.insert('users', realname=user.get('realname', ''), groups=int(user.get('grps', '')), ip=user_ip, mac=user_mac, channel=int(user.get('channel', '')), bw_up=int(user.get('bw_up', '')), bw_down=int(user.get('bw_down', '')) ) config_dhcp() config_static_arp() web.redirect('/users') except ValueError: return self.show(user, True)
def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): slug = slugify(name) for row in dbview.users(db, startkey=slug, endkey=slug): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you)
def GET(self): if FEED_PROXY and not os.environ.get('HTTP_USER_AGENT').startswith(FEED_PROXY_USER_AGENT): web.redirect(FEED_PROXY) else: posts = models.Post.get_recent_posts() web.header('Content-type', 'application/atom+xml') return render.feed(posts, utils.now().strftime("%Y-%m-%dT%H:%M:%SZ") )
def GET(self): db_connect = MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db) db_row = db_connect.cursor() query = db_row.execute("SELECT * FROM ADMIN") row = db_row.fetchone() password_row = row[2] check_Cookies = web.cookies().get(cookie_name) db_connect = MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db) db_row = db_connect.cursor() query = db_row.execute("SELECT * FROM ADMIN") user = db_row.fetchone() session_name = user[1] if password_row == check_Cookies: try: db_chart = MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db) db_row2 = db_chart.cursor() query2 = db_row2.execute("SELECT * FROM scans_info ORDER BY scan_id desc") chart = db_row2.fetchone() last_scan = chart[1] risk_high_chart = chart[6] risk_meduim_chart = chart[7] risk_low_chart = chart[8] risk_information_chart = chart[9] infected_file = chart[5] return render.new_index(last_scan,infected_file,session_name,risk_high_chart,risk_meduim_chart,risk_low_chart,risk_information_chart) except: return render.error_index(session_name) else: url = "/login" web.redirect(url)
def POST(self): auth() data = web.input(title='', contents='',tag='') ''' update tag ''' for tag in data.tag.split(';'): db.query('select name from tag') res = db.fetchAllRows() if len(tag) == 0: continue if (tag,) not in res: db.insert('insert into tag (name, num) values ("%s",1)'%tag) else: db.query('select id,num from tag where name="%s"'%tag) res = db.fetchOneRow() print res db.update('update tag set num=%d where id=%d'%((res[1]+1),res[0])) ''' update article ''' db.query('select * from article where title="%s"'%data.title) res = db.fetchOneRow() if res == None: res = db.insert('insert into article (title, content, tag, posttime) values ("%s", "%s", "%s", "%s")'%(data.title, data.contents, data.tag, time.strftime('%Y-%m-%d %H:%M:%S'))) if not res: web.redirect('/edit') return 'success' return 'repeated title'
def GET(self): db_connect = MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db) db_row = db_connect.cursor() query = db_row.execute("SELECT * FROM ADMIN") row = db_row.fetchone() password_row = row[2] check_Cookies = web.cookies().get(cookie_name) if password_row == check_Cookies: db_connect = MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db) db_row = db_connect.cursor() query = db_row.execute("SELECT * FROM scans_info ORDER BY scan_id desc") row = db_row.fetchone() rowz = list() while row is not None: rowz.append(row) row = db_row.fetchone() db_connect = MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db) db_row = db_connect.cursor() query = db_row.execute("SELECT * FROM ADMIN") user = db_row.fetchone() session_name = user[1] return render.reports(rowz,session_name) else: url = "/login" web.redirect(url)
def POST(self): # unlike the usual scheme of things, the POST is actually called # first here i = web.input(return_to='/') if i.get('action') == 'logout': oid.logout() return web.redirect(i.return_to) if not i.has_key('openid') or len(i.openid) == 0: return web.redirect(i.return_to) session_data = {'webpy_return_to': i.return_to} session_hash = oid._new_session(session_data) ax_req = ax.FetchRequest() ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/first', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/last', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/contact/email', required=True)) c = openid.consumer.consumer.Consumer(session_data, oid._get_openid_store()) a = c.begin(i.openid) a.addExtension(ax_req) a.addExtension(sreg.SRegRequest(optional=['email', 'fullname'])) f = a.redirectURL(web.ctx.home, web.ctx.home + web.ctx.fullpath) oid._save_session(session_hash, session_data) web.setcookie('openid_session_id', session_hash) return web.redirect(f)
def GET(self): url = "http://www.teampura.com/dialog/oauth?" url += "api_key=" + applify_api_key url += "&redirect_uri=" + str(urllib.quote("http://" + applify_host_name + "/login",'')) url += "&scope=user,project,items" web.redirect(url)
def POST(self): # unlike the usual scheme of things, the POST is actually called # first here i = web.input(return_to='/') if i.get('action') == 'logout': web.webopenid.logout() return web.redirect(i.return_to) i = web.input('openid', return_to='/') going = owevent.going_to_auth(owglobal.session.datapath, owglobal.session.host, i['openid']) owglobal.server.post_event(going) output.dbg(str(owglobal.session.host)+\ " is going to "+going.server()+" to authenticate", self.__class__.__name__) n = web.webopenid._random_session() web.webopenid.sessions[n] = {'webpy_return_to': i.return_to} c = openid.consumer.consumer.Consumer(web.webopenid.sessions[n], web.webopenid.store) a = c.begin(i.openid) f = a.redirectURL(web.ctx.home, web.ctx.home + web.ctx.fullpath) web.setcookie('openid_session_id', n) return web.redirect(f)
def POST(self): var = web.input() if 'fb' in var: xsrf = util.select_one('xsrf', where='token=$tok', vars={'tok': var.xsrf}) if xsrf is None: raise status.ApiError('401 Unauthorized') try: xsrf = util.select_one('xsrf', where='token=$tok', vars={'tok': var.xsrf}) if xsrf is None: raise status.ApiError('401 Unauthorized') user = self.user_auth(var.email, var.pword) if user is None: print "this one" raise status.ApiError('401 Unauthorized') sess = str(uuid.uuid4())[:64] values = { 'sess': sess, 'uid': user['id'] } util.insert('sessions', **values) web.setcookie('wsid_login', sess, path='/') except AttributeError as err: print "that one" raise status.ApiError('401 Unauthorized (%s)' % err) web.redirect('/')
def GET(self, post_id = None, slug = None): try: #Return to canonical if the slug is missing if post_id and not slug: post = models.Post.get(post_id) if post: return web.redirect('/post/%s/%s' % (post_id, post.slug)) else: raise web.notfound() #Gest post if post_id: post = models.Post.get_post(post_id) else: post = models.Post.get_latest_post() if post: #Return to canonical if the slug is truncated if slug and slug.strip() != post.slug: return web.redirect('/post/%s/%s' % (post_id, post.slug)) prev_post, next_post = models.Post.get_prev_next(post) else: raise web.notfound() return render_template(render.post(post, prev_post, next_post, utils.ContentDiscoverer(post.link, post.category).get_content_block(), is_user_admin = users.is_current_user_admin()), title = post.title, canonical = "post/%s" % (post.get_path())) except BadKeyError: raise web.notfound()
def POST(self): color='red' try: user=web.input().user passwd=md5str(web.input().passwd) if cmp(web.session.Session.yzm.upper(),web.input().yzm.upper()): f='请输入正确的验证码' color='red' return render.login(f,color,imgs=authidentcode(),b=web.session.Session.yzm) else: pass if checkpass(user,passwd): web.session.Session.user=user web.session.Session.uuid=md5str(user+config.mi_key) session_add('client_ip','0.0.0.0') session_add('user_info','') web.session.Session.user_info=user_persion_info(web.session.Session.user).list()[0] web.session.Session.client_ip=web.ctx.env.get('REMOTE_ADDR') n_time=str(nowtime()) login_logs(user,n_time,web.session.Session.client_ip) session_add('login_time','') web.session.Session.login_time=n_time web.redirect('/admin/manager/') else: f='验证失败!请输入正确的用户名和密码' return render.login(f,color,imgs=authidentcode(),b=web.session.Session.yzm) except: f='验证失败!请开启浏览器的cookies' return render.login(f,color,imgs=authidentcode(),b=web.session.Session.yzm)
def GET(self,name): #идентификация сессии и идентификация пользователя. print '2222', 'cdx' web.header('Content-type', 'text/html; charset=utf-8') con = sqlite3.connect('overhead.sqlite') cur = con.cursor() i = web.input() if i: #Открыть навую сессию после идентификации пользователя n = i.name p = i.passw sql = u"select * from auth_ko where user=? and passw=?" cur.execute(sql, (n, p)) r = cur.fetchall() if r: rez = r[0][1] sid = uuid.uuid4().hex sid = str(sid) sqlu = u"update auth_ko set sid=? where user=? and passw=?" cur.execute(sqlu, (sid, n, p)) con.commit web.setcookie('sid', sid, 3600) print rez, 'sid=',sid raise web.redirect('/cdx1') #Начата новая сессия. Переходим на следующий шаг. else: return render.index('Логин или пароль неверен! ') else: raise web.redirect('/cdn') #Сюда попал, если логин и пароль не введены.
def POST_leave_waitinglist(self, edition, user, i): waitinglist.leave_waitinglist(user.key, edition.key) stats.increment('ol.loans.leaveWaitlist') if i.get("redirect"): raise web.redirect(i.redirect) else: raise web.redirect(edition.url())
def GET(self): if not session.loggedin: web.redirect("/login?out=1") else: userid = int(web.input().get("id")) act = int(web.input().get("act")) try: if userid: if act == 1: db.update('users', where='id=$userid', active='true', vars=locals()) ips = db.select('users', what='ip', where='id=$userid', limit='1', vars=locals())[0] sps = db.select('pipes', what='COUNT(id) AS num', where='user=$userid', limit='1', vars=locals())[0] if sps.num == 1: sp = db.select('pipes', what='pipe_in,pipe_out', where='user=$userid', limit='1', vars=locals())[0] os.system("/sbin/ipfw -q table 0 add %(ip)s %(sp_out)d" % {'ip':ips.ip, 'sp_out':sp.pipe_out}) os.system("/sbin/ipfw -q table 1 add %(ip)s %(sp_in)d" % {'ip':ips.ip, 'sp_in':sp.pipe_in}) else: reconfig() if act == 2: db.update('users', where='id=$userid', active='false', vars=locals()) ips = db.select('users', what='ip', where='id=$userid', limit='1', vars=locals())[0] os.system("/sbin/ipfw -q table 0 delete %s" % ips.ip) os.system("/sbin/ipfw -q table 1 delete %s" % ips.ip) else: raise Exception ('Error user id') except: pass finally: web.redirect("/users")
def __init__(self, isadmin=""): base_view.__init__(self) web.header("Content-type", "text/html;UTF-8") if not self.login_user.logged: # 是否登录 web.seeother("/login/") elif isadmin == "admin" and not self.login_user.isadmin: # 是否必须是管理员 web.redirect("/error/403")
def GET(self): if not session.loggedin: web.redirect("/login?out=1") else: userid = int(web.input().get("id")) user = db.select('users', where='id=$userid', vars=locals())[0] return self.show(user, False)
def POST(self, req_path): req_path = cgi.escape(req_path) inputs = web.input() action = inputs.get("action") if action and action not in ("edit", "rename"): raise web.BadRequest() content = inputs.get("content") content = web.utils.safestr(content) # NOTICE: if req_path == `users/`, fullpath will be `/path/to/users/`, # parent will be `/path/to/users`. fullpath = get_page_file_or_dir_fullpath_by_req_path(req_path) parent = osp.dirname(fullpath) if not osp.exists(parent): os.makedirs(parent) if action == "edit": if not osp.isdir(fullpath): web.utils.safewrite(fullpath, content) else: idx_dot_md_fullpath = osp.join(fullpath, ".index.md") web.utils.safewrite(idx_dot_md_fullpath, content) web.seeother("/%s" % req_path) elif action == "rename": new_path = inputs.get("new_path") if not new_path: raise web.BadRequest() old_fullpath = get_page_file_or_dir_fullpath_by_req_path(req_path) if osp.isfile(old_fullpath): new_fullpath = get_page_file_or_dir_fullpath_by_req_path(new_path) elif osp.isdir(old_fullpath): new_fullpath = osp.join(conf.pages_path, new_path) else: raise Exception('unknow path') if osp.exists(new_fullpath): err_info = "Warning: The page foobar already exists." return t_render.rename(req_path, err_info, static_files=DEFAULT_GLOBAL_STATIC_FILES) parent = osp.dirname(new_fullpath) if not osp.exists(parent): os.makedirs(parent) shutil.move(old_fullpath, new_fullpath) if osp.isfile(new_fullpath): web.seeother("/%s" % new_path) elif osp.isdir(new_fullpath): web.seeother("/%s/" % new_path) return url = osp.join("/", req_path) web.redirect(url)
def GET(self): ''' 声音控制器 静态指令执行 :return: ''' username = Common.getLoginUsername() # 获得登录用户名 if not username: # 不存在则返回重定向 return web.redirect('/404') input = web.input(op=None) op = input.op # 操作码 if op: r, d = ApiManager.getDeviceInfo(username) # 获取设备信息 if r == 'fail': if d == errors.NOT_BIND: # 设备未绑定 url = '/bind?username='******'/404') if op == 'open': # 打开声音 ApiManager.sendOrder(d['id'], orders.OPEN_SOUND) elif op == 'close': # 关闭声音 ApiManager.sendOrder(d['id'], orders.CLOSE_SOUND) else: '''指令错误''' return web.redirect('/404') r, status, time = ApiManager.getSoundStatus(username) return config.render.sound(status, time)
def POST(self, table_name): inp = web.input() state = inp.get('state') if state == 'hapus': asset_id = inp.get('asset_id') delete = Delete('asset', where='id=' + asset_id) query = conn.sqlrepr(delete) conn.query(query) return "ok" elif state == 'tambah': nama = inp.get('nama_asset_add') kategori = inp.get('kategori-asset') merk = inp.get('merk') model = inp.get('model') tgl_perolehan = inp.get('tgl_perolehan') if inp.get('nilai'): n1 = inp.get('nilai').replace('Rp. ', '') n2 = n1.replace('.', '') nilai = n2 bmn = inp.get('bmn') Asset(table_name=table_name, cuser=session.get('username'), kategori=kategori + '_' + nama, nama=nama, merk=merk, model=model, perolehan=tgl_perolehan, nilai_perolehan=int(nilai), bmn=bmn) return web.redirect('asset') else: try: asset = Asset.get(int(inp.get('pk'))) asset.set(**{inp.get('name'): inp.get('value')}) except SQLObjectNotFound: return web.notfound() web.header('Content-Type', 'application/json') return json.dumps({"Ok": "true"})
def GET(self, courseid, taskid, path): # pylint: disable=arguments-differ """ GET request """ try: course = self.course_factory.get_course(courseid) if not self.user_manager.course_is_open_to_user(course): return handle_course_unavailable(self.app.get_homepath(), self.template_helper, self.user_manager, course) path_norm = posixpath.normpath(urllib.parse.unquote(path)) if taskid == "$common": public_folder = course.get_fs().from_subfolder( "$common").from_subfolder("public") else: task = course.get_task(taskid) if not self.user_manager.task_is_visible_by_user( task): # ignore LTI check here return self.template_helper.get_renderer( ).task_unavailable() public_folder = task.get_fs().from_subfolder("public") (method, mimetype_or_none, file_or_url) = public_folder.distribute(path_norm, False) if method == "local": web.header('Content-Type', mimetype_or_none) return file_or_url elif method == "url": raise web.redirect(file_or_url) else: raise web.notfound() except web.HTTPError as error_or_redirect: raise error_or_redirect except: if web.config.debug: raise else: raise web.notfound()
def POST(self): if not 'user' in session or session.user is None: f = register_form() return render.login(f) i = web.input(name="", description="", command="") if i.name == "": return render.error("No mutation engine name specified") elif i.description == "": return render.error("No mutation engine description specified") elif i.command == "": return render.error("No mutation engine command specified") elif i.command.find("%INPUT%") == -1 and i.command.find("%TEMPLATES_PATH%") == -1: return render.error("No input template filename specified in the mutation engine command") elif i.command.find("%OUTPUT%") == -1: return render.error("No output mutated filename specified in the mutation engine command") db = init_web_db() with db.transaction(): db.insert("mutation_engines", name=i.name, command=i.command, description=i.description, date=web.SQLLiteral("CURRENT_DATE")) return web.redirect("/engines")
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ """ POST request """ # Change to teacher privilege when created if not self.user_manager.user_is_superadmin(): raise self.app.forbidden( message=_("You're not allowed to do that")) course = self.get_course(courseid) user_input = web.input() errors = [] if "new_courseid" in user_input: new_courseid = user_input["new_courseid"] try: import_course(course, new_courseid, self.user_manager.session_username(), self.course_factory) except ImportCourseException as e: errors.append(str(e)) if not errors: raise web.redirect(self.app.get_homepath() + "/admin/{}".format(new_courseid)) return self.show_page(course, errors)
def POST_AUTH(self): # pylint: disable=arguments-differ """ POST request """ username = self.user_manager.session_username() user_input = web.input() # Change to professors right when available if "new_courseid" in user_input and self.user_manager.user_is_superadmin( ): try: export(self.template_factory, self.course_factory, user_input["templateid"], user_input["new_courseid"], username) raise web.redirect( self.app.get_homepath() + "/admin/{}".format(user_input["new_courseid"])) except: message, success = _("Failed to create the course."), False # Change to professors right when available elif "new_templateid" in user_input and self.user_manager.user_is_superadmin( ): try: templateid = user_input["new_templateid"] self.template_factory.create_course(templateid, { "name": templateid, "editors": [username] }) message, success = _("Template created."), True except: message, success = _("Failed to create the course."), False elif "pull" in user_input and self.user_manager.user_is_superadmin(): try: self.template_factory.pull_git_templates() message, success = _("Templates pulled."), True except: message, success = _("Failed to pull the course."), False else: return self.page() return self.page(success, message)
def scaffolding(rawuri): inputuri = rawuri """ currency = gettag(rawuri, routeconfig['currencies']) if currency: inputuri = uristring[:-1 * len(URISEPARATOR + currency)] """ try: pt.setUri(lib.misc.urldecode(inputuri)) if pt.forceredirect and inputuri != pt.getUri(): redirecturl = URISEPARATOR + lib.misc.urlencode(pt.getUri()) #if currency: redirecturl += URISEPARATOR + currency logger.info('%s is not canonical. Redirecting to %s', inputuri, redirecturl) logRequest('301:' + redirecturl) raise web.redirect(redirecturl) except NotImplementedError, e: logRequest('404:' + str(e)) raise web.notfound()
def POST(self): inp = web.input() if inp.get('state') == '0': kategori = inp.get('kategori') if inp.get('lanjut') == '0': lanjut = False elif inp.get('lanjut') == '1': lanjut = True kerusakan_id = inp.get('kerusakan_id') uraian = inp.get('uraian') Tanggapan1(kerusakan=int(kerusakan_id), uraian=uraian, kategori=kategori, lanjut=lanjut, cuser=session.get('username')) return "ok" elif inp.get('state') == '1': kategori = "" lanjut = False kerusakan_id = inp.get('kerusakan_id') uraian = inp.get('uraian') Tanggapan1(kerusakan=int(kerusakan_id), uraian=uraian, kategori=kategori, lanjut=lanjut, cuser=session.get('username')) return "ok" elif inp.get('state') == 'update': table_name = inp.get('table_name') tanggapan1_id = inp.get('tanggapan1_id') uraian = inp.get('uraian') update = Update('tanggapan1', values={'uraian': uraian}, where='id=' + tanggapan1_id) query = conn.sqlrepr(update) conn.query(query) # return "ok" return web.redirect(table_name + '/kerusakan?' + str(datetime.datetime.now()))
def GET(self): print('PROCESS GET method') path = '/root/GFS/rawfile' files = os.listdir(path) piclist = [] colcount = 0 rowcount = 0 result = '' downloadhour = [ '000', '006', '012', '018', '024', '030', '036', '042', '048', '054', '060', '066', '072', '078', '084', '090', '096', '102', '108', '114', '120', '126', '132', '138', '144', '150', '156', '162', '168', '174', '180', '186', '192', '198', '204', '210', '216', '222', '228', '234', '240' ] count = 0 finalfilelist = [] for count in range(0, len(downloadhour)): for file in files: # gfs.GFS2017121718.f120 fcst = file[file.find('.') + file[file.find('.') + 1:].find('.') + 3:] # print(fcst) if fcst == downloadhour[count]: finalfilelist.append(file) for file in finalfilelist: result += '<option value="' + file + '"> ' + file + ' </option>' if iscookie() == True: rawhtml = open(r'addmapmission.html', 'r').read() return rawhtml[0:rawhtml.find('<select name="time" class="form-control">')+len('<select name="time" class="form-control">')] \ + result + rawhtml[rawhtml.find('<select name="time" class="form-control"></select>')+len('<select name="time" class="form-control">'):] else: return web.redirect('login')
def GET(self, key): nkey = self.normalize_key(key) if nkey != key: raise web.redirect(nkey) # this needs to be updated to include: #q=public_scan_b:true+OR+lending_edition_s:* subj = get_subject(key, details=True, filters={ 'public_scan_b': 'false', 'lending_edition_s': '*' }) subj.v2 = True delegate.context.setdefault('bodyid', 'subject') if not subj or subj.work_count == 0: web.ctx.status = "404 Not Found" page = render_template('subjects/notfound.tmpl', key) else: page = render_template("subjects", page=subj) page.v2 = True return page
def __call__(self, handler): # temp hack to handle languages and users during upstream-to-www migration if web.ctx.path.startswith("/l/"): raise web.seeother("/languages/" + web.ctx.path[len("/l/"):]) if web.ctx.path.startswith("/user/"): if not web.ctx.site.get(web.ctx.path): raise web.seeother("/people/" + web.ctx.path[len("/user/"):]) real_path, readable_path = get_readable_path(web.ctx.site, web.ctx.path, self.patterns, encoding=web.ctx.encoding) #@@ web.ctx.path is either quoted or unquoted depends on whether the application is running #@@ using builtin-server or lighttpd. That is probably a bug in web.py. #@@ take care of that case here till that is fixed. # @@ Also, the redirection must be done only for GET requests. if readable_path != web.ctx.path and readable_path != urllib.parse.quote( web.safestr(web.ctx.path)) and web.ctx.method == "GET": raise web.redirect( web.safeunicode(readable_path) + web.safeunicode(web.ctx.query)) web.ctx.readable_path = readable_path web.ctx.path = real_path web.ctx.fullpath = web.ctx.path + web.ctx.query out = handler() V2_TYPES = [ 'works', 'books', 'people', 'authors', 'publishers', 'languages', 'account' ] # Exclude noindex items if web.ctx.get('exclude'): web.ctx.status = "404 Not Found" return render.notfound(web.ctx.path) return out
def POST(self): data = web.input() if data.password and data.repassword and data.password == data.repassword: # 锁的问题有点操蛋。。。还是用 mongod 维护多一个表存储自增 id 吧 # findAndModify 会锁定表 uid = db['ids'].find_and_modify(query={'name': 'user'}, update={'$inc': { 'id': 1 }}, new=True)['id'] db['users'].insert({ 'uid': int(uid), 'username': data.username, 'nickname': data.nickname, 'avatar': getAvatar(data.username), 'password': hashlib.md5(data.password).hexdigest(), 'regDate': time.time(), 'regIp': web.ctx.ip, 'loginIp': web.ctx.ip, 'lastLoginTime': time.time() }) # session.hasLogin = True # session.username = data.username writeSession({'hasLogin': True, 'username': data.username}) web.setcookie('pyname', data.username, 72000, path='/') # web.setcookie('pyconnect',sign(data.username),72000,path='/') # 删除 token 表中的 document db['regToken'].remove({'email': data['username']}) return web.redirect('/0')
def POST(self): if not 'user' in session or session.user is None: f = register_form() return render.login(f) i = web.input(name="", description="", subfolder="", tube_prefix="", max_files=100, max_iteration=1000000, ignore_duplicates=0) if i.name == "": return render.error("No project name specified") elif i.description == "": return render.error("No project description specified") elif i.tube_prefix == "": return render.error("Invalid tube prefix") if i.ignore_duplicates == "on": ignore_duplicates = 1 else: ignore_duplicates = 0 db = init_web_db() with db.transaction(): db.insert("projects", name=i.name, description=i.description, subfolder=i.subfolder, tube_prefix=i.tube_prefix, maximum_samples=i.max_files, archived=0, maximum_iteration=i.max_iteration, date=web.SQLLiteral("CURRENT_DATE"), ignore_duplicates=ignore_duplicates) return web.redirect("/projects")
def GET(self, key): web.header('Content-Type', 'application/json') # If the key is not in the normalized form, redirect to the normalized form. nkey = self.normalize_key(key) if nkey != key: raise web.redirect(nkey) # Does the key requires any processing before passing using it to query solr? key = self.process_key(key) i = web.input(offset=0, limit=DEFAULT_RESULTS, details='false', has_fulltext='false', sort='editions', available='false') i.limit = safeint(i.limit, DEFAULT_RESULTS) i.offset = safeint(i.offset, 0) if i.limit > MAX_RESULTS: msg = json.dumps({'error': 'Specified limit exceeds maximum of %s.' % MAX_RESULTS}) raise web.HTTPError('400 Bad Request', data=msg) filters = {} if i.get('has_fulltext') == 'true': filters['has_fulltext'] = 'true' if i.get('published_in'): if '-' in i.published_in: begin, end = i.published_in.split('-', 1) if safeint(begin, None) is not None and safeint(end, None) is not None: filters['publish_year'] = (begin, end) # range else: y = safeint(i.published_in, None) if y is not None: filters['publish_year'] = i.published_in subject_results = get_subject(key, offset=i.offset, limit=i.limit, sort=i.sort, details=i.details.lower() == 'true', **filters) if i.has_fulltext: subject_results['ebook_count'] = subject_results['work_count'] return json.dumps(subject_results)
def POST(self): x = web.input(agedata={}) agebits = {} try: description = x['description'] shortname = x['shortname'] fullname = x['fullname'] agefile = x['agedata'].file gamever = x['gameversion'] agever = x['version'] except KeyError: raise common.MissingParam() # Confirm that the zip file looks like a real age plasma_utils.validate_zip(agefile, shortname) if not age_name_re.match(shortname): raise common.BadParam('shortname') if not age_fullname_re.match(fullname): raise common.BadParam('fullname') if not gamever in config.acceptable_game_versions: raise common.BadParam('gameversion') new_id = agedb.createAge(shortname=shortname, fullname=fullname, description=description, creator=userdb.ctx.uid) # Now that we have an age, we need to stash the file fileid = agedb.createFile(age=new_id, gamever=gamever, version=agever, status='NEW') filename = config.agefiles_path + str(fileid) + '.zip' out = open(filename, 'wb') agefile.seek(0) out.write(agefile.read()) out.close() plasma_utils.update_seqprefix(filename, new_id) raise web.redirect(config.ages_path + '/' + str(new_id))
def POST(self): data = web.input() if data.username: user = db['users'].find_one({'username': data.username}) if user: if hashlib.md5( data.password).hexdigest() == user.get('password'): # success # 更新最后登录时间,ip db['users'].update({'username': data.username}, { '$set': { 'loginIp': web.ctx.ip, 'lastLoginTime': time.time() } }) writeSession({'hasLogin': True, 'username': data.username}) web.setcookie('pyname', data.username, 36000, path='/') # web.setcookie('pyconnect',sign(data.username),36000,path='/') return web.redirect('/0') else: return '密码错误' else: return '用户不存在'
def POST(self): if not 'user' in session or session.user is None: f = register_form() return render.login(f) i = web.input(id=-1, name="", description="", command="") if i.id == -1: return render.error("Invalid mutation engine identifier") elif i.name == "": return render.error("No mutation engine name specified") elif i.description == "": return render.error("No mutation engine description specified") elif i.command == "": return render.error("No mutation engine command specified") elif i.command.find("%OUTPUT%") == -1: return render.error("No output mutated filename specified in the mutation engine command") db = init_web_db() with db.transaction(): where = "mutation_engine_id = $id" vars = {"id":i.id} db.update("mutation_engines", name=i.name, command=i.command, description=i.description, where=where, vars=vars) return web.redirect("/engines")
def GET(self, path): if not path: raise web.redirect('/docadhoc') full_path = './static/' + path files_and_dirs = sorted(os.listdir(full_path)) files = [ file_name for file_name in files_and_dirs if os.path.isfile(full_path + '/' + file_name) ] dirs = [ file_name for file_name in files_and_dirs if os.path.isdir(full_path + '/' + file_name) ] page = header page += '\n\n<h1>' # breadcrumbs places = path.split('/') for i in range(len(places) - 1): page += '\n<a href="/' + '/'.join( places[:i + 1]) + '">' + places[i] + '</a> / ' page += places[-1] + '</h1>' page += '\n\n<ul>' # directories for dir_name in dirs: page += '\n<li><a href="/' + path + '/' + dir_name + '">' + dir_name + '</a></li>' page += '</ul>' page += '\n\n<ol>' # files for file_name, no in zip(files, range(1, len(files) + 1)): page += '\n<li><a name="' + str(no) + '"></a>' page += '<a href="/static/' + path + '/' + file_name + '">' + file_name + '</a>' if file_name.split('.')[-1] in texts: page += '<br /><pre>' + open(full_path + '/' + file_name, 'r').read() + '</pre>' if file_name.split('.')[-1] in images: page += '<br /><img src="/static/' + path + '/' + file_name + '" />' page += '</li>' page += '</ol>' return page + footer
def POST(self): if not 'user' in session or session.user is None: f = register_form() return render.login(f) i = web.input(anal_engine="", ida_path="", pyew_path="") if i.anal_engine == "" or (i.ida_path + i.pyew_path == ""): render.error("Invalid analysis engine, IDA path or Pyew path.") db = open_db() with db.transaction(): sql = "select 1 from config where name = 'IDA_PATH'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'IDA_PATH'" else: sql = "insert into config (name, value) values ('IDA_PATH', $value)" db.query(sql, vars={"value": i.ida_path}) sql = "select 1 from config where name = 'PYEW_PATH'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'PYEW_PATH'" else: sql = "insert into config (name, value) values ('PYEW_PATH', $value)" db.query(sql, vars={"value": i.pyew_path}) sql = "select 1 from config where name = 'ANAL_ENGINE'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'ANAL_ENGINE'" else: sql = "insert into config (name, value) values ('ANAL_ENGINE', $value)" db.query(sql, vars={"value": i.anal_engine}) return web.redirect("/config")
def POST(self): flag = True runData = {'runFlag': True, 'showMsg': 'OK'} req = web.input() # 检查必填项是否都有值 mustName = [ 'c0_1', ] runData = lazy.checkInput(req, mustName, runData) cx = lazy.getConn() cu = cx.cursor() strUpdate = "UPDATE temp_data SET use_flag='2' where data_no='" + req[ 'c0_1'] + "'" print strUpdate cu.execute(strUpdate) cx.commit() cu.close() cx.close raise web.redirect('/')
def POST(self): if not 'user' in session or session.user is None: f = register_form() return render.login(f) i = web.input(id=-1, name="", description="", subfolder="", tube_prefix="", enabled="", archived="") if i.id == -1: return render.error("Invalid project identifier") elif i.name == "": return render.error("No project name specified") elif i.description == "": return render.error("No project description specified") elif i.tube_prefix == "": return render.error("No tube prefix specified") if i.enabled == "on": enabled = 1 else: enabled = 0 if i.archived == "on": archived = 1 else: archived = 0 db = init_web_db() with db.transaction(): enabled = i.enabled == "on" archived = i.archived == "on" db.update("projects", name=i.name, description=i.description, subfolder=i.subfolder, tube_prefix=i.tube_prefix, maximum_samples=i.max_files, enabled=enabled, maximum_iteration=i.max_iteration, archived=archived, where="project_id = $project_id", vars={"project_id":i.id}) return web.redirect("/projects")
def POST(self, table_name): agent_id = dict([a.split('\t') for a in open('agent_table.txt').readlines()]).get(table_name) pos = Agent.get(agent_id) try: pos = [a for a in AgentCh.select(AgentCh.q.AgentType==1) if a.table_name == table_name][0] except IndexError: return web.notfound() inp = web.input() float_list = 'ch_m,temp_min_m,temp_max_m,humi_m,kec_angin_m,penguapan_m'.split(',') for kol in float_list: if inp.get(kol): inp.update({kol: float(inp.get(kol))}) else: inp.update({kol: None}) inp.update({'penyinaran_m': inp.get('penyinaran_m') and int(inp.get('penyinaran_m')) or None}) inp.update({'agentID': pos.id, 'cuser': session.username, 'cdate': datetime.datetime.now()}) inp.update({'sampling': to_date(inp.get('sampling'))}) if 'csrf_token' in inp: del inp['csrf_token'] rst = KlimatManual.select(AND(KlimatManual.q.agent==pos, func.DATE(KlimatManual.q.sampling)==inp.get('sampling'))) if rst.count(): rst[0].set(**inp) else: km = KlimatManual(**inp) # table curahhujan perlu ditambah/update ch = CurahHujan.select(AND(CurahHujan.q.agent==pos, func.DATE(CurahHujan.q.waktu) == inp.get('sampling'))) if ch.count(): ch[0].set(**{'manual': float(inp.get('ch_m', 0))}) else: ch = CurahHujan(**{'waktu': inp.get('sampling'), 'manual': float(inp.get('ch_m', 0)), 'agent': pos}) return web.redirect('/adm/klimatologi/' + table_name, absolute=True)
def GET(self, key): # If the key is not in the normalized form, redirect to the normalized form. nkey = self.normalize_key(key) if nkey != key: raise web.redirect(nkey) # Does the key requires any processing before passing using it to query solr? key = self.process_key(key) i = web.input(offset=0, limit=12, has_fulltext="false") filters = {} if i.get("has_fulltext") == "true": filters["has_fulltext"] = "true" if i.get("published_in"): if "-" in i.published_in: begin, end = i.published_in.split("-", 1) if safeint(begin, None) is not None and safeint( end, None) is not None: filters["publish_year"] = (begin, end) else: y = safeint(i.published_in, None) if y is not None: filters["publish_year"] = i.published_in i.limit = safeint(i.limit, 12) i.offset = safeint(i.offset, 0) results = get_subject(key, offset=i.offset, limit=i.limit, details=False, **filters) return json.dumps(results)
def GET(self, key): if key.lower() != key: raise web.redirect(key.lower()) i = web.input(offset=0, limit=12, details='false', has_fulltext='false', sort='editions') filters = {} if i.get('has_fulltext') == 'true': filters['has_fulltext'] = 'true' if i.get('published_in'): if '-' in i.published_in: begin, end = i.published_in.split('-', 1) if safeint(begin, None) is not None and safeint( end, None) is not None: filters['publish_year'] = [begin, end] else: y = safeint(i.published_in, None) if y is not None: filters['publish_year'] = i.published_in i.limit = safeint(i.limit, 12) i.offset = safeint(i.offset, 0) subject = get_subject(key, offset=i.offset, limit=i.limit, sort=i.sort, details=i.details.lower() == 'true', **filters) return json.dumps(subject)
def GET(self, shareid): if (shareid.isalnum()): return web.redirect(BaiduPanRealUrlB(shareid)) else: return web.notfound()
def GET(self, shareid, uk): if (shareid.isdigit() and uk.isdigit()): return web.redirect(BaiduPanRealUrl(shareid, uk)) else: return web.notfound()
def POST(self, username): i = web.input(changesets=[], comment="Revert", action="revert") if i.action == "revert" and i.changesets: ipaddress_view().revert(i.changesets, i.comment) raise web.redirect(web.ctx.path)
def POST_join_waitinglist(self, edition, user): waitinglist.join_waitinglist(user.key, edition.key) stats.increment('ol.loans.joinWaitlist') raise web.redirect(edition.url())
def GET(self): i = web.input(url='') image_url = i.url return web.redirect(image_url)
def powerPublish(owner, modelName): 'Hook to pull data back to DRPOWER main repository.' return web.redirect( os.environ.get('DRP_URL') + '/' + owner + '/' + modelName)
def POST(self): if not 'user' in session or session.user is None: f = register_form() return render.login(f) i = web.input(samples_path="", templates_path="", nightmare_path="", \ temporary_path="") if i.samples_path == "" or i.templates_path == "" or \ i.nightmare_path == "" or i.temporary_path == "": render.error("Invalid samples, templates, temporary or nightmare path") db = init_web_db() with db.transaction(): sql = "select 1 from config where name = 'SAMPLES_PATH'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'SAMPLES_PATH'" else: sql = "insert into config (name, value) values ('SAMPLES_PATH', $value)" db.query(sql, vars={"value":i.samples_path}) sql = "select 1 from config where name = 'TEMPLATES_PATH'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'TEMPLATES_PATH'" else: sql = "insert into config (name, value) values ('TEMPLATES_PATH', $value)" db.query(sql, vars={"value":i.templates_path}) sql = "select 1 from config where name = 'NIGHTMARE_PATH'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'NIGHTMARE_PATH'" else: sql = "insert into config (name, value) values ('NIGHTMARE_PATH', $value)" db.query(sql, vars={"value":i.nightmare_path}) sql = "select 1 from config where name = 'TEMPORARY_PATH'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'TEMPORARY_PATH'" else: sql = "insert into config (name, value) values ('TEMPORARY_PATH', $value)" db.query(sql, vars={"value":i.temporary_path}) sql = "select 1 from config where name = 'QUEUE_HOST'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'QUEUE_HOST'" else: sql = "insert into config (name, value) values ('QUEUE_HOST', $value)" db.query(sql, vars={"value":i.queue_host}) sql = "select 1 from config where name = 'QUEUE_PORT'" res = list(db.query(sql)) if len(res) > 0: sql = "update config set value = $value where name = 'QUEUE_PORT'" else: sql = "insert into config (name, value) values ('QUEUE_PORT', $value)" db.query(sql, vars={"value":i.queue_port}) return web.redirect("/config")