Skip to content

Instantly share code, notes, and snippets.

@monklof
Created April 14, 2016 14:19
Show Gist options
  • Save monklof/e99ad3fa212a17e38878a959d18d2c7d to your computer and use it in GitHub Desktop.
Save monklof/e99ad3fa212a17e38878a959d18d2c7d to your computer and use it in GitHub Desktop.
some basic processing protocols for flask I flavored in my projects
import os, sys
from flask import jsonify
import datetime
def convert_datatype(val):
if type(val) == dict:
converted = {}
for k in val:
if type(k) != unicode and type(k) != str:
raise TypeError('the key of dict must be strings.')
converted[k] = convert_datatype(val[k])
return converted
elif type(val) == list or type(val) == set:
converted = []
for v in val:
converted.append(convert_datatype(v))
return converted
elif type(val) == datetime.datetime or type(val) == datetime.date:
return datetime_to_str(val)
else:
return val
def send_success(data=None):
''' send success data to front end.
the key of data must be type `string`'''
return jsonify({
'success': True,
'data': convert_datatype(data)})
def send_error(msg=""):
return jsonify({
'success': False,
'msg': msg or "request failed on the server!"
})
def str_to_datetime(string):
return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
def datetime_to_str(date):
return datetime.datetime.strftime(date, "%Y-%m-%d %H:%M:%S")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment