Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 42 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
42
Dung lượng
1,05 MB
Nội dung
Execute the Code Created for the Client To implement or view the output of the client program, perform the following steps on the client computer: 1. Write the client code in a text editor and save it as MultiThrClient.py. 2. At the shell prompt, type: $ python MultiThrServer.py 3. At the prompt Enter data:, enter: How do I start a comment in Python? Figure 13.2 shows a client connected and sending data to the server. 4. The server sends the data written to the file back to the client. 5. Open another terminal window, and start the client program again. Notice that the message sent by the previous client appears here. 6. At the prompt Enter data:, enter: In python, comments begin with a pound (#) sign. Figure 13.3 shows another client connected and sending data to the server. Figure 13.2 The client sending data to the server. Multithreaded Programming 311 TEAM LinG - Live, Informative, Non-cost and Genuine! Figure 13.3 The second client sending data to the server. 7. Once again, the server sends the data back to the second client, as shown in Figure 13.4. 8. Open another terminal window and start the client program again. Notice that the messages sent by both the previous clients appear. (Refer to Figure 13.5.) Figure 13.4 The server sending data to the sending client. 312 Chapter 13 TEAM LinG - Live, Informative, Non-cost and Genuine! Figure 13.5 The third client receiving data from the server. 9. To exit from all the client programs, at the prompt Enter data:, press the Enter key. NOTE Regularly observe the output of all programs to understand the communication between the server and clients. The server program will not end on its own because it is in an infinite loop. You will have to close the terminal window in which the server program is running to end it. Summary In this chapter, you learned the following: ■■ A thread is the smallest unit of code that can be executed. Any program that has more than one thread is called a multithreaded program. ■■ A process is an executing instance of a program. ■■ A single-threaded application has only one thread. In a single-threaded appli- cation, user input and any processing that does not require user input are handled by the same thread. ■■ Python provides two modules to support multithreaded programming: ■■ thread ■■ threading Multithreaded Programming 313 TEAM LinG - Live, Informative, Non-cost and Genuine! ■■ The thread module provides the basic thread and locking features and is appropriate for lower-level thread access, whereas the threading module provides higher-level thread functionality. ■■ The most commonly used thread functions available in the thread module are as follows: ■■ thread.start_new_thread(func, args,[,kwargs]) ■■ thread.exit() ■■ thread.get_thread() ■■ thread.allocate_lock() ■■ The following functions are exposed to a lock object: ■■ lock_obj.acquire([waitflag]) ■■ lock_obj.release() ■■ lock_obj.locked() ■■ The threading module exposes all the functions of the thread module and provides some additional functions. These functions are as follows: ■■ threading.activeCount() ■■ threading.currentThread() ■■ threading.enumerate() ■■ In addition to the functions, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows: ■■ run() ■■ start() ■■ join([time]) ■■ isAlive() ■■ getName() ■■ setName() ■■ The steps involved in creating a single-threaded application are these: 1. Extending the Thread class 2. Defining the run() method 3. Creating an object of the Thread class and calling the start() method ■■ Creating a multithreaded application also requires the same steps except that you have to specify a join method for each thread object to ensure that the program does not exit the main loop as all threads terminate. 314 Chapter 13 TEAM LinG - Live, Informative, Non-cost and Genuine! 315 OBJECTIVES: In this chapter, you will learn to do the following: ߜ Create Web servers by using: ߜ The SocketServer module ߜ The BaseHTTPServer module ߜ The SimpleHTTPServer module ߜ The CGIHTTPServer module ߜ Access URLs in Python by using: ߜ The urlparse module ߜ The urllib module ߜ Upload files across an HTTP connection ߜ Use cookies for data persistence on the client side Advanced Web Programming CHAPTER 14 TEAM LinG - Live, Informative, Non-cost and Genuine! Getting Started Web programming and network programming were introduced in Chapter 10, “CGI Programming,” and Chapter 12, “Network Programming.” You are now familiar with the way data is handled over networks and how it can be transferred from a client to a server or vice versa using Python. This chapter takes you further and discusses advanced Web programming concepts. To start, this chapter discusses how to create your own Web server. Next, it talks about how you can work with URLs by using Python. Finally, this chapter explains advanced CGI to generate dynamic Web pages using cookies and uploading files across an HTTP connection. Creating Web Servers You already know that CGI request processing involves Web servers and clients. Usu- ally, we use browsers, such as Netscape Navigator and Internet Explorer, as Web clients. The most popular Web servers are IIS, Apache, and Netscape. You can use Python for creating a Web server and Web clients. Some of the modules available in Python for building Web servers are SocketServer, BaseHTTPServer, SimpleHTTPServer, and CGIHTTPServer. The SocketServer Module The SocketServer module is used for creating general IP servers. It provides the necessary framework for network servers and simplifies the job of writing them. While using this module, you do not require the socket module to implement servers. This module implements servers by using four classes: TCPServer, UDPServer, UnixStreamServer, and UnixDatagramServer. These classes provide interfaces to the most commonly used protocols, and they handle requests in a synchronous manner. The UnixStreamServer and UnixDatagramServer classes use Unix domain sockets and are not meant for non-Unix platforms. The TCPServer and UDPServer classes implement a server and support the TCP protocol and the UDP protocol, respectively. In addition, it also provides StreamRequestHandler and DatagramRequest- Handler classes to handle requests. While using the SocketServer module, you can handle requests as separate threads. The following steps explain the creation of a Web server by using the Socket- Server module: 1. Create a request handler class by subclassing the StreamRequestHandler class or the DatagramRequestHandler class and overriding its handle() method. The handle() method processes incoming requests. 2. Instantiate one of the server classes by passing the address of the server and the instance of the request handler class. 3. Finally, call the handle_request() method to process the request of a client or the serve_forever() method of the server object to process the requests of many clients. 316 Chapter 14 TEAM LinG - Live, Informative, Non-cost and Genuine! TCPServer, UDPServer, UnixStreamServer, and UnixDatagramServer classes require two parameters. The first parameter is a 2-tuple comprising the host name and the port of the server address; the second parameter is the request handler class, which is an instance of the BaseRequestHandler class. All of the classes dis- cussed have their own instances of class variables; however, all of them implement the following methods and attributes: fileno(). This method returns an integer file descriptor for the socket of the Web server that you create. handle_request(). This method processes a single request at a time and invokes the handle() method of the handler class. serve_forever(). This method handles an infinite number of requests by calling handle_request() inside an infinite loop. address_family. This is the family of protocols of the server socket, socket. AF_INET and socket.AF_UNIX. RequestHandlerClass. This is the class that handles all the requests through the handle() method; an instance of this class is created for each request. server_address. This is the address containing the IP address and an integer port number of the socket on which the server is listening. socket. This is the socket object on which the server listens for approaching requests. The following code, SocServer.py, creates a Web server by using the Socket- Server module. A TCP client or a UDP client can be used to connect to this server. import SocketServer from time import sleep port=8888 class myR(SocketServer.StreamRequestHandler): def handle(self): print “connection from”,self.client_address try: self.wfile.write(“SocketServer works!”) except IOError: print “Connection from the client “,\ self.client_address,” closed” while 1: srvsocket=SocketServer.TCPServer((“”,port),myR) print “the socket is listening to the port”, port srvsocket.serve_forever() When you start the server and connect it with two clients, it displays the following: the socket is listening to the port 8888 connection from (‘127.0.0.1’, 34181) connection from (‘127.0.0.1’, 34182) The serve_forever() method ensures that multiple clients can access the server. Advanced Web Programming 317 TEAM LinG - Live, Informative, Non-cost and Genuine! The BaseHTTPServer Module The BaseHTTPServer module provides the infrastructure required for creating HTTP servers (Web servers). To implement these servers, the BaseHTTPServer module defines two classes, HTTPServer and BaseHTTPRequestHandler. The HTTPServer class is the subclass of TCPServer, which belongs to the ServerSocket module. You use this class to create Web sockets. The HTTPServer class also listens to Web sockets and directs requests to the concerned handler. The BaseHTTPRequestHandler class is used to handle HTTP requests. You need to create a subclass of the BaseHTTPRequestHandler class to handle each request method. The BaseHTTPRequestHandler class defines various instance variables, class vari- ables, and methods that can be used by its subclasses. The following methods are exposed by the BaseHTTPRequestHandler class: handle(). This method handles a request by calling the do_GET() method when the base server receives a GET request and by calling the do_POST() method when the base server receives a POST request. send_error[error code[,error message]]. This method sends an error to the client along with the error code that is the HTTP error code and the mes- sage that is the optional text you can specify. send_response[response code[,response message]]. This method sends a response header. You can specify a more specific response message also. For example, the response code 200 returns an “OK” status. send_header[keyword,value]. This method sends the MIME header to the output stream where a keyword specifies the header keyword and a value speci- fies the header value. end_headers(). This method indicates the end of MIME headers. The following attributes are also exposed by the BaseHTTPRequestHandler class: client_address. Returns a tuple containing the host and port number refer- ring to the address of the client. command. Returns the request type, such as GET, POST, etc. path. Returns the request path. request_version. Returns the version string from a request, such as HTTP/1.0. headers. Contains the message headers in the HTTP request. rfile. Contains the input stream used to read the data received from the client. wfile. Contains the input stream used for sending a response to the client. The following code, Mywebserver.py, illustrates a Web server created using the BaseHTTPServer module: #!/usr/bin/python2.2 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer dynhtml=””” <HTML><HEAD><TITLE>My Home Page</TITLE></HEAD> 318 Chapter 14 TEAM LinG - Live, Informative, Non-cost and Genuine! <BR><BR><BR><BR><BR><BR><HR> <BODY><CENTER><H1><U>Hello client!</U></H1> <H2>You are connected to Mywebserver</H2><HR></BODY> </HTML>””” nf=”File not found” class req_handler(BaseHTTPRequestHandler): def do_GET(self): if self.path==”/”: self.send_response(200) self.send_header(‘Content-type’,’text/html’) self.end_headers() self.wfile.write(dynhtml) else: self.send_error(404,nf) try: server=HTTPServer((‘’,8000),req_handler) print ‘Welcome to the Mywebserver ’ print ‘Press ^C once or twice to quit’ server.serve_forever() except KeyboardInterrupt: print ‘^C pressed, shutting down server’ server.socket.close() When you execute the preceding code, a Web server starts. When a client tries to access the server, an OK status is returned with the response code 200 and the default page of the server is displayed, as shown in Figure 14.1. Figure 14.1 The default page displayed when the Web server is accessed. Advanced Web Programming 319 TEAM LinG - Live, Informative, Non-cost and Genuine! Figure 14.2 Accessing the Web server. This is a simple program to create a Web server, and it cannot access files on the server. If the client tries to access a file, the “file not found” message code is displayed with the error code 404. The server displays loggable output as shown in Figure 14.2. NOTE Standard Web servers run on port 80. Other Web servers that you create do not have access to this port. Therefore, if you are accessing a Web server from a client browser, do not forget to specify the server’s port number along with its host name, which is the name of the computer on which the server resides. The SimpleHTTPServer Module The SimpleHTTPServer module is used for creating simple Web servers. It defines a class, SimpleHTTPRequestHandler, for handling requests to serve only base direc- tory files. This module is compatible with the BaseHTTPServer module. Therefore, the methods and attributes exposed by the SimpleHTTPServer module are similar to the BaseHTTPServer module; however, this module is suitable for implementing GET and HEAD requests. The following code, Mysimplewebserver.py, illustrates a Web server created using the SimpleHTTPServer module: #!/usr/bin/python2.2 from os import curdir, sep from BaseHTTPServer import HTTPServer 320 Chapter 14 TEAM LinG - Live, Informative, Non-cost and Genuine! [...]... can be used to store user identification Instead of specifying the username and password during subsequent visits to a Web site, cookies can be used to store the username and the password After a user registers on the Web site, a cookie is created with a unique ID that is associated with a specific user When the user subsequently visits the site, the user’s ID is used to identify the registered user... protocol://server_loc/path:params?query#frag Let’s understand each of these components: protocol refers to the type of protocol to be used server_loc refers to the location of the server where the resource to be accessed or user information is stored User information can be stored in this component of URL in the form user:password@host:port path refers to the path of a file or a CGI application separated by slashes params refers to optional... without requiring username and password specifications Such a methodology is used only for low-security sites Web page customizations Cookies can store user-specified formats that are used to change the appearance of Web pages according to users’ preferences The changed format of a page is retained and can be retrieved during subsequent visits to the site Each cookie contains several bits of information,... attribute of the uploaded file is used to read data from the uploaded file, and the filename attribute of the uploaded file is used to return the name of the file s s Cookies are pieces of information stored by a Web server on a client computer, and they are managed by a browser s s The Cookie module has many classes that handle the creation of cookie objects The base class for the creation of all cookie... The Menubutton widget is used to display menus in your application Menu The Menu widget is used to provide various commands to a user These commands are contained inside Menubutton Message The Message widget is used to display multiline text fields for accepting values from a user Radiobutton The Radiobutton widget is used to display a number of options as radio buttons The user can select only one... urlopenmod.py, to illustrate the retrieval of a Web page from www .python. org and copy the Web page to another local file import urllib copyfile=open(“copypage.html”,”wb”) f=urllib.urlopen(“http://www .python. org/”) data=f.read(500) while data: copyfile.write(data) data=f.read(500) copyfile.close() f.close() The preceding code opens the home page of the official Web site of Python and transfers it to another... widget is used to display buttons in your application Canvas The Canvas widget is used to draw shapes, such as lines, ovals, polygons, and rectangles, in your application Checkbutton The Checkbutton widget is used to display a number of options as checkboxes The user can select multiple options at a time Entry The Entry widget is used to display a single-line text field for accepting values from a user... HTML form Notice that the file input type is used to submit multipart form data to the Web server The file attribute of the uploaded file is used to read data from the uploaded file, and the filename attribute of the uploaded file is used to return the name of the file When the CGI script is accessed, the screen shown in Figure 14.6 is displayed When you use the Browse button on the form to navigate... details on the Python prompt Such applications that interact with a user by means of an interface represented using icons, menus, and dialog boxes on the screen are called graphical user interface (GUI) applications In this chapter, you will learn about Tkinter, the official GUI framework for Python, to create GUI applications As a part of this, you will learn about various controls that can be included... GUI applications A graphical user interface (GUI ) application, like a painting, has a user interface In the case of a painting, the canvas holds various components, such as lines, circles, and boxes Similarly, a GUI application consists of a number of controls, such as text boxes, labels, and buttons, which are contained inside a window You would have come across a number of GUI applications in day-to-day . refers to the location of the server where the resource to be accessed or user information is stored. User information can be stored in this component of URL in the form user:password@host:port path. opens the home page of the official Web site of Python and transfers it to another HTML file. The code transfers only 500 bytes at a time. The urllib.urlopen (“http://www .python. org/”) command. used to submit multipart form data to the Web server. The file attribute of the uploaded file is used to read data from the uploaded file, and the filename attribute of the uploaded file is used