id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
18,300 | found_terminator(called when the termination condition set by set_terminator(holds this method must be implemented by the user typicallyit would process data previously collected by the collect_incoming_data(method get_terminator(returns the terminator for the channel push(datapushes data onto the channel' outgoing producer fifo queue data is string containing the data to be sent push_with_producer(producerpushes producer objectproduceronto the producer fifo queue producer may be any object that has simple methodmore(the more(method should produce string each time it is invoked an empty string is returned to signal the end of data internallythe async_chat class repeatedly calls more(to obtain data to write on the outgoing channel more than one producer object can be pushed onto the fifo by calling push_with_producer(repeatedly set_terminator(termsets the termination condition on the channel term may either be stringan integeror none if term is stringthe method found_terminator(is called whenever that string appears in the input stream if term is an integerit specifies byte count after many bytes have been readfound_terminator(will be called if term is nonedata is collected forever the module defines one class that can produce data for the push_with_producer(method simple_producer(data [buffer_size]creates simple producer object that produces chunks from byte string data buffer_size specifies the chunk size and is by default the asynchat module is always used in conjunction with the asyncore module for instanceasyncore is used to set up the high-level serverwhich accepts incoming connections asynchat is then used to implement handlers for each connection the following example shows how this works by implementing minimalistic web server that handles get requests the example omits lot of error checking and details but should be enough to get you started readers should compare this example to the example in the asyncore modulewhich is covered next an asynchronous http server using asynchat import asynchatasyncoresocket import os import mimetypes tryfrom http client import responses except importerrorfrom httplib import responses python python lib fl ff |
18,301 | network programming and sockets this class plugs into the asyncore module and merely handles accept events class async_http(asyncore dispatcher)def _init_ (self,port)asyncore dispatcher _init_ (selfself create_socket(socket af_inet,socket sock_streamself setsockopt(socket sol_socketsocket so_reuseaddr self bind(('',port)self listen( def handle_accept(self)client,addr self accept(return async_http_handler(clientclass that handles asynchronous http requests class async_http_handler(asynchat async_chat)def _init_ (self,conn=none)asynchat async_chat _init_ (self,connself data [self got_header false self set_terminator( "\ \ \ \ "get incoming data and append to data buffer def collect_incoming_data(self,data)if not self got_headerself data append(datagot terminator (the blank linedef found_terminator(self)self got_header true header_data "join(self datadecode header data (binaryinto text for further processing header_text header_data decode('latin- 'header_lines header_text splitlines(request header_lines[ split(op request[ url request[ ][ :self process_request(op,urlpush text onto the outgoing streambut encode it first def push_text(self,text)self push(text encode('latin- ')process the request def process_request(selfopurl)if op ="get"if not os path exists(url)self send_error( ,"file % not found\ \ "elsetypeencoding mimetypes guess_type(urlsize os path getsize(urlself push_text("http/ ok\ \ "self push_text("content-length% \ \nsizeself push_text("content-type% \ \ntypeself push_text("\ \ "self push_with_producer(file_producer(url)elseself send_error( ,"% method not implementedopself close_when_done( lib fl ff |
18,302 | error handling def send_error(self,code,message)self push_text("http/ % % \ \ (coderesponses[code])self push_text("content-typetext/plain\ \ "self push_text("\ \ "self push_text(messageclass file_producer(object)def _init_ (self,filename,buffer_size= )self open(filename,"rb"self buffer_size buffer_size def more(self)data self read(self buffer_sizeif not dataself close(return data async_http( asyncore loop(to test this exampleyou will need to supply url corresponding to file in the same directory as where you are running the server asyncore the asyncore module is used to build network applications in which network activity is handled asynchronously as series of events dispatched by an event loopbuilt using the select(system call such an approach is useful in network programs that want to provide concurrencybut without the use of threads or processes this method can also provide high performance for short transactions all the functionality of this module is provided by the dispatcher classwhich is thin wrapper around an ordinary socket object dispatcher([sock]base class defining an event-driven nonblocking socket object sock is an existing socket object if omitteda socket must be created using the create_socket(method (described shortlyonce it' creatednetwork events are handled by special handler methods in additionall open dispatcher objects are saved in an internal list that' used by number of polling functions the following methods of the dispatcher class are called to handle network events they should be defined in classes derived from dispatcher handle_accept(called on listening sockets when new connection arrives handle_close(called when the socket is closed handle_connect(called when connection is made handle_error(called when an uncaught python exception occurs lib fl ff |
18,303 | network programming and sockets handle_expt(called when out-of-band data for socket is received handle_read(called when new data is available to be read from socket handle_write(called when an attempt to write data is made readable(this function is used by the select(loop to see whether the object is willing to read data returns true if sofalse if not this method is called to see if the handle_read(method should be called with new data writable(called by the select(loop to see if the object wants to write data returns true if sofalse otherwise this method is always called to see whether the handle_write(method should be called to produce output in addition to the preceding methodsthe following methods are used to perform low-level socket operations they're similar to those available on socket object accept(accepts connection returns pair (clientaddrwhere client is socket object used to send and receive data on the connection and addr is the address of the client bind(addressbinds the socket to address address is typically tuple (hostport)but this depends the address family being used close(closes the socket connect(addressmakes connection address is tuple (hostportd create_socket(familytypecreates new socket arguments are the same as for socket socket( listen([backlog]listens for incoming connections backlog is an integer that is passed to the underlying socket listen(function recv(sizereceives at most size bytes an empty string indicates the client has closed the channel send(datasends data data is byte string lib fl ff |
18,304 | the following function is used to start the event loop and process eventsloop([timeout [use_poll [map [count]]]]polls for events indefinitely the select(function is used for polling unless the use_poll parameter is truein which case poll(is used instead timeout is the timeout period and is set to seconds by default map is dictionary containing all the channels to monitor count specifies how many polling operations to perform before returning if count is none (the default)loop(polls forever until all channels are closed if count is the function will execute single poll for events and return example the following example implements minimalistic web server using asyncore it implements two classes--asynhttp for accepting connections and asynclient for processing client requests this should be compared with the example in the asynchat module the main difference is that this example is somewhat lower-level--requiring us to worry about breaking the input stream into linesbuffering excess dataand identifying the blank line that terminates the request header an asynchronous http server import asyncoresocket import os import mimetypes import collections tryfrom http client import responses except importerrorfrom httplib import responses python python this class merely handles accept events class async_http(asyncore dispatcher)def _init_ (self,port)asyncore dispatcher _init_ (selfself create_socket(socket af_inet,socket sock_streamself setsockopt(socket sol_socketsocket so_reuseaddr self bind(('',port)self listen( def handle_accept(self)client,addr self accept(return async_http_handler(clienthandle clients class async_http_handler(asyncore dispatcher)def _init_ (selfsock none)asyncore dispatcher _init_ (self,sockself got_request false self request_data "self write_queue collections deque(self responding false read http requestonly readable if request header not read def readable(self)return not self got_request lib fl ff |
18,305 | network programming and sockets read incoming request data def handle_read(self)chunk self recv( self request_data +chunk if '\ \ \ \nin self request_dataself handle_request(handle an incoming request def handle_request(self)self got_request true header_data self request_data[:self request_data find( '\ \ \ \ ')header_text header_data decode('latin- 'header_lines header_text splitlines(request header_lines[ split(op request[ url request[ ][ :self process_request(op,urlprocess the request def process_request(self,op,url)self responding true if op ="get"if not os path exists(url)self send_error( ,"file % not found\ \nurlelsetypeencoding mimetypes guess_type(urlsize os path getsize(urlself push_text('http/ ok\ \ 'self push_text('content-length% \ \nsizeself push_text('content-type% \ \ntypeself push_text('\ \ 'self push(open(url,"rb"read()elseself send_error( ,"% method not implementedself operror handling def send_error(self,code,message)self push_text('http/ % % \ \ (coderesponses[code])self push_text('content-typetext/plain\ \ 'self push_text('\ \ 'self push_text(messageadd binary data to the output queue def push(self,data)self write_queue append(dataadd text data to the output queue def push_text(self,text)self push(text encode('latin- ')only writable if response is ready def writable(self)return self responding and self write_queue write response data def handle_write(self)chunk self write_queue popleft(bytes_sent self send(chunkif bytes_sent !len(chunk)self write_queue appendleft(chunk[bytes_sent:]if not self write_queueself close( lib fl ff |
18,306 | create the server async_http( poll forever asyncore loop(see alsosocket ( )select ( )http ( )socketserver ( select the select module provides access to the select(and poll(system calls select(is typically used to implement polling or to multiplex processing across multiple input/output streams without using threads or subprocesses on unixit works for filessocketspipesand most other file types on windowsit only works for sockets select(iwtdowtdewtd [timeout]queries the inputoutputand exceptional status of group of file descriptors the first three arguments are lists containing either integer file descriptors or objects with methodfileno()that can be used to return file descriptor the iwtd parameter specifies objects waiting for inputowtd specifies objects waiting for outputand ewtd specifies objects waiting for an exceptional condition each list may be empty timeout is floating-point number specifying timeout period in seconds if timeout is omittedthe function waits until at least one file descriptor is ready if it' the function merely performs poll and returns immediately the return value is tuple of lists containing the objects that are ready these are subsets of the first three arguments if none of the objects is ready before the timeout occursthree empty lists are returned if an error occursa select error exception raised its value is the same as that returned by ioerror and oserror poll(creates polling object that utilizes the poll(system call this is only available on systems that support poll( polling objectpreturned by poll(supports the following methodsp register(fd [eventmask]registers new file descriptorfd fd is either an integer file descriptor or an object that provides the fileno(method from which the descriptor can be obtained eventmask is the bitwise or of the following flagswhich indicate events of interestconstant description pollin pollpri pollout pollerr data is available for reading urgent data is available for reading ready for writing error condition lib fl ff |
18,307 | network programming and sockets constant description pollhup pollnval hang up invalid request if eventmask is omittedthe pollinpollpriand pollout events are checked unregister(fdremoves the file descriptor fd from the polling object raises keyerror if the file is not registered poll([timeout]polls for events on all the registered file descriptors timeout is an optional timeout specified in milliseconds returns list of tuples (fdevent)where fd is file descriptor and event is bitmask indicating events the fields of this bitmask correspond to the constants pollinpolloutand so on for exampleto check for the pollin eventsimply test the value using event pollin if an empty list is returnedit means timeout occurred and no events occurred advanced module features the select(and poll(functions are the most generally portable functions defined by this module on linux systemsthe select module also provides an interface to the edge and level trigger polling (epollinterface which can offer significantly better performance on bsd systemsaccess to kernel queue and event objects is provided these programming interfaces are described in the online documentation for select at advanced asynchronous / example the select module is sometimes used to implement servers based on tasklets or coroutines-- technique that can be used to provide concurrent execution without threads or processes the following advanced example illustrates this concept by implementing an / -based task scheduler for coroutines be forewarned--this is the most advanced example in the book and it will require some study for it to make sense you might also want to consult my pycon' tutorial " curious course on coroutines and concurrency(material import select import types import collections lib fl ff |
18,308 | object that represents running task class task(object)def _init_ (self,target)self target target coroutine self sendval none value to send when resuming self stack [call stack def run(self)tryresult self target send(self sendvalif isinstance(result,systemcall)return result if isinstance(result,types generatortype)self stack append(self targetself sendval none self target result elseif not self stackreturn self sendval result self target self stack pop(except stopiterationif not self stackraise self sendval none self target self stack pop(object that represents "system callclass systemcall(object)def handle(self,sched,task)pass scheduler object class scheduler(object)def _init_ (self)self task_queue self read_waiting self write_waiting self numtasks collections deque({{ create new task out of coroutine def new(self,target)newtask task(targetself schedule(newtaskself numtasks + put task on the task queue def schedule(self,task)self task_queue append(taskhave task wait for data on file descriptor def readwait(self,task,fd)self read_waiting[fdtask lib fl ff |
18,309 | network programming and sockets have task wait for writing on file descriptor def writewait(self,task,fd)self write_waiting[fdtask main scheduler loop def mainloop(self,count=- ,timeout=none)while self numtaskscheck for / events to handle if self read_waiting or self write_waitingwait if self task_queue else timeout , , select select(self read_waitingself write_waiting[]waitfor fileno in rself schedule(self read_waiting pop(fileno)for fileno in wself schedule(self write_waiting pop(fileno)run all of the tasks on the queue that are ready to run while self task_queuetask self task_queue popleft(tryresult task run(if isinstance(result,systemcall)result handle(self,taskelseself schedule(taskexcept stopiterationself numtasks - if no tasks can runwe decide if we wait or return elseif count count - if count = return implementation of different system calls class readwait(systemcall)def _init_ (self, )self def handle(self,sched,task)fileno self fileno(sched readwait(task,filenoclass writewait(systemcall)def _init_ (self, )self def handle(self,sched,task)fileno self fileno(sched writewait(task,filenoclass newtask(systemcall)def _init_ (self,target)self target target def handle(self,sched,task)sched new(self targetsched schedule(taskthe code in this example implements very tiny "operating system here are some details concerning its operationn all work is carried out by coroutine functions recall that coroutine uses the yield statement like generator except that instead of iterating on ityou send it values using send(valuemethod lib fl ff |
18,310 | the task class represents running task and is just thin layer on top of coroutine task object task has only one operationtask run(this resumes the task and runs it until it hits the next yield statementat which point the task suspends when running taskthe task sendval attribute contains the value that is to be sent into the task' corresponding yield expression tasks run until they encounter the next yield statement the value produced by this yield controls what happens next in the taskn if the value is another coroutine (type generatortype)it means that the task wants to temporarily transfer control to that coroutine the stack attribute of task objects represents call-stack of coroutines that is built up when this happens the next time the task runscontrol will be transferred into this new coroutine if the value is systemcall instanceit means that the task wants the scheduler to do something on its behalf (such as launch new taskwait for /oand so onthe purpose of this object is described shortly if the value is any other valueone of two things happens if the currently executing coroutine was running as subroutineit is popped from the task call stack and the value saved so that it can be sent to the caller the caller will receive this value the next time the task executes if the coroutine is the only executing coroutinethe return value is simply discarded the handling of stopiteration is to deal with coroutines that have terminated when this happenscontrol is returned to the previous coroutine (if there was oneor the exception is propagated to the scheduler so that it knows that the task terminated the systemcall class represents system call in the scheduler when running task wants the scheduler to carry out an operation on its behalfit yields systemcall instance this object is called "system callbecause it mimics the behavior of how programs request the services of real multitasking operating system such as unix or windows in particularif program wants the services of the operating systemit yields control and provides some information back to the system so that it knows what to do in this respectyielding systemcall is similar to executing kind of system "trap the scheduler class represents collection of task objects that are being managed at its corethe scheduler is built around task queue (the task_queue attributethat keeps track of tasks that are ready to run there are four basic operations concerning the task queue new(takes new coroutinewraps it with task objectand places it on the work queue schedule(takes an existing task and puts it back on the work queue mainloop(runs the scheduler in loopprocessing tasks one by one until there are no more tasks the readwait(and writewait(methods put task object into temporary staging areas where it will wait for / events in this casethe task isn' runningbut it' not dead either--it' just sitting around biding its time the mainloop(method is the heart of the scheduler this method first checks to see if any tasks are waiting for / events if soit arranges call to select(in order to poll for / activity if there are any events of interestthe associated tasks are placed back onto the task queue so that they can run nextthe mainloop(method pops tasks off of the task queue and calls their run( lib fl ff |
18,311 | network programming and sockets method if any task exits (stopiteration)it is discarded if task merely yieldsit is just placed back onto the task queue so that it can run again this continues until there are either no more tasks or all tasks are blockedwaiting for more / events as an optionthe mainloop(function accepts count parameter that can be used to make it return after specified number of / polling operations this might be useful if the scheduler is to be integrated into another event loop perhaps the most subtle aspect of the scheduler is the handling of systemcall instances in the mainloop(method if task yields systemcall instancethe scheduler invokes its handle(methodpassing in the associated scheduler and task objects as parameters the purpose of system call is to carry out some kind of internal operation concerning tasks or the scheduler itself the readwait()writewait()and newtask(classes are examples of system calls that suspend task for / or create new task for examplereadwait(takes task and invokes the readwait(method on the scheduler the scheduler then takes the task and places it into an appropriate holding area againthere is critical decoupling of objects going on here tasks yield systemcall objects to request servicebut do not directly interact with the scheduler systemcall objectsin turncan perform operations on tasks and schedulers but are not tied to any specific scheduler or task implementation soin theoryyou could write completely different scheduler implementation (maybe using threadsthat could just be plugged into this whole framework and it would still work here is an example of simple network time server implemented using this / task scheduler it will illuminate many of the concepts described in the previous listfrom socket import socketaf_inetsock_stream def time_server(address)import time socket(af_inet,sock_streams bind(addresss listen( while trueyield readwait(sconn,addr accept(print("connection from %sstr(addr)yield writewait(connresp time ctime("\ \nconn send(resp encode('latin- ')conn close(sched scheduler(sched new(time_server(('', ))sched new(time_server(('', ))sched run(server on port server on port in this exampletwo different servers are running concurrently--each listening on different port number (use telnet to connect and testthe yield readwait(and yield writewait(statements cause the coroutine running each server to suspend until / is possible on the associated socket when these statements returnthe code immediately proceeds with an / operation such as accept(or send( lib fl ff |
18,312 | the use of readwait and writewait might look rather low-level fortunatelyour design allows these operations to be hidden behind library functions and methods-provided that they are also coroutines consider the following object that wraps socket object and mimics its interfaceclass cosocket(object)def _init_ (self,sock)self sock sock def close(self)yield self sock close(def bind(self,addr)yield self sock bind(addrdef listen(self,backlog)yield self sock listen(backlogdef connect(self,addr)yield writewait(self sockyield self sock connect(addrdef accept(self)yield readwait(self sockconnaddr self sock accept(yield cosocket(conn)addr def send(self,bytes)while bytesevt yield writewait(self socknsent self sock send(bytesbytes bytes[nsent:def recv(self,maxsize)yield readwait(self sockyield self sock recv(maxsizehere is reimplementation of the time server using the cosocket classfrom socket import socketaf_inetsock_stream def time_server(address)import time cosocket(socket(af_inet,sock_stream)yield bind(addressyield listen( while trueconn,addr yield accept(print(connprint("connection from %sstr(addr)resp time ctime()+"\ \nyield conn send(resp encode('latin- ')yield conn close(sched scheduler(sched new(time_server(('', ))sched new(time_server(('', ))sched run(server on port server on port in this examplethe programming interface of cosocket object looks lot like normal socket the only difference is that every operation must be prefaced with yield (since every method is defined as coroutineat firstit looks crazy so you might ask what does all of this madness buy youif you run the above serveryou will find that it is able to run concurrently without using threads or subprocesses not only thatit has "normallooking control flow as long as you ignore all of the yield keywords lib fl ff |
18,313 | network programming and sockets here is an asynchronous web server that concurrently handles multiple client connectionsbut which does not use callback functionsthreadsor processes this should be compared to examples in the asynchat and asyncore modules import os import mimetypes tryfrom http client import responses except importerrorfrom httplib import responses from socket import python python def http_server(address) cosocket(socket(af_inet,sock_stream)yield bind(addressyield listen( while trueconn,addr yield accept(yield newtask(http_request(conn,addr)del connaddr def http_request(conn,addr)request "while truedata yield conn recv( request +data if '\ \ \ \nin requestbreak header_data request[:request find( '\ \ \ \ ')header_text header_data decode('latin- 'header_lines header_text splitlines(methodurlproto header_lines[ split(if method ='get'if os path exists(url[ :])yield serve_file(conn,url[ :]elseyield error_response(conn, ,"file % not foundurlelseyield error_response(conn, ,"% method not implementedmethodyield conn close(def serve_file(conn,filename)content,encoding mimetypes guess_type(filenameyield conn send( "http/ ok\ \ "yield conn send(("content-type% \ \ncontentencode('latin- ')yield conn send(("content-length% \ \nos path getsize(filename)encode('latin- ')yield conn send( "\ \ " open(filename,"rb"while truedata read( if not databreak yield conn send(datadef error_response(conn,code,message)yield conn send(("http/ % % \ \ (coderesponses[code])encode('latin- ')yield conn send( "content-typetext/plain\ \ "yield conn send( "\ \ "yield conn send(message encode('latin- ') lib fl ff |
18,314 | sched scheduler(sched new(http_server(('', ))sched mainloop(careful study of this example will yield tremendous insight into coroutines and concurrent programming techniques used by some very advanced third-party modules howeverexcessive usage of these techniques might get you fired after your next code review when to consider asynchronous networking use of asynchronous / (asyncore and asynchat)pollingand coroutines as shown in previous examples remains one of the most mysterious aspects of python development yetthese techniques are used more often than you might think an often-cited reason for using asynchronous / is to minimize the perceived overhead of programming with large number of threadsespecially when managing large number of clients and in light of restrictions related to the global interpreter lock (refer to "threads and concurrency"historicallythe asyncore module was one of the first library modules to support asynchronous / the asynchat module followed some time later with the aim of simplifying much of the coding howeverboth of these modules take the approach of processing / as events for examplewhen an / event occursa callback function is triggered the callback then reacts in response to the / event and carries out some processing if you build large application in this styleyou will find that event handling infects almost every part of the application ( / events trigger callbackswhich trigger more callbackswhich trigger other callbacksad nauseumone of the more popular networking packages,twisted (and significantly builds upon it coroutines are more modern but less commonly understood and used since they were only first introduced in python an important feature of coroutines is that you can write programs that look more like threaded programs in their overall control flow for instancethe web server in the example does not use any callback functions and looks almost identical to what you would write if you were using threads--you just have to become comfortable with the use of the yield statement stackless python (as general ruleyou probably should resist the urge to use asynchronous / techniques for most network applications for instanceif you need to write server that constantly transmits data over hundreds or even thousands of simultaneous network connectionsthreads will tend to have superior performance this is because the performance of select(degrades significantly as the number of connections it must monitor increases on linuxthis penalty can be reduced using special functions such as epoll()but this limits the portability of your code perhaps the main benefit of asynchronous / is in applications where networking needs to be integrated with other event loops ( guisor in applications where networking is added into code that also performs significant amount of cpu processing in these casesthe use of asynchronous networking may result in quicker response time lib fl ff |
18,315 | network programming and sockets just to illustrateconsider the following program that carries out the task described in the song " million bottles of beer on the wall"bottles def drink_beer()remaining while remaining remaining - def drink_bottles()global bottles while bottles drink_beer(bottles - nowsuppose you wanted to add remote monitoring capability to this code that allows clients to connect and see how many bottles are remaining one approach is to launch server in its own thread and have it run alongside the main application like thisdef server(port) socket socket(socket af_inet,socket sock_streams bind(('',port) listen( while trueclient,addr accept(client send(("% bottles\ \nbottlesencode('latin- 'client close(launch the monitor server thr threading thread(target=server,args=( ,)thr daemon=true thr start(drink_bottles(the other approach is to write server based on / polling and embed polling operation directly into the main computation loop here is an example that uses the coroutine scheduler developed earlierdef drink_bottles()global bottles while bottles drink_beer(bottles - scheduler mainloop(count= ,timeout= poll for connections an asynchronous server based on coroutines def server(port) cosocket(socket socket(socket af_inet,socket sock_stream)yield bind(('',port)yield listen( while trueclient,addr yield accept(yield client send(("% bottles\ \nbottlesencode('latin- 'yield client close(scheduler scheduler(scheduler new(server( )drink_bottles(if you write separate program that periodically connects to the bottles of beer program and measures the response time required to receive status messagethe results are lib fl ff |
18,316 | surprising on the author' machine ( dual-core ghz macbook)the average response time (measured over , requestsfor the coroutine-based server is about ms versus ms for threads this difference is explained by the fact that the coroutinebased code is able to respond as soon as it detects connection whereas the threaded server doesn' get to run until it is scheduled by the operating system in the presence of cpu-bound thread and the python global interpreter lockthe server may be delayed until the cpu-bound thread exceeds its allotted time slice on many systemsthe time slice is about ms so the above rough measurement of thread response time is exactly the average time you might expect to wait for cpu-bound task to be preempted by the operating system the downside to polling is that it introduces significant overhead if it occurs too often for instanceeven though the response time is lower in this examplethe program instrumented with polling takes more than longer to run to completion if you change the code to only poll after every six-pack of beerthe response time increases slightly to ms whereas the run time of the program is only greater than the program without any polling unfortunatelythere is often no clear-cut way to know how often to poll other than to make measurements of your application even though this improved response time might look like winthere are still horrible problems associated with trying to implement your own concurrency for exampletasks need to be especially careful when performing any kind of blocking operation in the web server examplethere is fragment of code that opens and reads data from file when this operation occursthe entire program will be frozen--potentially for long period of time if the file access involves disk seek the only way to fix this would be to additionally implement asynchronous file access and add it as feature to the scheduler for more complicated operations such as performing database queryfiguring out how to carry out the work in an asynchronous manner becomes rather complex one way to do it would be to carry out the work in separate thread and to communicate the results back to the task scheduler when available--something that could be carried out with careful use of message queues on some systemsthere are low-level system calls for asynchronous / (such as the aio_family of functions on unixas of this writingthe python library provides no access to those functionsalthough you can probably find bindings through third-party modules in the author' experienceusing such functionality is lot trickier than it looks and is not really worth the added complexity that gets introduced into your program--you're often better off letting the thread library deal with such matters socket the socket module provides access to the standard bsd socket interface although it' based on unixthis module is available on all platforms the socket interface is designed to be generic and is capable of supporting wide variety of networking protocols (internet,tipcbluetoothand so onhoweverthe most common protocol is the internet protocol (ip)which includes both tcp and udp python supports both ipv and ipv although ipv is far more common it should be noted that this module is relatively low-levelproviding direct access to the network functions provided by the operating system if you are writing network applicationit may be easier to use the modules described in or the socketserver module described at the end of this lib fl ff |
18,317 | network programming and sockets address families some of the socket functions require the specification of an address family the family specifies the network protocol being used the following constants are defined for this purposeconstant description af_bluetooth af_inet af_inet bluetooth protocol ipv protocols (tcpudpipv protocols (tcpudpnetlink interprocess communication link-level packets transparent inter-process communication protocol unix domain protocols af_netlink af_packet af_tipc af_unix of theseaf_inet and af_inet are the most commonly used because they represent standard internet connections af_bluetooth is only available on systems that support it (typically embedded systemsaf_netlinkaf_packetand af_tipc are only supported on linux af_netlink is used for fast interprocess communication between user applications and the linux kernel af_packet is used for working directly at the datalink layer ( raw ethernet packetsaf_tipc is protocol used for high-performance ipc on linux clusters (socket types some socket functions also require the specification of socket type the socket type specifies the type of communications (streams or packetsto be used within given protocol family the following constants are used for this purposeconstant description sock_stream sock_dgram sock_raw sock_rdm sock_seqpacket reliable connection-oriented byte stream (tcpdatagrams (udpraw socket reliable datagrams sequenced connection-mode transfer of records the most common socket types are sock_stream and sock_dgram because they correspond to tcp and udp in the internet protocol suite sock_rdm is reliable form of udp that guarantees the delivery of datagram but doesn' preserve ordering (datagrams might be received in different order than sentsock_seqpacket is used to send packets through stream-oriented connection in manner that preserves their order and packet boundaries neither sock_rdm or sock_seqpacket are widely supportedso it' best not to use them if you care about portability sock_raw is used to provide low-level access to the raw protocol and is used if you want to carry out special-purpose operations such as sending control messages ( icmp messagesuse of sock_raw is usually restricted to programs running with superuser or administrator access lib fl ff |
18,318 | not every socket type is supported by every protocol family for exampleif you're using af_packet to sniff ethernet packets on linuxyou can' establish streamoriented connection using sock_stream insteadyou have to use sock_dgram or sock_raw for af_netlink socketssock_raw is the only supported type addressing in order to perform any communication on socketyou have to specify destination address the form of the address depends on the address family of the socket af_inet (ipv for internet applications using ipv addresses are specified as tuple (hostporthere are two examples('www python org' ( ' if host is the empty stringit has the same meaning as inaddr_anywhich means any address this is typically used by servers when creating sockets that any client can connect to if host is set to ''it has the same meaning as the inaddr_broadcast constant in the socket api be aware that when host names such as 'www python orgare usedpython uses dns to resolve the host name into an ip address depending on how dns has been configuredyou may get different ip address each time use raw ip address such as to avoid this behaviorif needed af_inet (ipv for ipv addresses are specified as -tuple (hostportflowinfoscopeidwith ipv the host and port components work in the same way as ipv except that the numerical form of an ipv host address is typically specified by string of eight colon-separated hexadecimal numberssuch as 'fedc:ba : : :fedc:ba : : or ' :: : (in this casethe double colon fills in range of address components with sthe flowinfo parameter is -bit number consisting of -bit flow label (the low bits) -bit priority (the next bits)and four reserved bits (the high bitsa flow label is typically only used when sender wants to enable special handling by routers otherwiseflowinfo is set to the scopeid parameter is -bit number that' only needed when working with link-local and site-local addresses link-local address always starts with the prefix 'fe and is used between machines on the same lan (routers will not forward link-local packetsin this casescopeid an interface index that identifies specific network interface on the host this information can be viewed using command such as 'ifconfigon unix or 'ipv ifon windows site-local address always starts with the prefix 'fec and is used between machines within the same site (for exampleall machines on given subnetin this casescopeid is site-identifier number if no data is given for flowinfo or scopeidan ipv address can be given as the tuple (hostport)as with ipv lib fl ff |
18,319 | network programming and sockets af_unix for unix domain socketsthe address is string containing path name--for example'/tmp/myserveraf_packet for the linux packet protocolthe address is tuple (deviceprotonum [pkttype [hatype [addr]]]where device is string specifying the device name such as "eth and protonum is an integer specifying the ethernet protocol number as defined in the header file ( for an ip packetpacket_type is an integer specifying the packet type and is one of the following constantsconstant description packet_host packet_broadcast packet_multicast packet_otherhost packet address to the local host physical layer broadcast packet physical layer multicast packet destined for different hostbut caught by device driver in promiscuous mode packet originating on the machinebut which has looped back to packet socket packet_outgoing hatype is an integer specifying the hardware address type as used in the arp protocol and defined in the header file addr is byte string containing hardware addressthe structure of which depends on the value of hatype for ethernetaddr will be -byte string holding the hardware address af_netlink for the linux netlink protocolthe address is tuple (pidgroupswhere pid and groups are both unsigned integers pid is the unicast address of the socket and is usually the same as the process id of the process that created the socket or for the kernel groups is bit mask used to specify multicast groups to join refer to the netlink documentation for more information af_bluetooth bluetooth addresses depend on the protocol being used for capthe address is tuple (addrpsmwhere addr is string such as ' : : : : :aband psm is an unsigned integer for rfcommthe address is tuple (addrchannelwhere addr is an address string and channel is an integer for hcithe address is -tuple (deviceno,where deviceno is an integer device number for scothe address is string host the constant bdaddr_any represents any address and is string ' : : : : : the constant bdaddr_local is string ' : : :ff:ff:ffaf_tipc for tipc socketsthe address is tuple (addr_typev [scope]where all fields are unsigned integers addr_type is one of the following valueswhich also determines the values of and lib fl ff |
18,320 | address type description tipc_addr_nameseq tipc_addr_name is the server typev is the port identifierand is is the server typev is the lower port numberand is the upper port number is the nodev is the referenceand is tipc_addr_id the optional scope field is one of tipc_zone_scopetipc_cluster_scopeor tipc_node_scope functions the socket module defines the following functionscreate_connection(address [timeout]establishes sock_stream connection to address and returns an already connected socket object address is tuple of the form (hostport)and timeout specifies an optional timeout this function works by first calling getaddrinfo(and then trying to connect to each of the tuples that gets returned fromfd(fdfamilysocktype [proto]creates socket object from an integer file descriptorfd the address familysocket typeand protocol number are the same as for socket(the file descriptor must refer to previously created socket it returns an instance of sockettype getaddrinfo(hostport [,family [socktype [proto [flags]]]]given host and port information about hostthis function returns list of tuples containing information needed to open up socket connection host is string containing host name or numerical ip address port is number or string representing service name (for example"http""ftp""smtp"each returned tuple consists of five elements (familysocktypeprotocanonnamesockaddrthe familysocktypeand proto items have the same values as would be passed to the socket(function canonname is string representing the canonical name of the host sockaddr is tuple containing socket address as described in the earlier section on internet addresses here' an examplegetaddrinfo("www python org", [( , , ,'',( ', ))( , , ,'',( '), ))in this examplegetaddrinfo(has returned information about two possible socket connections the first one (proto= is udp connectionand the second one (proto= is tcp connection the additional parameters to getaddrinfo(can be used to narrow the selection for instancethis example returns information about establishing an ipv tcp connectiongetaddrinfo("www python org", ,af_inet,sock_stream[( , , ,'',( ', )) lib fl ff |
18,321 | network programming and sockets the special constant af_unspec can be used for the address family to look for any kind of connection for examplethis code gets information about any tcp-like connection and may return information for either ipv or ipv getaddrinfo("www python org","http"af_unspecsock_stream[( , , ,'',( ', ))getaddrinfo(is intended for very generic purpose and is applicable to all supported network protocols (ipv ipv and so onuse it if you are concerned about compatibility and supporting future protocolsespecially if you intend to support ipv getdefaulttimeout(returns the default socket timeout in seconds value of none indicates that no timeout has been set getfqdn([name]returns the fully qualified domain name of name if name is omittedthe local machine is assumed for examplegetfqdn("foo"might return "foo quasievil orggethostbyname(hostnametranslates host name such as 'www python orgto an ipv address the ip address is returned as stringsuch as it does not support ipv gethostbyname_ex(hostnametranslates host name to an ipv address but returns tuple (hostnamealiaslistipaddrlistin which hostname is the primary host namealiaslist is list of alternative host names for the same addressand ipaddrlist is list of ipv addresses for the same interface on the same host for examplegethostbyname_ex('www python org'returns something like ('fang python org'['www python org'][ ']this function does not support ipv gethostname(returns the host name of the local machine gethostbyaddr(ip_addressreturns the same information as gethostbyname_ex()given an ip address such as if ip_address is an ipv address such as 'fedc:ba : : :fedc:ba : : 'information regarding ipv will be returned getnameinfo(addressflagsgiven socket addressaddressthis function translates the address into -tuple (hostport)depending on the value of flags the address parameter is tuple specifying an address--for example('www python org', flags is the bitwise or of the following constantsf lib fl ff |
18,322 | constant description ni_nofqdn ni_numerichost ni_namereqd don' use fully qualified name for local hosts returns the address in numeric form requires host name returns an error if address has no dns entry the returned port is returned as string containing port number specifies that the service being looked up is datagram service (udpinstead of tcp (the defaultni_numericserv ni_dgram the main purpose of this function is to get additional information about an address here' an examplegetnameinfo(( ', ), ('fang python org''http'getnameinfo(( ', ),ni_numericserv('fang python org',' 'getprotobyname(protocolnametranslates an internet protocol name (such as 'icmp'to protocol number (such as the value of ipproto_icmpthat can be passed to the third argument of the socket(function raises socket error if the protocol name isn' recognized normallythis is only used with raw sockets getservbyname(servicename [protocolname]translates an internet service name and protocol name to port number for that service for examplegetservbyname('ftp''tcp'returns the protocol nameif suppliedshould be 'tcpor 'udpraises socket error if servicename doesn' match any known service getservbyport(port [protocolname]this is the opposite of getservbyname(given numeric port numberportthis function returns string giving the service nameif any for examplegetservbyport( 'tcp'returns 'ftpthe protocol nameif suppliedshould be 'tcpor 'udpraises socket error if no service name is available for port has_ipv boolean constant that is true if ipv support is available htonl(xconverts -bit integers from host to network byte order (big-endianhtons(xconverts -bit integers from host to network byte order (big-endianinet_aton(ip_stringconverts an ipv address provided as string (for example 'to -bit packed binary format for use as the raw-encoding of the address the returned lib fl ff |
18,323 | network programming and sockets value is four-character string containing the binary encoding this may be useful if passing the address to or if the address must be packed into data structure passed to other programs does not support ipv inet_ntoa(packedipconverts binary-packaged ipv address into string that uses the standard dotted representation (for example 'packedip is four-character string containing the raw -bit encoding of an ip address the function may be useful if an address has been received from or is being unpacked from data structure it does not support ipv inet_ntop(address_familypacked_ipconverts packed binary string packed_ip representing an ip network address into string such as address_family is the address family and is usually af_inet or af_inet this can be used to obtain network address string from buffer of raw bytes (for instancefrom the contents of low-level network packetinet_pton(address_familyip_stringconverts an ip address such as into packed byte string address_family is the address family and is usually af_inet or af_inet this can be used if you're trying to encode network address into raw binary data packet ntohl(xconverts -bit integers from network (big-endianto host byte order ntohs(xconverts -bit integers from network (big-endianto host byte order setdefaulttimeout(timeoutsets the default timeout for newly created socket objects timeout is floating-point number specified in seconds value of none may be supplied to indicate no timeout (this is the defaultsocket(familytype [proto]creates new socket using the given address familysocket typeand protocol number family is the address family and type is the socket type as discussed in the first part of this section to open tcp connectionuse socket(af_inetsock_streamto open udp connectionuse socket(af_inetsock_dgramthe function returns an instance of sockettype (described shortlythe protocol number is usually omitted (and defaults to this is typically only used with raw sockets (sock_rawand is set to constant that depends on the address family being used the following list shows all of the protocol numbers that python may define for af_inet and af_inet depending on their availability on the host systemconstant description ipproto_ah ipproto_bip ipproto_dstopts ipproto_egp ipv authentication header banyan vines ipv destination options exterior gateway protocol lib fl ff |
18,324 | constant description ipproto_eon ipproto_esp ipproto_fragment ipproto_ggp iso cnlp (connectionless network protocolipv encapsulating security payload ipv fragmentation header gateway to gateway protocol (rfc generic routing encapsulation (rfc fuzzball hello protocol ipv hop-by-hop options ipv icmp ipv icmp xns idp group management protocol ipv ip payload compression protocol ip inside ip ipv header ipv header ip mobility netdisk protocol ipv no next header protocol independent multicast xerox parc universal packet (pupraw ip packet ipv routing header resource reservation tcp osi transport protocol (tp- udp virtual router redundancy protocol express transfer protocol ipproto_gre ipproto_hello ipproto_hopopts ipproto_icmp ipproto_icmpv ipproto_idp ipproto_igmp ipproto_ip ipproto_ipcomp ipproto_ipip ipproto_ipv ipproto_ipv ipproto_mobile ipproto_nd ipproto_none ipproto_pim ipproto_pup ipproto_raw ipproto_routing ipproto_rsvp ipproto_tcp ipproto_tp ipproto_udp ipproto_vrrp ipproto_xtp the following protocol numbers are used with af_bluetoothconstant description btproto_l cap btproto_hci btproto_rfcomm btproto_sco logical link control and adaption protocol host/controller interface cable replacement protocol synchronous connection oriented link socketpair([family [type [proto ]]]creates pair of connected socket objects using the given familytypeand proto optionswhich have the same meaning as for the socket(function this function only applies to unix domain sockets (family=af_unixtype may be either sock_dgram or sock_stream if type is sock_streaman object known as stream pipe is created proto is usually (the defaultthe primary use of this function would lib fl ff |
18,325 | network programming and sockets be to set up interprocess communication between processes created by os fork(for examplethe parent process would call socketpair(to create pair of sockets and call os fork(the parent and child processes would then communicate with each other using these sockets sockets are represented by an instance of type sockettype the following methods are available on socketss accept(accepts connection and returns pair (connaddress)where conn is new socket object that can be used to send and receive data on the connection and address is the address of the socket on the other end of the connection bind(addressbinds the socket to an address the format of address depends on the address family in most casesit' tuple of the form (hostnameportfor ip addressesthe empty string represents inaddr_any and the string 'represents inaddr_broadcast the inaddr_any host name (the empty stringis used to indicate that the server allows connections on any internet interface on the system this is often used when server is multihomed the inaddr_broadcast host name (''is used when socket is being used to send broadcast message close(closes the socket sockets are also closed when they're garbage-collected connect(addressconnects to remote socket at address the format of address depends on the address familybut it' normally tuple (hostnameportit raises socket error if an error occurs if you're connecting to server on the same computeryou can use the name 'localhostas hostname connect_ex(addresslike connect(address)but returns on success or the value of errno on failure fileno(returns the socket' file descriptor getpeername(returns the remote address to which the socket is connected usually the return value is tuple (ipaddrport)but this depends on the address family being used this is not supported on all systems getsockname(returns the socket' own address usually this is tuple (ipaddrports getsockopt(leveloptname [buflen]returns the value of socket option level defines the level of the option and is sol_socket for socket-level options or protocol number such as ipproto_ip for protocol-related options optname selects specific option if buflen is omittedan integer option is assumed and its integer value is returned if buflen is givenit specifies the maximum length of the buffer used to receive the option this buffer is lib fl ff |
18,326 | returned as byte stringwhere it' up to the caller to decode its contents using the struct module or other means the following tables list the socket options defined by python most of these options are considered part of the advanced sockets api and control low-level details of the network you will need to consult other documentation to find more detailed descriptions when type names are listed in the value columnthat name is same as the standard data structure associated with the value and used in the standard socket programming interface not all options are available on all machines the following are commonly used option names for level sol_socketoption name value so_acceptconn determines whether or not the socket is accepting connections allows sending of broadcast datagrams determines whether or not debugging information is being recorded bypasses routing table lookups int gets error status , prevents other sockets from being forcibly bound to the same address and port this disables the so_reuseaddr option periodically probes the other end of the connection and terminates if it' half-open linger lingers on close(if the send buffer contains data linger is packed binary string containing two -bit integers (onoffseconds places out-of-band data into the input queue int size of receive buffer (in bytesint number of bytes read before select(returns the socket as readable timeval timeout on receive calls in seconds timeval is packed binary string containing two -bit unsigned integers (secondsmicroseconds allows local address reuse allows multiple processes to bind to the same address as long as this socket option is set in all processes int size of send buffer (in bytesint number of bytes available in send buffer before select(returns the socket as writable timeval timeout on send calls in seconds see so_rcvtimeo for description of timeval int gets socket type routing socket gets copy of what it sends so_broadcast so_debug so_dontroute so_error so_exclusiveaddruse so_keepalive so_linger so_oobinline so_rcvbuf so_rcvlowat so_rcvtimeo so_reuseaddr so_reuseport so_sndbuf so_sndlowat so_sndtimeo so_type so_useloopback description lib fl ff |
18,327 | network programming and sockets the following options are available for level ipproto_ipoption name value description ip_add_membership ip_mreg ip_drop_membership ip_mreg ip_hdrincl ip_max_memberships ip_multicast_if int int in_addr ip_multicast_loop ip_multicast_ttl , uint ip_options ipopts ip_recvdstaddr , ip_recvopts ip_recvretopts ip_retopts , , , ip_tos ip_ttl int int join multicast group (set onlyip_mreg is packed binary string containing two bit ip addresses (multiaddrlocaladdr)where multiaddr is the multicast address and localaddr is the ip of the local interface being used leave multicast group (set onlyip_mreg is described above ip header included with data maximum number of multicast groups outgoing interface in_addr is packed binary string containing -bit ip address loopback time to live uint is packed binary string containing -byte unsigned char ip header options ipopts is packed binary string of no more than bytes the contents of this string are described in rfc receive ip destination address with datagram receive all ip options with datagram receive ip options with response same as ip_recvoptsleaves the options unprocessed with no timestamp or route record options filled in type of service time to live the following options are available for level ipproto_ipv option name value description ipv _checksum ipv _dontfrag , , ipv _dstopts ip _dest ipv _hoplimit ipv _hopopts int ip _hbh have system compute checksum don' fragment packets if they exceed the mtu size destination options ip _dest is packed binary string of the form (nextlenoptionswhere next is an -bit integer giving the option type of the next headerlen is an -bit integer specifying the length of the header in units of bytesnot including the first bytesand options is the encoded options hop limit hop-by-hop options ip _hbh has the same encoding as ip _dest lib fl ff |
18,328 | option name value description ipv _join_group ip _mreq join multicast group ip _mreq is packed binary string containing (multiaddrindexwhere multiaddr is -bit ipv multicast address and index is -bit unsigned integer interface index for the local interface leave multicast group hop-limit for multicast packets interface index for outgoing multicast packets deliver outgoing multicast packets back to local application set the next hop address for outgoing packets sockaddr_in is packed binary string containing the sockaddr_in structure as typically defined in packet information structure ip _pktinfo is packed binary string containing (addrindexwhere addr is -bit ipv address and index is bit unsigned integer with the interface index receive destination options receive the hop limit receive hop-by-hop options receive packet information receive routing header receive the traffic class routing header ip _rthdr is packed binary string containing (nextlentypesegleftdatawhere nextlentypeand segleft are all -bit unsigned integers and data is routing data see rfc destination options header before the routing options header enable the receipt of ipv _pathmtu ancillary data items traffic class hop limit for unicast packets path mtu discovery disables it for all desinations - disables it only for multicast destinations only connect to other ipv nodes ipv _leave_group ip _mreq ipv _multicast_hops int ipv _multicast_if int ipv _multicast_loop , ipv _nexthop sockaddr_in ipv _pktinfo ip _pktinfo ipv _recvdstopts ipv _recvhoplimit ipv _recvhopopts ipv _recvpktinfo ipv _recvrthdr ipv _recvtclass ipv _rthdr , , , , , , ip _rthdr ipv _rthdrdstopts ip _dest ipv _recvpathmtu , ipv _tclass ipv _unicast_hops ipv _use_min_mtu int int - , , ipv _v only , lib fl ff |
18,329 | network programming and sockets the following options are available for level sol_tcpoption name value description tcp_cork tcp_defer_accept , , tcp_info tcp_info tcp_keepcnt int tcp_keepidle int tcp_keepintvl tcp_linger int int tcp_maxseg int tcp_nodelay tcp_quickack , , tcp_syncnt int tcp_window_clamp int don' send out partial frames if set awake listener only when data arrives on socket returns structure containing information about the socket tcp_info is implementation specific maximum number of keepalive probes tcp should send before dropping connection time in seconds the connection should be idle before tcp starts sending keepalive probes if the tcp_keepalive option has been set time in seconds between keepalive probes lifetime of orphaned fin_wait state sockets maximum segment size for outgoing tcp packets if setdisables the nagle algorithm if setacks are sent immediately disables the tcp delayed ack algorithm number of syn retransmits before aborting connection request sets an upper bound on the advertised tcp window size gettimeout(returns the current timeout value if any returns floating-point number in seconds or none if no timeout is set ioctl(controloptionprovides limited access to the wsaioctl interface on windows the only supported value for control is sio_rcvall which is used to capture all received ip packets on the network this requires administrator access the following values can be used for optionsoption description rcvall_off prevent the socket from receiving all ipv or ipv packets enable promiscuous modeallowing the socket to receive all ipv or ipv packets on the network the type of packet received depends on the socket address family this does not capture packets associated with other network protocols such as arp receive all ip packets received on the networkbut do not enable promiscuous mode this will capture all ip packets directed at the host for any configured ip address rcvall_on rcvall_iplevel lib fl ff |
18,330 | listen(backlogstarts listening for incoming connections backlog specifies the maximum number of pending connections the operating system should queue before connections are refused the value should be at least with being sufficient for most applications makefile([mode [bufsize]]creates file object associated with the socket mode and bufsize have the same meaning as with the built-in open(function the file object uses duplicated version of the socket file descriptorcreated using os dup()so the file object and socket object can be closed or garbage-collected independently the socket should not have timeout and should not be configured in nonblocking mode recv(bufsize [flags]receives data from the socket the data is returned as string the maximum amount of data to be received is specified by bufsize flags provides additional information about the message and is usually omitted (in which case it defaults to zeroif usedit' usually set to one of the following constants (system-dependent)constant description msg_dontroute msg_dontwait msg_eor bypasses routing table lookup (sends onlynon-blocking operation indicates that the message is last in record usually only used when sending data on sock_seqpacket sockets looks at data but doesn' discard (receives onlyreceives/sends out-of-band data doesn' return until the requested number of bytes have been read (receives onlymsg_peek msg_oob msg_waitall recv_into(buffer [nbytes [flags]]the same as recv(except that data is written into an object buffer supporting the buffer interface nbytes is the maximum number of bytes to receive if omittedthe maximum size is taken from the buffer size flags has the same meaning as for recv( recvfrom(bufsize [flags]like the recv(method except that the return value is pair (dataaddressin which data is string containing the data received and address is the address of the socket sending the data the optional flags argument has the same meaning as for recv(this function is primarily used in conjunction with the udp protocol recvfrom_info(buffer [nbytes [flags]]the same as recvfrom(but the received data is stored in the buffer object buffer nbytes specifies the maximum number of bytes of receive if omittedthe maximum size is taken from the size of buffer flags has the same meaning as for recv( lib fl ff |
18,331 | network programming and sockets send(string [flags]sends data in string to connected socket the optional flags argument has the same meaning as for recv()described earlier returns the number of bytes sentwhich may be fewer than the number of bytes in string raises an exception if an error occurs sendall(string [flags]sends data in string to connected socketexcept that an attempt is made to send all of the data before returning returns none on successraises an exception on failure flags has the same meaning as for send( sendto(string [flags]addresssends data to the socket flags has the same meaning as for recv(address is tuple of the form (hostport)which specifies the remote address the socket should not already be connected returns the number of bytes sent this function is primarily used in conjunction with the udp protocol setblocking(flagif flag is zerothe socket is set to nonblocking mode otherwisethe socket is set to blocking mode (the defaultin nonblocking modeif recv(call doesn' find any data or if send(call cannot immediately send the datathe socket error exception is raised in blocking modethese calls block until they can proceed setsockopt(leveloptnamevaluesets the value of the given socket option level and optname have the same meaning as for getsockopt(the value can be an integer or string representing the contents of buffer in the latter caseit' up to the caller to ensure that the string contains the proper data see getsockopt(for socket option namesvaluesand descriptions settimeout(timeoutsets timeout on socket operations timeout is floating-point number in seconds value of none means no timeout if timeout occursa socket timeout exception is raised as general ruletimeouts should be set as soon as socket is created because they can be applied to operations involved in establishing connection (such as connect() shutdown(howshuts down one or both halves of the connection if how is further receives are disallowed if how is further sends are disallowed if how is further sends and receives are disallowed in addition to these methodsa socket instance also has the following read-only properties which correspond to the arguments passed to the socket(function property description family proto type the socket address family ( af_inetthe socket protocol the socket type ( sock_streamf lib fl ff |
18,332 | exceptions the following exceptions are defined by the socket module error this exception is raised for socketor address-related errors it returns pair (errnomesgwith the error returned by the underlying system call inherits from ioerror herror error raised for address-related errors returns tuple (herrnohmesgcontaining an error number and error message inherits from error gaierror error raised for address-related errors in the getaddrinfo(and getnameinfo(functions the error value is tuple (errnomesg)where errno is an error number and mesg is string containing message errno is set to one of the following constants defined in the socket moduleconstant description eai_addrfamily eai_again eai_badflags eai_badhints eai_fail eai_family eai_memory eai_nodata eai_noname eai_protocol eai_service eai_socktype eai_system address family not supported temporary failure in name resolution invalid flags bad hints nonrecoverable failure in name resolution address family not supported by host memory allocation failure no address associated with node name no node name or service name provided protocol not supported service name not supported for socket type socket type not supported system error timeout exception raised when socket operation times out this only occurs if timeout has been set using the setdefaulttimeout(function or settimeout(method of socket object exception value is string'timeoutinherits from error example simple example of tcp connection is shown in the introduction to this the following example illustrates simple udp echo serverudp message server receive small packets from anywhere and print them out import socket socket socket(socket af_inetsocket sock_dgrams bind(("", )while truedataaddress recvfrom( print("received connection from %sstr(address) sendto( "echo:dataaddressf lib fl ff |
18,333 | here client that sends messages to the previous serverudp message client import socket socket socket(socket af_inetsocket sock_dgrams sendto( "hello world"("" )respaddr recvfrom( print(resps sendto( "spam"("" )respaddr recvfrom( print(resps close(notes not all constants and socket options are available on all platforms if portability is your goalyou should only rely upon options that are documented in major sources such as the richard stevens unix network programming book cited at the beginning of this section notable omissions from the socket module are recvmsg(and sendmsg(system callscommonly used to work with ancillary data and advanced network options related to packet headersroutingand other details for this functionalityyou must install third-party module such as pyxapi ( there is subtle difference between nonblocking socket operations and operations involving timeout when socket function is used in nonblocking modeit will return immediately with an error if the operation would have blocked when timeout is seta function returns an error only if the operation doesn' complete within specified timeout ssl the ssl module is used to wrap socket objects with the secure sockets layer (ssl)which provides data encryption and peer authentication python uses the openssl library (sojust the essential elements of using this module are covered here with the assumption that you know what you're doing when it comes to ssl configurationkeyscertificatesand other related matterswrap_socket(sock [**opts]wraps an existing socket sock (created by the socket modulewith ssl support and returns an instance of sslsocket this function should be used before subsequent connect(or accept(operations are made opts represents number of keyword arguments that are used to specify additional configuration data lib fl ff |
18,334 | keyword argument description boolean flag that indicates whether or not the socket is operating as server (trueor client (falseby defaultthis is false keyfile the key file used to identify the local side of the connection this should be pem-format file and usually only included if the file specified with the certfile doesn' include the key certfile the certificate file used to identify the local side of the connection this should be pem-format file cert_reqs specifies whether certificate is required from the other side of the connection and whether or not it will be validated value of cert_none means that certificates are ignoredcert_optional means that certificates are not required but will be validated if givenand cert_required means that certificates are required and will be validated if certificates are going to be validatedthe ca_certs parameter must also be given ca_certs filename of the file holding certificate authority certificates used for validation ssl_version ssl protocol version to use possible values are protocol_tlsv protocol_sslv protocol_sslv or protocol_sslv the default protocol is protocol_sslv do_handshake_on_connect boolean flag that specifies whether or not the ssl handshake is performed automatically on connect by defaultthis is true suppress_ragged_eofs specifies how read(handles an unexpected eof on the connection if true (the default) normal eof is signaled if falsean exception is raised server_side an instance of sslsocket inherits from socket socket and additionally supports the following operationss cipher(returns tuple (nameversionsecretbitswhere name is the cipher name being usedversion is the ssl protocoland secretbits is the number of secret bits being used do_handshake(performs the ssl handshake normally this is done automatically unless the do_handshake_on_connect option was set to false in the wrap_socket(function if the underlying socket is nonblockingan sslerror exception will be raised if the operation couldn' be completed the args[ attribute of an sslerror exception will have the value ssl_error_want_read or ssl_error_want_write depending on the operation that needs to be performed to continue the handshake process once reading or writing can continuesimply call do_handshake(again lib fl ff |
18,335 | network programming and sockets getpeercert([binary_form]returns the certificate from the other end of the connectionif any if there is no certificate none is returned if there was certificate but it wasn' validatedan empty dictionary is returned if validated certificate is receiveda dictionary with the keys 'subjectand 'notafteris returned if binary_form is set truethe certificate is returned as der-encoded byte sequence read([nbytes]reads up to nbytes of data and returns it if nbytes is omittedup to , bytes are returned write(datawrites the byte string data returns the number of bytes written unwrap(shuts down the ssl connection and returns the underlying socket object on which further unencrypted communication can be carried out the following utility functions are also defined by the modulecert_time_to_seconds(timestringconverts string timestring from the format used in certificates to floating-point number as compatible with the time time(function der_cert_to_pem_cert(derbytesgiven byte string derbytes containing der-encoded certificatereturns pemencoded string version of the certificate pem_cert_to_der_cert(pemstringgiven string pemstring containing pem-encoded string version of certificatereturns der-encoded byte string version of the certificate get_server_certificate(addr [ssl_version [ca_certs]]retrieves the certificate of an ssl server and returns it as pem-encoded string addr is an address of the form (hostnameportssl_version is the ssl version numberand ca_certs is the name of file containing certificate authority certificates as described for the wrap_socket(function rand_status(returns true or false if the ssl layer thinks that the pseudorandom number generator has been seeded with enough randomness rand_egd(pathreads bytes of randomness from an entropy-gathering daemon and adds it to the pseudorandom number generator path is the name of unix-domain socket for the daemon rand_add(bytesentropyadds the bytes in byte string bytes into the pseudorandom number generator entropy is nonnegative floating-point number giving the lower bound on the entropy lib fl ff |
18,336 | examples the following example shows how to use this module to open an ssl-client connectionimport socketssl socket socket(socket af_inetsocket sock_streamssl_s ssl wrap_socket(sssl_s connect(('gmail google com', )print(ssl_s cipher()send request ssl_s write( "get http/ \ \ \ \ "get the response while truedata ssl_s read(if not databreak print(datassl_s close(here is an example of an ssl-secured time serverimport socketssltime socket socket(socket af_inetsocket sock_streams setsockopt(socket sol_socketsocket so_reuseaddr, bind(('', ) listen( while trueclientaddr accept(get connection print "connection from"addr client_ssl ssl wrap_socket(clientserver_side=truecertfile="timecert pem"client_ssl sendall( "http/ ok\ \ "client_ssl sendall( "connectionclose\ \ "client_ssl sendall( "content-typetext/plain\ \ \ \ "resp time ctime("\ \nclient_ssl sendall(resp encode('latin- ')client_ssl close(client close(in order to run this serveryou will need to have signed server certificate in the file timecert pem for the purposes of testingyou can create one using this unix commandopenssl req -new - -days -nodes -out timecert pem -keyout timecert pem to test this servertry connecting with browser using url such as 'about you using self-signed certificate if you agreeyou should see the output of the server socketserver this module is called socketserver in python the socketserver module provides classes that simplify the implementation of tcpudpand unix domain socket servers lib fl ff |
18,337 | network programming and sockets handlers to use the moduleyou define handler class that inherits from the base class baserequesthandler an instance of baserequesthandler implements one or more of the following methodsh finish(called to perform cleanup actions after the handle(method has completed by defaultit does nothing it' not called if either the setup(or handle(method generates an exception handle(this method is called to perform the actual work of request it' called with no argumentsbut several instance variables contain useful values request contains the requesth client_address contains the client addressand server contains an instance of the server that called the handler for stream services such as tcpthe request attribute is socket object for datagram servicesit' byte string containing the received data setup(this method is called before the handle(method to perform initialization actions by defaultit does nothing if you wanted server to implement further connection setup such as establishing ssl connectionyou could implement it here here is an example of handler class that implements simple time server that operates with streams or datagramstryfrom socketserver import baserequesthandler except importerrorfrom socketserver import baserequesthandler import socket import time python python class timeserver(baserequesthandler)def handle(self)resp time ctime("\ \nif isinstance(self request,socket socket) stream-oriented connection self request sendall(resp encode('latin- ')elsea datagram-oriented connection self server socket sendto(resp encode('latin- '),self client_addressif you know that handler is only going to operate on stream-oriented connections such as tcphave it inherit from streamrequesthandler instead of baserequesthandler this class sets two attributesh wfile is file-like object that writes data to the clientand rfile is file-like object that reads data from the client here is an exampletryfrom socketserver import streamrequesthandler except importerrorfrom socketserver import streamrequesthandler import time python python lib fl ff |
18,338 | class timeserver(streamrequesthandler)def handle(self)resp time ctime("\ \nself wfile write(resp encode('latin- ')if you are writing handler that only operates with packets and always sends response back to the senderhave it inherit from datagramrequesthandler instead of baserequesthandler it provides the same file-like interface as streamrequesthandler for exampletryfrom socketserver import datagramrequesthandler except importerrorfrom socketserver import datagramrequesthandler import time python python class timeserver(datagramrequesthandler)def handle(self)resp time ctime("\ \nself wfile write(resp encode('latin- 'in this caseall of the data written to self wfile is collected into single packet that is returned after the handle(method returns servers to use handlerit has to be plugged into server object there are four basic server classes definedtcpserver(addresshandlera server supporting the tcp protocol using ipv address is tuple of the form (hostporthandler is an instance of subclass of the baserequesthandler class described later udpserver(addresshandlera server supporting the internet udp protocol using ipv address and handler are the same as for tcpserver(unixstreamserver(addresshandlera server implementing stream-oriented protocol using unix domain sockets inherits from tcpserver unixdatagramserver(addresshandlera server implementing datagram protocol using unix domain sockets this inherits from udpserver instances of all four server classes have the following basic methodss fileno(returns the integer file descriptor for the server socket the presence of this method makes it legal to use server instances with polling operations such as the select(function serve_forever(handles an infinite number of requests lib fl ff |
18,339 | network programming and sockets shutdown(stops the serve_forever(loop the following attributes give some basic information about the configuration of running servers requesthandlerclass the user-provided request handler class that was passed to the server constructor server_address the address on which the server is listeningsuch as the tuple ( ' socket the socket object being used for incoming requests here is an example of running the timehandler as tcp serverfrom socketserver import tcpserver serv tcpserver(('', ,timehandlerserv serve_forever(here is an example of running the handler as udp serverfrom socketserver import udpserver serv udpserver(('', ,timehandlerserv serve_forever( key aspect of the socketserver module is that handlers are decoupled from servers that isonce you have written handleryou can plug it into many different kinds of servers without having to change its implementation defining customized servers servers often need special configuration to account for different network address familiestimeoutsconcurrencyand other features this customization is carried out by inheriting from one of the four basic servers described in the previous section the following class attributes can be defined to customize basic settings of the underlying network socketserver address_family the address family used by the server socket the default value is socket af_inet use socket af_inet if you want to use ipv server allow_reuse_address boolean flag that indicates whether or not socket should reuse an address this is useful when you want to immediately restart server on the same port after program has terminated (otherwiseyou have to wait few minutesthe default value is false server request_queue_size the size of the request queue that' passed to the socket' listen(method the default value is lib fl ff |
18,340 | server socket_type the socket type used by the serversuch as socket sock_stream or socket sock_dgram server timeout timeout period in seconds that the server waits for new request on timeoutthe server calls the handle_timeout(method (described belowand goes back to waiting this timeout is not used to set socket timeout howeverif socket timeout has been setits value is used instead of this value here is an example of how to create server that allows the port number to be reusedfrom socketserver import tcpserver class timeserver(tcpserver)allow_reuse_address true serv timeserver(('', ,timehandlerserv serve_forever(if desiredthe following methods are most useful to extend in classes that inherit from one of the servers if you define any of these methods in your own servermake sure you call the same method in the superclass server activate(method that carries out the listen(operation on the server the server socket is referenced as self socket server bind(method that carries out the bind(operation on the server server handle_error(requestclient_addressmethod that handles uncaught exceptions that occur in handling to get information about the last exceptionuse sys exc_info(or functions in the traceback module server handle_timeout(method that is called when the server timeout occurs by redefining this method and adjusting the timeout settingyou can integrate other processing into the server event loop server verify_request(requestclient_addressredefine this method if you want to verify the connection before any further processing this is what you define if you wanted to implement firewall or perform some other kind of validation finallyaddition server features are available through the use of mixin classes this is how concurrency via threads or processing forking is added the following classes are defined for this purposeforkingmixin mixin class that adds unix process forking to serverallowing it to serve multiple clients the class variable max_children controls the maximum number of child lib fl ff |
18,341 | processesand the timeout variable determines how much time elapses between attempts to collect zombie processes an instance variable active_children keeps track of how many active processes are running threadingmixin mixin class that modifies server so that it can serve multiple clients with threads there is no limit placed on the number of threads that can be created by defaultthreads are non-daemonic unless the class variable daemon_threads is set to true to add these features to serveryou use multiple inheritance where the mixin class is listed first for examplehere is forking time serverfrom socketserver import tcpserverforkingmixin class timeserver(forkingmixintcpserver)allow_reuse_address true max_children serv timeserver(('', ,timehandlerserv serve_forever(since concurrent servers are relatively commonthe socketserver predefines the following server classes for this purpose forkingudpserver(addresshandlern forkingtcpserver(addresshandlern threadingudpserver(addresshandlern threadingtcpserver(addresshandlerthese classes are actually just defined in terms of the mixins and server classes for examplehere is the definition of forkingtcpserverclass forkingtcpserver(forkingmixintcpserver)pass customization of application servers other library modules often use the socketserver class to implement servers for application-level protocols such as http and xml-rpc those servers can also be customized via inheritance and extending the methods defined for basic server operation for examplehere is forking xml-rpc server that only accepts connections originating on the loopback interfacetryfrom xmlrpc server import simplexmlrpcserver from socketserver import forkingmixin except importerrorfrom simplexmlrpcserver import simplexmlrpcserver from socketserver import forkingmixin python python class myxmlrpcserver(forkingmixin,simplexmlrpcserver)def verify_request(selfrequestclient_address)hostport client_address if host ! 'return false return simplexmlrpcserver verify_request(self,request,client_addressf lib fl ff |
18,342 | sample use def add( , )return + server myxmlrpcserver(("", )server register_function(addserver serve_forever(to test thisyou will need to use the xmlrpclib module run the previous server and then start separate python processimport xmlrpclib xmlrpclib serverproxy( add( , to test the rejection of connectionstry the same codebut from different machine on the network for thisyou will need to replace "localhostwith the hostname of the machine that' running the server lib fl ff |
18,343 | lib fl ff |
18,344 | internet application programming his describes modules related to internet application protocols including httpxml-rpcftpand smtp web programming topics such as cgi scripting are covered in "web programming modules related to dealing with common internet-related data formats are covered in "internet data handling and encoding the organization of network-related library modules is one area where there are significant differences between python and in the interest of looking forwardthis assumes the python library organization because it is more logical howeverthe functionality provided by the library modules is virtually identical between python versions as of this writing when applicablepython module names are noted in each section ftplib the ftplib module implements the client side of the ftp protocol it' rarely necessary to use this module directly because the urllib package provides higher-level interface howeverthis module may still be useful if you want to have more control over the low-level details of an ftp connection in order to use this moduleit may be helpful to know some of the details of the ftp protocol which is described in internet rfc single class is defined for establishing an ftp connectionftp([host [user [passwd [acct [timeout]]]]]creates an object representing an ftp connection host is string specifying host name userpasswdand acct optionally specify usernamepasswordand account if no arguments are giventhe connect(and login(methods must be called explicitly to initiate the actual connection if host is givenconnect(is automatically invoked if userpasswdand acct are givenlogin(is invoked timeout is timeout period in seconds an instance of ftp has the following methodsf abort(attempts to abort file transfer that is in progress this may or may not work depending the remote server lib fl ff |
18,345 | internet application programming close(closes the ftp connection after this has been invokedno further operations can be performed on the ftp object connect(host [port [timeout]]opens an ftp connection to given host and port host is string specifying the host name port is the integer port number of the ftp server and defaults to port timeout is the timeout period in seconds it is not necessary to call this if host name was already given to ftp( cwd(pathnamechanges the current working directory on the server to pathname delete(filenameremoves the file filename from the server dir([dirname [[callback]]]generates directory listing as produced by the 'listcommand dirname optionally supplies the name of directory to list in additionif any additional arguments are suppliedthey are simply passed as additional arguments to 'listif the last argument callback is functionit is used as callback function to process the returned directory listing data this callback function works in the same way as the callback used by the retrlines(method by defaultthis method prints the directory list to sys stdout login([user[passwd [acct]]]logs in to the server using the specified usernamepasswordand account user is string giving the username and defaults to 'anonymouspasswd is string containing the password and defaults to the empty string 'acct is string and defaults to the empty string it is not necessary to call this method if this information was already given to ftp( mkd(pathnamecreates new directory on the server ntransfercmd(command [rest]the same as transfercmd(except that tuple (socksizeis returned where sock is socket object corresponding to the data connection and size is the expected size of the data in bytesor none if the size could not be determined pwd(returns string containing the current working directory on the server quit(closes the ftp connection by sending the 'quitcommand to the server rename(oldname,newnamerenames file on the server lib fl ff |
18,346 | retrbinary(commandcallback [blocksize [rest]]returns the results of executing command on the server using binary transfer mode command is string that specifies the appropriate file retrieval command and is almost always 'retr filenamecallback is callback function that is invoked each time block of data is received this callback function is invoked with single argument which is the received data in the form of string blocksize is the maximum block size to use and defaults to bytes rest is an optional offset into the file if suppliedthis specifies the position in the file where you want to start the transfer howeverthis is not supported by all ftp servers so this may result in an error_reply exception retrlines(command [callback]returns the results of executing command on the server using text transfer mode command is string that specifies the command and is usually something like 'retr filenamecallback is callback function that is invoked each time line of data is received this callback function is called with single argument which is string containing the received data if callback is omittedthe returned data is printed to sys stdout rmd(pathnameremoves directory from the server sendcmd(commandsends simple command to the server and returns the server response command is string containing the command this method should only be used for commands that don' involve the transfer of data set_pasv(pasvsets passive mode pasv is boolean flag that turns passive mode on if true or off if false by defaultpassive mode is on size(filenamereturns the size of filename in bytes returns none if the size can' be determined for some reason storbinary(commandfile [blocksize]executes command on the server and transmits data using binary transfer mode command is string that specifies the low-level command it is almost always set to 'stor filename'where filename is the name of file you want to place on the server file is an open file-object from which data will be read using file read(blocksizeand transferred to the server blocksize is the blocksize to use in the transfer by defaultit is bytes storlines(commandfileexecutes command on the server and transfers data using text transfer mode command is string which specifies the low-level command it is usually 'stor filenamefile is an open file-object from which data will be read using file readline(and sent to the server lib fl ff |
18,347 | internet application programming transfercmd(command [rest]initiates transfer over the ftp data connection if active mode is being usedthis sends 'portor 'eprtcommand and accepts the resulting connection from the server if passive mode is being usedthis sends 'epsvor 'pasvcommand followed by connection to the server in either caseonce the data connection has been establishedthe ftp command in command is then issued this function returns socket object corresponding to the open data connection the optional rest parameter specifies starting byte offset into files requested on the server howeverthis is not supported on all servers and could result in an error_reply exception example the following example shows how to use this module to upload file to ftp serverhost "ftp foo comusername "davepassword " filename "somefile datimport ftplib ftp_serv ftplib ftp(host,username,passwordopen the file you want to send open(filename,"rb"send it to the ftp server resp ftp_serv storbinary("stor "+filenamefclose the connection ftp_serv close to fetch documents from an ftp serveruse the urllib package for exampletryfrom urllib request import urlopen except importerrorfrom urllib import urlopen python python urlopen("ftp://username:password@somehostname/somefile"contents read(http package the http package consists of modules for writing http clients and servers as well as support for state management (cookiesthe hypertext transfer protocol (httpis simple text-based protocol that works as follows client makes connection to an http server and sends request header of the following formget /document html http/ connectionkeep-alive user-agentmozilla/ [en( usunos sun uhostrustler cs uchicago edu: acceptimage/gifimage/ -xbitmapimage/jpegimage/pjpegimage/png*/accept-encodinggzip accept-languageen accept-charsetiso- - ,*,utf- optional data lib fl ff |
18,348 | the first line defines the request typedocument (the selector)and protocol version following the request line is series of header lines containing various information about the clientsuch as passwordscookiescache preferencesand client software following the header linesa single blank line indicates the end of the header lines after the headerdata may appear in the event that the request is sending information from form or uploading file each of the lines in the header should be terminated by carriage return and newline ('\ \ ' the server sends response of the following formhttp/ ok content-typetext/html content-length bytes headerdata data the first line of the server response indicates the http protocol versiona success codeand return message following the response line is series of header fields that contain information about the type of the returned documentthe document sizeweb server softwarecookiesand so forth the header is terminated by single blank line followed by the raw data of the requested document the following request methods are the most commonmethod description get post head put get document post data to form return header information only upload data to the server the response codes detailed in table are most commonly returned by servers the symbolic constant column is the name of predefined variable in http client that holds the integer response code value and which can be used in code to improve readability table code response codes commonly returned by servers description symbolic constant success codes ( xx ok created accepted no content ok created accepted no_content redirection ( xx multiple choices moved permanently moved temporarily not modified multiple_choices moved_permanently moved_temporarily not_modified lib fl ff |
18,349 | internet application programming table code continued description symbolic constant client error ( xx bad request unauthorized forbidden not found bad_request unauthorized forbidden not_found server error ( xx internal server error not implemented bad gateway service unavailable internal_server_error not_implemented bad_gateway service_unavailable the headers that appear in both requests and responses are encoded in format widely known as rfc- then general form of each header is headernamedataalthough further details can be found in the rfc it is almost never necessary to parse these headers as python usually does it for you when applicable http client (httplibthe http client module provides low-level support for the client side of http in python this module is called httplib use functions in the urllib package instead the module supports both http/ and http/ and additionally allows connections via ssl if python is built with openssl support normallyyou do not use this package directlyinsteadyou should consider using the urllib package howeverbecause http is such an important protocolyou may encounter situations where you need to work with the low-level details in way that urllib cannot easily address--for exampleif you wanted to send requests with commands other than get or post for more details about httpconsult rfc (http/ and rfc (http/ the following classes can be used to establish an http connection with serverhttpconnection(host [,port]creates an http connection host is the host nameand port is the remote port number the default port is returns an httpconnection instance httpsconnection(host [port [key_file=kfile [cert_file=cfile ]]]creates an http connection but uses secure socket the default port is key_file and cert_file are optional keyword arguments that specify client pemformatted private-key and certificate chain filesshould they be needed for client authentication howeverno validation of server certificates is performed returns an httpsconnection instance lib fl ff |
18,350 | an instancehof httpconnection or httpsconnection supports the following methodsh connect(initializes the connection to the host and port given to httpconnection(or httpsconnection(other methods call this automatically if connection hasn' been made yet close(closes the connection send(bytessends byte stringbytesto the server direct use of this function is discouraged because it may break the underlying response/request protocol it' most commonly used to send data to the server after endheaders(has been called putrequest(methodselector [skip_host [skip_accept_encoding]]sends request to the server method is the http methodsuch as 'getor 'postselector specifies the object to be returnedsuch as '/index htmlthe skip_host and skip_accept_encoding parameters are flags that disable the sending of hostand accept-encodingheaders in the http request by defaultboth of these arguments are false because the http/ protocol allows multiple requests to be sent over single connectiona cannotsendrequest exception may be raised if the connection is in state that prohibits new requests from being issued putheader(headervaluesends an rfc- -style header to the server it sends line to the serverconsisting of the headera colon and spaceand the value additional arguments are encoded as continuation lines in the header raises cannotsendheader exception if is not in state that allows headers to be sent endheaders(sends blank line to the serverindicating the end of the header lines request(methodurl [body [headers]]sends complete http request to the server method and url have the same meaning as for putrequest(body is an optional string containing data to upload to the server after the request has been sent if body is suppliedthe context-lengthheader will automatically be set to an appropriate value headers is dictionary containing header:value pairs to be given to the putheader(method getresponse(gets response from the server and returns an httpresponse instance that can be used to read data raises responsenotready exception if is not in state where response would be received an httpresponse instanceras returned by the getresponse(methodsupports the following methodsf lib fl ff |
18,351 | internet application programming read([size]reads up to size bytes from the server if size is omittedall the data for this request is returned getheader(name [,default]gets response header name is the name of the header default is the default value to return if the header is not found getheaders(returns list of (headervaluetuples an httpresponse instance also has the following attributesr version http version used by the server status http status code returned by the server reason http error message returned by the server length number of bytes left in the response exceptions the following exceptions may be raised in the course of handling http connectionsexception description httpexception notconnected invalidurl unknownprotocol unknowntransferencoding unimplementedfilemode incompleteread badstatusline base class of all http-related errors request was made but not connected bad url or port number given unknown http protocol number unknown transfer encoding unimplemented file mode incomplete data received unknown status code received the following exceptions are related to the state of http/ connections because http/ allows multiple requests/responses to be sent over single connectionextra rules are imposed as to when requests can be sent and responses received performing operations in the wrong order will generate an exception exception description improperconnectionstate cannotsendrequest cannotsendheader responsenotready base class of all http-connection state errors can' send request can' send headers can' read response lib fl ff |
18,352 | example the following example shows how the httpconnection class can be used to perform memory-efficient file upload to server using post request--something that is not easily accomplished within the urllib framework import os tryfrom httplib import httpconnection except importerrorfrom http client import httpconnection python python boundary "$python-essential-reference$crlf '\ \ndef upload(addrurlformfieldsfilefields)create the sections for form fields formsections [for name in formfieldssection '--'+boundary'content-dispositionform-dataname="% "name''formfields[nameformsections append(crlf join(section)+crlfcollect information about all of the files to be uploaded fileinfo [(os path getsize(filename)formnamefilenamefor formnamefilename in filefields items()create the http headers for each file filebytes fileheaders [for filesizeformname,filename in fileinfoheaders '--'+boundary'content-dispositionform-dataname="% "filename="% "(formnamefilename)'content-length%dfilesize'fileheaders append(crlf join(headers)+crlffilebytes +filesize closing marker closing "--"+boundary+"--\ \ndetermine the entire length of the request content_size (sum(len(ffor in formsectionssum(len(ffor in fileheadersfilebytes+len(closing)upload it conn httpconnection(*addrconn putrequest("post",urlconn putheader("content-type"'multipart/form-databoundary=%sboundaryconn putheader("content-length"str(content_size)conn endheaders( lib fl ff |
18,353 | internet application programming send all form sections for in formsectionsconn send( encode('latin- ')send all files for head,filename in zip(fileheaders,filefields values())conn send(head encode('latin- ') open(filename,"rb"while truechunk read( if not chunkbreak conn send(chunkf close(conn send(closing encode('latin- ') conn getresponse(responsedata read(conn close(return responsedata sampleupload some files the form fields 'name''email'file_ ','file_ 'and so forth are what the remote server is expecting (obviously this will varyserver ('localhost' url '/cgi-bin/upload pyformfields 'name'dave''email'dave@dabeaz comfilefields 'file_ 'img_ jpg''file_ 'img_ jpgresp upload(serverurl,formfields,filefieldsprint(resphttp server (basehttpservercgihttpserversimplehttpserverthe http server module provides various classes for implementing http servers in python the contents of this module are split across three library modulesbasehttpservercgihttpserverand simplehttpserver httpserver the following class implements basic http server in python it is located in the basehttpserver module httpserver(server_addressrequest_handlercreates new httpserver object server_address is tuple of the form (hostporton which the server will listen request_handler is handler class derived from basehttprequesthandlerwhich is described later httpserver inherits directly from tcpserver defined in the socketserver module thusif you want to customize the operation of the http server in any wayyou lib fl ff |
18,354 | inherit from httpserver and extend it here is how you would define multithreaded http server that only accepts connections from specific subnettryfrom http server import httpserver from socketserver import threadingmixin except importerrorfrom basehttpserver import httpserver from socketserver import threadingmixin python python class myhttpserver(threadingmixin,httpserver)def _init_ (self,addr,handler,subnet)httpserver _init_ (self,addr,handlerself subnet subnet def verify_request(selfrequestclient_address)hostport client_address if not host startswith(subnet)return false return httpserver verify_request(self,request,client_addressexample of how the server runs serv myhttpserver(('', )somehandler'serv serve_forever(the httpserver class only deals with the low-level http protocol to get the server to actually do anythingyou have to supply handler class there are two built-in handlers and base class that can be used for defining your own custom handling these are described next simplehttprequesthandler and cgihttprequesthandler two prebuilt web server handler classes can be used if you want to quickly set up simple stand-alone web server these classes operate independently of any third-party web server such as apache cgihttprequesthandler(requestclient_addressserverserves files from the current directory and all its subdirectories in additionthe handler will run file as cgi script if it' located in special cgi directory (defined by the cgi_directories class variable which is set to ['/cgi-bin''/htbin'by defaultthe handler supports getheadand post methods howeverit does not support http redirects (http code )which limits its use to only more simple cgi applications for security purposescgi scripts are executed with uid of nobody in python this class is defined in the cgihttpserver module simplehttprequesthandler(requestclient_addressserverserves files from the current directory and all its subdirectories the class provides support for head and get requestsrespectively all ioerror exceptions result in " file not founderror attempts to access directory result in " directory listing not supportederror in python this class is defined in the simplehttpserver module both of these handlers define the following class variables that can be changed via inheritance if desiredhandler server_version server version string returned to clients by defaultthis is set to string such as 'simplehttp/ lib fl ff |
18,355 | internet application programming handler extensions_map dictionary mapping suffixes to mime types unrecognized file types are considered to be of type 'application/octet-streamhere is an example of using these handler classes to run stand-alone web server capable of running cgi scriptstryfrom http server import httpservercgihttprequesthandler python except importerrorfrom basehttpserver import httpserver python from cgihttpserver import cgihttprequesthandler import os change to the document root os chdir("/home/httpd/html"start the cgihttp server on port serv httpserver(("", ),cgihttprequesthandlerserv serve_forever(basehttprequesthandler the basehttprequesthandler class is base class that' used if you want to define your own custom http server handling the prebuilt handlers such as simplehttprequesthandler and cgihttprequesthandler inherit from this in python this class is defined in the basehttpserver module basehttprequesthandler(requestclient_addressserverbase handler class used to handle http requests when connection is receivedthe request and http headers are parsed an attempt is then made to execute method of the form do_request based on the request type for examplea 'getmethod invokes do_get(and 'postmethod invokes do_post by defaultthis class does nothingso these methods are expected to be defined in subclasses the following class variables are defined for basehttprequesthandler and can be redefined in subclasses basehttprequesthandler server_version specifies the server software version string that the server reports to clients--for example'servername/ basehttprequesthandler sys_version python system versionsuch as 'python/ basehttprequesthandler error_message_format format string used to build error messages sent to the client the format string is applied to dictionary containing the attributes codemessageand explain for example''error response error response error code %(code) message%(message) error code explanation%(code) %(explain) '' lib fl ff |
18,356 | basehttprequesthandler protocol_version http protocol version used in responses the default is 'http/ basehttprequesthandler responses mapping of integer http error codes to two-element tuples (messageexplainthat describe the problem for examplethe integer code is mapped to ("not found""nothing matches the given uri"the integer code and strings in this mapping are use when creating error messages as defined in the error_message_format attribute shown previously when created to handle connectionan instancebof basehttprequesthandler has the following attributesattribute description client_address command path request_version headers client address as tuple (hostportrequest typesuch as 'get''post''head'and so on the request path such as '/index htmlhttp version string from the requestsuch as 'http/ http headers stored in mapping object to test for or extract the contents of headeruse dictionary operations such as headername in headers or headerval headers[headernameinput stream for reading optional input data this is used when client is uploading data (for exampleduring post requestoutput stream for writing response back to the client rfile wfile the following methods are commonly used or redefined in subclassesb send_error(code [message]sends response for an unsuccessful request code is the numeric http response code message is an optional error message log_error(is called to record the error this method creates complete error response using the error_message_format class variablesends it to the clientand closes the connection no further operations should be performed after calling this send_response(code [message]sends response for successful request the http response line is sentfollowed by server and date headers code is an http response codeand message is an optional message log_request(is called to record the request send_header(keywordvaluewrites mime header entry to the output stream keyword is the header keywordand value is its value this should only be called after send_response( end_headers(sends blank line to signal the end of the mime headers lib fl ff |
18,357 | internet application programming log_request([code [size]]logs successful request code is the http codeand size is the size of the response in bytes (if availableby defaultlog_message(is called for logging log_error(formatlogs an error message by defaultlog_message(is called for logging log_message(formatlogs an arbitrary message to sys stderr format is format string applied to any additional arguments passed the client address and current time are prefixed to every message here is an example of creating custom http server that runs in separate thread and lets you monitor the contents of dictionaryinterpreting the request path as key tryfrom http server import basehttprequesthandlerhttpserver except importerrorfrom basehttpserver import basehttprequesthandlerhttpserver py py class dictrequesthandler(basehttprequesthandler)def _init_ (self,thedict,*args,**kwargs)self thedict thedict basehttprequesthandler _init_ (self,*args,**kwargsdef do_get(self)key self path[ :strip the leading '/if not key in self thedictself send_error( "no such key"elseself send_response( self send_header('content-type','text/plain'self end_headers(resp "key % \nkey resp +"value% \nself thedict[keyself wfile write(resp encode('latin- ')example use 'name'dave''values[ , , , , ]'email'dave@dabeaz comfrom functools import partial serv httpserver(("", )partial(dictrequesthandler, )import threading d_mon threading thread(target=serv serve_foreverd_mon start(to test this examplerun the server and then enter url such as /name or contents of the dictionary being displayed this example also shows technique for how to get servers to instantiate handler classes with extra parameters normallyservers create handlers using predefined set of arguments that are passed to _init_ (if you want to add additional parametersuse the functools partial(function as shown this creates callable object that includes your extra parameter but preserves the calling signature expected by the server lib fl ff |
18,358 | http cookies (cookiethe http cookies module provides server-side support for working with http cookies in python the module is called cookie cookies are used to provide state management in servers that implement sessionsuser loginsand related features to drop cookie on user' browseran http server typically adds an http header similar to the following to an http responseset-cookiesession= expires=sun -feb- : : gmtpath=/domain=foo bar com alternativelya cookie can be set by embedding javascript in the section of an html documentdocument cookie "session= expires=sun -feb- : : gmtfeb path=/domain=foo bar com;the http cookies module simplifies the task of generating cookie values by providing special dictionary-like object which stores and manages collections of cookie values known as morsels each morsel has namea valueand set of optional attributes containing metadata to be supplied to the browser {expirespathcommentdomainmax-agesecureversionhttponlythe name is usually simple identifier such as "nameand must not be the same as one of the metadata names such as "expiresor "paththe value is usually short string to create cookiesimply create cookie object like thisc simplecookie(nextcookie values (morselscan be set using ordinary dictionary assignmentc["session" ["user""beazleyadditional attributes of specific morsel are set as followsc["session"]["path""/ ["session"]["domain""foo bar comc["session"]["expires"" -feb- : : gmtto create output representing the cookie data as set of http headersuse the output(method for exampleprint( output()produces two lines of output set-cookiesession= expirespath=/domainset-cookieuser=beazley when browser sends cookie back to an http serverit is encoded as string of key=value pairssuch as "session= user=beazleyoptional attributes such as expirespathand domain are not returned the cookie string can usually be found in the http_cookie environment variablewhich can be read by cgi applications to recover cookie valuesuse code similar to the followingc simplecookie(os environ["http_cookie"]session ["session"value user ["user"value the following documentation describes the simplecookie object in more detail lib fl ff |
18,359 | internet application programming simplecookie([input]defines cookie object in which cookie values are stored as simple strings cookie instancecprovides the following methodsc output([attrs [,header [,sep]]]generates string suitable for use in setting cookie values in http headers attrs is an optional list of the optional attributes to include ("expires""path""domain"and so onby defaultall cookie attributes are included header is the http header to use ('set-cookie:by defaultsep is the character used to join the headers together and is newline by default js_output([attrs]generates string containing javascript code that will set the cookie if executed on browser supporting javascript attrs is an optional list of the attributes to include load(rawdataloads the cookie with data found in rawdata if rawdata is stringit' assumed to be in the same format as the http_cookie environment variable in cgi program if rawdata is dictionaryeach key-value pair is interpreted by setting [key]=value internallythe key/value pairs used to store cookie value are instances of morsel class an instancemof morsel behaves like dictionary and allows the optional "expires""path""comment""domain""max-age""secure""version"and "httponlykeys to be set in additionthe morsel has the following methods and attributesm value string containing the raw value of the cookie coded_value string containing the encoded value of the cookie that would be sent to or received from the browser key the cookie name set(key,value,coded_valuesets the values of keym valueand coded_value shown previously isreservedkey(ktests whether is reserved keywordsuch as "expires""path""domain"and so on output([attrs [,header]]produces the http header string for this morsel attrs is an optional list of the additional attributes to include ("expires""path"and so onheader is the header string to use ('set-cookie:by defaultm js_output([attrs]outputs javascript code that sets the cookie when executed lib fl ff |
18,360 | outputstring([attrs]returns the cookie string without any http headers or javascript code exceptions if an error occurs during the parsing or generation of cookie valuesa cookieerror exception is raised http cookiejar (cookielibthe http cookiejar module provides client-side support for storing and managing http cookies in python the module is called cookielib the primary role of this module is to provide objects in which http cookies can be stored so that they can be used in conjunction with the urllib packagewhich is used to access documents on the internet for instancethe http cookiejar module can be used to capture cookies and to retransmit them on subsequent connection requests it can also be used to work with files containing cookie data such as files created by various browsers the following objects are defined by the modulecookiejar(an object that manages http cookie valuesstoring cookies received as result of http requestsand adding cookies to outgoing http requests cookies are stored entirely in memory and lost when the cookiejar instance is garbage-collected filecookiejar(filename [delayload ]creates filecookiejar instance that retrieves and stores cookie information to file filename is the name of the file delayloadif trueenables lazy access to the file that isthe file won' be read or stored except by demand mozillacookiejar(filename [delayload ]creates filecookiejar instance that is compatible with the mozilla cookies txt file lwpcookiejar(filename [delayload ]creates filecookiejar instance that is compatible with the libwww-perl set-cookie file format it is somewhat rare to work with the methods and attributes of these objects directly if you need to know their low-level programming interfaceconsult the online documentation insteadit is more common to simply instantiate one of the cookie jar objects and plug it into something else that wants to work with cookies an example of this is shown in the urllib request section of this smtplib the smtplib module provides low-level smtp client interface that can be used to send mail using the smtp protocol described in rfc and rfc this module contains number of low-level functions and methods that are described in detail in the online documentation howeverthe following covers the most useful parts of this modulef lib fl ff |
18,361 | internet application programming smtp([host [port]]creates an object representing connection to an smtp server if host is givenit specifies the name of the smtp server port is an optional port number the default port is if host is suppliedthe connect(method is called automatically otherwiseyou will need to manually call connect(on the returned object to establish the connection an instance of smtp has the following methodss connect([host [port]]connects to the smtp server on host if host is omitteda connection is made to the local host ( 'port is an optional port number that defaults to if omitted it is not necessary to call connect(if host name was given to smtp( login(userpasswordlogs into the server if authentication is required user is usernameand password is password quit(terminates the session by sending 'quitcommand to the server sendmail(fromaddrtoaddrsmessagesends mail message to the server fromaddr is string containing the email address of the sender toaddrs is list of strings containing the email addresses of recipients message is string containing completely formatted rfc- compliant message the email package is commonly used to create such messages it is important to note that although message can be given as text stringit should only contain valid ascii characters with values in the range to otherwiseyou will get an encoding error if you need to send message in different encoding such as utf- encode it into byte string first and supply the byte string as message example the following example shows how the module can be used to send messageimport smtplib fromaddr "someone@some comtoaddrs ["recipient@other com"msg "from% \ \nto% \ \ \ \ (fromaddr",join(toaddrs)msg +""refinance your mortgage to buy stocks and viagra""server smtplib smtp('localhost'server sendmail(fromaddrtoaddrsmsgserver quit(urllib package the urllib package provides high-level interface for writing clients that need to interact with http serversftp serversand local files typical applications include scraping data from web pagesautomationproxiesweb crawlersand so forth this is one of the most highly configurable library modulesso every last detail is not presented here insteadthe most common uses of the package are described lib fl ff |
18,362 | in python the urllib functionality is spread across several different library modules including urlliburllib urlparseand robotparser in python all of this functionality has been consolidated and reorganized under the urllib package urllib request (urllib the urllib request module provides functions and classes to open and fetch data from urls in python this functionality is found in module urllib the most common use of this module is to fetch data from web servers using http for examplethis code shows the easiest way to simply fetch web pagetryfrom urllib request import urlopen except importerrorfrom urllib import urlopen python python urlopen("data read(of coursemany complexities arise when interacting with servers in the real world for exampleyou might have to worry about proxy serversauthenticationcookiesuser agentsand other matters all of these are supportedbut the code is more complicated (keep readingurlopen(and requests the most straightforward way to make request is to use the urlopen(function urlopen(url [data [timeout]]opens the url url and returns file-like object that can be used to read the returned data url may either be string containing url or an instance of the request classdescribed shortly data is url-encoded string containing form data to be uploaded to the server when suppliedthe http 'postmethod is used instead of 'get(the defaultdata is generally created using function such as urllib parse urlencode(timeout is an optional timeout in seconds for all blocking operations used internally the file-like object returned by urlopen(supports the following methodsmethod description read([nbytes] readline( readlines( fileno( close( info(reads nbytes of data as byte string reads single line of text as byte string reads all input lines and returns list returns the integer file descriptor closes the connection returns mapping object with meta-information associated with the url for httpthe http headers included with the server response are returned for ftpthe headers include 'content-lengthfor local filesthe headers include date'content-length'and 'content-typefield returns the http response code as an integer--for example for success or for file not found returns the real url of the returned datataking into account any redirection that may have occurred getcode( geturl( lib fl ff |
18,363 | internet application programming it is important to emphasize that the file-like object operates in binary mode if you need to process the response data as textyou will need to decode it using the codecs module or some other means if an error occurs during downloadan urlerror exception is raised this includes errors related to the http protocol itself such as forbidden access or requests for authentication for these kinds of errorsa server typically returns content that gives more descriptive information to get this contentthe exception instance itself operates as file-like object that can be read for exampletryu urlopen("resp read(except httperror as eresp read( very common error that arises with urlopen(is accessing web pages through proxy server for exampleif your organization routes all web traffic through proxyrequests may fail if the proxy server doesn' require any kind of authenticationyou may be able to fix this by merely setting the http_proxy environment variable in the os environ dictionary for exampleos environ['http_proxy''for simple requeststhe url parameter to urlopen(is string such as 'make modifications to http request headerscreate request instance and use that as the url parameter request(url [data [headers [origin_req_host [unverifiable]]]]creates new request instance url specifies the url (for example'the server in http requests when this is suppliedit changes the http request type from 'getto 'postheaders is dictionary containing key-value mappings representing the contents of the http headers origin_req_host is set to the request-host of the transaction--typically it' the host name from which the request is originating unverifiable is set to true if the request is for an unverifiable url an unverifiable url is informally defined as url not directly entered by the user--for instancea url embedded within page that loads an image the default value of unverifiable is false an instance of request has the following methodsr add_data(dataadds data to request if the request is an http requestthe method is changed to 'postdata is url-encoded data as described for request(this does not append data to any previously set datait simply replaces the old data with data add_header(keyvaladds header information to the request key is the header nameand val is the header value both arguments are strings lib fl ff |
18,364 | add_unredirected_header(keyvaladds header information to request that will not be added to redirected requests key and val have the same meaning as for add_header( get_data(returns the request data (if anyr get_full_url(returns the full url of request get_host(returns the host to which the request will be sent get_method(returns the http methodwhich is either 'getor 'postr get_origin_req_host(returns the request-host of the originating transaction get_selector(returns the selector part of the url (for example'/index html' get_type(returns the url type (for example'http' has_data(returns true if data is part of the request is_unverifiable(returns true if the request is unverifiable has_header(headerreturns true if the request has header header set_proxy(hosttypeprepares the request for connecting to proxy server this replaces the original host with host and the original type of the request with type the selector part of the url is set to the original url here is an example that uses request object to change the 'user-agentheader used by urlopen(you might use this if you wanted server to think you were making connection from internet explorerfirefoxor some other browser headers 'user-agent''mozilla/ (compatiblemsie windows nt net clr ) request(" urlopen(rf lib fl ff |
18,365 | internet application programming custom openers the basic urlopen(function does not provide support for authenticationcookiesor other advanced features of http to add supportyou must create your own custom opener object using the build_opener(functionbuild_opener([handler [handler ]]builds custom opener object for opening urls the arguments handler handler and so on are all instances of special handler objects the purpose of these handlers is to add various capabilities to the resulting opener object the following lists all the available handler objectshandler description cacheftphandler filehandler ftphandler httpbasicauthhandler httpcookieprocessor httpdefaulterrorhandler ftp handler with persistent ftp connections opens local files opens urls via ftp basic http authentication handling processing of http cookies handles http errors by raising an httperror exception http digest authentication handling opens urls via http handles http redirects opens urls via secure http redirects requests through proxy basic proxy authentication digest proxy authentication handler that deals with all unknown urls httpdigestauthhandler httphandler httpredirecthandler httpshandler proxyhandler proxybasicauthhandler proxydigestauthhandler unknownhandler by defaultan opener is always created with the handlers proxyhandlerunknownhandlerhttphandlerhttpshandlerhttpdefaulterrorhandlerhttpredirecthandlerftphandlerfilehandlerand httperrorprocessor these handlers provide basic level of functionality extra handlers supplied as arguments are added to this list howeverif any of the extra handlers are of the same type as the defaultsthey take precedence for exampleif you added an instance of httphandler or some class that derived from httphandlerit would be used instead of the default the object returned by build_opener(has methodopen(url [data [timeout]])that is used to open urls according to all the rules provided by the various handlers the arguments to open(are the same as what are passed to the urlopen(function install_opener(openerinstalls different opener object for use as the global url opener used by urlopen(opener is usually of an opener object created by build_opener(the next few sections show how to create custom openers for some of the more common scenarios that arise when using urlib request module lib fl ff |
18,366 | password authentication to handle requests involving password authenticationyou create an opener with some combination of httpbasicauthhandlerhttpdigestauthhandlerproxybasicauthhandleror proxydigestauthhandler handlers added to it each of these handlers has the following method which can be used to set passwordh add_password(realmuriuserpasswdadds user and password information for given realm and uri all parameters are strings uri can optionally be sequence of urisin which case the user and password information is applied to all the uris in the sequence the realm is name or description associated with the authentication its value depends on the remote server howeverit' usually common name associated with collection of related web pages uri is base url associated with the authentication typical values for realm and uri might be something like ('administrator''and password specify username and passwordrespectively here is an example of how to set up an opener with basic authenticationauth httpbasicauthhandler(auth add_password("administrator","create opener with authentication added opener build_opener(authopen url opener open("http cookies to manage http cookiescreate an opener object with an httpcookieprocessor handler added to it for examplecookiehand httpcookieprocessor(opener build_opener(cookiehandu opener open("by defaultthe httpcookieprocessor uses the cookiejar object found in the http cookiejar module different types of cookie processing can be supported by supplying different cookiejar object as an argument to httpcookieprocessor for examplecookiehand httpcookieprocessorhttp cookiejar mozillacookiejar("cookies txt"opener build_opener(cookiehandu opener open("proxies if requests need to be redirected through proxycreate an instance of proxyhandler proxyhandler([proxies]creates proxy handler that routes requests through proxy the argument proxies is dictionary that maps protocol names (for example'http''ftp'and so onto the urls of the corresponding proxy server lib fl ff |
18,367 | internet application programming the following example shows how to use thisproxy proxyhandler({'http''auth httpbasicauthhandler(auth add_password("realm","host""username""password"opener build_opener(proxyauthu opener open("urllib response this is an internal module that implements the file-like objects returned by functions in the urllib request module there is no public api urllib parse the urllib parse module is used to manipulate url strings such as "url parsing (urlparse module in python the general form of url is "scheme://netlocpath;parameters?query#fragmentin additionthe netloc part of url may include port number such as "hostname:portor user authentication information such as "user:pass@hostnamethe following function is used to parse urlurlparse(urlstring [default_scheme [allow_fragments]]parses the url in urlstring and returns parseresult instance default_scheme specifies the scheme ("http""ftp"and so onto be used if none is present in the url if allow_fragments is zerofragment identifiers are not allowed parseresult instance is named tuple the form (schemenetlocpathparametersqueryfragmenthoweverthe following read-only attributes are also definedattribute description scheme netloc path params query fragment username url scheme specifier (for example'http'netloc specifier (for example'www python org'hierarchical path (for example'/index html'parameters for the last path element query string (for example'name=dave&id= 'fragment identifier without the leading '#username component if the netloc specifier is of the form 'username:password@hostnamepassword component from the netloc specifier host name component from the netloc specifier port number from the netloc specifier if it is of the form 'hostname:portr password hostname port parseresult instance can be turned back into url string using geturl( lib fl ff |
18,368 | urlunparse(partsconstructs url string from tuple-representation of url as returned by urlparse(parts must be tuple or iterable with six components urlsplit(url [default_scheme [allow_fragments]]the same as urlparse(except that the parameters portion of url is left unmodified in the path this allows for parsing of urls where parameters might be attached to individual path components such as 'scheme://netloc/path ;param /path ;param /path ?query#fragmentthe result is an instance of splitresultwhich is named tuple containing (schemenetlocpathqueryfragmentthe following read-only attributes are also definedattribute description scheme netloc path query fragment username url scheme specifier (for example'http'netloc specifier (for example'www python org'hierarchical path (for example'/index html'query string (for example'name=dave&id= 'fragment identifier without the leading '#username component if the netloc specifier is of the form 'username:password@hostnamepassword component from the netloc specifier host name component from the netloc specifier port number from the netloc specifier if it is of the form 'hostname:portr password hostname port splitresult instance can be turned back into url string using geturl(urlunsplit(partsconstructs url from the tuple-representation created by urlsplit(parts is tuple or iterable with the five url components urldefrag(urlreturns tuple (newurlfragmentwhere newurl is url stripped of fragments and fragment is string containing the fragment part (if anyif there are no fragments in urlthen newurl is the same as url and fragment is an empty string urljoin(baseurl [allow_fragments]constructs an absolute url by combining base urlbasewith relative url url allow_fragments has the same meaning as for urlparse(if the last component of the base url is not directoryit' stripped parse_qs(qs [keep_blank_values [strict_parsing]]parses url-encoded (mime type application/ -www-form-urlencodedquery string qs and returns dictionary where the keys are the query variable names and the values are lists of values defined for each name keep_blank_values is boolean flag lib fl ff |
18,369 | internet application programming that controls how blank values are handled if truethey are included in the dictionary with value set to the empty string if false (the default)they are discarded strict_parsing is boolean flag that if trueturns parsing errors into valueerror exception by defaulterrors are silently ignored parse_qsl(qs [keep_blank_values [strict_parsing]]the same as parse_qs(except that the result is list of pairs (namevaluewhere name is the name of query variable and value is the value url encoding (urllib module in python the following functions are used to encode and decode data that make up urls quote(string [safe [encoding [errors]]]replaces special characters in string with escape sequences suitable for including in url lettersdigitsand the underscore )comma (,)period )and hyphen characters are unchanged all other characters are converted into escape sequences of the form '%xxsafe provides string of additional characters that should not be quoted and is '/by default encoding specifies the encoding to use for non-ascii characters by defaultit is 'utf- errors specifies what to do when encoding errors are encountered and is 'strictby default the encoding and errors parameters are only available in python quote_plus(string [safe [encoding [errors]]]calls quote(and additionally replaces all spaces with plus signs string and safe are the same as in quote(encoding and errors are the same as with quote(quote_from_bytes(bytes [safe]the same as quote(but accepts byte-string and performs no encoding the return result is text string python only unquote(string [encoding [errors]]replaces escape sequences of the form '%xxwith their single-character equivalent encoding and errors specify the encoding and error handling for decoding data in '%xxescapes the default encoding is 'utf- 'and the default errors policy is 'replaceencoding and errors are python only unquote_plus(string [encoding [errors]]like unquote(but also replaces plus signs with spaces unquote_to_bytes(stringthe same as unquote(but performs no decoding and returns byte string urlencode(query [doseq]converts query values in query to url-encoded string suitable for inclusion as the query parameter of url or for uploading as part of post request query is either dictionary or sequence of (keyvaluepairs the resulting string is series of 'key=valuepairs separated by '&characterswhere both key and value are quoted using quote_plus(the doseq parameter is boolean flag that should be set to true if any value in query is sequencerepresenting multiple values for the same key in this casea separate 'key=vstring is created for each in value lib fl ff |
18,370 | examples the following examples show how to turn dictionary of query variables into url suitable for use in an http get request and how you can parse urltryfrom urllib parse import urlparseurlencodeparse_qsl except importerrorfrom urlparse import urlparseparse_qsl from urllib import urlencode python python example of creating url with properly encoded query varibles form_fields 'name'dave''email'dave@dabeaz com''uid' form_data urlencode(form_fieldsurl "example of parsing url into components urlparse(urlprint( scheme'httpprint( netloc'www somehost comprint( path'/cgi-bin/view pyprint( params'print( query'uid= &name=dave&email=dave% dabeaz comprint( fragment'extract query data parsed_fields dict(parse_qsl( query)assert form_fields =parsed_fields urllib error the urllib error module defines exceptions used by the urllib package contenttooshort raised when the amount of downloaded data is less than the expected amount (as defined by the 'content-lengthheaderdefined in the urllib module in python httperror raised to indicate problems with the http protocol this error may be used to signal events such as authentication required this exception can also be used as file object to read the data returned by the server that' associated with the error this is subclass of urlerror it is defined in the urllib module in python urlerror error raised by handlers when problem is detected this is subclass of ioerror the reason attribute of the exception instance has more information about the problem this is defined in the urllib module in python urllib robotparser (robotparserthe urllib robotparser module (robotparser in python is used to fetch and parse the contents of 'robots txtfiles used to instruct web crawlers consult the online documentation for further usage information lib fl ff |
18,371 | internet application programming notes advanced users of the urllib package can customize its behavior in almost every way imaginable this includes creating new kinds of openershandlersrequestsprotocolsetc this topic is beyond the scope of what can be covered herebut the online documentation has some further details users of python should take note that the urllib urlopen(functionwhich is in widespread useis officially deprecated in python and eliminated in python instead of using urllib urlopen()you should use urllib urlopen()which provides the same functionality as urllib request urlopen(described here xmlrpc package the xmlrpc package contains modules for implement xml-rpc servers and clients xml-rpc is remote procedure call mechanism that uses xml for data encoding and http as transport mechanism the underlying protocol is not specific to python so programs using these modules can potentially interact with programs written in other languages more information about xml-rpc can be obtained at xmlrpc com xmlrpc client (xmlrpclibthe xmlrpc client module is used to write xml-rpc clients in python this module is called xmlrpclib to operate as clientyou create an instance of serverproxyserverproxy(uri [transport [encoding [verbose [allow_none [use_datetime]]]]uri is the location of the remote xml-rpc server--for example"foo com/rpc if necessarybasic authentication information can be added to the uri using the format "username and password this information is base- encoded and put in an 'authorization:header on transport if python is configured with openssl supporthttps can also be used transport specifies factory function for creating an internal transport object used for low-level communication this argument is only used if xml-rpc is being used over some kind of connection other than http or https it is almost never necessary to supply this argument in normal use (consult the online documentation for detailsencoding specifies the encodingwhich is utf- by default verbose displays some debugging information if true allow_noneif trueallows the value none to be sent to remote servers by defaultthis is disabled because it' not universally supported use_datetime is boolean flag that if set to trueuses the datetime module to represent dates and times by defaultthis is false an instancesof serverproxy transparently exposes all the methods on the remote server the methods are accessed as attributes of for examplethis code gets the current time from remote server providing that services serverproxy( currenttime getcurrenttime( lib fl ff |
18,372 | for the most partrpc calls work just like ordinary python functions howeveronly limited number of argument types and return values are supported by the xml-rpc protocolxml-rpc type python equivalent boolean integer float string array structure dates binary true and false int float string or unicode (must only contain characters valid in xmlany sequence containing valid xml-rpc types dictionary containing string keys and values of valid types date and time (xmlrpc client datetimebinary data (xmlrpc client binarywhen dates are receivedthey are stored in an xmlrpc client datetime instance the value attribute contains the date as an iso time/date string to convert it into time tuple compatible with the time moduleuse timetuple(when binary data is receivedit is stored in an xmlrpc client binary instance the data attribute contains the data as byte string be aware that strings are assumed to be unicode and that you will have to worry about using proper encodings sending raw python byte strings will work if they contain ascii but will break otherwise to deal with thisconvert to unicode string first if you make an rpc call with arguments involving invalid typesyou may get typeerror or an xmlrpclib fault exception if the remote xml-rpc server supports introspectionthe following methods may be availables system listmethods(returns list of strings listing all the methods provided by the xml-rpc server methodsignatures(namegiven the name of methodnamereturns list of possible calling signatures for the method each signature is list of types in the form of comma-separated string (for example'stringintint')where the first item is the return type and the remaining items are argument types multiple signatures may be returned due to overloading in xml-rpc servers implemented in pythonsignatures are typically empty because functions and methods are dynamically typed methodhelp(namegiven the name of methodnamereturns documentation string describing the use of that method documentation strings may contain html markup an empty string is returned if no documentation is available the following utility functions are available in the xmlrpclib moduleboolean(valuecreates an xml-rpc boolean object from value this function predates the existence of the python boolean typeso you may see it used in older code lib fl ff |
18,373 | internet application programming binary(datacreates an xml-rpc object containing binary data data is string containing the raw data returns binary instance the returned binary instance is transparently encoded/decoded using base during transmission to extract binary from binary instance buse data datetime(daytimecreates an xml-rpc object containing date daytime is either an iso format date stringa time tuple or struct as returned by time localtime()or datetime instance from the datetime module dumps(params [methodname [methodresponse [encoding [allow_none]]]]converts params into an xml-rpc request or responsewhere params is either tuple of arguments or an instance of the fault exception methodname is the name of the method as string methodresponse is boolean flag if truethen the result is an xml-rpc response in this caseonly one value can be supplied in params encoding specifies the text encoding in the generated xml and defaults to utf- allow_none is flag that specifies whether or not none is supported as parameter type none is not explicitly mentioned by the xml-rpc specificationbut many servers support it by defaultallow_none is false loads(dataconverts data containing an xml-rpc request or response into tuple (paramsmethodnamewhere params is tuple of parameters and methodname is string containing the method name if the request represents fault condition instead of an actual valuethen the fault exception is raised multicall(servercreates multicall object that allows multiple xml-rpc requests to be packaged together and sent as single request this can be useful performance optimization if many different rpc requests need to be made on the same server server is an instance of serverproxyrepresenting connection to remote server the returned multicall object is used in exactly the same way as serverproxy howeverinstead of immediately executing the remote methodsthe method calls as queued until the multicall object is called as function once this occursthe rpc requests are transmitted the return value of this operation is generator that yields the return result of each rpc operation in sequence note that multicall(only works if the remote server provides system multicall(method here is an example that illustrates the use of multicallmulti multicall(servermulti foo( , , remote method foo multi bar("hello world"remote method bar multi spam(remote method spam nowactually send the xml-rpc request and get return results foo_resultbar_resultspam_result multi( lib fl ff |
18,374 | exceptions the following exceptions are defined in xmlrpc clientfault indicates an xml-rpc fault the faultcode attribute contains string with the fault type the faultstring attribute contains descriptive message related to the fault protocolerror indicates problem with the underlying networking--for examplea bad url or connection problem of some kind the url attribute contains the uri that triggered the error the errcode attribute contains an error code the errmsg attribute contains descriptive string the headers attribute contains all the http headers of the request that triggered the error xmlrpc server (simplexmlrpcserverdocxmlrpcserverthe xmlrpc server module contains classes for implementing different variants of xml-rpc servers in python this functionality is found in two separate modulessimplexmlrpcserver and docxmlrpcserver simplexmlrpcserver(addr [requesthandler [logrequests]]creates an xml-rpc server listening on the socket address addr (for example('localhost', )requesthandler is factory function that creates handler request objects when connections are received by defaultit is set to simplexmlrpcrequesthandlerwhich is currently the only available handler logrequests is boolean flag that indicates whether or not to log incoming requests the default value is true docxmlrpcserver(addr [requesthandler [logrequest]creates documenting xml-rpc that additionally responds to http get requests (normally sent by browserif receivedthe server generates documentation from the documentation strings found in all of the registered methods and objects the arguments have the same meaning as for simplexmlrpcserver an instancesof simplexmlrpcserver or docxmlrpcserver has the following methodss register_function(func [name]registers new functionfuncwith the xml-rpc server name is an optional name to use for the function if name is suppliedit' the name clients will use to access the function this name may contain characters that are not part of valid python identifiersincluding periods if name is not suppliedthen the actual function name of func is used instead register_instance(instance [allow_dotted_names]registers an object that' used to resolve method names not registered with the register_function(method if the instance instance defines the method _dispatch(selfmethodnameparams)it is called to process requests methodname is the name of the methodand params is tuple containing arguments the return value of _dispatch(is returned to clients if no _dispatch(method is definedthe instance is lib fl ff |
18,375 | internet application programming checked to see if the method name matches the names of any methods defined for instance if sothe method is called directly the allow_dotted_names parameter is flag that indicates whether hierarchical search should be performed when checking for method names for exampleif request for method 'foo bar spamis receivedthis determines whether or not search for instance foo bar spam is made by defaultthis is false it should not be set to true unless the client has been verified otherwiseit opens up security hole that can allow intruders to execute arbitrary python code note thatat mostonly one instance can be registered at time register_introspection_functions(adds xml-rpc introspection functions system listmethods()system methodhelp()and system methodsignature(to the xml-rpc server system methodhelp(returns the documentation string for method (if anythe system methodsignature(function simply returns message indicating that the operation is unsupported (because python is dynamically typedtype information is availables register_multicall_functions(adds xml-rpc multicall function support by adding the system multicall(function to the server an instance of docxmlrpcserver additionally provides these methodss set_server_title(server_titlesets the title of the server in html documentation the string is placed in the html tag set_server_name(server_namesets the name of the server in html documentation the string appears at the top of the page in an tag set_server_documentation(server_documentationadds descriptive paragraph to the generated html output this string is added right after the server namebut before description of the xml-rpc functions although it is common for an xml-rpc server to operate as stand-alone processit can also run inside cgi script the following classes are used for thiscgixmlrpcrequesthandler([allow_none [encoding]] cgi request handler that operates in the same manner as simplexmlrpcserver the arguments have the same meaning as described for simplexmlrpcserver doccgixmlrpcrequesthandler( cgi request handler that operates in the same manner as docxmlrpcserver please note that as of this writingthe calling arguments are different than cgixmlrpcrequesthandler(this might be python bug so you should consult the online documentation in future releases an instancecof either cgi handler has the same methods as normal xml-rpc server for registering functions and instances howeverthey additionally define the following methodf lib fl ff |
18,376 | handle_request([request_text]processes an xml-rpc request by defaultthe request is read from standard input if request_text is suppliedit contains the request data in the form received by an http post request examples here is very simple example of writing standalone server it adds single functionadd in additionit adds the entire contents of the math module as an instanceexposing all the functions it contains tryfrom xmlrpc server import simplexmlrpcserver python except importerrorfrom simplexmlrpcserver import simplexmlrpcserver python import math def add( , )"adds two numbersreturn + simplexmlrpcserver(('', ) register_function(adds register_instance(maths register_introspection_functions( serve_forever(here is the same functionality implemented as cgi-scripttryfrom xmlrpc server import cgixmlrpcrequesthandler python except importerrorfrom simplexmlrpcserver import cgixmlrpcrequesthandler python import math def add( , )"adds two numbersreturn + cgixmlrpcrequesthandler( register_function(adds register_instance(maths register_introspection_functions( handle_request(to access xml-rpc functions from other python programsuse the xmlrpc client or xmlrpclib module here is short interactive session that shows how it worksfrom xmlrpc client import serverproxy serverproxy( add( , system listmethods(['acos''add''asin''atan''atan ''ceil''cos''cosh''degrees''exp''fabs''floor''fmod''frexp''hypot''ldexp''log''log ''modf''pow''radians''sin''sinh''sqrt''system listmethods''system methodhelp''system methodsignature''tan''tanh' tan( lib fl ff |
18,377 | internet application programming advanced server customization the xml-rpc server modules are easy to use for basic kinds of distributed computing for examplexml-rpc could be used as protocol for high-level control of other systems on the networkprovided they were all running suitable xml-rpc server more interesting objects can also be passed between systems if you additionally use the pickle module one concern with xml-rpc is that of security by defaultan xml-rpc server runs as an open service on the networkso anyone who knows the address and port of the server can connect to it (unless it' shielded by firewallin additionxml-rpc servers place no limit on the amount of data that can be sent in request an attacker could potentially crash the server by sending an http post request with payload so large as to exhaust memory if you want to address any of these issuesyou will need to customize the xmlrpc server classes or request handlers all of the server classes inherit from tcpserver in the socketserver module thusthe servers can be customized in the same manner as other socket server classes (for exampleadding threadingforkingor validating client addressesa validation wrapper can be placed around the request handlers by inheriting from simplexmlrpcrequesthandler or docxmlrpcrequesthandler and extending the do_post(method here is an example that limits the size of incoming requeststryfrom xmlrpc server import (simplexmlrpcserversimplexmlrpcrequesthandlerexcept importerrorfrom simplexmlrpcserver import (simplexmlrpcserversimplexmlrpcrequesthandlerclass maxsizexmlrpchandler(simplexmlrpcrequesthandler)maxsize * mb def do_post(self)size int(self headers get('content-length', )if size >self maxsizeself send_error( ,"bad request"elsesimplexmlrpcrequesthandler do_post(selfs simplexmlrpcserver(('', ),maxsizexmlrpchandlerif you wanted to add any kind of http-based authenticationit could also be implemented in similar manner lib fl ff |
18,378 | web programming ython is widely used when building websites and serves several different roles in this capacity firstpython scripts are often useful way to simply generate set of static html pages to be delivered by web server for examplea script can be used to take raw content and decorate it with additional features that you typically see on website (navigation barssidebarsadvertisementsstylesheetsetc this is mainly just matter of file handling and text processing--topics that have been covered in other sections of the book secondpython scripts are used to generate dynamic content for examplea website might operate using standard webserver such as apache but would use python scripts to dynamically handle certain kinds of requests this use of python is primarily associated with form processing for examplean html page might include form like thisyour name your email addresswithin the formthe action attribute names python script 'subscribe pythat will execute on the server when the form is submitted another common scenario involving dynamic content generation is with ajax (asynchronous javascript and xmlwith ajaxjavascript event handlers are associated with certain html elements on page for examplewhen the mouse hovers over specific document elementa javascript function might execute and send an http request to the webserver that gets processed (possibly by python scriptwhen the associated response is receivedanother javascript function executes to process the response data and displays the result there are many ways in which results might be returned for examplea server might return data as plaintextxmljsonor any number of other formats here is an example html document that illustrates one way to implement hover popup where moving the mouse over selected elements causes popup window to appear acme officials quiet after corruption probe popup border-bottom: px dashed greenpopup:hover background-color# fff lib fl ff |
18,379 | <span id="popupboxstyle="visibility:hiddenposition:absolutebackground-color#ffffff;"/get reference to the popup box element *var popup document getelementbyid("popupbox")var popupcontent document getelementbyid("popupcontent")/get pop-up data from the server and display when received *function showpopup(hoveritem,namevar request new xmlhttprequest()request open("get","cgi-bin/popupdata py?name="+nametrue)request onreadystatechange function(var done ok if (request readystate =done &request status =okif (request responsetextpopupcontent innerhtml request responsetextpopup style left hoveritem offsetleft+ popup style top hoveritem offsettop+ popup style visibility "visible"}request send()/hide the popup box *function hidepopup(popup style visibility "hidden"acme officials quiet after corruption probe todayshares of acme corporation (<span class="popuponmouseover="showpopup(this,'acme');onmouseout="hidepopup();">acmeplummetted by more than after federal investigators revealed that the board of directors is the target of corruption probe involving the governorstate lottery officialsand the archbishop in this examplethe javascript function showpopup(initiates request to python script popupdata py on the server the result of this script is just fragment of htmlwhich is then displayed in popup window figure shows what this might look like in the browser finallythe entire website might run under the control of python within the context of framework written in python it has been humorously noted that python has "more web programming frameworks than language keywords "the topics of web frameworks is far beyond the scope of this bookbut moin/webframeworks is good starting point for finding more information lib fl ff |
18,380 | figure possible browser display where the background text is just an ordinary html document and the pop-up window is dynamically generated by the popupdata py script the rest of this describes built-in modules related to the low-level interface by which python interfaces with webservers and frameworks topics include cgi scriptinga technique used to access python from third-party web servers and wsgia middleware layer used for writing components that integrate with python' various web frameworks cgi the cgi module is used to implement cgi scriptswhich are programs typically executed by webserver when it wants to process user input from form or generate dynamic content of some kind when request corresponding to cgi script is submittedthe webserver executes the cgi program as subprocess cgi programs receive input from two sourcessys stdin and environment variables set by the server the following list details common environment variables set by webserversvariable description auth_type content_length content_type document_root gateway_interface http_accept http_cookie http_from http_referer http_user_agent path_info path_translated query_string remote_addr remote_host authentication method length of data passed in sys stdin type of query data document root directory cgi revision string mime types accepted by the client netscape persistent cookie value email address of client (often disabledreferring url client browser extra path information passed translated version of path_info query string remote ip address of the client remote host name of the client lib fl ff |
18,381 | web programming variable description remote_ident remote_user request_method script_name user making the request authenticated username method ('getor 'post'name of the program server host name server port number server protocol name and version of the server software server_name server_port server_protocol server_software as outputa cgi program writes to standard output sys stdout the gory details of cgi programming can be found in book such as cgi programming with perl nd editionby shishir gundavaram ( 'reilly associates for our purposesthere are really only two things to know firstthe contents of an html form are passed to cgi program in sequence of text known as query string in pythonthe contents of the query string are accessed using the fieldstorage class for exampleimport cgi form cgi fieldstorage(name form getvalue('name'email form getvalue('email'get 'namefield from form get 'emailfield from form secondthe output of cgi program consists of two partsan http header and the raw data (which is typically htmla blank line always separates these two components simple http header looks like thisprint 'content-typetext/html\rprint '\rhtml output blank line (required!the rest of the output is the raw output for exampleprint 'my cgi scriptprint 'hello world!print 'you are % (% )(nameemailit is standard practice that http headers are terminated using the windows lineending convention of '\ \nthat is why the '\rappears in the example if you need to signal an errorinclude special 'status:header in the output for exampleprint 'status forbidden\rhttp error code print 'content-typetext/plain\rprint '\rblank line (requiredprint 'you're not worthy of accessing this page!if you need to redirect the client to different pagecreate output like thisprint 'status moved\rprint 'locationprint '\rmost of the work in the cgi module is performed by creating an instance of the fieldstorage class fieldstorage([input [headers [outerboundary [environ [keep_blank_values [strict_parsing]]]]]]read the contents of form by reading and parsing the query string passed in an environment variable or standard input input specifies file-like object from which form lib fl ff |
18,382 | data will be read in post request by defaultsys stdin is used headers and outerboundary are used internally and should not be given environ is dictionary from which cgi environment variables are read keep_blank_values is boolean flag that controls whether blank values are retained or not by defaultit is false strict_parsing is boolean flag that causes an exception to be raised if there is any kind of parsing problem by defaultit is false fieldstorage instance form works similarly to dictionary for examplef form[keywill extract an entry for given parameter key an instance extracted in this manner is either another instance of fieldstorage or an instance of minifieldstorage the following attributes are defined on fattribute description name filename value file type type_options the field nameif specified client-side filename used in uploads value as string file-like object from which data can be read content type dictionary of options specified on the content-type line of the http request the 'content-dispositionfieldnone if not specified dictionary of disposition options dictionary-like object containing all the http header contents disposition disposition_options headers values from form can be extracted using the following methodsform getvalue(fieldname [default]returns the value of given field with the name fieldname if field is defined twicethis function will return list of all values defined if default is suppliedit specifies the value to return if the field is not present one caution with this method is that if the same form field name is included twice in the requestthe returned value will be list containing both values to simplify programmingyou can use form getfirst()which simply returns the first value found form getfirst(fieldname [default]returns the first value defined for field with the name fieldname if default is suppliedit specifies the value to return if the field is not present form getlist(fieldnamereturns list of all values defined for fieldname it always returns listeven if only one value is definedand returns an empty list if no values exist in additionthe cgi module defines classminifieldstoragethat contains only the attribute' name and value this class is used to represent individual fields of form passed in the query stringwhereas fieldstorage is used to contain multiple fields and multipart data lib fl ff |
18,383 | web programming instances of fieldstorage are accessed like python dictionarywhere the keys are the field names on the form when accessed in this mannerthe objects returned are themselves an instance of fieldstorage for multipart data (content type is 'multipart/form-data'or file uploadsan instance of minifieldstorage for simple fields (content type is 'application/ -www-form-urlencoded')or list of such instances in cases where form contains multiple fields with the same name for exampleform cgi fieldstorage(if "namenot in formerror("name is missing"return name form['name'value email form['email'value get 'namefield from form get 'emailfield from form if field represents an uploaded fileaccessing the value attribute reads the entire file into memory as byte string because this may consume large amount of memory on the serverit may be preferable to read uploaded data in smaller pieces by reading from the file attribute directly for instancethe following example reads uploaded data line by linefileitem form['userfile'if fileitem fileit' an uploaded filecount lines linecount while trueline fileitem file readline(if not linebreak linecount linecount the following utility functions are often used in cgi scriptsescape( [quote]converts the characters '&''in string to html-safe sequences such as '&''<'and '>if the optional flag quote is truethe double-quote character ("is also translated to '"parse_header(stringparses the data supplied after an http header field such as 'content-typethe data is split into primary value and dictionary of secondary parameters that are returned in tuple for examplethe command parse_header('text/htmla=hellob="world"'returns this result('text/html'{' ':'hello'' ':'world'}parse_multipart(fppdictparse_multipart(fp,pdictparses input of type 'multipart/form-dataas is commonly used with file uploads fp is the input fileand pdict is dictionary containing parameters of the content-type header it returns dictionary mapping field names to lists of values this function doesn' work with nested multipart data the fieldstorage class should be used instead lib fl ff |
18,384 | print_directory(formats the name of the current working directory in html and prints it out the resulting output will be sent back to the browserwhich can be useful for debugging print_environ(creates list of all environment variables formatted in html and is used for debugging print_environ_usage(prints more selected list of useful environment variables in html and is used for debugging print_form(formformats the data supplied on form in html form must be an instance of fieldstorage used for debugging test(writes minimal http header and prints all the information provided to the script in html format primarily used for debugging to make sure your cgi environment is set up correctly cgi programming advice in the current age of web frameworkscgi scripting seems to have fallen out of fashion howeverif you are going to use itthere are couple of programming tips that can simplify your life firstdon' write cgi scripts where you are using huge number of print statements to produce hard-coded html output the resulting program will be horrible tangled mess of python and html that is not only impossible to readbut also impossible to maintain better approach is to rely on templates minimallythe string template object can be used for this here is an example that outlines the conceptimport cgi from string import template def error(message)temp template(open("errormsg html"read()print 'content-typetext/html\rprint '\rprint temp substitute({'messagemessage}form cgi fieldstorage(name form getfirst('name'email form getfirst('email'if not nameerror("name not specified"raise systemexit elif not emailerror("email not specified"raise systemexit do various processing confirmation subscribe(nameemailf lib fl ff |
18,385 | print the output page values 'namename'emailemail'confirmation'confirmationadd other values here temp template(open("success html"read(print temp substitute(valuesin this examplethe files 'error htmland 'success htmlare html pages that have all of the output but include $variable substitutions corresponding to dynamically generated values used in the cgi script for examplethe 'success htmlfile might look like thissuccess welcome $name you have successfully subscribed to our newsletter your confirmation code is $confirmation the temp substitute(operation in the script is simply filling in the variables in this file an obvious benefit of this approach is that if you want to change the appearance of the outputyou just modify the template filesnot the cgi script there are many thirdparty template engines available for python--maybe in even greater numbers than web frameworks these take the templating concept and build upon it in substantial ways see secondif you need to save data from cgi scripttry to use database although it is easy enough to write data directly to fileswebservers operate concurrentlyand unless you've taken steps to properly lock and synchronize resourcesit is possible that files will get corrupted database servers and their associated python interface usually don' have this problem so if you need to save datatry to use module such as sqlite or third-party module for something like mysql finallyif you find yourself writing dozens of cgi scripts and code that has to deal with low-level details of http such as cookiesauthenticationencodingand so forthyou may want to consider web framework instead the whole point of using framework is so that you don' have to worry about those details--wellat least not as much sodon' reinvent the wheel notes the process of installing cgi program varies widely according to the type of webserver being used typically programs are placed in special cgi-bin directory server may also require additional configuration you should consult the documentation for the server or the server' administrator for more details lib fl ff |
18,386 | on unixpython cgi programs may require appropriate execute permissions to be set and line such as the following to appear as the first line of the program#!/usr/bin/env python import cgi to simplify debuggingimport the cgitb module--for exampleimport cgitbcgitb enable(this modifies exception handling so that errors are displayed in the web browser if you invoke an external program--for examplevia the os system(or os popen(function--be careful not to pass arbitrary strings received from the client to the shell this is well-known security hole that hackers can use to execute arbitrary shell commands on the server (because the command passed to these functions is first interpreted by the unix shell as opposed to being executed directlyin particularnever pass any part of url or form data to shell command unless it has first been thoroughly checked by making sure that the string contains only alphanumeric charactersdashesunderscoresand periods on unixdon' give cgi program setuid mode this is security liability and not supported on all machines don' use 'from cgi import *with this module the cgi module defines wide variety of names and symbols that you probably don' want in your namespace cgitb this module provides an alternative exception handler that displays detailed report whenever an uncaught exception occurs the report contains source codevalues of parametersand local variables originallythis module was developed to help debug cgi scriptsbut it can be used in any application enable([display [logdir [context [format]]]]enables special exception handling display is flag that determines whether any information is displayed when an error occurs the default value is logdir specifies directory in which error reports will be written to files instead of printed to standard output when logdir is giveneach error report is written to unique file created by the tempfile mkstemp(function context is an integer specifying the number of lines of source code to display around lines upon which the exception occurred format is string that specifies the output format format of 'htmlspecifies html (the defaultany other value results in plain-text format handle([info]handles an exception using the default settings of the enable(function info is tuple (exctypeexcvaluetbwhere exctype is an exception typeexcvalue is an exception valueand tb is traceback object this tuple is normally obtained using sys exc_info(if info is omittedthe current exception is used lib fl ff |
18,387 | web programming note to enable special exception handling in cgi scriptsinclude the line import cgitbenable(at the beginning of the script wsgiref wsgi (python web server gateway interfaceis standardized interface between webservers and web applications that is designed to promote portability of applications across different webservers and frameworks an official description of the standard is found in pep (about the standard and its use can also be found at package is reference implementation that can be used for testingvalidationand simple deployments the wsgi specification with wsgia web application is implemented as function or callable object webapp(environstart_responsethat accepts two arguments environ is dictionary of environment settings that is minimally required to have the following values which have the same meaning and names as is used in cgi scriptingenviron variables description content_length content_type http_accept http_cookie http_referer http_user_agent path_info query_string request_method script_name server_name server_port server_protocol length of data passed type of query data mime types accepted by the client netscape persistent cookie value referring url client browser extra path information passed query string method ('getor 'post'name of the program server host name server port number server protocol in additionthe environ dictionary is required to contain the following wsgi-specific valuesenviron variables description wsgi version wsgi url_scheme tuple representing the wsgi version ( ( , for wsgi string representing the scheme component of the url for example'httpor 'httpsa file-like object representing the input stream additional data such as form data or uploads are read from this file-like object opened in text mode for writing error output wsgi input wsgi errors lib fl ff |
18,388 | environ variables description wsgi multithread boolean flag that' true if the application can be executed concurrently by another thread in the same process boolean flag that' true if the application can be executed concurrently by another process boolean flag that' true if the application will only be executed once during the lifetime of the executing process wsgi multiprocess wsgi run_once the start_response parameter is callable object of the form start_response(statusheadersthat is used by the application to start response status is string such as ' okor ' not foundheaders is list of tupleseach of the form (namevaluecorresponding to http header to be included in the response--for example('content-type','text/html'the data or body of response is returned by the web application function as an iterable object that produces sequence of byte strings or text strings that only contain characters which can be encoded as single byte ( compatible with the iso- - or latin- character setexamples include list of byte strings or generator function producing byte strings if an application needs to do any kind of character encoding such as utf- it must do this itself here is an example of simple wsgi application that reads form fields and produces some outputsimilar to what was shown in the cgi module sectionimport cgi def subscribe_app(environstart_response)fields cgi fieldstorage(environ['wsgi input']environ=environname fields getvalue("name"email fields getvalue("email"various processing status " okheaders [('content-type','text/plain')start_response(statusheadersresponse 'hi % thank you for subscribing name'you should expect response soon return (line encode('utf- 'for line in responsethere are few critical details in this example first,wsgi application components are not tied to specific frameworkwebserveror set of library modules in the examplewe're only using one library modulecgisimply because it has some convenience functions for parsing query variables the example shows how the start_response(function is used to initiate response and supply headers the response itself is constructed as list of strings the final statement in this application is generator expression that turns all strings into byte strings if you're using python this is critical step--all wsgi applications are expected to return encoded bytesnot unencoded unicode data to deploy wsgi applicationit has to be registered with the web programming framework you happen to be using for thisyou'll have to read the manual lib fl ff |
18,389 | web programming wsgiref package the wsgiref package provides reference implementation of the wsgi standard that allows applications to be tested in stand-alone servers or executed as normal cgi scripts wsgiref simple_server the wsgiref simple_server module implements simple stand-alone http server that runs single wsgi application there are just two functions of interestmake_server(hostportappcreates an http server that accepts connections on the given host name host and port number port app is function or callable object that implements wsgi application to run the serveruse serve_forever(where is an instance of the server that is returned demo_app(environstart_responsea complete wsgi application that returns page with "hello worldmessage on it this can be used as the app argument to make_server(to verify that the server is working correctly here is an example of running simple wsgi serverdef my_app(environstart_response)some application start_response(" ok",[('content-type','text/plain')]return ['hello world'if _name_ =' _main_ 'from wsgiref simple_server import make_server serv make_server('', my_appserv serve_forever(wsgiref handlers the wsgiref handlers module contains handler objects for setting up wsgi execution environment so that applications can run within another webserver ( cgi scripting under apachethere are few different objects cgihandler(creates wsgi handler object that runs inside standard cgi environment this handler collects information from the standard environment variables and / streams as described in the cgi library module basecgihandler(stdinstdoutstderrenviron [multithread [multiprocess]]creates wsgi handler that operates within cgi environmentbut where the standard / streams and environment variables might be set up in different way stdinstdoutand stderr specify file-like objects for the standard / streams environ is dictionary of environment variables that is expected to already contain the standard cgi environment variables multithread and multiprocess are boolean flags that are used to set the wsgi multithread and wsgi multiprocess environment variables by defaultmultithread is true and multiprocess is false lib fl ff |
18,390 | simplehandler(stdinstdoutstderrenviron [multithread [multiprocess]]creates wsgi handler that is similar to basecgihandlerbut which gives the underlying application direct access to stdinstdoutstderrand environ this is slightly different than basecgihandler that provides extra logic to process certain features correctly ( in basecgihandlerresponse codes are translated into statusheadersall of these handlers have method run(appthat is used to run wsgi application within the handler here is an example of wsgi application running as traditional cgi script#!/usr/bin/env python def my_app(environstart_response)some application start_response(" ok",[('content-type','text/plain')]return ['hello world'from wgiref handlers import cgihandler hand cgihandler(hand run(my_appwsgiref validate the wsgiref validate module has function that wraps wsgi application with validation wrapper to ensure that both it and the server are operating according to the standard validator(appcreates new wsgi application that wraps the wsgi application app the new application transparently works in the same way as app except that extensive error-checking is added to make sure the application and the server are following the wsgi standard any violation results in an assertionerror exception here is an example of using the validatordef my_app(environstart_response)some application start_response(" ok",[('content-type','text/plain')]return ['hello world'if _name_ =' _main_ 'from wsgiref simple_server import make_server from wsgiref validate import validator serv make_server('', validator(my_app)serv serve_forever(note the material in this section is primarily aimed at users of wsgi who want to create application objects ifon the other handyou are implementing yet another web framework for pythonyou should consult pep for official details on precisely what is needed to make your framework support wsgi if you are using third-party web frameworkyou will need to consult the framework documentation for details concerning its support for wsgi objects given that wsgi is an officially blessed specification with reference implementation in the standard libraryit is increasingly common for frameworks to provide some level of support for it lib fl ff |
18,391 | web programming webbrowser the webbrowser module provides utility functions for opening documents in web browser in platform-independent manner the main use of this module is in development and testing situations for exampleif you wrote script that generated html outputyou could use the functions in this module to automatically direct your system' browser to view the results open(url [new [autoraise]]displays url with the default browser on the system if new is the url is opened in the same window as running browserif possible if new is new browser window is created if new is the url is opened within new tab within the browser if autoraise is truethe browser window is raised open_new(urldisplays url in new window of the default browser the same as open(url open_new_tab(urldisplays url in new tab of the default browser the same as open(url get([name]returns controller object for manipulating browser name is the name of the browser type and is typically string such as 'netscape''mozilla''kfm''grail''windows-default''internet-config'or 'command-linethe returned controller object has methods open(and open_new(that accept the same arguments and perform the same operation as the two previous functions if name is omitteda controller object for the default browser is returned register(nameconstructor[controller]registers new browser type for use with the get(function name is the name of the browser constructor is called without arguments to create controller object for opening pages in the browser controller is controller instance to use instead if suppliedconstructor is ignored and may be none controller instancecreturned by the get(function has the following methodsc open(url[new]same as the open(function open_new(urlsame as the open_new(function lib fl ff |
18,392 | internet data handling and encoding his describes modules related to processing common internet data formats and encodings such as base htmlxmland json base the base module is used to encode and decode binary data into text using base base or base encoding base is commonly used to embed binary data in mail attachments and with parts of the http protocol official details can be found in rfc- and rfc- base encoding works by grouping the data to be encoded into groups of bits ( byteseach -bit group is then subdivided into four -bit components each -bit value is then represented by printable ascii character from the following alphabetvalue encoding - - - pad abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz if the number of bytes in the input stream is not multiple of ( bits)the data is padded to form complete -bit group the extra padding is then indicated by special '=characters that appear at the end of the encoding for exampleif you encode byte character sequencethere are five -byte groups with byte left over the remaining byte is padded to form -byte group this group then produces two characters from the base alphabet (the first bitswhich include bits of real data)followed by the sequence '=='representing the bits of extra padding valid base encoding will only have zeroone (=)or two (==padding characters at the end of the encoding lib fl ff |
18,393 | internet data handling and encoding base encoding works by grouping binary data into groups of bits ( byteseach -bit group is subdivided into eight -bit components each -bit value is then encoded using the following alphabetvalue encoding - - abcdefghijklmnopqrstuvwxyz - as with base if the end of the input stream does not form -bit groupit is padded to bits and the '=character is used to represent the extra padding in the output at mostthere will be six padding characters ('======')which occurs if the final group only includes byte of data base encoding is the standard hexadecimal encoding of data each -bit group is represented by the digits ' '-' and the letters ' '-'fthere is no extra padding or pad characters for base encoding encode( [altchars]encodes byte string using base encoding altcharsif givenis two-character string that specifies alternative characters to use for '+and '/characters that normally appear in base output this is useful if base encoding is being used with filenames or urls decode( [altchars]decodes string swhich is encoded as base and returns byte string with the decoded data altcharsif givenis two-character string that specifies the alternative characters for '+and '/that normally appear in base -encoded data typeerror is raised if the input contains extraneous characters or is incorrectly padded standard_b encode(sencodes byte string using the standard base encoding standard_b decode(sdecodes string using standard base encoding urlsafe_b encode(sencodes byte string using base but uses the characters '-and '_instead of '+and '/'respectively the same as encode( '- 'urlsafe_b decode(sdecodes string encoded with url-safe base encoding encode(sencodes byte string using base encoding decode( [casefold [map ]]decodes string using base encoding if casefold is trueboth uppercase and lowercase letters are accepted otherwiseonly uppercase letters may appear (the defaultmap if presentspecifies which letter the digit maps to (for examplethe letter 'ior the letter ' 'if this argument is giventhe digit ' is also mapped to lib fl ff |
18,394 | the letter 'oa typeerror is raised if the input string contains extraneous characters or is incorrectly padded encode(sencodes byte string using base (hexencoding decode( [,casefold]decodes string using base (hexencoding if casefold is trueletters may be uppercase or lowercase otherwisehexadecimal letters ' '-'fmust be uppercase (the defaultraises typeerror if the input string contains extraneous characters or is malformed in any way the following functions are part of an older base module interface that you may see used in existing python codedecode(inputoutputdecodes base -encoded data input is filename or file object open for reading output is filename or file object open for writing in binary mode decodestring(sdecodes base -encoded strings returns string containing the decoded binary data encode(inputoutputencodes data using base input is filename or file object open for reading in binary mode output is filename or file object open for writing encodestring(sencodes byte stringsusing base binascii the binascii module contains low-level functions for converting data between binary and variety of ascii encodingssuch as base binhexand uuencoding b_uu(sconverts line of uuencoded text to binary and returns byte string lines normally contain (binarybytesexcept for the last line that may be less line data may be followed by whitespace a_uu(dataconverts string of binary data to line of uuencoded ascii characters the length of data should not be more than bytes otherwisethe error exception is raised b_base (stringconverts string of base -encoded text to binary and returns byte string a_base (dataconverts string of binary data to line of base -encoded ascii characters the length of data should not be more than bytes if the resulting output is to be transmitted through email (otherwise it might get truncatedf lib fl ff |
18,395 | internet data handling and encoding b_hex(stringconverts string of hexadecimal digits to binary data this function is also called as unhexlify(stringb a_hex(dataconverts string of binary data to hexadecimal encoding this function is also called as hexlify(dataa b_hqx(stringconverts string of binhex -encoded data to binary without performing rle (runlength encodingdecompression rledecode_hqx(dataperforms an rle decompression of the binary data in data returns the decompressed data unless the data input is incompletein which case the incomplete exception is raised rlecode_hqx(dataperforms binhex rle compression of data a_hqx(dataconverts the binary data to string of binhex -encoded ascii characters data should already be rle-coded alsounless data is the last data fragmentthe length of data should be divisible by crc_hqx(datacrccomputes the binhex crc checksum of the byte string data crc is starting value of the checksum crc (data [crc]computes the crc- checksum of the byte string data crc is an optional initial crc value if omittedcrc defaults to csv the csv module is used to read and write files consisting of comma-separated values (csva csv file consists of rows of texteach row consisting of values separated by delimiter charactertypically comma (,or tab here' an exampleblues,elwood," addison","chicagoil "," ", , variants of this format commonly occur when working with databases and spreadsheets for instancea database might export tables in csv formatallowing the tables to be read by other programs subtle complexities arise when fields contain the delimiter character for instancein the preceding exampleone of the fields contains comma and must be placed in quotes this is why using basic string operations such as split(','are often not enough to work with such files lib fl ff |
18,396 | reader(csvfile [dialect [**fmtparams]returns reader object that produces the values for each line of input of the input file csvfile csvfile is any iterable object that produces complete line of text on each iteration the returned reader object is an iterator that produces list of strings on each iteration the dialect parameter is either string containing the name of dialect or dialect object the purpose of the dialect parameter is to account for differences between different csv encodings the only built-in dialects supported by this module are 'excel(which is the default valueand 'excel-tab'but others can be defined by the user as described later in this section fmtparams is set of keyword arguments that customize various aspects of the dialect the following keyword arguments can be givenkeyword argument description delimiter doublequote character used to separate fields (the default is ','boolean flag that determines how the quote character (quotecharis handled when it appears in field if truethe character is simply doubled if falsean escape character (escapecharis used as prefix the default is true character used as an escape character when the delimiter appears in field and quoting is quote_none the default value is none line termination sequence ('\ \nis the defaultcharacter used to quote fields that contain the delimiter ('"is the defaultif truewhitespace immediately following the delimiter is ignored (false is the defaultescapechar lineterminator quotechar skipinitialspace writer(csvfile [dialect [**fmtparam]]returns writer object that can be used to create csv file csvfile is any file-like object that supports write(method dialect has the same meaning as for reader(and is used to handle differences between various csv encodings fmtparams has the same meaning as for readers howeverone additional keyword argument is availablekeyword argument description quoting controls the quoting behavior of output data it' set to one of quote_all (quotes all fields)quote_minimal (only quote fields that contain the delimiter or start with the quote character)quote_nonnumeric (quote all nonnumeric fields)or quote_none (never quote fieldsthe default value is quote_minimal writer instancewsupports the following methodsw writerow(rowwrites single row of data to the file row must be sequence of strings or numbers lib fl ff |
18,397 | internet data handling and encoding writerows(rowswrites multiple rows of data rows must be sequence of rows as passed to the writerow(method dictreader(csvfile [fieldnames [restkey [restval [dialect [**fmtparams]]]]]returns reader object that operates like the ordinary reader but returns dictionary objects instead of lists of strings when reading the file fieldnames provides list of field names used as keys in the returned dictionary if omittedthe dictionary key names are taken from the first row of the input file restkey provides the name of dictionary key that' used to store excess data--for instanceif row has more data fields than field names restval is default value that' used as the value for fields that are missing from the input--for instanceif row does not have enough fields the default value of restkey and restval is none dialect and fmtparams have the same meaning as for reader(dictwriter(csvfilefieldnames [restval [extrasaction [dialect [**fmtparams]]]]returns writer object that operates like the ordinary writer but writes dictionaries into output rows fieldnames specifies the order and names of attributes that will be written to the file restval is the value that' written if the dictionary being written is missing one of the field names in fieldnames extrasaction is string that specifies what to do if dictionary being written has keys not listed in fieldnames the default value of extrasaction is 'raise'which raises valueerror exception value of 'ignoremay be usedin which case extra values in the dictionary are ignored dialect and fmtparams have the same meaning as with writer( dictwriter instancewsupports the following methodsw writerow(rowwrites single row of data to the file row must be dictionary that maps field names to values writerows(rowswrites multiple rows of data rows must be sequence of rows as passed to the writerow(method sniffer(creates sniffer object that is used to try and automatically detect the format of csv file sniffer instanceshas the following methodss sniff(sample [delimiters]looks at data in sample and returns an appropriate dialect object representing the data format sample is portion of csv file containing at least one row of data delimitersif suppliedis string containing possible field delimiter characters has_header(samplelooks at the csv data in sample and returns true if the first row looks like collection of column headers lib fl ff |
18,398 | dialects many of the functions and methods in the csv module involve special dialect parameter the purpose of this parameter is to accommodate different formatting conventions of csv files (for which there is no official "standardformat)--for exampledifferences between comma-separated values and tab-delimited valuesquoting conventionsand so forth dialects are defined by inheriting from the class dialect and defining the same set of attributes as the formatting parameters given to the reader(and writer(functions (delimiterdoublequoteescapecharlineterminatorquotecharquotingskipinitialspacethe following utility functions are used to manage dialectsregister_dialect(namedialectregisters new dialect objectdialectunder the name name unregister_dislect(nameremoves the dialect object with name name get_dialect(namereturns the dialect object with name name list_dialects(returns list of all registered dialect names currentlythere are only two built-in dialects'exceland 'excel-tabexample import csv read basic csv file open("scmods csv"," "for in csv reader( )lastnamefirstnamestreetcityzip print("{ { { { { }format(* )using dictreader instead open("address csv" csv dictreader( ,['lastname','firstname','street','city','zip']for in rprint("{firstname{lastname{street{city{zip}format(** )write basic csv file data ['blues','elwood',' addison','chicago','il',' ]['mcgurn','jack',' broadway','chicago','il',' ] open("address csv"," " csv writer(fw writerows(dataf close( lib fl ff |
18,399 | internet data handling and encoding email package the email package provides wide variety of functions and objects for representingparsing and manipulating email messages encoded according to the mime standard covering every detail of the email package is not practical herenor would it be of interest to most readers thusthe rest of this section focuses on two common practical problems--parsing email messages in order to extract useful information and creating email messages so that they can be sent using the smtplib module parsing email at the top levelthe email module provides two functions for parsing messagesmessage_from_file(fparses an email message read from the file-like object which must be opened in text mode the input message should be complete mime-encoded email message including all headerstextand attachments returns message instance message_from_string(strparses an email message by reading an email message from the text string str returns message instance message instance returned by the previous functions emulates dictionary and supports the following operations for looking up message dataoperation description returns the value of header name returns list of all message header names returns list of message header values returns list of tuples containing message header names and values get(name [,def]returns header value for header name def specifies default value to return if not found len(mreturns the number of message headers str(mturns the message into string the same as the as_string(method name in returns true if name is the name of header in the message [namem keys( values( items(in addition to these operatorsm has the following methods that can be used to extract informationm get_all(name [default]returns list of all values for header with name name returns default if no such header exists get_boundary([default]returns the boundary parameter found within the 'content-typeheader of message typically the boundary is string such as '=============== ==that' used to separate the different subparts of message returns default if no boundary parameter could be found lib fl ff |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.