|
| 1 | +import logging |
| 2 | + |
| 3 | +from flask import Flask, request |
| 4 | +import datetime |
| 5 | +import decimal |
| 6 | +import pymysql |
| 7 | +import json |
| 8 | +import config |
| 9 | +from flask_cors import CORS |
| 10 | + |
| 11 | +app = Flask(__name__) |
| 12 | + |
| 13 | +""" |
| 14 | +CORS function is to avoid No 'Access-Control-Allow-Origin' error |
| 15 | +""" |
| 16 | +CORS(app) |
| 17 | + |
| 18 | +def type_handler(x): |
| 19 | + """type Serialization function. |
| 20 | +
|
| 21 | + Args: |
| 22 | + x: |
| 23 | +
|
| 24 | + Returns: |
| 25 | + Serialization format of data, add more isinstance(x,type) if needed |
| 26 | + """ |
| 27 | + if isinstance(x, datetime.datetime): |
| 28 | + return x.isoformat() |
| 29 | + if isinstance(x, decimal.Decimal): |
| 30 | + return '$%.2f'%(x) |
| 31 | + raise TypeError("Unknown type") |
| 32 | + |
| 33 | +def rows_to_json(cols,rows): |
| 34 | + """type Serialization function. |
| 35 | + Args: |
| 36 | + cols: column descriptions |
| 37 | + rows: sql query result rows |
| 38 | +
|
| 39 | + Returns: |
| 40 | + Array of json string with combination of columns and rows |
| 41 | + [ |
| 42 | + {"column0":row[0], "column1":row[1], "column2":row[2], .......}, |
| 43 | + {"column0":row[0], "column1":row[1], "column2":row[2], .......}, |
| 44 | + {"column0":row[0], "column1":row[1], "column2":row[2], .......}, |
| 45 | + {"column0":row[0], "column1":row[1], "column2":row[2], .......}, |
| 46 | + {"column0":row[0], "column1":row[1], "column2":row[2], .......} |
| 47 | + ] |
| 48 | + """ |
| 49 | + result = [] |
| 50 | + for row in rows: |
| 51 | + data = dict(zip(cols, row)) |
| 52 | + result.append(data) |
| 53 | + return json.dumps(result, default=type_handler) |
| 54 | + |
| 55 | + |
| 56 | +@app.route('/') |
| 57 | +def hello(): |
| 58 | + """webserice test method |
| 59 | + """ |
| 60 | + return 'Welcome Mysql Flask Demo' |
| 61 | + |
| 62 | +@app.route('/test') |
| 63 | +def test_get(): |
| 64 | + """ mysql test webservice '/test' |
| 65 | + """ |
| 66 | + # create mysql connection |
| 67 | + conn = pymysql.connect(host=config._DB_CONF['host'], |
| 68 | + port=config._DB_CONF['port'], |
| 69 | + user=config._DB_CONF['user'], |
| 70 | + passwd=config._DB_CONF['passwd'], |
| 71 | + db=config._DB_CONF['db']) |
| 72 | + cur = conn.cursor() |
| 73 | + sql="<PUT YOUR MySQL QUERY HERE>" |
| 74 | + cur.execute(sql) |
| 75 | + |
| 76 | + # get all column names |
| 77 | + columns = [desc[0] for desc in cur.description] |
| 78 | + # get all data |
| 79 | + rows=cur.fetchall() |
| 80 | + |
| 81 | + # build json |
| 82 | + result = rows_to_json(columns,rows) |
| 83 | + #print(result) |
| 84 | + |
| 85 | + cur.close() |
| 86 | + conn.close() |
| 87 | + |
| 88 | + return result |
| 89 | + |
| 90 | +@app.errorhandler(500) |
| 91 | +def server_error(e): |
| 92 | + logging.exception('An error occurred during a request.') |
| 93 | + return """ |
| 94 | + An internal error occurred: <pre>{}</pre> |
| 95 | + See logs for full stacktrace. |
| 96 | + """.format(e), 500 |
| 97 | + |
| 98 | +if __name__ == '__main__': |
| 99 | + # This is used when running locally. Gunicorn is used to run the |
| 100 | + #app.run(host='0.0.0.0', port=8080, debug=True, processes=4, threaded=True) |
| 101 | + app.run(threaded=True,debug=True) |
| 102 | + #app.run(host='127.0.0.1', port=8080, debug=True) |
| 103 | +## [END app] |
| 104 | + |
0 commit comments