id
int64
0
25.6k
text
stringlengths
0
4.59k
19,400
python semaphores the sample program howeverstarts up five threadsthis therefore means that the first running threads will acquire the semaphore and the remaining thee will have to wait to acquire the semaphore once the first two release the semaphore further two can acquire it and so on from threading import threadsem...
19,401
inter thread/process synchronisation both these queue classes are thread and process safe that is they work appropriately (using internal locksto manage data access from concurrent threads or processes an example of using queue to exchange data between worker process and the main process is shown below the worker proce...
19,402
the concurrent queue class in the above diagram the main process waits for result to be returned from the queue following the call to the get(methodas it is waiting it is not using any system resources in turn the worker process sleeps for two seconds before putting some data onto the queue (via put('hello world')after...
19,403
inter thread/process synchronisation it should follow similar pattern to the queue class described above but support the first in last out (filobehaviour of stack and be usable with any number of producer and consumer threads (you can ignore processes for this exercisethe key to implementing the stack is to remember th...
19,404
exercises create shared stack stackstack[creating and starting consumer threads creating and starting producer thread producer pushingtask consumer stack pop()task producer pushingtask consumer stack pop()task producer pushingtask consumer stack pop()task producer pushingtask consumer stack pop()task producer pushingta...
19,405
futures introduction future is thread (or processthat promises to return value in the futureonce the associated behaviour has completed it is thus future value it provides very simple way of firing off behaviour that will either be time consuming to execute or which may be delayed due to expensive operations such as in...
19,406
futures howeverneither the thread or the process by default provide simple mechanism for obtaining result from such an independent operation this may not be problem as operations may be self-containedfor example they may obtain data from the database or from today' date and then updated ui howeverin many situations the...
19,407
futures in python it should be noted howeverthat future instances should not be created directlyrather they should be created via the submit method of an appropriate executor future creation futures are created and executed by executors an executor provides two methods that can be used to execute future (or futuresand ...
19,408
futures we can make the invocation of this method into future to do this we use threadpoolexecutor imported from the concurrent futures module we will then submit the worker function to the pool for execution this returns reference to future which we can use to obtain the resultfrom time import sleep from concurrent fu...
19,409
futures in python from concurrent futures import processpoolexecutor print('setting up the threadpoolexecutor'pool processpoolexecutor( print('submitting the worker to the pool'future pool submit(worker' 'print('obtained reference to the future object'future print('future result():'future result()print('done'the output...
19,410
futures when this runs we can see that the futures for ab and all run concurrently but must wait until one of the others finishesstarting abcacbcabcbabcacbacabcbacabcbadddddddddd future result() all done the main thread also waits for future to finish as it requests the result which is blocking call that will only retu...
19,411
running multiple futures first_exception the function will return when any future finishes by raising an exception if no future raises an exceptionthen it is equivalent to all_completed all_completed the function will return when all futures finish or are cancelled the wait(function returns two sets done and not_done t...
19,412
futures processing results as completed what if we want to process each of the results returned by our collection of futureswe could loop through the futures list in the previous section once all the results have been generated howeverthis means that we would have to wait for them all to complete before processing the ...
19,413
running multiple futures started checking if is even checking if is even checking if is even checking if is even checking if is even checking if is even false true false false true true done as you can see from this output although the six futures were started in sequence the results returned are in different order (wi...
19,414
futures from concurrent futures import threadpoolexecutor from time import sleep from random import randint def is_even( )print('checking if' 'is even'sleep(randint( )return str(nstr( = def print_future_result(future)print('in callback future result'future result()print('started'data [ pool threadpoolexecutor( for in d...
19,415
online resources online resources see the following online resources for information on futureslibrary documentation on futures on futures exercises in mathematicsthe factorial of positive integer ndenoted by !is the product of all positive integers less than or equal to for example note that the value of is write futu...
19,416
concurrency with asyncio introduction the async io facilities in python are relatively recent additions originally introduced in python and evolving up to and including python they are comprised (as of python of two new keywords async and await (introduced in python and the async io python package in this we first disc...
19,417
concurrency with asyncio multitasking these cooperating tasks operate asynchronouslyby this we mean that the tasksare able to operate separately from other tasksare able to wait for another task to return result when requiredand are thus able to allow other tasks to run while they are waiting the io (input/outputaspect...
19,418
async io event loop an important point to note in the above description is that task does not give up the processor unless it decides tofor example by having to wait for something else they never get interrupted in the middle of an operationthis avoids the problem that two threads might have when being time sliced by s...
19,419
concurrency with asyncio the main(function is the entry point for the program and callsasyncio run(do_something()this starts the async io event loop running and results in the do_something(function being wrapped up in task that is managed by the loop note that you do not explicitly create task in async iothey are alway...
19,420
the async and await keywords the full listing for the program is given belowimport asyncio import time async def worker()print('worker will take some time'time sleep( print('worker done it'return async def do_something()print('do_something will wait for worker'result await worker(print('do_something result:'resultdef m...
19,421
concurrency with asyncio asyncio create_task()asyncio gather(and asyncio as_completed(these additional task creation functions are described belowasyncio create_task(this function takes function marked with async and wraps it inside task and schedules it for execution by the async io event loop this function was added ...
19,422
async io tasks async def do_something()print('do_something create task for worker'task asyncio create_task(worker()print('do_something add callback'task add_done_callback(print_itawait task information on task print('do_something task cancelled():'task cancelled()print('do_something task done():'task done()print('do_so...
19,423
concurrency with asyncio running multiple tasks in many cases it is useful to be able to run several tasks concurrently there are two options provided for this the asyncio gather(and the asyncio as_completed(functionwe will look at both in this section collating results from multiple tasks it is often useful to collect...
19,424
running multiple tasks this makes is very easy to work with multiple concurrent tasks and to collate their results note that in this code example the worker async function returns random number between and the output from this program ismain starting do_something will wait for worker worker will take some time worker w...
19,425
concurrency with asyncio we have also modified the worker function slightly so that label is added to the random number generated so that it is clear which invocation of the worker function return which resultasync def worker(label)print('worker will take some time'await asyncio sleep( result random randint( , print('w...
19,426
exercises exercises this exercise will use the facilities in the asyncio library to calculate set of factorial numbers the factorial of positive integer is the product of all positive integers less than or equal to for example note that the value of is create an application that will use the async and await keywords to...
19,427
reactive programming
19,428
reactive programming introduction introduction in this we will introduce the concept of reactive programming reactive programming is way of write programs that allow the system to reactive to data being published to it we will look at the rxpy library which provides python implementation of the reactivex approach to re...
19,429
reactive programming introduction publishedthen the application must update the value of the trade within the table such an application can be described as being reactive reactive programming is programming style (typically supported by librariesthat allows code to be written that follow the ideas of reactive systems o...
19,430
the observer pattern there are two key roles within the observer patternthese are the observable and the observer roles observable this is the object that is responsible for notifying other objects that change in its state has occurred observer an observer is an object that will be notified of the change in state of th...
19,431
reactive programming introduction hot observablesby contrastpublish data whether there is an observer subscribed or not cold observables cold observable will not publish any data unless there is at least one observer subscribed to process that data in addition cold observable only provides data to an observer when that...
19,432
differences between event driven programming and reactive programming differences between event driven programming and reactive programming in event driven programmingan event is generated in response too something happeningthe event then represents this with any associated data for exampleif the user clicks the mouse ...
19,433
reactive programming introduction simpler asynchronousmulti threaded execution the approach adopted by rxpy makes it very easy to execute operationsbehaviour within multi threaded environment with independent asynchronous functions available operators the rxpy library comes pre built with numerous operators that make p...
19,434
reference reference for more information on the observer observable design pattern see the "patternsbook by the gang of four gammar helmr johnsonj vlissadesdesign patternselements of reusable object-oriented softwareaddison-wesley (
19,435
rxpy observablesobservers and subjects introduction in this we will discuss observablesobservers and subjects we also consider how observers may or may not run concurrently in the remainder of this we look at rxpy version which is major update from rxpy version (you will therefore need to be careful if you are looking ...
19,436
rxpy observablesobservers and subjects observers in rxpy we can add an observer to an observable using the subcribe(method this method can be supplied with lambda functiona named function or an object whose class implements the observer protocol for examplethe simplest way to create an observer is to use lambda functio...
19,437
observers in rxpy each of the above can be used as positional parameters or as keyword argumentsfor exampleuse lambdas to set up all three functions observable subscribeon_next lambda valueprint('received on_next'value)on_error lambda expprint('error occurred'exp)on_completed lambdaprint('received completed notificatio...
19,438
rxpy observablesobservers and subjects the observer class must ensure that the methods implemented adhere to the observer protocol ( that the signatures of the on_next()on_completed (and on_error(methods are correct multiple subscribers/observers an observable can have multiple observers subscribed to it in this case e...
19,439
multiple subscribers/observers the output from this program iscreate the observable object set up observers subscribers lambda received lambda received lambda received lambda received function received function received function received function received object received object received object received object received ...
19,440
rxpy observablesobservers and subjects the following example creates subject that enriches the data it receives by adding timestamp to each data item it then republishes the data item to any observers that have subscribed to it import rx from rx subjects import subject from datetime import datetime source rx from_list(...
19,441
subjects in rxpy observable if the subject was subscribed to the observable before the observers were subscribed to the subjectthen all the data could have been published before the observers were registered with the subject the output from this program isset up subject received function received ( datetime datetime( )...
19,442
rxpy observablesobservers and subjects subscribe(method this keyword is given an appropriate scheduler such as the rx concurrency newthreadscheduler this scheduler will ensure that the observer runs in separate thread to see the difference look at the following two programs the main difference between the programs is t...
19,443
observer concurrency note that we have to ensure that the main thread running the program does not terminate (as all the observables are now running in their own threadsby waiting for user input the output from this version islambda received lambda received lambda received lambda received lambda received lambda receive...
19,444
rxpy observablesobservers and subjects online resources see the following online resources for information on rxpyoperators exercises given the following set of tuples representing stock/equity pricesstocks (('appl' )('ibm' )('msft' )('appl' )write program that will create an observable based on the stocks data next su...
19,445
rxpy operators introduction in this we will look at the types of operators provided by rxpy that can be applied to the data emitted by an observable reactive programming operators behind the interaction between an observable and an observer is data stream that is the observable supplies data stream to an observer that ...
19,446
rxpy operators in fact rxpy provides wide variety of operators and these operators can be categorised as followscreationaltransformationalcombinatorialfilterserror handlersconditional and boolean operatorsmathematicalconnectable examples of some of these categories are presented in the rest of this section piping opera...
19,447
creational operators creational operators you have already seen an example of creational operator in the examples presented earlier in this this is because the rx from_list(operator is an example of creational operator it is used to create new observable based on data held in list like structure more generic version of...
19,448
rxpy operators the rx operators flat_map(operator also applies function to each data item but then applies flatten operation to the result for exampleif the result is list of lists then flat_map will flatten this into single list in this section we will focus on the rx operators map(operator the rx operators map(operat...
19,449
transformational operators the output from this program islambda received ' lambda received ' lambda received ' lambda received ' is string is string is string is string true true true true combinatorial operators combinatorial operators combine together multiple data items in some way one example of combinatorial oper...
19,450
rxpy operators the output from this program is presented below , , , , , , notice from the output the way in which the data held in the original observables is intertwined in the output of the observable generated by the merge(operator filtering operators there are several operators in this category including rx operat...
19,451
filtering operators lambda received lambda received lambda received the first(and last(operators emit only the first and last data item published by the observable the distinct(operator suppresses duplicate items being published by the observable for examplein the following list used as the data for the observablethe n...
19,452
rxpy operators the output from the rx operators sum(operator is the total of the data items published by the observable (in this case the total of and the observer function that is subscribed to the rx operators sum(operators observable will print out this valuehoweverin some cases it may be useful to be notified of th...
19,453
chaining operators for examplewe might first start off by filtering the output from an observable such that only certain data items are published we might then apply transformation in the form of map(operator to that dataas shown belownote the the order in which we have applied the operatorswe first filter out data tha...
19,454
rxpy operators the output from this application is given belowreceived ' received ' received ' this makes it clear that only the three even numbers ( and are allowed through to the map(function online resources see the following online resources for information on rxpyoperators exercises given the following set of tupl...
19,455
network programming
19,456
introduction to sockets and web services introduction in the following two we will explore socket based and web service approaches to inter process communications these processes may be running on the same computer or different computers on the same local area network or may be geographically far apart in all cases inf...
19,457
introduction to sockets and web services broadcast systemswhere multiple clients may need to receive the data published by server host (particularly if data loss is not an issue web services web service is service offered by host computer that can be invoked by remote client using the hypertext transfer protocol (httph...
19,458
addressing services on any given network there may be multiple hostseach with their own host id but with shared network id for exampleon private home network there may be jasmine' laptop adam' pc home printer smart tv in many ways the network id and host id elements of an ip address are like the postal address for hous...
19,459
introduction to sockets and web services localhost (and is used to refer to the computer you are currently on when program is runthat is it is your local host computer (hence the name localhostfor exampleif you start up socket server on your local computer and want client socket programrunning on the same computerto co...
19,460
ipv versus ipv ipv versus ipv what we have described in this in terms of ip addresses is in fact based on the internet protocol version (aka ipv this version of the internet protocol was developed during the and published by the ietf (internet engineering task forcein september (replacing an earlier definition publishe...
19,461
introduction to sockets and web services online resources see the following online resources for information ip addresses dns
19,462
sockets in python introduction socket is an end point in communication link between separate processes in python sockets are objects which provide way of exchanging information between two processes in straight forward and platform independent manner in this we will introduce the basic idea of socket communications and...
19,463
sockets in python setting up connection to set up the connectionone process must be running program that is waiting for connection while the other must try to connect up to the first program the first is referred to as server socket while the second just as socket for the second process to connect to the first (the ser...
19,464
an example client server application implementing the server application we shall describe the server application first this is the python application program that will service requests from client applications to do this it must provide server socket for clients to connect to this is done by first binding server socke...
19,465
sockets in python tryprint('connection from'client_addresswhile truedata connection recv( decode(print('received'dataif datakey str(dataupper(response addresses[keyprint('sending data back to the client'responseconnection sendallresponse encode()elseprint('no more data from'client_addressbreak finallyconnection close(i...
19,466
an example client server application once the address is obtained it can be sent back to the client in python it is necessary to decode(and encoded(the string format to the raw data transmitted via the socket streams note you should always close socket when you have finished with it socket types and domains when we cre...
19,467
sockets in python the implementation of the client is given belowimport socket def main()print('starting client'print('create tcp/ip socket'sock socket socket(socket af_inetsocket sock_streamprint('connect the socket to the server port'server_address (socket gethostname() print('connecting to'server_addresssock connect...
19,468
implementing the client application as you can see from this diagramthe server waits for connection from the client when the client connects to the serverthe server waits to receive data from the client at this point the client must wait for data to be sent to it from the server the server then sets up the response dat...
19,469
sockets in python import socketserver class mytcphandler(socketserver baserequesthandler)""the requesthandler class for the server ""def __init__(selfrequestclient_addressserver)print('setup names and offices'self addresses {'john'' ''denise'' ''phoebe'' ''adam'' 'super(__init__(requestclient_addressserverdef handle(se...
19,470
the socketserver module threadingmixin and tcpserver and creating an instane of this new class instead of the tcpserver directly for exampleclass threadedechoserversocketserver threadingmixinsocketserver tcpserver)pass def main()print('starting'address ('localhost' server threadedechoserver(addressmytcphandlerprint('ac...
19,471
sockets in python in the above diagram the user is using browser (such as chromeie or safarito access web server the browser is running on their local machine (which could be pca maca linux boxan ipada smart phone etc to access the web server they enter url (universal resource locatoraddress into their browser in the e...
19,472
http server the following short program creates simple web server that will generate welcome message and the current time as response to get request it does this by using the datetime module to create time stamp of the date and time using the today(function this is converted into byte array using the utf- character enc...
19,473
sockets in python self send_header('content-length'str(len(byte_msg))self end_headers(print('do_get(replying with message'self wfile write(byte_msgdef main()print('setting up server'server_address ('localhost' httpd threadinghttpserver(server_addressmyhttprequesthandlerprint('activating http server'httpd serve_forever(...
19,474
online resources online resources see the following online resources for information on the topics in this in python page page on socketserver documentation page on the http server module development for creating web applications exercises the aim of this exercise is to explore working with tcp/ip sockets you should cr...
19,475
sockets in python an example of the type of output the client might generate is given below to illustrate the general aim of the exercisestarting client please provide an input (datetimedataandtime or - to exit)date connected to server sending data received from serverclosing socket please provide an input (datetimedat...
19,476
web services in python introduction this looks at restful web services as implemented using the flask framework restful services rest stands for representational state transfer and was termed coined by roy fielding in his ph to describe the lightweightresource-oriented architectural style that underpins the web fieldin...
19,477
web services in python verbs to indicate the type of action being requested typically these are used as followsretrieve information (http get)create information (http post)update information (http put)delete information (http deleteit should be noted that rest is not standard in the way that html is standard rather it ...
19,478
restful api we also need to design the representation or formats that the service can supply these could include plain textjsonxml etc json standards for the javascript object notation and is concise way to describe data that is to be transferred from service running on server to client running in browser this is the f...
19,479
web services in python be invoked over httphowever this has been extended to provide more rest like facilities in this we will focus on flask as it is one of the most widely used frameworks for light weight restful services in python flask flask is web development framework for python it describes itself as micro frame...
19,480
hello world in flask json is actually built on some basic structuresa collection of name/value pairs in which the name and value are separated buy colon ':and each pair can be separated by comma ',an ordered list of values that are encompassed in square brackets ('[]'this makes it very easy to build up structures that ...
19,481
web services in python we then need to create the main application object which is an instance of the flask classfrom flask import flaskjsonify app flask(__name__the argument passed into the flask(constructor is the name of the application' module or package as this is simple example we will use the __name__ attribute ...
19,482
hello world in flask the second thing is that we are going to return our data using the json formatwe therefore use the jsonify(function and pass it python dictionary structure with single key/value pair in this case the key is 'msgand the data associated with that key is 'hello flask worldthe jsonify(function will con...
19,483
web services in python invoking the service we will use web browser to access the web service to do this we must enter the full url that will route the request to our running application and to the welcome(function the url is actually comprised of two elementsthe first part is the machine on which the application is ru...
19,484
hello world in flask the final solution we can tidy this example up little by defining function hat can be used to create the flask application object and by ensuring that we only run the application if the code is being run as the main modulefrom flask import flaskjsonifyurl_for def create_service()app flask(__name__@...
19,485
web services in python server gateway interface standard status codes
19,486
bookshop web service building flask bookshop service the previous illustrated the basic structure of very simple web service application we are now in position to explore the creation of set of web services for something little more realisticthe bookshop web service application in this we will implement the set of web ...
19,487
bookshop web service the overall design is shown belowthis shows that book object will have an isbna titlean author and price attribute in turn the bookshop object will have books attribute that will hold zero or more books the books attribute will actually hold list as the list of books needs to change dynamically as ...
19,488
the domain model the book class is simple value type class (that is it is data oriented with no behaviour of its own)class bookdef __init__(selfisbntitleauthorprice)self isbn isbn self title title self author author self price price def __str__(self)return self title by self author str(self pricethe bookshop class hold...
19,489
bookshop web service bookshop bookshop[book( 'xml''gryff smith' )book( 'java''phoebe cooke' )book( 'scala''adam davies' )book( 'python''jasmine byrne' )] encoding books into json one issue we have is that although the jsonify(function knows how to convert built in types such as stringsintegerslistsdictionaries etc into...
19,490
encoding books into json this approach certainly works and provides very lightweight way to convert book into json howeverthe approach presented above does mean that every time we want to jsonify book we must remember to call the to_json(method in some cases this means that we will also have to write some slightly conv...
19,491
bookshop web service app flask(__name__app json_encoder bookjsonencoder now if we wish to encode single book or list of books the above encoder will be used automatically and thus we do not need to do anything else thus our earlier examples can be written to simply by referencing the book or bookshop books attributejso...
19,492
setting up the get services in the above example we have also (optionallyindicated the type of the parameter by default the type will be stringhowever we know that the isbn is in fact an integer and so we have indicated that by prefixing the parameter name with the type int (and separated the type information from the ...
19,493
bookshop web service deleting book the delete book web service is very similar to the get book service in that it takes an isbn as url path parameter howeverin this case it merely returns an acknowledgement that the book was deleted successfully@app route('/book/'methods=['delete']def delete_book(isbn)bookshop delete_b...
19,494
deleting book this confirms that book has been deleted adding new book we also want to support adding new book to the bookshop the details of new book could just be added to the url as url path parametershowever as the amount of data to be added grows this would become increasingly difficult to maintain and verify inde...
19,495
bookshop web service the url and thus to the function insteadwithin the function it is necessary to obtain the request object and then to use that to obtain the information held within the body of the request key attribute on the request objectavailable when http request contains json datais the request json attribute ...
19,496
adding new book we can now test this service using the curl command line programcurl - "content-typeapplication/json- post - '{"title":"read book""author":"bob","isbn":" ""price":" "}the options used with this command indicate the type of data being sent in the body of the request (-halong with the data to include in t...
19,497
bookshop web service this function resets the titleauthor and price of the book retrieved from the bookshop it again returns the updated book as the result of running the function the curl program can again be used to invoke this functionalthough this time the http put method must be specifiedcurl - "content-typeapplic...
19,498
iii example programbatch usernames summary exercises defining functions the function of functions functionsinformally future value with function functions and parametersthe exciting details getting results from function functions that return values functions that modify parameters functions and program structure summar...
19,499
contents boolean algebra other common structures post-test loop loop and half boolean expressions as decisions summary exercises simulation and design simulating racquetball simulation problem analysis and specification pseudo random numbers top-down design top-level design separation of concerns second-level design de...