Skip to content

Instantly share code, notes, and snippets.

@adamharder
Last active February 19, 2018 09:59
Show Gist options
  • Select an option

  • Save adamharder/470161874a2e21e546fad9a0d76526f9 to your computer and use it in GitHub Desktop.

Select an option

Save adamharder/470161874a2e21e546fad9a0d76526f9 to your computer and use it in GitHub Desktop.
Flask notes

Return Json

from flask import Flask, Response,

# return 
dat = ... # your JSON serialized data
resp = Response(response=dat,
    status=200, \
    mimetype="application/json")
return(resp)

Receive a file

file = request.files['datafile']
fileContents = file.stream.read()

return an xls

from flask import render_template, Response
import StringIO
import mimetypes
import xlwt
from werkzeug.datastructures import Headers

    workbook = xlwt.Workbook()
    sheet = newWb.add_sheet(“NEW PAGE")

    output = StringIO.StringIO()
    workbook.save(output)

    response = Response()
    response.status_code = 200
    response.data = output.getvalue()
    filename = “XXXXXX.xls"
    mimetype_tuple = mimetypes.guess_type(filename)
    response_headers = Headers({
        'Pragma': "public",  # required,
        'Expires': '0',
        'Cache-Control': 'must-revalidate, post-check=0, pre-check=0',
        'Cache-Control': 'private',  # required for certain browsers,
        'Content-Type': mimetype_tuple[0],
        'Content-Disposition': 'attachment; filename=\"%s\";' % filename,
        'Content-Transfer-Encoding': 'binary',
        'Content-Length': len(response.data)
    })

    if not mimetype_tuple[1] is None:
        response.update({'Content-Encoding': mimetype_tuple[1]})
    response.headers = response_headers
    return response

Is the call a POST or a GET?

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()    

Allow cross-domain calls

########################################################################
###### CRAZY DANGEROUS! ################################################
########################################################################
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper


def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

########################################################################



@app.route('/api/status', methods=['GET'])
@crossdomain(origin='*')  # you can specify acceptable posts in this argument
def get_status():
    return Response(json.dumps({}, indent=2),
            status=200,
            mimetype="application/json")

accept JSON from a post

flask code

@app.route('/api/add_message/<uuid>', methods=['POST'])
def add_message(uuid):
    content={}
    try:
        content = request.get_json(silent=True)
    except:
        content={'error':"error reading content"}

    ts=datetime.datetime.now()
    content["uuid"]=uuid
    content["ts"]=str(ts)
    print json.dumps(content, indent=2)

    return "OK"

Compatable requests post

#requeres a recent version of requests
resp=requests.post(url, json=x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment