Skip to content

Commit 2b2d930

Browse files
committed
init draft
1 parent 214bf06 commit 2b2d930

File tree

4 files changed

+149
-0
lines changed

4 files changed

+149
-0
lines changed

config.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'''
2+
This is the config file which include all ccnfiguation info here
3+
'''
4+
5+
_DB_CONF = {
6+
'host':'<YOUR-MYSQL-HOST>',
7+
'port':3306,
8+
'user':'<YOUR-MYSQL-USERNAME>',
9+
'passwd':'<YOUR-MYSQL-PASSWORD>',
10+
'db':'<YOUR-MYSQL-DATABASE>'
11+
}
12+

gunicorn.conf.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#By default the multi-process version of the runtime is launched via the Gunicorn webserver and is configured to use gevent-based concurrency and a number of processes equal to the number of CPU cores available.
2+
3+
#This can be changed by creating a file called gunicorn.conf.py in your applications root directory, which will override the default gunicorn.conf.py included with this project
4+
5+
6+
import multiprocessing
7+
8+
# Use threaded workers. Thread-based concurrency is provided via the 'futures'
9+
# package. 'gevent' or other workers would be candidates, except that the ndb
10+
# library has its own concurrency model that conflicts with gevent and possibly
11+
# with similar approaches.
12+
worker_class = 'gthread'
13+
14+
# Use a number of workers equal to the number of CPU cores available.
15+
# Reducing this number on a multicore instance will reduce memory consumption,
16+
# but will also reduce the app's ability to utilize all available CPU resources.
17+
workers = multiprocessing.cpu_count()
18+
#workers = 8 # good
19+
20+
# Use an arbitrary number of threads for concurrency. This will dictate the
21+
# maximum number of requests handled concurrently by EACH worker.
22+
threads = 25
23+
24+
# Settings specific to the Managed VMs production environment such as "bind"
25+
# and "logfile" are set in the Dockerfile's ENTRYPOINT directive.
26+
27+
# Store the process ID of gunicorn. Used for testing.
28+
pidfile = 'gunicorn_pid.txt'

main.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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+

requirement.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
simplejson
2+
pymysql
3+
Flask==0.10.1
4+
flask-cors
5+
gunicorn==19.6.0

0 commit comments

Comments
 (0)