def action_view_POST(self, req, page): submit_mtime = int(req.params.get("mtime") or "0") or None if page.mtime != submit_mtime: return exc.HTTPPreconditionFailed( "The page has been updated since you started editing it") page.set(title=req.params["title"], content=req.params["content"]) resp = exc.HTTPSeeOther(location=req.path_url) resp.set_cookie("message", "Page updated") return resp
def action_view_POST(self, req, page): submit_mtime = int(req.params.get('mtime') or '0') or None if page.mtime != submit_mtime: return exc.HTTPPreconditionFailed( "The page has been updated since you started editing it") page.set(title=req.params['title'], content=req.params['content']) resp = exc.HTTPSeeOther(location=req.path_url) resp.set_cookie('message', 'Page updated') return resp
def redirect(location=None, permanent=False): " Redirect to other page " # .exeception for Python 2.3 compatibility # 307 if location is None: location = req.environ["PATH_INFO"] if permanent: raise exc.HTTPMovedPermanently(location=url(location)).exception else: raise exc.HTTPSeeOther(location=url(location)).exception
def post(self, request): """ return response to a POST request """ contents = request.POST.get('svenweb.resource_body') message = request.POST.get('svenweb.commit_message') metadata = {} loc = location(request) return (contents, message, metadata, exc.HTTPSeeOther(location=loc))
def __call__(self, environ, start_response): req = Request(environ) try: rsp = req.get_response(self.app) except xmlrpclib.Fault, err: log.exception('AuthErrorMiddleware:') # faultString is something like: <'__main__.AuthException'>:invalid user or password c = err.faultString.split("'",2)[1].partition(".")[2] if c == "AuthException": rsp = exc.HTTPSeeOther(location = url(controller='login', action = 'invalid')) else: raise err
def on_after_post(self, request, response, ids): """Generate a redirection after a POST In: - ``request`` -- the web request object - ``response`` -- the web response object - ``ids`` -- identifiers to put into the generated redirection URL Return: - a ``webob.exc`` object, used to generate the response to the browser """ return exc.HTTPSeeOther(location=request.path_url + '?' + '&'.join(ids))
def convert(self, request): assert False content = request.POST.get('svenweb.resource_body') mimetype = request.POST.get('svenweb.mimetype') _from = request.POST['convert_from'] message = request.POST.get('svenweb.commit_message') loc = location(request) return (convert(_from, mimetype, content), message, { 'mimetype': mimetype }, exc.HTTPSeeOther(location=loc))
def action_view_POST(self, req, page): submit_mtime = int(req.params.get('mtime') or '0') or None if page.mtime != submit_mtime: return exc.HTTPPreconditionFailed( "The page has been updated since you started editing it") # fields has to be modified below in page.set that user will submit while filling the query or edit page page.set( title=req.params['title'], content=req.params['content']) resp = exc.HTTPSeeOther( location=req.path_url) resp.set_cookie('message', 'Page updated') return resp
def process_comment(self, req): try: url = req.params['url'] name = req.params['name'] homepage = req.params['homepage'] comments = req.params['comments'] except KeyError as e: resp = exc.HTTPBadRequest('Missing parameter: %s' % e) return resp data = self.get_data(url) data.append( dict(name=name, homepage=homepage, comments=comments, time=time.gmtime())) self.save_data(url, data) resp = exc.HTTPSeeOther(location=url + '#comment-area') return resp
def __call__(self, request): module_name = request.path_info_pop() section_name = request.path_info_pop() apps_data = OrderedDict() for app in apps: app_data = inspect_app(app) apps_data[app_data['name']] = (app, app_data) modules = [data for (_, data) in apps_data.values()] if not module_name: return render('index', modules=modules) if not module_name in apps_data: raise exc.HTTPNotFound app, module = apps_data[module_name] if module['disabled']: raise exc.HTTPNotFound if not section_name: section_name = module['sections'][0]['name'] raise exc.HTTPSeeOther(location=request.path + '/' + section_name) if not hasattr(app, section_name): raise exc.HTTPNotFound section = next((section for section in module['sections'] if section['name'] == section_name), None) resp = getattr(app, section_name)(request) if isinstance(resp, Response): return resp return render('app_base', modules=modules, module=module, section=section, title='YubiAdmin - %s - %s' % (module_name, section_name), page=resp)
def redirect_response(url): return exc.HTTPSeeOther(location=url)
def redirect(request, target): return exc.HTTPSeeOther(location=request.relative_url(target, True))
def redirect(self, url): raise exc.HTTPSeeOther(location=url)
def __call__(self, environ, start_response): req = Request(environ) step = req.path_info.strip('/') try: if step in [i[0] for i in self.steps]: # determine which step we are on index = [i[0] for i in self.steps].index(step) else: # delegate to Trac environ['trac.env_parent_dir'] = self.directory environ['trac.env_index_template'] = self.index # data for index template if req.remote_user and self.remote_user_name: # XXX fails if unicode req.remote_user = str( self.remote_user_name(req.remote_user)) data = { 'remote_user': req.remote_user or '', 'auth': self.auth and 'yes' or '' } environ['trac.template_vars'] = ','.join( ["%s=%s" % (key, value) for key, value in data.items()]) return dispatch_request(environ, start_response) # if self.auth, enforce remote_user to be set if self.auth and not req.remote_user: return exc.HTTPUnauthorized()(environ, start_response) # if POST-ing, validate the request and store needed information errors = [] name, step = self.steps[index] base_url = req.url.rsplit(step.name, 1)[0] project = req.params.get('project') if req.method == 'POST': # check for project existence if not project and index: res = exc.HTTPSeeOther("No session found", location="create-project") return res(environ, start_response) if index: if project not in self.projects: errors.append('Project not found') project_data = self.projects.get(project) errors = step.errors(project_data, req.POST) if not index: project_data = self.projects[project] = {} # set *after* error check so that `create-project` doesn't find itself project_data['base_url'] = base_url if not errors: # success step.transition(project_data, req.POST) # find the next step and redirect to it while True: index += 1 if index == len(self.steps): destination = self.done % self.projects[project][ 'vars'] time.sleep(1) # XXX needed? self.projects.pop( project) # successful project creation break else: name, step = self.steps[index] if step.display(project_data): destination = '%s?project=%s' % ( self.steps[index][0], project) break else: step.transition(project_data, {}) res = exc.HTTPSeeOther(destination, location=destination) return res(environ, start_response) else: # GET project_data = self.projects.get(project, {}) project_data['base_url'] = base_url if index and project not in self.projects: res = exc.HTTPSeeOther("No session found", location="create-project") return res(environ, start_response) # render the template and return the response data = step.data(project_data) data['req'] = req data['errors'] = errors template = self.loader.load(step.template) html = template.generate(**data).render('html', doctype='html') res = Response(content_type='text/html', body=html) return res(environ, start_response) except: # error handling exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() buffer = StringIO() traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback, limit=20, file=buffer) res = exc.HTTPServerError(buffer.getvalue()) return res(environ, start_response)
def redirect(self, location): raise exc.HTTPSeeOther(location=location)
def redirect(self, request): "Perform a redirect to ``target``" target = request.params.get('target', '/') return exc.HTTPSeeOther(location=target)
def redirect(self, location, query=None, anchor=None): return exc.HTTPSeeOther(location=self.app.baseurl + '/' + location + (query and self.query_string(query) or '') + (anchor and ('#' + anchor) or ''))
class Commenter(object): def __init__(self, app, storage_dir): self.app = app self.storage_dir = storage_dir if not os.path.exists(storage_dir): os.makedirs(storage_dir) def __call__(self, environ, start_response): from webob import Request req = Request(environ) if req.path_info_peek() == '.comments': return self.process_comment(req)(environ, start_response) # URL without PATH_INFO: base_url = req.application_url resp = req.get_response(self.app) if resp.content_type != 'text/html' or resp.status_int != 200: # Not an HTML response, we don't want to # do anything to it return resp(environ, start_response) # Make sure the content isn't gzipped: resp.decode_content() comments = self.get_data(req.url) body = resp.body body = self.add_to_end(body, self.format_comments(comments)) body = self.add_to_end(body, self.submit_form(base_url, req)) resp.body = body return resp(environ, start_response) def get_data(self, url): from cPickle import load filename = self.url_filename(url) if not os.path.exists(filename): return [] else: f = open(filename, 'rb') data = load(f) f.close() return data def save_data(self, url, data): from cPickle import dump filename = self.url_filename(url) f = open(filename, 'wb') dump(data, f) f.close() def url_filename(self, url): # Double-quoting makes the filename safe import urllib return os.path.join(self.storage_dir, urllib.quote(url, '')) import re _end_body_re = re.compile(r'</body.*?>', re.I|re.S) def add_to_end(self, html, extra_html): match = self._end_body_re.search(html) if not match: return html + extra_html else: return html[:match.start()] + extra_html + html[match.start():] def format_comments(self, comments): import time from webob import html_escape if not comments: return '' text = [] text.append('<hr>') text.append('<h2><a name="comment-area"></a>Comments (%s):</h2>' % len(comments)) for comment in comments: text.append('<h3><a href="%s">%s</a> at %s:</h3>' % ( html_escape(comment['homepage']), html_escape(comment['name']), time.strftime('%c', comment['time']))) # Susceptible to XSS attacks!: text.append(comment['comments']) return ''.join(text) def submit_form(self, base_path, req): from webob import html_escape return '''<h2>Leave a comment:</h2> <form action="%s/.comments" method="POST"> <input type="hidden" name="url" value="%s"> <table width="100%%"> <tr><td>Name:</td> <td><input type="text" name="name" style="width: 100%%"></td></tr> <tr><td>URL:</td> <td><input type="text" name="homepage" style="width: 100%%"></td></tr> </table> Comments:<br> <textarea name="comments" rows=10 style="width: 100%%"></textarea><br> <input type="submit" value="Submit comment"> </form> ''' % (base_path, html_escape(req.url)) def process_comment(self, req): import time from webob import exc try: url = req.params['url'] name = req.params['name'] homepage = req.params['homepage'] comments = req.params['comments'] except KeyError, e: resp = exc.HTTPBadRequest('Missing parameter: %s' % e) return resp data = self.get_data(url) data.append(dict( name=name, homepage=homepage, comments=comments, time=time.gmtime())) self.save_data(url, data) resp = exc.HTTPSeeOther(location=url+'#comment-area') return resp
class Commenter(object): def __init__(self, app, storage_dir): self.app = app self.storage_dir = storage_dir if not os.path.exists(storage_dir): os.makedirs(storage_dir) def __call__(self, environ, start_response): req = Request(environ) if req.path_info_peek() == ".comments": return self.process_comment(req)(environ, start_response) # This is the base path of *this* middleware: base_url = req.application_url resp = req.get_response(self.app) if resp.content_type != "text/html" or resp.status_code != 200: # Not an HTML response, we don't want to # do anything to it return resp(environ, start_response) # Make sure the content isn't gzipped: resp.decode_content() comments = self.get_data(req.url) body = resp.body body = self.add_to_end(body, self.format_comments(comments)) body = self.add_to_end(body, self.submit_form(base_url, req)) resp.body = body return resp(environ, start_response) def get_data(self, url): # Double-quoting makes the filename safe filename = self.url_filename(url) if not os.path.exists(filename): return [] else: f = open(filename, "rb") data = load(f) f.close() return data def save_data(self, url, data): filename = self.url_filename(url) f = open(filename, "wb") dump(data, f) f.close() def url_filename(self, url): return os.path.join(self.storage_dir, urllib.quote(url, "")) _end_body_re = re.compile(r"</body.*?>", re.I | re.S) def add_to_end(self, html, extra_html): """ Adds extra_html to the end of the html page (before </body>) """ match = self._end_body_re.search(html) if not match: return html + extra_html else: return html[:match.start()] + extra_html + html[match.start():] def format_comments(self, comments): if not comments: return "" text = [] text.append("<hr>") text.append('<h2><a name="comment-area"></a>Comments (%s):</h2>' % len(comments)) for comment in comments: text.append('<h3><a href="%s">%s</a> at %s:</h3>' % ( html_escape(comment["homepage"]), html_escape(comment["name"]), time.strftime("%c", comment["time"]), )) # Susceptible to XSS attacks!: text.append(comment["comments"]) return "".join(text) def submit_form(self, base_path, req): return """<h2>Leave a comment:</h2> <form action="%s/.comments" method="POST"> <input type="hidden" name="url" value="%s"> <table width="100%%"> <tr><td>Name:</td> <td><input type="text" name="name" style="width: 100%%"></td></tr> <tr><td>URL:</td> <td><input type="text" name="homepage" style="width: 100%%"></td></tr> </table> Comments:<br> <textarea name="comments" rows=10 style="width: 100%%"></textarea><br> <input type="submit" value="Submit comment"> </form> """ % ( base_path, html_escape(req.url), ) def process_comment(self, req): try: url = req.params["url"] name = req.params["name"] homepage = req.params["homepage"] comments = req.params["comments"] except KeyError, e: resp = exc.HTTPBadRequest("Missing parameter: %s" % e) return resp data = self.get_data(url) data.append( dict(name=name, homepage=homepage, comments=comments, time=time.gmtime())) self.save_data(url, data) resp = exc.HTTPSeeOther(location=url + "#comment-area") return resp