Python flask.make_response() Examples

The following are 30 code examples of flask.make_response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: server.py    From grlc with MIT License 8 votes vote down vote up
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
    """Execute SPARQL query for a specific grlc-generated API endpoint"""
    glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
    glogger.debug("Request accept header: " + request.headers["Accept"])

    requestArgs = request.args
    acceptHeader = request.headers['Accept']
    requestUrl = request.url
    formData = request.form

    query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
                                                           sha=sha, content=content, requestArgs=requestArgs,
                                                           acceptHeader=acceptHeader,
                                                           requestUrl=requestUrl, formData=formData)
    if isinstance(query_response, list):
        query_response = jsonify(query_response)

    return make_response(query_response, status, headers)

### Server routes ### 
Example #2
Source File: server.py    From BASS with GNU General Public License v2.0 7 votes vote down vote up
def function_raw_hash_get():
    global Session
    session = Session()
    filename, file_ = request.files.items()[0]
    db = Database(pickle.load(file_))

    arch_name = db.architecture_name
    if arch_name == "metapc":
        arch_name = "x86"
    try:
        arch = session.query(Architecture).filter(Architecture.name == arch_name and \
                Architecture.bits == db.architecture_bits and \
                Architecture.little_endian == db.architecture_endianness == "little").one()
    except NoResultFound:
        return make_response(jsonify(message = "Architecture not found"), 404)
    
    try:
        func = next(db.functions)
    except StopIteration:
        return make_response(jsonify(message = "No function found in database"), 500)

    raw_hash = _function_calculate_raw_sha256(func)
    size = _function_get_size(func)

    try:
        function = session.query(Function).filter(Function.raw_sha256 == raw_hash and \
                Function.size == size and \
                Function.arch == arch.id).one()
        return make_response(jsonify(**json.loads(function.data)), 200)
    except NoResultFound:
        return make_response(jsonify(message = "Function not found"), 404) 
Example #3
Source File: decorators.py    From api-pycon2014 with MIT License 7 votes vote down vote up
def rate_limit(limit, per, scope_func=lambda: request.remote_addr):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            if current_app.config['USE_RATE_LIMITS']:
                key = 'rate-limit/%s/%s/' % (f.__name__, scope_func())
                limiter = RateLimit(key, limit, per)
                if not limiter.over_limit:
                    rv = f(*args, **kwargs)
                else:
                    rv = too_many_requests('You have exceeded your request rate')
                #rv = make_response(rv)
                g.headers = {
                    'X-RateLimit-Remaining': str(limiter.remaining),
                    'X-RateLimit-Limit': str(limiter.limit),
                    'X-RateLimit-Reset': str(limiter.reset)
                }
                return rv
            else:
                return f(*args, **kwargs)
        return wrapped
    return decorator 
Example #4
Source File: __init__.py    From beavy with Mozilla Public License 2.0 6 votes vote down vote up
def api_only(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        accepted = set(request.accept_mimetypes.values())
        explicit = not(not request.args.get("json", False))
        if not (accepted & API_MIMETYPES) and not explicit:
            return abort(415, "Unsupported Media Type")

        resp = fn(*args, **kwargs)
        if not isinstance(resp, ResponseBase):
            data, code, headers = unpack(resp)
            # we've found one, return json
            if isinstance(data, MarshalResult):
                data = data.data
            resp = make_response(json.dumps(data,
                                            indent=explicit and 4 or 0),
                                 code)

            if headers:
                resp.headers.update(headers)
            resp.headers["Content-Type"] = 'application/json'
        return resp
    return wrapped 
Example #5
Source File: welcome.py    From github-stats with MIT License 6 votes vote down vote up
def organization():
  limit = min(int(util.param('limit', int) or flask.request.cookies.get('limit') or config.MAX_DB_LIMIT), config.MAX_DB_LIMIT)
  order = util.param('order') or '-stars'
  if 'repo' in order:
    order = '-public_repos'

  organization_dbs, organization_cursor = model.Account.get_dbs(
      order=order,
      organization=True,
      limit=limit,
    )

  response = flask.make_response(flask.render_template(
    'account/list_organization.html',
    title='Organizations',
    description='Top Organizations on GitHub',
    html_class='account-organization',
    organization_dbs=organization_dbs,
    order=order,
    limit=limit,
  ))
  response.set_cookie('limit', str(limit))
  return response 
Example #6
Source File: welcome.py    From github-stats with MIT License 6 votes vote down vote up
def person():
  limit = min(int(util.param('limit', int) or flask.request.cookies.get('limit') or config.MAX_DB_LIMIT), config.MAX_DB_LIMIT)
  order = util.param('order') or '-stars'
  if 'repo' in order:
    order = '-public_repos'
  elif 'follower' in order:
    order = '-followers'

  person_dbs, person_cursor = model.Account.get_dbs(
      order=order,
      organization=False,
      limit=limit,
    )

  response = flask.make_response(flask.render_template(
    'account/list_person.html',
    title='People',
    description='Top People on GitHub',
    html_class='account-person',
    person_dbs=person_dbs,
    order=order,
    limit=limit,
  ))
  response.set_cookie('limit', str(limit))
  return response 
Example #7
Source File: helper.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def do_download_file(book, book_format, client, data, headers):
    if config.config_use_google_drive:
        startTime = time.time()
        df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format)
        log.debug('%s', time.time() - startTime)
        if df:
            return gd.do_gdrive_download(df, headers)
        else:
            abort(404)
    else:
        filename = os.path.join(config.config_calibre_dir, book.path)
        if not os.path.isfile(os.path.join(filename, data.name + "." + book_format)):
            # ToDo: improve error handling
            log.error('File not found: %s', os.path.join(filename, data.name + "." + book_format))

        if client == "kobo" and book_format == "kepub":
            headers["Content-Disposition"] = headers["Content-Disposition"].replace(".kepub", ".kepub.epub")

        response = make_response(send_from_directory(filename, data.name + "." + book_format))
        # ToDo Check headers parameter
        for element in headers:
            response.headers[element[0]] = element[1]
        return response

################################## 
Example #8
Source File: decorators.py    From api-pycon2014 with MIT License 6 votes vote down vote up
def etag(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        # only for HEAD and GET requests
        assert request.method in ['HEAD', 'GET'],\
            '@etag is only supported for GET requests'
        rv = f(*args, **kwargs)
        rv = make_response(rv)
        etag = '"' + hashlib.md5(rv.get_data()).hexdigest() + '"'
        rv.headers['ETag'] = etag
        if_match = request.headers.get('If-Match')
        if_none_match = request.headers.get('If-None-Match')
        if if_match:
            etag_list = [tag.strip() for tag in if_match.split(',')]
            if etag not in etag_list and '*' not in etag_list:
                rv = precondition_failed()
        elif if_none_match:
            etag_list = [tag.strip() for tag in if_none_match.split(',')]
            if etag in etag_list or '*' in etag_list:
                rv = not_modified()
        return rv
    return wrapped 
Example #9
Source File: views_default_to_current_conversation.py    From python-slackclient with MIT License 6 votes vote down vote up
def slack_app():
    if not signature_verifier.is_valid_request(request.get_data(), request.headers):
        return make_response("invalid request", 403)

    if "command" in request.form \
        and request.form["command"] == "/view":
        trigger_id = request.form["trigger_id"]
        return open_modal(trigger_id)

    elif "payload" in request.form:
        payload = json.loads(request.form["payload"])
        if payload["type"] == "view_submission" \
            and payload["view"]["callback_id"] == "modal-id":
            submitted_data = payload["view"]["state"]["values"]
            print(submitted_data)  # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
            return make_response("", 200)
        if payload["type"] == "shortcut" \
            and payload["callback_id"] == "view-test":
            return open_modal(payload["trigger_id"])

    return make_response("", 404) 
Example #10
Source File: issue_497.py    From python-slackclient with MIT License 6 votes vote down vote up
def per_request():
    try:
        client = WebClient(
            token=os.environ["SLACK_BOT_TOKEN"],
            run_async=False
        )
        response = client.chat_postMessage(
            channel="#random",
            text="You used a new WebClient for posting this message!"
        )
        return str(response)
    except SlackApiError as e:
        return make_response(str(e), 400)


# This doesn't work 
Example #11
Source File: issue_497.py    From python-slackclient with MIT License 6 votes vote down vote up
def per_request_async():
    try:
        # This is not optimal and the host should have a large number of FD (File Descriptor)
        loop_for_this_request = asyncio.new_event_loop()

        async_client = WebClient(
            token=os.environ["SLACK_BOT_TOKEN"],
            run_async=True,
            loop=loop_for_this_request
        )
        future = async_client.chat_postMessage(
            channel="#random",
            text="You used the singleton WebClient for posting this message!"
        )
        response = loop_for_this_request.run_until_complete(future)
        return str(response)
    except SlackApiError as e:
        return make_response(str(e), 400) 
Example #12
Source File: admin.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def list_domain(allow):
    answer = ub.session.query(ub.Registration).filter(ub.Registration.allow == allow).all()
    json_dumps = json.dumps([{"domain": r.domain.replace('%', '*').replace('_', '?'), "id": r.id} for r in answer])
    js = json.dumps(json_dumps.replace('"', "'")).lstrip('"').strip('"')
    response = make_response(js.replace("'", '"'))
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response 
Example #13
Source File: main.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def export(deck_id: int) -> Response:
    d = ds.load_deck(deck_id)
    if d.is_in_current_run():
        if not session.get('admin') and (not auth.person_id() or auth.person_id() != d.person_id):
            abort(403)
    safe_name = deck_name.file_name(d)
    return make_response(mc.to_mtgo_format(str(d)), 200, {'Content-type': 'text/plain; charset=utf-8', 'Content-Disposition': 'attachment; filename={name}.txt'.format(name=safe_name)}) 
Example #14
Source File: views_default_to_current_conversation.py    From python-slackclient with MIT License 5 votes vote down vote up
def open_modal(trigger_id: str):
    try:
        view = View(
            type="modal",
            callback_id="modal-id",
            title=PlainTextObject(text="Awesome Modal"),
            submit=PlainTextObject(text="Submit"),
            close=PlainTextObject(text="Cancel"),
            blocks=[
                InputBlock(
                    block_id="b-id-1",
                    label=PlainTextObject(text="Input label"),
                    element=ConversationSelectElement(
                        action_id="a",
                        default_to_current_conversation=True,
                    )
                ),
                InputBlock(
                    block_id="b-id-2",
                    label=PlainTextObject(text="Input label"),
                    element=ConversationMultiSelectElement(
                        action_id="a",
                        max_selected_items=2,
                        default_to_current_conversation=True,
                    )
                ),
            ]
        )
        response = client.views_open(
            trigger_id=trigger_id,
            view=view
        )
        return make_response("", 200)
    except SlackApiError as e:
        code = e.response["error"]
        return make_response(f"Failed to open a modal due to {code}", 200) 
Example #15
Source File: admin.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def list_restriction(res_type):
    if res_type == 0:   # Tags as template
        restrict = [{'Element': x, 'type':_('Deny'), 'id': 'd'+str(i) }
                    for i,x in enumerate(config.list_denied_tags()) if x != '' ]
        allow = [{'Element': x, 'type':_('Allow'), 'id': 'a'+str(i) }
                 for i,x in enumerate(config.list_allowed_tags()) if x != '']
        json_dumps = restrict + allow
    elif res_type == 1:  # CustomC as template
        restrict = [{'Element': x, 'type':_('Deny'), 'id': 'd'+str(i) }
                    for i,x in enumerate(config.list_denied_column_values()) if x != '' ]
        allow = [{'Element': x, 'type':_('Allow'), 'id': 'a'+str(i) }
                 for i,x in enumerate(config.list_allowed_column_values()) if x != '']
        json_dumps = restrict + allow
    elif res_type == 2:  # Tags per user
        usr_id = os.path.split(request.referrer)[-1]
        if usr_id.isdigit() == True:
            usr = ub.session.query(ub.User).filter(ub.User.id == usr_id).first()
        else:
            usr = current_user
        restrict = [{'Element': x, 'type':_('Deny'), 'id': 'd'+str(i) }
                    for i,x in enumerate(usr.list_denied_tags()) if x != '' ]
        allow = [{'Element': x, 'type':_('Allow'), 'id': 'a'+str(i) }
                 for i,x in enumerate(usr.list_allowed_tags()) if x != '']
        json_dumps = restrict + allow
    elif res_type == 3:  # CustomC per user
        usr_id = os.path.split(request.referrer)[-1]
        if usr_id.isdigit() == True:
            usr = ub.session.query(ub.User).filter(ub.User.id==usr_id).first()
        else:
            usr = current_user
        restrict = [{'Element': x, 'type':_('Deny'), 'id': 'd'+str(i) }
                    for i,x in enumerate(usr.list_denied_column_values()) if x != '' ]
        allow = [{'Element': x, 'type':_('Allow'), 'id': 'a'+str(i) }
                 for i,x in enumerate(usr.list_allowed_column_values()) if x != '']
        json_dumps = restrict + allow
    else:
        json_dumps=""
    js = json.dumps(json_dumps)
    response = make_response(js.replace("'", '"'))
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response 
Example #16
Source File: about.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def about_gp() -> Response:
    return make_response(redirect(url_for('about', src='gp'))) 
Example #17
Source File: league.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def retire_deck() -> wrappers.Response:
    form = RetireForm(request.form, discord_user=session.get('id'))
    if form.validate():
        d = ds.load_deck(form.entry)
        ps.associate(d, session['id'])
        lg.retire_deck(d)
        return redirect(url_for('signup'))
    return make_response(retire(form)) 
Example #18
Source File: views_2.py    From python-slackclient with MIT License 5 votes vote down vote up
def slack_app():
    if not signature_verifier.is_valid_request(request.get_data(), request.headers):
        return make_response("invalid request", 403)

    if "command" in request.form \
        and request.form["command"] == "/open-modal":
        trigger_id = request.form["trigger_id"]
        try:
            view = View(
                type="modal",
                callback_id="modal-id",
                title=PlainTextObject(text="Awesome Modal"),
                submit=PlainTextObject(text="Submit"),
                close=PlainTextObject(text="Cancel"),
                blocks=[
                    InputBlock(
                        block_id="b-id",
                        label=PlainTextObject(text="Input label"),
                        element=PlainTextInputElement(action_id="a-id")
                    )
                ]
            )
            response = client.views_open(
                trigger_id=trigger_id,
                view=view
            )
            return make_response("", 200)
        except SlackApiError as e:
            code = e.response["error"]
            return make_response(f"Failed to open a modal due to {code}", 200)

    elif "payload" in request.form:
        payload = json.loads(request.form["payload"])
        if payload["type"] == "view_submission" \
            and payload["view"]["callback_id"] == "modal-id":
            submitted_data = payload["view"]["state"]["values"]
            print(submitted_data)  # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
            return make_response("", 200)

    return make_response("", 404) 
Example #19
Source File: league.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def add_report() -> Response:
    form = ReportForm(request.form)
    if form.validate() and lg.report(form):
        response = make_response(redirect(url_for('deck', deck_id=form.entry)))
        response.set_cookie('deck_id', form.entry)
        return response
    return report(form) 
Example #20
Source File: issue_497.py    From python-slackclient with MIT License 5 votes vote down vote up
def singleton_async():
    try:
        future = singleton_async_client.chat_postMessage(
            channel="#random",
            text="You used the singleton WebClient for posting this message!"
        )
        # blocking here!!!
        # as described at https://github.com/slackapi/python-slackclient/issues/497
        # until this completion, other simultaneous requests get "RuntimeError: This event loop is already running"
        response = singleton_loop.run_until_complete(future)
        return str(response)
    except SlackApiError as e:
        return make_response(str(e), 400) 
Example #21
Source File: resources.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def rotation_speculation_files(changes_type: str) -> Response:
    out = changes_type != 'new'
    changes = oracle.if_todays_prices(out=out)
    s = '\n'.join('4 {name}'.format(name=c.name) for c in changes)
    return make_response(s, 200, {'Content-type': 'text/plain; charset=utf-8', 'Content-Disposition': f'attachment; filename={changes_type}.txt'}) 
Example #22
Source File: resources.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def rotation_changes_files(changes_type: str) -> Response:
    changes = oracle.pd_rotation_changes(get_season_id())[0 if changes_type == 'new' else 1]
    s = '\n'.join('4 {name}'.format(name=c.name) for c in changes)
    return make_response(s, 200, {'Content-type': 'text/plain; charset=utf-8', 'Content-Disposition': f'attachment; filename={changes_type}.txt'}) 
Example #23
Source File: main.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def image(c: str = '') -> wrappers.Response:
    names = c.split('|')
    try:
        requested_cards = oracle.load_cards(names)
        path = image_fetcher.download_image(requested_cards)
        if path is None:
            raise InternalServerError(f'Failed to get image for {c}')
        return send_file(os.path.abspath(path)) # Send abspath to work around monolith root versus web root.
    except TooFewItemsException as e:
        logger.info(f'Did not find an image for {c}: {e}')
        if len(names) == 1:
            return redirect(f'https://api.scryfall.com/cards/named?exact={c}&format=image', code=303)
        return make_response('', 400) 
Example #24
Source File: welcome.py    From github-stats with MIT License 5 votes vote down vote up
def repo():
  limit = min(int(util.param('limit', int) or flask.request.cookies.get('limit') or config.MAX_DB_LIMIT), config.MAX_DB_LIMIT * 4)
  order = util.param('order') or '-stars'
  if 'fork' in order:
    order = '-forks'
  repo_dbs, repo_cursor = model.Repo.get_dbs(
      order=order,
      limit=limit,
    )

  response = flask.make_response(flask.render_template(
      'account/list_repo.html',
      title='Repositories',
      description='Top Repositories on GitHub',
      html_class='account-repo',
      repo_dbs=repo_dbs,
      order=order.replace('-', ''),
      limit=limit,
    ))
  response.set_cookie('limit', str(limit))
  return response


###############################################################################
# Sitemap stuff
############################################################################### 
Example #25
Source File: base_view.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def response(self) -> wrappers.Response:
        return make_response(self.page()) 
Example #26
Source File: decorators.py    From api-pycon2014 with MIT License 5 votes vote down vote up
def cache_control(*directives):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            rv = f(*args, **kwargs)
            rv = make_response(rv)
            rv.headers['Cache-Control'] =', '.join(directives)
            return rv
        return wrapped
    return decorator 
Example #27
Source File: views.py    From Simpleblog with MIT License 5 votes vote down vote up
def show_followed(nickname):
    resp = make_response(redirect(url_for('user.follows',nickname=nickname)))
    resp.set_cookie('show_followed','',max_age=30*24*60*60)
    return resp

# 全文搜索 
Example #28
Source File: views.py    From Simpleblog with MIT License 5 votes vote down vote up
def show_follower(nickname):
    resp = make_response(redirect(url_for('user.follows',nickname=nickname)))
    resp.set_cookie('show_followed','1',max_age=30*24*60*60)
    return resp 
Example #29
Source File: factory-package-news-web.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def diff(version):
    _dir = get_dir(request.url_root)
    fn = os.path.join(_dir, 'current')
    if not os.path.exists(fn):
        return "current version doesn't exist", 404
    if not os.path.exists(os.path.join(_dir, version)):
        return "invalid version", 400
    import subprocess
    cmd = [os.path.dirname(os.path.abspath(__file__)) + '/factory-package-news.py',
            'diff', '--dir', _dir, "current", version]
    app.logger.debug(cmd)
    response = make_response(subprocess.check_output(cmd))
    response.content_type = "text/plain"
    return response 
Example #30
Source File: router.py    From maple-file with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self, filename):
        config = current_app.config
        width = request.args.get("width", 0, type=int)
        height = request.args.get("height", 0, type=int)
        if width or height:
            img = os.path.join(config['UPLOAD_FOLDER'], filename)
            stream = gen_thumb_image(img, width, height)
            buf_value = stream.getvalue()
            response = make_response(buf_value)
            response.headers['Content-Type'] = 'image/jpeg'
            return response
        return send_from_directory(config['UPLOAD_FOLDER'], filename)