Python twisted Learning

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.