我需要创建20个API才能使用我的应用。这些API将从我的MySQL数据库中获取数据。由于我预计流量在高峰时段(高峰时段仅为2小时)相当高,并且每秒可能会收到30到50个请求。
我关心的是联系。由于一次只允许3个连接,使用方法我关闭游标和数据库将能够处理高流量,用户能够访问20个API而没有问题?我获取的数据很小,因为我在文本中的整个数据库只有2MB。
如果此方法可以处理高流量,我不想切换到sqlalchemy。
# A very simple Flask Hello World app for you to get started with...
from flask import Flask,jsonify,abort,make_response,request,render_template
import MySQLdb
import MySQLdb.cursors
app = Flask(__name__)
@app.route('/MUSIC', methods=['GET'])
def Music():
db = MySQLdb.connect(host='doreme.mysql.pythonanywhere-services.com',user='doreme',passwd='pw',db='doreme$default',cursorclass=MySQLdb.cursors.DictCursor)
curs = db.cursor()
try:
curs.execute("SELECT * FROM MUSIC")
a = curs.fetchall()
except Exception:
return 'Error: unable to fetch items'
finally:
curs.close()
db.close()
return jsonify({'Music': a})
@app.route('/MUSICKorea', methods=['GET'])
def MusicKorea():
db = MySQLdb.connect(host='doreme.mysql.pythonanywhere-services.com',user='doreme',passwd='pw',db='doreme$default',cursorclass=MySQLdb.cursors.DictCursor)
curs = db.cursor()
try:
curs.execute("SELECT * FROM MusicKorea")
b = curs.fetchall()
except Exception:
return 'Error: unable to fetch items'
finally:
curs.close()
db.close()
#return "hihi"
return jsonify({'Song': b})
@app.route('/MUSICKorea/<Item>', methods=['GET'])
def Musicitem(Korea):
db = MySQLdb.connect(host='doreme.mysql.pythonanywhere-services.com',user='doreme',passwd='pw',db='doreme$default',cursorclass=MySQLdb.cursors.DictCursor)
try:
curs.execute("SELECT * FROM MUSIC WHERE Song LIKE %s",(Korea,))
c = curs.fetchall()
except Exception:
return 'Error: unable to fetch items'
finally:
curs.close()
db.close()
return jsonify({'Korea': c})
答案 0 :(得分:1)
您可以使用http基准测试工具(ab,wrk,...列出更多工具here)轻松测试您的wsgi应用程序。
测量python函数和/或mysql查询所花费的时间(非常简单,timeit可能更好):
import time
...
@app.route('/MUSICKorea/<Item>', methods=['GET'])
def Musicitem(Korea):
t = time.time()
db = MySQLdb.connect(host='doreme.mysql.pythonanywhere-services.com',user='doreme',passwd='pw',db='doreme$default',cursorclass=MySQLdb.cursors.DictCursor)
print('connecting took %.6f seconds' % (time.time()-t))
try:
curs.execute("SELECT * FROM MUSIC WHERE Song LIKE %s",(Korea,))
c = curs.fetchall()
except Exception:
return 'Error: unable to fetch items'
finally:
curs.close()
db.close()
print('Musicitem took %.6f seconds' % (time.time()-t))
return jsonify({'Korea': c})