flask.Response

Here are the examples of the python api flask.Response taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

181 Examples 7

Example 1

Project: hualos Source File: api.py
Function: subscribe
@app.route("/subscribe/epoch/end/")
def subscribe():
    def gen():
        q = Queue()
        subscriptions.append(q)
        try:
            while True:
                result = q.get()
                event = ServerSentEvent(str(result))
                yield event.encode()
        except GeneratorExit:
            subscriptions.remove(q)

    return Response(gen(), mimetype="text/event-stream")

Example 2

Project: flask-docjson Source File: tests.py
    def test_validate_empty_string_response(self):
        assert m.validate_response(Response('', 201), [{'status_code': [201],
                                                        'schema': None}]) is \
            None
        assert m.validate_response(('', 201), [{'status_code': [201],
                                                'schema': None}]) is \
            None

Example 3

Project: bitHopper Source File: Data_Page.py
@app.route("/data", methods=['POST', 'GET'])
def data():
    response = {}
    response['current'] = ', '.join([s.name for s in get_current_servers()])
    response['mhash'] = get_hashrate() 
    response['diffs'] = dict([(coin.name, float(coin.difficulty)) for coin in btcnet_info.get_coins() if coin.difficulty])
    response['sliceinfo'] = None
    response['servers'] = list(transform_data(btcnet_info.get_pools())) 
    response['user'] = None
    
    return Response(json.dumps(response), mimetype='text/json') 

Example 4

Project: aurora Source File: views.py
Function: export
@stages.route('/export/<int:id>/fabfile.py')
def export(id):
    stage = get_or_404(Stage, id=id)

    deployment = Deployment(stage=stage, tasks=stage.tasks)
    return Response(deployment.code, mimetype='application/python')

Example 5

Project: flask-cors Source File: test_duplicate_headers.py
Function: set_up
    def setUp(self):
        self.app = Flask(__name__)

        @self.app.route('/test_multiple_set_cookie_headers')
        @cross_origin()
        def test_multiple_set_cookie_headers():
            resp = Response("Foo bar baz")
            resp.headers.add('set-cookie', 'foo')
            resp.headers.add('set-cookie', 'bar')
            return resp

Example 6

Project: mcflyin Source File: application.py
Function: hourly
@app.route('/hourly', methods=['POST'])
def hourly():
    '''Return a JSON of hourly summed data'''
    if request.method == 'POST':
        data = json.loads(request.form['data'])
        how = json.loads(request.form['how'])
        df = tr.to_df(data)
        json_return = tr.hourly(df=df, how=how)
        resp = Response(json.dumps(json_return), status=200,
                        mimetype='application/json')
        return resp

Example 7

Project: soapfish Source File: flask_.py
def flask_dispatcher(service, **dispatcher_kwargs):
    from flask import request, Response

    def flask_dispatch():
        soap_request = SOAPRequest(request.environ, request.data)
        soap_dispatcher = SOAPDispatcher(service, **dispatcher_kwargs)
        soap_response = soap_dispatcher.dispatch(soap_request)

        response = Response(soap_response.http_content)
        response.status_code = soap_response.http_status_code
        for header_key, value in soap_response.http_headers.items():
            response.headers[header_key] = value
        return response

    return flask_dispatch

Example 8

Project: flask-nsa Source File: __init__.py
def basic_authenticate():
    """ Sends a 401 response that enables Basic Auth.
    """
    return Response(
        'Could not verify your access level for that URL.\n'
        'You have to login with proper credentials', 401,
        {'WWW-Authenticate': 'Basic realm="Login Required"'}
    )

Example 9

Project: indico Source File: conferenceDisplay.py
    def _process( self ):
        if not self._reqParams.has_key("showDate"):
            self._reqParams["showDate"] = "all"
        if not self._reqParams.has_key("showSession"):
            self._reqParams["showSession"] = "all"
        if not self._reqParams.has_key("detailLevel"):
            self._reqParams["detailLevel"] = "contribution"

        view = self._reqParams.get('view')
        if view == 'xml':
            serializer = XMLEventSerializer(self.event_new, user=session.user, include_timetable=True,
                                            event_tag_name='iconf')
            return Response(serializer.serialize_event(), mimetype='text/xml')
        else:
            p = self.render_meeting_page(self._conf, view, self._reqParams.get('fr') == 'no')
            return p.display()

Example 10

Project: qutebrowser Source File: webserver_sub.py
@app.route('/custom/redirect-later-continue')
def redirect_later_continue():
    """Continue a redirect-later request."""
    if _redirect_later_event is None:
        return flask.Response(b'Timed out or no redirect pending.')
    else:
        _redirect_later_event.set()
        return flask.Response(b'Continued redirect.')

Example 11

Project: rivescript-python Source File: server.py
Function: index
@app.route("/")
@app.route("/<path:path>")
def index(path=None):
    """On all other routes, just return an example `curl` command."""
    payload = {
        "username": "soandso",
        "message": "Hello bot",
        "vars": {
            "name": "Soandso",
        }
    }
    return Response(r"""Usage: curl -i \
    -H "Content-Type: application/json" \
    -X POST -d '{}' \
    http://localhost:5000/reply""".format(json.dumps(payload)),
    mimetype="text/plain")

Example 12

Project: arkos Source File: test-port.py
Function: hello
@app.route("/" + sys.argv[2], methods=["POST", ])
def hello():
    global exit_code
    exit_code = 0
    func = request.environ.get('werkzeug.server.shutdown')
    func()
    return Response("")

Example 13

Project: flask-apscheduler Source File: views.py
def delete_job(job_id):
    """Deletes a job."""

    try:
        current_app.apscheduler.delete_job(job_id)
        return Response(status=204)
    except JobLookupError:
        return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
    except Exception as e:
        return jsonify(dict(error_message=str(e)), status=500)

Example 14

Project: unix2web Source File: unix2web.py
Function: wrapper
@app.route('/index.css')
def wrapper():
    resp = Response(response=open('/var/www/unix2web/index.css', 'r').read(),
                    status=200,
                    mimetype="text/css")
    return resp

Example 15

Project: codenn Source File: legacy.py
Function: format
@legacy.route('/format/', methods=['GET', 'POST'])
@legacy.route('/format', methods=['GET', 'POST'])
def format_():
    if request.method == 'POST':
        sql = _get_sql(request.form, request.files)
        data = request.form
    else:
        sql = _get_sql(request.args)
        data = request.args
    formatted = _format_sql(sql, data, format='text')
    return make_response(Response(formatted, content_type='text/plain'))

Example 16

Project: Flask-GAE-py27 Source File: responses.py
Function: api_response
def api_response(
    status=200, payload=None, message='success',
    headers=None, mimetype='application/json'):
    status = int(status)
    data = json.dumps(payload)
    return Response(
        headers=headers,
        status=status,
        mimetype=mimetype,
        response=data)

Example 17

Project: zifb.in Source File: app.py
    @app.route('/raw/<string:id>')
    @app.route('/raw/<sha1:digest>')
    def raw(id=None, digest=None):
        if id:
            paste = database.Paste.objects(name__exact=id).first()
        if digest:
            paste = database.Paste.objects(digest__exact=digest).first()

        if paste is None:
            abort(404)
        else:
            return Response(paste.paste, mimetype="text/plain")

Example 18

Project: alerta Source File: views.py
@app.route('/management/properties', methods=['OPTIONS', 'GET'])
@cross_origin()
@auth_required
def properties():

    properties = ''

    for k, v in app.__dict__.items():
        properties += '%s: %s\n' % (k, v)

    for k, v in app.config.items():
        properties += '%s: %s\n' % (k, v)

    return Response(properties, content_type='text/plain')

Example 19

Project: sulley Source File: sulley.py
    def _sms_handler(self):
        from_number, text = self._get_request_arguments(request)

        func = self._matcher.match(text) or self._default_handler
        func(Message(from_number, text, provider=self._provider))

        # TODO: handle providers
        xml = '<?xml version="1.0" encoding="UTF-8"?><Response></Response>'
        return Response(xml, mimetype='text/xml')

Example 20

Project: restfulgit Source File: routes.py
@porcelain.route('/repos/<repo_key>/raw/<branch_or_tag_or_sha>/<path:file_path>')
@corsify
def get_raw(repo_key, branch_or_tag_or_sha, file_path):
    repo = get_repo(repo_key)
    commit = get_commit_for_refspec(repo, branch_or_tag_or_sha)
    tree = get_tree(repo, commit.tree.id)
    data = get_raw_file_content(repo, tree, file_path)
    mime_type = guess_mime_type(os.path.basename(file_path), data)
    if mime_type is None:
        mime_type = mime_types.OCTET_STREAM
    return Response(data, mimetype=mime_type)

Example 21

Project: splinter Source File: fake_webapp.py
Function: authenticate
def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
        'Could not verify your access level for that URL.\n'
        'You have to login with proper credentials', 401,
        {'WWW-Authenticate': 'Basic realm="Login Required"'})

Example 22

Project: peewee Source File: app.py
Function: script
@app.route('/a.js')
def script():
    account_id = request.args.get('id')
    if account_id:
        return Response(
            app.config['JAVASCRIPT'] % (app.config['DOMAIN'], account_id),
            mimetype='text/javascript')
    return Response('', mimetype='text/javascript')

Example 23

Project: cronq Source File: web.py
Function: status
@app.route('/_status')
def status():
    return Response(
        json.dumps({'status': 'OK'}),
        mimetype='application/json',
    )

Example 24

Project: whiskyton Source File: files.py
@files.route('/charts/<reference_slug>-<whisky_slug>.svg')
def create_chart(reference_slug, whisky_slug):

    # get whisky objects form db
    reference_obj = models.Whisky.query.filter_by(slug=reference_slug).first()
    whisky_obj = models.Whisky.query.filter_by(slug=whisky_slug).first()

    # error page if whisky doesn't exist
    if reference_obj is None or whisky_obj is None:
        return abort(404)

    # if file does not exists, create it
    chart = Chart(reference=reference_obj, comparison=whisky_obj)
    filename = chart.cache_name(True)
    if not filename.exists():
        chart.cache()

    # return the chart to the user
    return Response(filename.read_file(), mimetype='image/svg+xml')

Example 25

Project: cabu Source File: auth.py
Function: authenticate
def authenticate():
    """Response helper for un-authorized attempts to access to the app.

    Returns:
        response (object): A Flask Response object with a custom message
        and a 401 status.
    """
    return Response(
        json.dumps({
            'message':
                'Could not verify your access level for that URL.\n'
                'You have to login with proper credentials',
        }),
        401,
        {'WWW-Authenticate': 'Basic realm="Login Required"'}
    )

Example 26

Project: vimfox Source File: server.py
Function: debug
@app.route('/debug')
def debug():
    return Response("""
            <!DOCTYPE html>
        <html>
        <head>
            <title></title>
            <meta charset="utf-8" />
            <link rel="stylesheet" href="/assets/css/style2.css">
            <link rel="stylesheet" href="/assets/css/style3.css">
        </head>
        <body>
            <script rel="text/javascript" src="/vimfox/vimfox.js"></script>
        </body>
        </html>""")

Example 27

Project: reflectrpc Source File: flask-server.py
Function: rpc_handler
@app.route('/rpc', methods=['POST'])
def rpc_handler():
    response = jsonrpc.process_request(request.get_data().decode('utf-8'))
    reply = json.dumps(response)

    return Response(reply, 200, mimetype='application/json-rpc')

Example 28

Project: slack-TheL Source File: app.py
@app.route('/thel',methods=['post'])
def thel():
    '''
    :Example:
    /thel current weather in mumbai?
    '''
    text = request.values.get('text')
    try:
        res = client.query(text)
    except UnicodeEncodeError:
        return Response(('Sorry I did\'t get you. Would you please simplify your query?'
                        '%s is not valid input.' % text),
                        content_type='text\plain; charset=utf-8')
    resp_qs = ['Hi Top Answer for "%s"\n' % text]
    resp_qs.extend(next(res.results).text)

    return Response(''.join(resp_qs),
                    content_type='text/plain; chatset=utf-8')

Example 29

Project: codebox Source File: views.py
@app.route('/<org>/<uuid:id>/raw')
@login_required
@can_view_org
def snippet_detail_raw(org, id):
    org = get_object_or_404(Organization, org)

    snippet = get_object_or_404(Snippet, id)
    if snippet.org != org.pk:
        abort(404)

    return Response(snippet.text, mimetype="text/plain")

Example 30

Project: fosspay Source File: common.py
Function: json_output
def json_output(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        def jsonify_wrap(obj):
            jsonification = json.dumps(obj)
            return Response(jsonification, mimetype='application/json')

        result = f(*args, **kwargs)
        if isinstance(result, tuple):
            return jsonify_wrap(result[0]), result[1]
        if isinstance(result, dict):
            return jsonify_wrap(result)
        if isinstance(result, list):
            return jsonify_wrap(result)

        # This is a fully fleshed out response, return it immediately
        return result

    return wrapper

Example 31

Project: learning-python Source File: decorators.py
Function: jsonify
def jsonify(func):
    """JSON decorator."""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        r = func(*args, **kwargs)
        if isinstance(r, tuple):
            code, data = r
        else:
            code, data = 200, r
        return Response(json.dumps(data), status=code, mimetype='application/json')

    return wrapper

Example 32

Project: analytics-quarry-web Source File: app.py
@app.route('/run/<int:qrun_id>/status')
def run_status(qrun_id):
    qrun = g.conn.session.query(QueryRun).get(qrun_id)
    return Response(json.dumps({
        'status': qrun.status_message,
        'extra': json.loads(qrun.extra_info or "{}")
    }), mimetype='application/json', headers={'Access-Control-Allow-Origin': '*'})

Example 33

Project: browsepy Source File: file.py
Function: download
    def download(self):
        if self.is_directory:
            stream = TarFileStream(
                self.path,
                self.app.config["directory_tar_buffsize"]
                )
            return Response(stream, mimetype="application/octet-stream")
        directory, name = os.path.split(self.path)
        return send_from_directory(directory, name, as_attachment=True)

Example 34

Project: rentmybikes Source File: response.py
Function: render
def render(template_name, request, status_code=None, **template_vars):
    template_vars['request'] = request
    template_vars['session'] = session
    template_vars['config'] = current_app.config
    current_app.update_template_context(template_vars)
    body = renderer.render(template_name, **template_vars)

    if status_code is None:
        if request.method == 'POST':
            status_code = 201
        elif request.method == 'DELETE':
            status_code = 204
        else:
            status_code = 200

    return Response(body, status=status_code)

Example 35

Project: datagrepper Source File: app.py
@app.errorhandler(404)
def not_found(error):
    return flask.Response(
        response=fedmsg.encoding.dumps({'error': 'not_found'}),
        status=404,
        mimetype='application/json',
    )

Example 36

Project: uwsgi-nginx-flask-docker-for-sinaimg Source File: main.py
@app.errorhandler(500)
def internal_server_rror(e):
	r = requests.get("http://ww3.sinaimg.cn/large/images/default_large.gif", stream=True)
	def generate():
		for chunk in r.iter_content(CHUNK_SIZE):
			yield chunk
	return Response(generate(), headers = r.raw.headers.items())

Example 37

Project: partify Source File: player.py
@app.route('/player/status/idle')
@with_mpd
def idle(mpd):
    """An endpoint for push-based player events.

    The function issues an MPD IDLE command to Mopidy and blocks on response back from Mopidy. Once a response is received, a Server-Sent Events (SSE) transmission is prepared
    and returned as the response to the request.

    **Note:** This endpoint is not currently in use but sticking around
    until SSEs are implemented better or long-polling is needed."""
    mpd.send_idle()
    select.select([mpd], [], [])
    changed = mpd.fetch_idle()
    status = _get_status(mpd)
    event = "event: %s\ndata: %s" % (changed[0], json.dumps(status))
    app.logger.debug(event)
    return Response(event, mimetype='text/event-stream', direct_passthrough=True)

Example 38

Project: translator Source File: __init__.py
Function: statistics
@main_module.route('/statistics')
def statistics():
    if request.args.get('format') == 'json':
        from analytics import generate_output
        from flask import Response
        return Response(generate_output(), mimetype='application/json')
    else:
        context = dict(
            version=__version__,
            timestamp=datetime.now().strftime('%Y%m%d%H%M')
        )
        return render_template('statistics.html', **context)

Example 39

Project: flask-gae_blobstore Source File: flask_gae_blobstore.py
def send_blob_download():
    '''Sends a file to a client for downloading.

      :param data: Stream data that will be sent as the file contents.
      :param filename: String, name of the file.
      :param contenttype: String, content-type of the file.
    '''
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kw):
            data, filename, contenttype = fn(*args, **kw)
            headers = {
                'Content-Type': contenttype,
                'Content-Encoding': contenttype,
                'Content-Disposition': 'attachment; filename={}'.format(filename)}
            return Response(data, headers=headers)
        return decorated
    return wrapper

Example 40

Project: blaze Source File: server.py
Function: authorization
def authorization(f):
    @functools.wraps(f)
    def authorized(*args, **kwargs):
        if not _get_auth()(flask.request.authorization):
            return Response('bad auth token',
                            RC.UNAUTHORIZED,
                            {'WWW-Authenticate': 'Basic realm="Login Required"'})
        return f(*args, **kwargs)
    return authorized

Example 41

Project: funnel Source File: schedule.py
@app.route('/<space>/schedule/ical', subdomain='<profile>')
@load_models(
    (Profile, {'name': 'profile'}, 'g.profile'),
    ((ProposalSpace, ProposalSpaceRedirect), {'name': 'space', 'profile': 'profile'}, 'space'),
    permission='view')
def schedule_ical(profile, space):
    cal = Calendar()
    cal.add('prodid', "-//Schedule for {event}//funnel.hasgeek.com//".format(event=space.title))
    cal.add('version', "2.0")
    cal.add('summary', "Schedule for {event}".format(event=space.title))
    # Last updated time for calendar needs to be set. Cannot figure out how.
    # latest_session = Session.query.with_entities(func.max(Session.updated_at).label('updated_at')).filter_by(proposal_space=space).first()
    # cal.add('last-modified', latest_session[0])
    cal.add('x-wr-calname', "{event}".format(event=space.title))
    for session in space.sessions:
        cal.add_component(session_ical(session))
    return Response(cal.to_ical(), mimetype='text/calendar')

Example 42

Project: eb-py-flask-signup Source File: application.py
Function: sign_up
@application.route('/signup', methods=['POST'])
def signup():
    signup_data = dict()
    for item in request.form:
        signup_data[item] = request.form[item]

    try:
        store_in_dynamo(signup_data)
        publish_to_sns(signup_data)
    except ConditionalCheckFailedException:
        return Response("", status=409, mimetype='application/json')

    return Response(json.dumps(signup_data), status=201, mimetype='application/json')

Example 43

Project: beeswarm Source File: app.py
@app.route('/data/sessions/<_type>', methods=['GET'])
@login_required
def data_sessions_attacks(_type):
    sessions = []
    if _type == 'all':
        sessions = send_database_request('{0}'.format(Messages.GET_SESSIONS_ALL.value))
    elif _type == 'bait_sessions':
        sessions = send_database_request('{0}'.format(Messages.GET_SESSIONS_BAIT.value))
    elif _type == 'attacks':
        sessions = send_database_request('{0}'.format(Messages.GET_SESSIONS_ATTACKS.value))
    rsp = Response(response=json.dumps(sessions), status=200, mimetype='application/json')
    return rsp

Example 44

Project: vmnetx Source File: http.py
Function: check_running
    def _check_running(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            if not self._server.running:
                return Response('Server unavailable', 503)
            try:
                return func(self, *args, **kwargs)
            except ServerUnavailableError:
                return Response('Server unavailable', 503)
        return wrapper

Example 45

Project: aurproxy Source File: http.py
Function: get
  def get(self):
    status, message = lifecycle.check_health()
    if not status:
      # Still respond with 200, otherwise Aurora UI doesn't show failure text.
      return Response(response='Health checks failed: %s' % message)

    return Response(response='OK')

Example 46

Project: hacker-news-digest Source File: index.py
Function: image
@app.route('/img/<img_id>')
def image(img_id):
    if request.if_none_match or request.if_modified_since:
        return Response(status=304)
    img = models.Image.query.get_or_404(img_id)
    return send_file(img.makefile(), img.content_type, cache_timeout=864000, conditional=True)

Example 47

Project: flaskberry Source File: routes.py
@mod.route("/subtitleproxy")
def subtitle_proxy():
    src = request.args.get('src')
    vtt = cache.get(src)
    if vtt == None:
        r = requests.get(src)
        gzipped = StringIO.StringIO(r.content)
        gzipped.seek(0)
        srt = gzip.GzipFile(fileobj=gzipped, mode='rb')
        vtt = srt_to_vtt(srt.read())
        cache.set(src, vtt, timeout=7 * 24 * 60 * 60)
    return Response(vtt, mimetype='text/vtt')

Example 48

Project: flask-sse Source File: test_blueprint.py
Function: test_stream
def test_stream(bp, app, mockredis):
    app.config["SSE_REDIS_URL"] = "redis://localhost"
    pubsub = mockredis.pubsub.return_value
    pubsub.listen.return_value = [
        {
            "type": "message",
            "data": '{"data": "thing", "type": "example"}',
        }
    ]

    resp = bp.stream()

    assert isinstance(resp, flask.Response)
    assert resp.mimetype == "text/event-stream"
    assert resp.is_streamed
    output = resp.get_data(as_text=True)
    assert output == "event:example\ndata:thing\n\n"
    pubsub.subscribe.assert_called_with('sse')

Example 49

Project: cloud-asr Source File: run.py
@app.route('/crowdflower-export/<model>.csv')
def crowdflower_export(model):
    def generate():
        yield "url\n"
        for row in recordings_model.get_random_recordings(model):
            yield "%s\n" % row.url

    return Response(stream_with_context(generate()), mimetype='text/csv')

Example 50

Project: reloaded Source File: server.py
@app.route('/reloaded/<path:filename>')
def send_reloaded_file(filename):
    try:
        return send_file(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../assets', filename))
    except:
        return Response(':(', status=404)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4