def as_response(self, template=None, data=None, _in_decorator=False, _stream=False, **response_kwargs): """ Return a response object for the rendered template:: >>> from jinja2 import PackageLoader >>> from fresco import FrescoApp >>> app = FrescoApp() >>> render = Jinja2(app, loader=PackageLoader('myapp', 'tmpls')) >>> response = render.as_response('my_template.html', ... {'foo': 'bar'}) #doctest: +SKIP Can also be used as a decorator. The decorated function will merge the original function's return value (a dict) with the specified template:: >>> render = Jinja2(app, loader=PackageLoader('myapp', 'tmpls')) >>> >>> @render.as_response('my_template.html') #doctest: +SKIP ... def handler(request): ... return {'foo': 'bar'} ... """ if data is None and not _in_decorator: return _make_decorator_or_filter(self.as_response, template, **response_kwargs) return Response( TemplateContent(self, template, data, None, stream=_stream), **response_kwargs)
def record_trial_app(self, environ, start_response): request = Request(environ) experiment = request.query.get('e') try: record_trial(environ, experiment) except KeyError: pass return Response([], cache_control="no-cache")(environ, start_response)
def confirm_email(request, token): conn = request.getconn() with queries.transaction(conn): supporter_id = supporters.confirm_email(conn, token) if supporter_id is None: return piglet.render("default/invalid-confirmation-token.html", {}) request.remember_user_id(supporter_id) return Response.redirect(support_step, _query={"step": 2})
def support_step_submit(request): step = request.getint("step", None) if step is None or not request.is_authenticated(): return Response.redirect(support_us) conn = request.getconn() if step in (2, 3) and "skip" not in request: form = SupporterForm() form.bind_input(request.form) if form.errors: raise AssertionError( f"Form validation failed unexpectedly: {form.errors!r}") with queries.transaction(conn): supporters.update_profile(conn, id=request.get_user_id(), **form.data) return Response.redirect(support_step, _query={"step": step + 1})
def oauth_callback(request, provider): session = request.session state = object_or_404(session.get("oauth_state"), Forbidden) code = object_or_404(request.get("code")) profile = fetch_profile(provider, state, code, request.url) conn = request.getconn() with queries.transaction(conn): user_id, is_new = supporters.add_supporter_from_social_profile( conn, provider, profile) supporters.download_social_image(conn, user_id) request.remember_user_id(user_id) if not is_new: return Response.redirect(existing_support) return Response.redirect(support_step, _query={"step": 2})
def save_results(): context.request.MAX_SIZE = 200 * 1024 results = context.request.form.get('results') prolific_id = context.request.form.get('ID') with open('results/{}.json'.format(prolific_id), 'w') as f: f.write(results) return Response('')
def filepond_upload(request, media_dir="media/"): """ See https://pqina.nl/filepond/docs/patterns/api/server/ Expects a single field with two values: metadata, then upload """ form = request.form key = next(form.keys()) metadata, upload = form.getlist(key) filename = fileuploads.upload(media_dir, upload) return Response([filename], content_type="text/plain")
def submit_suggestion(request): conn = request.getconn() supporter_id = request.get_user_id() if supporter_id: supporter = supporters.get_supporter_by_id(conn, supporter_id) else: supporter = None suggestion = request.get("suggestion") suggestions.send_suggestion(conn, supporter, suggestion) return Response(headers=[("X-HX-Trigger", "suggestionSubmitted")])
def json_response(data=_marker, indent=None, separators=(',', ':'), content_type='application/json', **kwargs): """ JSON encode the function's result and return a response object with the content-type ``application/json``. May also be used as a regular function to directly create a JSON encoded response, however it's preferrable to use :meth:`~fresco.response.Response.json` for this. :param data: The data to json encode. If left unspecified, ``json_response`` will act as a function decorator. :param indent: The indent level. Defaults to ``None`` (no pretty printing) :param separators: Defaults to ``(',', ':')`` for the most compact JSON representation :param kwargs: Other keyword arguments are passed to ``json.dumps``. These may be used to change encoding paramters, for example overriding the default ``JSONEncoder`` class. """ # Called as a decorator or decorator factory if data is _marker or callable(data): def json_response_decorator(func): @wraps(func) def json_response_decorated(*fa, **fkw): return Response.json(func(*fa, **fkw), indent, separators, **kwargs) return json_response_decorated # Called as a decorator factory (``@json_response()``) if data is _marker: return json_response_decorator # Called as a decorator (ie no parens: ``@json_response``) return json_response_decorator(data) # Called as a regular function (or via ``Route(...).filter``) else: if isinstance(data, Response): return data return Response.json(data, indent=indent, separators=separators, content_type=content_type, **kwargs)
def oauth_login(request, provider, already_logged_in_redirect="index"): app = context.app session = request.session credentials = object_or_404(app.options.OAUTH_CREDENTIALS.get(provider)) provider_info = object_or_404(OAUTH_PROVIDERS.get(provider)) # if request.is_authenticated(): # return Response.redirect(already_logged_in_redirect) oauth = get_oauth2session(provider, credentials["id"]) url, session["oauth_state"] = oauth.authorization_url( provider_info["authorization_base_url"]) return Response.redirect(url)
def support_us_email(request): email = request.get("email", "").strip().lower() try: validate_email(email) except EmailNotValidError: flash.info("veuillez vérifier votre adresse e-mail") return support_us(request) conn = request.getconn() with queries.transaction(conn): user_id, is_new = supporters.add_supporter_from_email(conn, email) if not is_new: return Response.redirect(existing_support) supporters.send_confirmation_email( supporter_id=user_id, email=email, get_confirmation_url=lambda token: urlfor("confirm-email", token=token ), ) return Response.redirect(email_needs_confirmation, email=email)
def support_step(request): step = request.getint("step", None) if step is None or not request.is_authenticated(): return Response.redirect(support_us) conn = request.getconn() supporter = supporters.get_supporter_by_id(conn, request.get_user_id()) if supporter is None: return Response.redirect(support_us) occupation_options = supporters.occupation_options(conn) year_of_birth_range_options = supporters.year_of_birth_range_options( supporter) template = f"default/support-us-step-{step}.html" return piglet.render( template, { "step": step, "is_new": request.get("is_new"), "supporter": supporter, "occupation_options": occupation_options, "year_of_birth_range_options": year_of_birth_range_options, }, )
def serve_path(self, path="", splitext=os.path.splitext): for action, path in self.get_candidate_paths(path): if action == "redirect": return Response.redirect(urlfor(self.serve_path, path=path)) elif action == "serve": ext = splitext(path)[1].lower() if ext in self.responders: response = self.responders[ext](path) else: response = self.responder(path) if response is not None: return response elif action == "index": if self.make_index: response = self.make_index(path) if response is not None: return response raise NotFound()
def __init__( self, search_path, search_extensions=[], directory_indexes=[], rewriter=None, responder=None, responders=None, make_index=None, route_name=None, ): """ :param search_path: List of directories to search for content :param search_extensions: List of extensions to append to path (eg ``['.txt', '.md']`` etc). An extension will always be added, so if you want to be able to have the extension in the url you need to have ``''`` at the start of the list, eg ``['', '.htm', '.html']``. :param directory_indexes: List of default directory index filenames (eg ``['index.txt', 'readme.txt']`` etc) :param rewriter: Function that takes a virtual path and returns a list of virtual paths to serve. :param responder: Function that takes a file path and returns a response (or None if the file can't be served). :param responders: mapping of {<file extension>: responder} :param route_name: passed as the 'name' argument to fresco.routing.Route """ self.search_path = search_path self.rewriter = rewriter self.directory_indexes = directory_indexes self.search_extensions = [(ext if ext.startswith(".") else "." + ext) for ext in search_extensions] self.responder = responder if responders: self.responders = {(s if s.startswith(".") else f".{s}").lower(): fn for s, fn in responders.items()} else: self.responders = {} self.route_name = route_name self.make_index = ( make_index if make_index is not None else lambda p: Response.forbidden("Directory listing denied"))
def json_response_decorated(*fa, **fkw): return Response.json(func(*fa, **fkw), indent, separators, **kwargs)
def petition_count(request): count = supporters.supporter_count(request.getconn()) + 31300 return Response(request.format(count)).add_headers( cache_control="must-revalidate, max-age=3", vary="cookie")