id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
19,300 | transactions in databases transactions in databases another important concept within database is that of transaction transaction represents unit of work performed within database management system (or similar systemagainst database instanceand is independent of any other transaction transactions in database environment... |
19,301 | introduction to databases further reading if you want to know more about databases and database management systems here are some online resourcesmaterial database which provides short introduction to databases databases relational databases page if you want to explore the subject of database design (that is design of t... |
19,302 | python db-api accessing database from python the standard for accessing database in python is the python db-api this specifies set of standard interfaces for modules that wish to allow python to access specific database the standard is described in pep (dev/peps/pep- )-- pep is python enhancement proposal almost all py... |
19,303 | python db-api these elements are illustrated belowthe standard specifies set of functions and objects to be used to connect to database these include the connection functionthe connection object and the cursor object the above elements are described in more detail below the connect function the connection function is d... |
19,304 | the db-api rollback(used to rollback all the changes made to the database since the last transaction commit (optional as not all databases provide transaction supportcursor(returns new cursor object to use with the connection the cursor object the cursor object is returned from the connection cusor(method cursor object... |
19,305 | python db-api mappings from database types to python types the db-api standard also specifies set of mappings from the types used in database to the types used in python for full listing see the db-api standard itself but the key mappings includedate(yearmonthdaytime(hourminutesecondtimestamp(yearmonthdayhourminuteseco... |
19,306 | the db-api mysqlerror class that extends exception and is then extended by both warning and error also note that warning and error have no relationship with each other this is because warnings are not considered errors and thus have separate class hierarchies howeverthe error is the root class for all database error cl... |
19,307 | python db-api precision if real numeric value the precision supported by the attributescale indicates the scale of the attributenull_ok this indicates whether null values are acceptable for this attribute the first two items (name and type_codeare mandatorythe other five are optional and are set to none if no meaningfu... |
19,308 | online resources python |
19,309 | pymysql module the pymysql module the pymysql module provides access to mysql database from python it implements the python db-api this module is pure python database interface implementation meaning that it is portable across different operating systemsthis is notable because some database interface modules are merely... |
19,310 | pymysql module fetch the result(sof the sql using the cursor object ( fetchallfetchmany or fetchone close the database connection these steps are essentially boiler platecode that is you will use them whenever you access database via pymysql (or indeed any db-api compliant modulewe will take each of these steps in turn... |
19,311 | working with the pymysql module database these users are authenticated by requiring them to provide password the password for the user the database instance to connect to as mentioned in the previous database management system (dmscan manage multiple database instances and thus it is necessary to say which database ins... |
19,312 | pymysql module obtaining information about the results the cursor object can also be used to obtain information about the results to be fetched such as how many rows there are in the results and what the type is of each attribute in the resultscusor rowcount(this is read-only property that indicates the number of rows ... |
19,313 | working with the pymysql module into individual elements these elements could then be used to construct an object that could then be processed within an applicationfor examplefor row in dataidnamesurnamesubjectemail row student student(idnamesurnamesubjectemailprint(studentclose the connection once you have finished wi... |
19,314 | pymysql module execute sql query using execute(method cursor execute('select from students'print('cursor rowcount'cursor rowcountprint('cursor description'cursor descriptionfetch all the rows and then iterate over the data data cursor fetchall(for row in datastudent_idnamesurnamesubjectemail row student student(student... |
19,315 | inserting data to the database import pymysql open database connection connection pymysql connect('localhost''user''password''uni-database'prepare cursor object using cursor(method cursor connection cursor(tryexecute insert command cursor execute("insert into students (idnamesurnamesubjectemailvalues ( 'denise''byrne''... |
19,316 | pymysql module the commit(method on the database connection in turn we can indicate that we want to rollback the current transaction by calling rollback(in either caseonce the method has been invoked new transaction is started for any further database activity in the above code we have used try block to ensure that if ... |
19,317 | deleting data in the database deleting data in the database finallyit is also possible to delete data from databasefor example if student leaves their course this follows the same format as the previous two examples with the difference that the delete statement is used insteadimport pymysql open database connection con... |
19,318 | pymysql module creating tables it is not just data that you can add to databaseif you wish you can programmatically create new tables to be used with an application this process follows exactly the same pattern as those used for insertupdate and delete the only difference is that the command sent to the database contai... |
19,319 | online resources online resources see the following online resources for more information on the python database apilibrary exercises in this exercise you will create database and tables based on set of transactions stored in current account you can use the account class you created in the csv and excel for this you wi... |
19,320 | introduction to logging introduction many programming languages have common logging libraries including java and cand of course python also has logging module indeed the python logging module has been part of the built in modules since python this discusses why you should add logging to your programswhat you should (an... |
19,321 | introduction to logging regulatory or legal compliance in some cases records of program execution may be required for regulatory or legal reasons this is particularly true of the financial sector where records must be kept for many years in case there is need to investigate the organisationsor individualsbehaviour what... |
19,322 | what should you log in many cases developers log the entry (and to lesser extentthe exit from function or method howeverit may also be useful to log what happens at branch points within function or method so that the logic of the application can be followed all applications should log all errors/exceptions although car... |
19,323 | introduction to logging not log the actual userid--instead you may log an id that can be used to map to their actual userid you should also be careful about directly logging data input too an application directly into log file one way in which malicious agent can attack an application (particularly web applicationis by... |
19,324 | why not just use print displayed in the console window if you run an application from the command line then the output is directed back to that command/terminal window both of these are fine during developmentbut what if the program is not run from command windowperhaps instead it is started up by the operating system ... |
19,325 | logging in python the logging module python has included built-in logging module since python this modulethe logging moduledefines functions and classes which implement flexible logging framework that can be used in any python application/script or in python libraries/modules although different logging frameworks diffe... |
19,326 | logging in python log message the is the message to be logged from the application logger provides the programmers entry point/interface to the logging system the logger class provides variety of methods that can be used to log messages at different levels handler handlers determine where to send log messagedefault han... |
19,327 | controlling the amount of information logged controlling the amount of information logged log messages are actually associated with log level these log levels are intended to indicate the severity of the message being logged there are six different log levels associated with the python logging frameworkthese arenotset ... |
19,328 | logging in python systems (indeed this is why the default log level is set to warning within the python logging systemif we now look at the following code that obtains the default logger object and then uses several different logger methodswe can see the effect of the log levels on the outputimport logging logger loggi... |
19,329 | controlling the amount of information logged this will now output all the log messages as debug is the lowest logging level we can of course turn off logging by setting the log level to notset logger setlevel(logging notsetalternatively you can set the loggers disabled attribute to truelogging logger disabled true logg... |
19,330 | logging in python in addition there are several methods that are used to manage handlers and filtersaddfilter(filterthis method adds the specified filter filter to this logger removefilter(filterthe specified filter is removed from this logger object addhandler(handlerthe specified handler is added to this logger remov... |
19,331 | module level loggers module level loggers most modules will not use the root logger to log informationinstead they will use named or module level logger such logger can be configured independently of the root logger this allows developers to turn on logging just for module rather than for whole application this can be ... |
19,332 | logging in python we can see the effect of each of these statements by printing out each loggerlogger logging getlogger(print('root logger:'loggerlogger logging getlogger('my logger'print('named logger:'logger logger logging getlogger(__name__print('module logger:'logger when the above code is run the output isroot log... |
19,333 | logger hierarchy the logger name hierarchy is analogous to the python package hierarchyand identical to it if you organise your loggers on per-module basis using the recommended construction logging getlogger(__name__this hierarchy is important when considering the log level if log level has not been set for the curren... |
19,334 | logging in python the format parameter takes string that can contain logrecord attributes organised as you see fit there is comprehensive list of logrecord attributes which can be referenced at html#logrecord-attributes the key ones areargs tuple listing the arguments used to call the associated function or method asct... |
19,335 | formatters logging basicconfig(format='%(asctime) [%(levelname) %(funcname) %(message) 'level=logging debugwhich will now generate the output within log level information and the function involved : : , [debugdo_somethingthis is to help with debugging : : , [infodo_somethingthis is just for information : : , [warningdo... |
19,336 | logging in python online resources for further information on the python logging framework see the followingthe python standard library documentation page exercises this exercise will involve adding logging to the account class you have been working on in this book you should add log methods to each of the methods in t... |
19,337 | advanced logging introduction in this we go further into the configuration and modification of the python logging module in particular we will look at handlers (used to determine the destination fo log messages)filters which can be used by handlers to provide finer grained control of log output and logger configuration... |
19,338 | advanced logging in the above diagram the logger has been configured to send all log messages to four different handlers which allow log message to be written to the consoleto web server to file and to an email service such behaviour may be required becausethe web server will allow developers access to web interface th... |
19,339 | handlers logging handlers nteventloghandler that sends message to windows event log logging handlers httphandler which sends messages to http server logging nullhandler that does nothing with error messages this is often used by library developers who want to include logging in their applications but expect developers ... |
19,340 | advanced logging as can be seen from this the default formatter is now configured for filehandler this filehandler adds the log message level before the log message itself programmatically setting the handler it is also possible to programmatically create handler and set it for the logger this is done by instantiating ... |
19,341 | handlers given that this is lot more code than using the basicconfig(functionthe question here might be 'why bother?the answer is two foldyou can have different handlers for different loggers rather than setting the handler to be used centrally each handler can have its own format set so that logging to file has differ... |
19,342 | advanced logging multiple handlers as suggested in the previous section we can create multiple handlers to send log messages to different locationsfor example from the consoleto files and even email servers the following program illustrates setting up both file handler and console handler for module level logger to do ... |
19,343 | handlers create formatter for the console handler console_formatter logging formatter('%(asctime) %(funcname) %(message) 'console_handler setformatter(console_formatteradd the handlers to logger logger addhandler(console_handlerlogger addhandler(file_handler'applicationcode def do_something()logger debug('debug message... |
19,344 | advanced logging implementing the filter(method this method takes log record this log record can be validated to determine if the record should be output or not if it should be output then true is returnedif the record should be ignored false should be returned in the following examplea filter called myfilter is define... |
19,345 | logger configuration the logging configuration file can be written using several standard formats from json (the java script object notation)to yaml (yet another markup languageformator as set of key-value pairs in conf file for further information on the different options available see the python logging module docume... |
19,346 | advanced logging this file can be loaded into python application using the pyyaml module this provides yaml parser that can load yaml file as dictionary structure that can be passed to the logging config dictconfig(function as this is file it must be opened and closed to ensure that the resource is handled appropriatel... |
19,347 | logger configuration the output from this using the earlier yaml file is : : , [infomylogger starting : : , [debugmylogger do_somethingdebug message : : , [infomylogger do_somethinginfo message : : , [warningmylogger do_somethingwarn message : : , [errormylogger do_somethingerror message : : , [criticalmylogger do_some... |
19,348 | advanced logging now the two expensive functions will only be executed if the debug log level is set exercises using the logging you dded to the account class int he last you should load the log configuration information from yaml file similar to that used in this this should be loaded into the application program used... |
19,349 | concurrency and parallelism |
19,350 | introduction to concurrency and parallelism introduction in this we will introduce the concepts of concurrency and parallelism we will also briefly consider the related topic of distribution after this we will consider process synchronisationwhy object oriented approaches are well suited to concurrency and parallelism ... |
19,351 | introduction to concurrency and parallelism for examplelet us assume that we have program that will call three independent functionsthese functions aremake backup of the current data held by the programprint the data currently held by the programrun an animation using the current data let us assume that these functions... |
19,352 | concurrency results from any of the functionsthus the delay may be negligible (although there will typically be some small delay as each process is set upthis is shown graphically below parallelism distinction its often made in computer science between concurrency and parallelism in concurrencyseparate independent task... |
19,353 | introduction to concurrency and parallelism the following diagram illustrates the basic idea behind parallelisma main program fires off three subtasks each of which runs in parallel the main program then waits for all the subtasks to complete before combining together the results from the subtasks before it can continu... |
19,354 | grid computing in many cases the grid is made up of heterogeneous set of computers (rather than all computers being the sameand may be geographically dispersed these computers may be comprised of both physical computers and virtual machines virtual machine is piece of software that emulates whole computer and runs on s... |
19,355 | introduction to concurrency and parallelism the use of grids can make distributing concurrent/parallel processes amongst set of physical and virtual machines much easier concurrency and synchronisation concurrency relates to executing multiple tasks at the same time in many cases these tasks are not related to each oth... |
19,356 | object orientation and concurrency traditionally message send is treated like procedural callin which the calling object' execution is blocked until response is returned howeverwe can extend this model quite simply to view each object as concurrently executable programwith activity starting when the object is created a... |
19,357 | introduction to concurrency and parallelism some terminology the world of concurrent programming is full of terminology that you may not be familiar with some of those terms and concepts are outlined belowasynchronous versus synchronous invocations most of the methodfunction or procedure invocations you will have seen ... |
19,358 | online resources concurrency versus parallelism tutorial an introduction to grid computing |
19,359 | threading introduction threading is one of the ways in which python allows you to write programs that multitaskthat is appearing to do more than one thing at time this presents the threading module and uses short example to illustrate how these features can be used threads in python the thread class from the threading ... |
19,360 | threading un-started and dead are considered to indicate that the thread is alive (and therefore may run at some pointthis is shown belowa thread may also be in the waiting statefor examplewhen it is waiting for another thread to finish its work before continuing (possibly because it needs the results produced by that ... |
19,361 | creating thread create subclass of the thread class and redefine the run(method to perform the set of actions that the thread is intended to do we will look at both approaches as thread is an objectit can be treated just like any other objectit can be sent messagesit can have instance variables and it can provide metho... |
19,362 | threading once thread is created it must be started to become eligible for execution using the thread start(method the following illustrates very simple program that creates thread that will run the simple_worker(functionfrom threading import thread def simple_worker()print('hello'create new thread and start it the thr... |
19,363 | the thread class is_alive(return whether the thread is alive this method returns true just before the run(method starts until just after the run(method terminates the module function threading enumerate(returns list of all alive threads daemon boolean value indicating whether this thread is daemon thread (trueor not (f... |
19,364 | threading start(wait for the thread to complete join(print('\ndone'now the 'donemessage should not be printed out until after the worker thread has finished as shown belowstarting done the threading module functions there are set of threading module functions which support working with threadsthese functions includethr... |
19,365 | passing arguments to thread from threading import thread from time import sleep def worker(msg)for in range( )print(msgend=''flush=truesleep( print('starting' thread(target=workerargs=' ' thread(target=workerargs=' ' thread(target=workerargs=' ' start( start( start(print('done'in this examplethe worker function takes m... |
19,366 | threading the output generated by this program is illustrated belowstarting abcdone abcacbabcabccbaabcabcabcbac notice that the main thread is finished after the worker threads have only printed out single letter eachhowever as long as there is at least one non-daemon thread running the program will not terminateas non... |
19,367 | extending the thread class the output from this isstarting done note that it is common to call any subclasses of the thread classsomethingthreadto make it clear that it is subclass of the thread class and should be treated as if it was thread (which of course it is daemon threads thread can be marked as daemon thread b... |
19,368 | threading naming threads threads can be namedwhich can be very useful when debugging an application with multiple threads in the following examplethree threads have been createdtwo have been explicitly given name related to what they are doing while the middle one has been left with the default name we then start all t... |
19,369 | thread local data thread local data in some situations each thread requires its own copy of the data it is working withthis means that the shared (heapmemory is difficult to use as it is inherently shared between all threads to overcome this python provides concept known as thread-local data thread-local data is data w... |
19,370 | threading for in range( ) thread(name='wstr( )target=workerargs=[local_data] start(show_value(local_dataprint(currentthread(namedone'the output from this is mainthread starting mainthread no value yet no value yet value no value yet value mainthread no value yet mainthread done the example presented above defines two f... |
19,371 | timers timers are startedas with threadsby calling their start(method the timer can be stopped (before its action has begunby calling the cancel(method the interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user as another thread may be running when the... |
19,372 | threading or it has held the gil for certain amount of time if the maximum time that thread can hold the gil has been met the scheduler will release the gil from that thread (resulting it stopping execution and now having to wait until it has the gil returned to itand will select another thread to gain the gil and star... |
19,373 | exercise start( start( start( start(an example of the sort of output this could generate is given belowbaeaeabedaeaebedcecbeeeadcdbbdabcadbbdabadcdcdcccc |
19,374 | multiprocessing introduction the multiprocessing library supports the generation of separate (operating system levelprocesses to execute behaviour (such as functions or methodsusing an api that is similar to the threading api presented in the last it can be used to avoid the limitation introduced by the global interpre... |
19,375 | multiprocessing mac osin contrast thread runs within the same process as the original program this means that the process is managed and executed directly by the operating system on one of the processors that are part of the underlying computer hardware the up side of this is that you are able to exploit the underlying... |
19,376 | the process class is_alive(return whether the process is alive roughlya process object is alive from the moment the start(method returns until the child process terminates the process class also has several attributesname the process' name the name is string used for identification purposes only it has no semantics mul... |
19,377 | multiprocessing from multiprocessing import process from time import sleep def worker(msg)for in range( )print(msgend=''flush=truesleep( print('starting' process(target=workerargs=' ' process(target=workerargs=' ' process(target=workerargs=' ' start( start( start(print('done'it is essentially the same as the equivalent... |
19,378 | alternative ways to start process parent process will not be inherited starting process using this method is rather slow compared to using fork or forkserver available on unix and windows this is the default on windows 'forkthe parent process uses os fork(to fork the python interpreter the child processwhen it beginsis... |
19,379 | multiprocessing module name__main__ parent process process id aaaaaaaaaa note that the parent process and current process ids are printed out for the worker (functionwhile the main(method prints out only its own id this shows that the main application process id is the same as the worker process parentsid alternatively... |
19,380 | using pool context can be used to specify the context used for starting the worker processes usually pool is created using the function multiprocessing pool(alternatively the pool can be created using the pool(method of context object the pool class provides range of methods that can be used to submit work to the worke... |
19,381 | multiprocessing the following sample program illustrates the basic use of the pool and the map(method from multiprocessing import pool def worker( )print('in worker with'xreturn def main()with pool(processes= as poolprint(pool map(worker[ ])if __name__ ='__main__'main(note that the pool object must be closed once you h... |
19,382 | using pool as the new method obtains results as soon as they are availablethe order in which the results are returned may be differentas shown belowin worker with in worker with in worker with in worker with in worker with in worker with further method available on the pool class is the pool apply_async(method this met... |
19,383 | multiprocessing from multiprocessing import pool def collect_results(result)print('in collect_results'resultdef worker( )print('in worker with'xreturn def main()with pool(processes= as poolget based example res pool apply_async(worker[ ]print('result from async'res get(timeout= )with pool(processes= as poolcallback bas... |
19,384 | exchanging data between processes once program has finished with connection is should be closed using close (the following program illustrates how pipe connections are usedthe output from this pipe example ismain startingcreating the pipe main setting up the process main starting the process main wait for response from... |
19,385 | multiprocessing main closing parent process end of connection main done note that data in pipe may become corrupted if two processes try to read from or write to the same end of the pipe at the same time howeverthere is no risk of corruption from processes using different ends of the pipe at the same time sharing state... |
19,386 | sharing state between processes wheretypecode_or_type determines the type of the elements of the returned array size_or_initializer if size_or_initializer is an integerthen it determines the length of the arrayand the array will be initially zeroed otherwisesize_or_initializer is sequence which is used to initialise th... |
19,387 | multiprocessing exercises write program that can find the factorial of any given number for examplefind the factorial of the number (often written as !which is and equals the factorial is not defined for negative numbers and the factorial of zero is that is next modify the program to run multiple factorial calculations... |
19,388 | inter thread/process synchronisation introduction in this we will look at several facilities supported by both the threading and multiprocessing libraries that allow for synchronisation and cooperation between threads or processes in the remainder of this we will look at some of the ways in which python supports synchr... |
19,389 | inter thread/process synchronisation all parties reach the barrier but before allowing those parties to continue the post-phase action (the callbackexecutes in single thread (or processonce it is completed then all the parties are unblocked and may continue this is illustrated in the following diagram threads and are a... |
19,390 | using barrier parametersthis means that the function can be used with different barrier objects depending upon the context an example using the barrier class with set of threads is given belowfrom threading import barrierthread from time import sleep from random import randint def print_it(msgbarrier)print('print_it fo... |
19,391 | inter thread/process synchronisation the barrier class itself provides several methods used to manage or find out information about the barriermethod description wait(timeout=nonewait until all threads have notified the barrier (unless timeout is reached)--returns the number of threads that passed the barrier return ba... |
19,392 | event signalling the following program implements the above scenariofrom multiprocessing import processevent from time import sleep def wait_for_event(event)print('wait_for_event entered and waiting'event_is_set event wait(print('wait_for_event event is set'event_is_setdef set_event(event)print('set_event entered but a... |
19,393 | inter thread/process synchronisation the output from this program isstarting wait_for_event entered and waiting set_event entered but about to sleep set_event waking up and setting event set_event event set wait_for_event event is settrue done to change this to use threads we would merely need to change the import and ... |
19,394 | synchronising concurrent code in this diagram the producer is running in its own thread (although it could also run in separate processand places data onto some common shared data container subsequently number of independent consumers can consume that data when it is available and when they are free to process the data... |
19,395 | inter thread/process synchronisation from threading import threadlock class shareddata(object)def __init__(self)self value self lock lock(def read_value(self)tryprint('read_value acquiring lock'self lock acquire(return self value finallyprint('read_value releasing lock'self lock release(def change_value(self)print('cha... |
19,396 | python locks shared_data shareddata(def reader()while trueprint(shared_data read_value()def updater()while trueshared_data change_value(print('starting' thread(target=readert thread(target=updatert start( start(print('done'the output from this isstarting read_value acquiring lock read_value releasing lock read_value ac... |
19,397 | inter thread/process synchronisation python conditions conditions can be used to synchronise the interaction between two or more threads or processes conditions objects support the concept of notification modelideal for shared data resource being accessed by multiple consumers and producers condition can be used to not... |
19,398 | python conditions from threading import threadconditioncurrentthread from time import sleep from random import randint class dataresourcedef __init__(self)print('dataresource initialising the empty data'self data none print('dataresource setting up the condition object'self condition condition(def consumer(self)"""wait... |
19,399 | inter thread/process synchronisation the output from an example run of this program ismain starting main creating the dataresource object dataresource initialising the empty data dataresource setting up the condition object main create the consumer threads main create the producer thread main starting consumer threads ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.