@app.route('/getEmployees/<userid>')
def all(userid):
for i in range (0,200000,50):
g.db = connect_db()
cur=g.db.execute('select * from employees limit 50 offset '+ str(i))
entry=[dict(emp_no=row[0],birth_date=row[1],first_name=row[2],last_name=row[3],gender=row[4],hire_date=row[5]) for row in cur.fetchall()]
g.db.close()
return str(entry)
所以我想以50块为单位返回所有员工。数据库有200,000个条目。使用return语句这种方式只返回前50个条目并退出该函数。如何以另一种方式实现这种逻辑?
答案 0 :(得分:0)
您可以使用Flask sessions完成此操作,以跟踪上次请求期间使用的最后一个偏移量。
from flask import session, request
app = Flask(__name__)
@app.route('/getEmployees/<userid>')
def all(userid):
# Allow the user to specify an offset via querystring
offset = request.args.get('offset')
# Allow user to specify limit but default to 50
limit = request.args.get('limit', 50)
if offset is None:
# Look in the session and default to 0 if not defined
offset = session.get('offset', 0)
# Do your query
g.db = connect_db()
cur = g.db.execute('select * from employees limit %d offset %d' % (limit, int(offset)))
entry = [dict(emp_no=row[0],birth_date=row[1],first_name=row[2],last_name=row[3],gender=row[4],hire_date=row[5]) for row in cur.fetchall()]
g.db.close()
# Store the current offset in the session so it is available next request
session['offset'] = offset + limit;
return str(entry)
然后您可以通过以下方式查询它。
import requests
s = requests.Session()
s.get('http://localhost/getEmployees/1') # Get first 50
s.get('http://localhost/getEmployees/1') # Get next 50
params = {'offset': 0};
s.get('http://localhost/getEmployees/1', params=params) # Get First 50