Skip to content

Instantly share code, notes, and snippets.

@YoonHan
Last active September 2, 2021 08:21
Show Gist options
  • Save YoonHan/d8677dd7549b2d929187d5a8653d05bc to your computer and use it in GitHub Desktop.
Save YoonHan/d8677dd7549b2d929187d5a8653d05bc to your computer and use it in GitHub Desktop.
decorator function example: json data utf8 encoding & wrap it with Flask Response
from flask import Response
from functools import wraps
import json
# Define decorator factory
# with argument 'status_code' which means status code of http response
def utf8_encoding(status_code=200):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
result = f(*args, **kwargs)
result = json.dumps(result, ensure_ascii=False, indent=4).encode('utf8')
return Response(result, content_type='application/json; charset=utf-8', status=status_code)
return decorated_function
return decorator
@YoonHan
Copy link
Author

YoonHan commented Sep 2, 2021

# Flask use case
from decorators import utf8_encoding

# NOTICE: Take care about the order of decorators
@route('/path')
@utf8_encoding(status_code=200)
def post():
    ...
    result = some_json_data
    return result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment