def choose_results_view(request): target_lang = util.get_target_lang_from_request(request) context = _base_context(request, target_lang) request_form = request.GET or request.POST # Special case: if anyone is linking to GPL/LGPL (mistake on old # deeds), redirect them to gnu.org if request_form.get('license_code') in ("GPL", "LGPL"): return exc.HTTPMovedPermanently( location='http://www.gnu.org/licenses/gpl-howto.html') # Select a license based on the request form license = _issue_license(request_form) # If the request didn't have all the required information, we have no license if not license: return exc.HTTPBadRequest( 'Could not determine license from parameters.') # If the license is retired, redirect to info page if license.deprecated: # Special case: PDCC should redirect to /publicdomain/ if license.license_code == 'publicdomain': return exc.HTTPMovedPermanently(location="/publicdomain/") else: return exc.HTTPMovedPermanently(location="/retiredlicenses") # Generate the HTML+RDFa for the license + provided work information work_dict = _formatter_work_dict(request_form) license_slim_logo = license.logo_method('80x15') license_html = HTML_FORMATTER.format(license, work_dict, target_lang) context.update({ 'license': license, 'license_slim_logo': license_slim_logo, 'license_title': license.title(target_lang), 'license_html': license_html }) if request.GET.get('partner'): context.update({ 'exit_url': _generate_exit_url(request_form.get('exit_url', ''), request_form.get('referrer', ''), license) }) if request.GET.get('partner'): return Response( util.render_template(request, target_lang, 'chooser_pages/partner/results.html', context)) else: return Response( util.render_template(request, target_lang, 'chooser_pages/results.html', context))
def __call__(self, environ, start_response): req = Request(environ) if req.path_info_peek() == '.media': req.path_info_pop() app = StaticURLParser(os.path.join(os.path.dirname(__file__), 'media')) return app(environ, start_response) if self.base_dir: filename = os.path.join(self.base_dir, req.path_info.lstrip('/')) assert filename.startswith(self.base_dir) else: filename = self.filename if req.method not in ('GET', 'POST'): resp = exc.HTTPMethodNotAllowed('Bad method: %s' % req.method, allow='GET,POST') elif os.path.isdir(filename): if req.method == 'POST': resp = self.save_create(req, filename) else: if not req.path.endswith('/'): resp = exc.HTTPMovedPermanently(add_slash=True) else: resp = self.view_dir(req, filename) else: if req.method == 'POST': resp = self.save_file(req, filename) elif req.method == 'GET': resp = self.edit_file(req, filename) return resp(environ, start_response)
def license_redirect(request): new_url = '/choose/' + request.matchdict.get('remaining_url', '') request_form = request.GET or request.POST if request_form: new_url = '%s?%s' % (new_url, urllib.urlencode(request_form)) return exc.HTTPMovedPermanently(location=new_url)
def dispatch(self, request, response): """Main routing method called by every request.""" # TODO(user): memoize this and override match, so that we don't # have to rematch again in the super default_dispatcher call. route, unused_args, unused_kwargs = self.match(request) # SSL redirect handling. Must come before auth handling. require_secure = getattr(route, 'require_secure', False) if require_secure and not request.scheme == 'https': redirect_url = 'https://{}{}'.format(request.server_name, request.path_qs) raise webob_exceptions.HTTPMovedPermanently(location=redirect_url) # Maybe redirect to login or raise 403 Forbidden for non-admins. require_login = getattr(route, 'require_login', False) require_admin = getattr(route, 'require_admin', False) if require_login or require_admin: user = users.get_current_user(oauth_scopes=users.OAUTH_SCOPES) if not user: login_url = users.create_login_url(dest_url=request.url) raise webob_exceptions.HTTPFound(location=login_url) elif require_admin and not user.is_admin: raise webob_exceptions.HTTPForbidden return super(_RouterWithMiddleware, self).default_dispatcher(request, response)
def proxy_to_file(self, request, dest): """Handle local ``file:`` URLs""" orig_base = request.application_url ## FIXME: security restrictions here? assert dest.startswith('file:') if '?' in dest: dest = dest.split('?', 1)[0] filename = url_to_filename(dest) rest = posixpath.normpath(request.path_info) proxied_url = dest.lstrip('/') + '/' + urllib.parse.quote( rest.lstrip('/')) ## FIXME: handle /->/index.html filename = filename.rstrip('/') + '/' + rest.lstrip('/') if os.path.isdir(filename): if not request.path.endswith('/'): new_url = request.path + '/' if request.query_string: new_url += '?' + request.query_string resp = exc.HTTPMovedPermanently(location=new_url) return resp, orig_base, dest, proxied_url ## FIXME: configurable? StaticURLParser? for base in ['index.html', 'index.htm']: if os.path.exists(os.path.join(filename, base)): filename = os.path.join(filename, base) break else: resp = exc.HTTPNotFound( "There was no index.html file in the directory") if not os.path.exists(filename): resp = exc.HTTPNotFound("The file %s could not be found" % filename) else: app = FileApp(filename) resp = request.get_response(app) return resp, orig_base, dest, proxied_url
def redirect(req, _log=pymagic.get_lazy_logger("redirect")): """ Redirect controller to emit a HTTP 301. """ log = req.environ.get("wsgilog.logger", _log) target = req.relative_url(req.urlvars.to) log.info("Redirecting '%s' to '%s'" % (req.url, target)) return exc.HTTPMovedPermanently(location=target)
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 on_incomplete_url(self, request, response): """An URL without an application name was received In: - ``request`` -- the web request object - ``response`` -- the web response object Return: - raise a ``webob.exc`` object, used to generate the response to the browser """ raise exc.HTTPMovedPermanently(add_slash=True)
def publicdomain_direct_redirect(request): """ /choose/publicdomain-direct used to point to PDCC, which has been retired, so we redirect to CC0. """ new_url = '/choose/zero/partner' request_form = request.GET or request.POST if request_form: new_url = '%s?%s' % (new_url, urlencode(request_form)) return exc.HTTPMovedPermanently(location=new_url)
def on_expired_session(self, request, response): """The session or state id received is expired In: - ``request`` -- the web request object - ``response`` -- the web response object Return: - raise a ``webob.exc`` object, used to generate the response to the browser """ raise exc.HTTPMovedPermanently()
def static(): tail = req.urlvars["static"] path = os.path.join(req.urlvars["pyxer.path"], tail) # Is it a folder? Or a link? if os.path.isdir(path) or os.path.islink(path): if (not tail) or tail.endswith("/"): path = os.path.join(path, "index.html") elif tail: location = (req.environ["PATH_INFO"] + "/") # XXX not tested! if request.environ.has_key("HTTP_X_FORWARDED_HOST"): # log.debug("URL (x) %r %r", obj, request.environ["HTTP_X_FORWARDED_HOST"]) location = "http://" + request.environ["HTTP_X_FORWARDED_HOST"] raise exc.HTTPMovedPermanently(location = location).exception if not os.path.isfile(path): raise exc.HTTPNotFound().exception return paste.fileapp.FileApp(path)(request.environ, request.start_response)
def _process(self, req): """ a request URL is parsed as follow /object/resource?args object is the main python object GET /object is mapped to handle_get function(**kwargs) GET /object/resource is mapped to handle_get([resource,], **kwargs) GET /object/resource/resource2 is mapped to handle_get([resource,resource2], **kwargs) args are always passed on through **kwargs """ method = req.method object = req.path_info_pop() #do some static file serving logic first before trying functions on objects if object == None or object == "": #the root / is moved to static file serving res = exc.HTTPMovedPermanently(location="/static/") return res elif object == "static": # In here we are handling real files so be careful!!! if method == "GET": # simply serving static files #import os #print(os.getcwd()) res = static.DirectoryApp(self._httpdRoot) return res if method == "POST": # uploading new files filename = req.path_info_pop() filepath = os.path.join(os.path.join(self._httpdRoot, filename)) # if the file exists we raise an exception if filename == "": filename = req.params['file'] if os.path.exists(filepath): raise exc.HTTPForbidden("%s already exists" % filename) #print(dir(req)) #print(req.body) saveFile = open(os.path.join(self._httpdRoot, filename), 'wb') saveFile.write(req.body_file.read()) saveFile.close() return Response("ok") if method == "PUT": # This will overwrite your files # uploading files to update filename = req.path_info_pop() filepath = os.path.join(os.path.join(self._httpdRoot, filename)) # if the file exists we raise an exception if not os.path.exists(filepath): raise exc.HTTPNotFound("%s file not found" % filename) if filename == "": filename = req.params['file'] #print(dir(req)) #print(req.body) saveFile = open(os.path.join(self._httpdRoot, filename), 'wb') saveFile.write(req.body_file.read()) saveFile.close() return Response("ok") ################################################# # # After this we only handle JSON type content!!!! # ################################################# #Find the object obj = None try: obj = self._restObjects[object] except: #print(self._restObjects) #print(dir(self._restObjects)) raise exc.HTTPNotFound('No such resource: %s' % object) #Find the function func = None try: func = getattr(obj, 'handle_' + method) except: raise exc.HTTPNotFound('No %s method on resource: %s' % (method, object)) # Find resources: resources = [] # get first resource res = req.path_info_pop() while res: resources.append(res) # get next resource res = req.path_info_pop() #optional extra headers #FIXME: this shouldn't be hardcoded. The appie modules should take care of this #http://www.w3.org/TR/cors/#syntax extraHeaderList = [ ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS'), ('Access-Control-Max-Age', '86400'), ('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' ) ] #Get args kwargs = req.GET if (method == 'POST'): #curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d #curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"test" : "help" }' http://localhost:8000/bge/IcoSphere if req.content_type == 'application/json': encoding = req.charset body = req.body.decode(encoding) data = loads(body) #print(data) #print(type(data)) kwargs = data else: kwargs = req.POST try: result = func(*resources, **kwargs) except: raise exc.HTTPInternalServerError( "Appie raised an exception while calling the method with %s %s" % (str(resources), str(kwargs))) resp = Response(content_type='application/json', charset='utf8', body=dumps(result)) resp.headerlist.extend(extraHeaderList) return resp
def moved_permanently_redirect(request): """ General method for redirecting to something that's moved permanently """ return exc.HTTPMovedPermanently(location=request.matchdict['redirect_to'])
def gpl_redirect(request): """ Redirect GPL and the LGPL to the appropriate location on gnu.org """ return exc.HTTPMovedPermanently( location='http://www.gnu.org/licenses/gpl-howto.html')
def outdated_choosers_redirect(request): """ A couple of URLs (/choose/music and /choose/sampling) are outdated and so should redirect to the old chooser. """ return exc.HTTPMovedPermanently(location='/choose/')
def choose_wiki_redirect(request): return exc.HTTPMovedPermanently( location='/choose/results-one?license_code=by-sa')
def chooser_view(request): # Preserve the old partner interface by calling the old chooser view.. if request.GET.get('partner'): return classic_chooser_view(request) # # Used by the new-style chooser demos, for now. # target_lang = util.get_target_lang_from_request(request) context = _base_context(request, target_lang) request_form = request.GET or request.POST gettext = context['gettext'] available_jurisdiction_codes = [ j.code for j in get_selector_jurisdictions('standard') if j.code != '' ] requested_jurisdiction = None if request.GET.has_key('jurisdiction') and \ request.GET['jurisdiction'] in available_jurisdiction_codes: requested_jurisdiction = request.GET['jurisdiction'] # Sort the jurisdictions for the dropdown via the translated name jurisdictions_names = [(juris, gettext(mappers.COUNTRY_MAP[juris])) for juris in available_jurisdiction_codes] jurisdictions_names = sorted(jurisdictions_names, key=lambda juris: juris[1]) show_jurisdiction = request.GET.get('jurisdiction_choose') == '1' # Select a license based on the request form license = _issue_license(request_form) # Sets form default values, based on the request form or lack thereof defaults = { "license": { "nc": False, "sa": False, "nd": False, "jurisdiction": "", "currency": "", }, "meta": { "standard": "html+rdfa", "format": "", "title": "", "attrib_name": "", "attrib_url": "", "src_url": "", "permissions": "", }, "out": { "format": "html", "badge": "normal", }, "misc": { "lang": "", } } def equal_or_default(field, value, default=False): if request_form.has_key(field): return request_form[field] == value else: return default def value_or_default(field, default=""): if request_form.has_key(field): return unquote(request_form[field]).encode("utf-8") else: return default if request_form: defaults["license"] = { "nc": equal_or_default('field_commercial', u'n'), "sa": equal_or_default('field_derivatives', u'sa'), "nd": equal_or_default('field_derivatives', u'n'), "jurisdiction": value_or_default('field_jurisdiction'), "currency": util.currency_symbol_from_request_form(request_form), } defaults["meta"] = { "standard": value_or_default("field_metadata_standard", "html+rdfa"), "format": value_or_default("field_format"), "title": value_or_default("field_worktitle"), "attrib_name": value_or_default("field_attribute_to_name"), "attrib_url": value_or_default("field_attribute_to_url"), "src_url": value_or_default("field_sourceurl"), "permissions": value_or_default("field_morepermissionsurl"), } defaults["out"]["badge"] = value_or_default("field_iconsize", "normal") defaults["misc"] = { "lang": value_or_default("lang", ""), } # If the license is retired, redirect to info page if license.deprecated: # Special case: PDCC should redirect to /publicdomain/ if license.license_code == 'publicdomain': return exc.HTTPMovedPermanently(location="/publicdomain/") else: return exc.HTTPMovedPermanently(location="/retiredlicenses") # Generate the HTML+RDFa for the license + provided work information work_dict = _formatter_work_dict(request_form) license_norm_logo = license.logo_method('88x13') license_slim_logo = license.logo_method('80x15') picked_logo = { "normal": license_norm_logo, "small": license_slim_logo }[defaults['out']['badge']] license_html = HTML_FORMATTER.format(license, work_dict, target_lang) if defaults['out']['badge'] == u"small": license_html = license_html.replace("88x31.png", "80x15.png") def has_code(code): return license.license_code.count(code) >= 1 context.update({ 'jurisdictions_names': jurisdictions_names, 'show_jurisdiction': show_jurisdiction, 'requested_jurisdiction': requested_jurisdiction, 'referrer': request.headers.get('REFERER', ''), 'page_style': '2cols', 'last_query': request.query_string, 'form': defaults, 'currency': util.currency_symbol_from_request_form(request_form), 'license': license, 'license_logo': picked_logo, 'license_norm_logo': license_norm_logo, 'license_slim_logo': license_slim_logo, 'license_title': license.title(target_lang), 'license_html': license_html, 'license_code': { 'sa': has_code('sa'), 'nc': has_code('nc'), 'nd': has_code('nd'), }, }) return Response( util.render_template(request, target_lang, 'chooser_pages/interactive_chooser.html', context))
def permanent_redirect(url): try: tg.redirect(url) except exc.HTTPFound, err: raise exc.HTTPMovedPermanently(location=err.location)
def work_html_redirect(request): new_url = '/choose/work-html-popup' if request.GET: new_url = '%s?%s' % (new_url, urllib.urlencode(request.GET)) return exc.HTTPMovedPermanently(location=new_url)