我有一个django应用程序,它会在收到请求时从mysql db中获取数据。当一个用户处理请求时,这样可以正常工作,但是当超过用户发送请求时,我收到一条错误消息,说明“ url上的InterfaceError(0,'')“。
我正在使用Django 1.9版。
根据我的研究,我在settings.py中包含了CONN_MAX_AGE,但我仍然遇到了同样的错误。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
**'CONN_MAX_AGE': None**
}
}
我的 models.py
connection = pymysql.connect(host='localhost',user='user',password='password',db='db_name',port=3306,charset='utf8',cursorclass=pymysql.cursors.DictCursor)
def execute(query):
cur = connection.cursor()
cur.execute(query)
data = cur.fetchall()
connection.commit()
cur.close()
return data
def trending_assets():
sql = "select * from media_recommendation_engine.content_table t1 inner join (SELECT movieId,rank from" \
" media_recommendation_engine.asset_ranks limit 10) t2 on t1.movieId = " \
"t2.movieId order by t2.rank asc ;;"
data = execute(sql)
return data
views.py
@permission_classes((permissions.IsAuthenticated,))
class Trending(viewsets.GenericViewSet):
def list(self,request):
if request.query_params['type']=='trending':
result_data = models.trending_assets()
return Response(models.formatter(result_data))
#
else:
return JsonResponse({'message': 'Wrong Argument pass'},status= 400)
答案 0 :(得分:0)
每次需要处理请求时,都应该连接数据库。之前我在全球范围内使用过连接。并且不要使用db.close()。
def execute(query):
connection = pymysql.connect(host='localhost', user='user', password='passsword', db='db_name', port=3306, charset='utf8', cursorclass=pymysql.cursors.DictCursor)
cur = connection.cursor()
cur.execute(query)
data = cur.fetchall()
connection.commit()
cur.close()
return data
def trending_assets():
sql = "select * from media_recommendation_engine.content_table t1 inner join (SELECT movieId,rank from" \
" media_recommendation_engine.asset_ranks limit 10) t2 on t1.movieId = " \
"t2.movieId order by t2.rank asc ;;"
data = execute(sql)
return data