After reading the twisted reactor mode, the following example is provided in combination with the web service and dbconnection pool.
From twisted. Web import server, resource, HTTP
From twisted. Internet import Reactor
From twisted. Enterprise import adbapi
Import OS
Class dataprocess:
Def _ init _ (Self ):
Self. dbpool = adbapi. connectionpool ("mysqldb", DB = "test", user = "root", passwd = "111111 ")
Def getage (self, user ):
Print "getage"
Return self. dbpool. runquery ("select age from users where name = 'job '")
Def printresult (self, L ):
Print "print result"
If l:
Print L [0] [0], "years old"
Else:
Print "No such user"
Def errorhandler (self, error ):
# This isn't a very failed tive handling of the error, we just print it out:
Print "an error has occurred: <% S>" % STR (error)
Class simple (resource. Resource ):
Isleaf = true
# Allowedmethods = ('get ',)
Def _ init _ (Self ):
Pass
Def render_get (self, request ):
# Headers = request. getallheaders ()
Uri = request. Uri
Print URI
Print request. ARGs, "/N", request. Path
Mysqldata = dataprocess ()
D = mysqldata. getage ("Joe ")
D. addcallback (mysqldata. printresult)
D. adderrback (mysqldata. errorhandler)
# Request. setresponsecode (HTTP. not_found)
# Return ""
# Request. _ senderror (404, 'cann not found ')
Return "<HTML> Hello, world! /N you succeed
# Equivalent of cursor.exe cute (statement), return cursor. fetchall ():
If _ name __= = '_ main __':
Site = server. Site (simple ())
Reactor. listentcp (8000, site)
Print "run"
Reactor. Run ()
This example is a server program. The client needs http: // localhost: 8000 for testing. The server immediately queries the database after receiving the GET request, which works very well.