-sharp!/env/python
-sharpcoding: utf-8
import socketio
import eventlet
from flask import Flask, jsonify, render_template
from flaskext.mysql import MySQL
import pymysql
sio = socketio.Server(async_mode = "eventlet")
app = Flask(__name__)
app.wsgi_app = socketio.Middleware(sio, app.wsgi_app)
app.config["SECRET_KEY"] = "secret!"
app.config["JSON_SORT_KEYS"] = False
dbConfig = {
"MYSQL_DATABASE_HOST": "127.0.0.1",
"MYSQL_DATABASE_DB": "test",
"MYSQL_DATABASE_USER": "root",
"MYSQL_DATABASE_PASSWORD": "root1234"
}
for key,val in dbConfig.items():
app.config[key] = val
@app.route("/")
def hello():
mysql = MySQL( cursorclass = pymysql.cursors.DictCursor )
mysql.init_app(app)
cursor = self.__mysql.get_db().cursor()
cursor.execute("select id uid,cellphone,nickname,sex,age from tb_user limit 3")
data = cursor.fetchall()
return jsonify({"code": 200, "message": "", "data": data})
class MyCustomNamespace(socketio.Namespace):
def on_connect(self, sid, environ):
print("New client connected - {sid} ".format(sid = sid))
sio.emit("reply", {"data": "Connected", "count": 0},
room = sid)
def on_disconnect(self, sid):
print("Client disconnected [ {sid} ]".format(sid = sid))
def on_my_event(self, sid, data):
self.emit("my_response", data)
def on_disconnectRequest(self, sid):
sio.disconnect(sid)
sio.register_namespace(MyCustomNamespace("/test"))
if __name__ == "__main__":
eventlet.wsgi.server(eventlet.listen(("", 5000)), app)
then start server, to return data the first time you request the home page, but an error will be reported when you request the home page again:
Traceback (most recent call last):
File "D:\Tools\Python363\lib\site-packages\eventlet\wsgi.py", line 539, in handle_one_response
result = self.application(self.environ, start_response)
File "D:\Tools\Python363\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "D:\Tools\Python363\lib\site-packages\engineio\middleware.py", line 49, in __call__
return self.wsgi_app(environ, start_response)
File "D:\Tools\Python363\lib\site-packages\flask\app.py", line 1993, in wsgi_app
ctx.auto_pop(error)
File "D:\Tools\Python363\lib\site-packages\flask\ctx.py", line 387, in auto_pop
self.pop(exc)
File "D:\Tools\Python363\lib\site-packages\flask\ctx.py", line 353, in pop
self.app.do_teardown_request(exc)
File "D:\Tools\Python363\lib\site-packages\flask\app.py", line 1879, in do_teardown_request
func(exc)
File "D:\Tools\Python363\lib\site-packages\flaskext\mysql.py", line 58, in teardown_request
ctx.mysql_db.close()
File "D:\Tools\Python363\lib\site-packages\pymysql\connections.py", line 728, in close
raise err.Error("Already closed")
pymysql.err.Error: Already closed
ask the bosses, what is the reason for this situation, and then what should I do with it?