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 pro...
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(('',por...
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)da...
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 da...
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...
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_...
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 ...
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...
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 ...
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 , ...
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 int...
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...
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)...
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 ex...
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 ...
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 ...
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 ser...
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 (tcpudp...
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...
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 integ...
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 func...
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[( , , ,'',( ',...
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 datagra...
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 s...
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 grou...
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...
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...
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_recvopt...
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 ...
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 o...
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 s...
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]s...
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 (herrnohmesgcontainin...
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...
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 d...
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 'subjectan...
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 re...
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 noth...
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-lik...
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 li...
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...
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 p...
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...
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 e...
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 d...
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...
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...
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 heade...
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 ba...
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 s...
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 (header...
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 httpconnectio...
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...
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 pyt...
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 httpser...
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"th...
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 arbitr...
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...
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 option...
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...
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 cal...
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 ...
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 re...
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_meth...
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 open...
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_pa...
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 fu...
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 ...
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 ignor...
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 c...
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 us...
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 c...
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(daytimecreate...
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...
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 met...
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...
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 ob...
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 ...
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,namev...
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 cg...
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_soft...
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_pa...
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 ...
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 ...
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 dynamica...
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...
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 dif...
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 du...
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...
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...
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 auto...
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 ...
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...
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...
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 bin...
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 ...
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 ...
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 valuesquo...
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 th...