package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
zb-common
A package containing all the common utilities for the Zerobugz project. This version requires Python 2.7 or later
zbd-tools
Copyright (C) 2022 Western Digital Corporation or its affiliates.zbd-toolszbd-toolsis a tool set providing functions determining the availability of zone block device support. These tools will help identify kernel configurations and whether zone block device software packages are installed.Contributions and Bug ReportsContributions are accepted as github pull requests or via email (git send-emailpatches). Any problem may also be reported through github issues page or by contacting:Tommy.McGee ([email protected])RepositoryPLEASE DO NOT SUBMIT CONFIDENTIAL INFORMATION OR INFORMATION SPECIFIC TO DRIVES THAT ARE VENDOR SAMPLES OR NOT PUBLICLY AVAILABLE.Requirementszbd-toolsrequires the following for installation and usage:Python 3.0 or higherInstallation UsingpipThe following command can be executed to fetch and install thezbd-toolspackage.$ pip install zbd-tools Collecting zbd-tools Downloading zbd_tools-1.0-py3-none-any.whl (6.3 kB) Installing collected packages: zbd-tools Successfully installed zbd-tools-1.0To uninstallzbd-toolsfrom the system, use the following command.$ pip uninstall zbd-tools Found existing installation: zbd-tools 1.0 Uninstalling zbd-tools-1.0: Would remove: /usr/local/bin/zbd-check /usr/local/lib/python3.9/dist-packages/check/* /usr/local/lib/python3.9/dist-packages/zbd_tools-1.0.dist-info/* Proceed (Y/n)? Y Successfully uninstalled zbd-tools-1.0Usagezbd-toolsprovides thezbd-checkutility to check the zoned block device features and applications supported by a Linux distribution.zbd-checkThis utility allows checking a Linux distribution for zoned block device support. Three different class of features are checked:Kernel features: device types, device mapper targets and file systems support are checked.User Libraries:zbd-checkwill list the installation status of user libraries related to zoned block devices.User Applications:zbd-checkwill list the installation status of user applications related to zoned block devices.zbd-checkcommand line usage is displayed using the option "--help".$ zbd-check --help usage: zbd-check.py [-h] [--version] options: -h, --help show this help message and exit --version show the version of zbd-checkThe following shows an example output of thezbd-checkutility executed on a system running Fedora Linux 37.$ zbd-check ------------------------------------------------------------------------ System Information: ------------------------------------------------------------------------ - Distribution: Fedora Linux 37 (Workstation Edition) - Kernel Version: 6.0 ------------------------------------------------------------------------ Kernel features: ------------------------------------------------------------------------ - Zoned block devices: supported - Devices types: - SAS and SATA SMR hard-disks: supported - NVMe ZNS devices: supported - SCSI debug device ZBC emulation: supported - null_blk device zoned mode: supported - file systems: - zonefs: supported - f2fs zoned mode: supported - btrfs zoned mode: supported - Device mapper targets: - dm-linear: supported - dm-flakey: supported - dm-crypt: supported - dm-zoned: supported ------------------------------------------------------------------------ User Kernel zone management API: ------------------------------------------------------------------------ - Zone management kernel API header file: installed ------------------------------------------------------------------------ User Libraries: ------------------------------------------------------------------------ - libzbc: - Dynamic library installed, version 5.13.0 - Static library installed - Development header files installed - libzbd: - Dynamic library installed, version 2.0.2 - Static library installed - Development header files installed - libnvme: - Dynamic library installed, version 1.2 - Static library not installed - Development header files installed ------------------------------------------------------------------------ User Applications: ------------------------------------------------------------------------ - fio: installed, version fio-3.29-7-g01686 - nvme-cli: installed, version 2.2.1 - dm-zoned-tools: installed, version 2.2.1 - zonefs-tools: installed, version 1.5.2
zbench
zbenchThis package benchmarks lossless compression algorithms likegzipandbzip2, facilitating quick comparison of the trade-offs between disk space and CPU time onyourfile(s).It is implemented in Python and provides a command line tool,zbench.Install fromPyPI:pipinstallzbenchExample$zbenchsetup.cfgpath algorithm size percentage timesetup.cfg raw_py 853 100.000% 0.000setup.cfg gzip_py 488 57.210% 0.000setup.cfg bz2_py 547 64.127% 0.000setup.cfg lzma_py 572 67.057% 0.011setup.cfg zlib_py 476 55.803% 0.000LicenseCopyright 2020 Christopher Brown.MIT Licensed.
zbg
zbg is a general-purpose library for serialization and deserialization with zbg encoding. It is a very simple format supporting nested containers and arbitrary binary blobs, with a slightly more efficient implementation of 256-bit and 512-bit objects, intended to be used with cryptographic hashes and keys.
zbig
好像是一个乱七八糟, 什么都要一些的公用库, 主要是给 Bigzhu 开发用的.不要随意用, 小心非死即伤testpytest
zbitvector
zbitvectoris an efficient, well-typed interface to the Z3 and Bitwuzla SMT solvers. It can be used to represent and manipulate symbolic expressions in the theory of fixed-sized bitvectors and arrays (QF_BVA).importtypingimportzbitvectorUint8=zbitvector.Uint[typing.Literal[8]]Uint64=zbitvector.Uint[typing.Literal[64]]Uint64("X")+Uint64(1)# => Uint64(`(bvadd X #x01)`)Uint64("X")+Uint8(1)# fails to typecheckProject homepage →
zbl
zblzblis a Rust and Python library aiming to make it easier to integrate OpenCV (and possibly other CV libraries) with Windows Desktop apps for real-time processing. It does so by providing a simplified interface toWindows.Graphics.Capture.This library is not well-tested against corner cases, and was only verified to work for a 'happy path' scenarios, so beware of bugs!PythonInstallationpip install zblAlternatively, you can install suitable wheel fromreleases page.UsagefromzblimportCapturewithCapture(window_name='visual studio code')ascap:frame=next(cap.frames())print(frame.shape)The snippet above will capture a window which title contains the stringvisual studio code, take one frame (which is represented as anumpyarray) and print its shape.SeeCaptureconstructor for more options. It is possible to capture the entire screen usingdisplay_idargument, for example.To run an example using OpenCV'shighgui:Installopencv-pythonRunpython -m zbl --window-name '<full or partial window name, case insensitive>'RustSeeexamples. Note: if you are getting OpenCV build errors when building the example, check outhow to build OpenCV rust bindings.Why notmss/pyautogui?Those are the definition of "slow" at the time of writing.msstops at 30-50 fps in a tight loop,pyautoguiis even slower than that. Due to GPU accel which comes with D3D11,zblcaptures at 500-700 fps - an order of magnitude faster, which allows a lot more time for the actual processing.Why Rust for the native code part and not C++ / C#?I need it for the Rust project, hence it is in Rust.Creditszblis heavily inspired byscreenshot-rs.
zblib
py_priprivate python library
zblocker
阻塞器, 单人阻塞器和多人阻塞器单人阻塞器:一个线程调用lock()会立即阻塞, 直到另一个线程调用unlock()为止, 同一个阻塞器只能阻塞一个线程测试代码:if __name__ == '__main__':print('测试单人阻塞器')def fun():for i in range(5):time.sleep(1)a.unlock()import threadingimport timea = BLock()threading.Thread(target=fun).start()for i in range(5):print('开始锁定', i, time.strftime('%H:%M:%S', time.localtime()))a.lock() # 阻塞print(' 解除', i, time.strftime('%H:%M:%S', time.localtime()))print('结束\n\n')多人阻塞器:任何线程在调用lock()的时候都会被阻塞, 直到有一个线程调用一次unlock()来解除所有阻塞测试代码if __name__ == '__main__':print('测试多人阻塞器')def fun1(value):print('阻塞', value)a.lock()print(' 解除', value)def fun2():print('--2秒后解除所有阻塞--', time.strftime('%H:%M:%S', time.localtime()))time.sleep(2)print('--即将解除所有阻塞--', time.strftime('%H:%M:%S', time.localtime()))a.unlock()import threadingimport timea = BLock_more()for i in range(5):threading.Thread(target=fun1, args=(i,)).start()threading.Thread(target=fun2).start()a.join()print('结束')
zbmain
zbmain个人代码库持续新增。先持续0.x.x,待完整再正式发布更新1.0安装说明pip install zbmain使用方法import zbmain
zboard
zboardFULL CREDIT GOES TO THE ORIGINAL AUTHER AND OPEN SOURCE COMMUNITY!!!!!MADE SOME CHANGES(TWEAKS) FOR PERSONAL USE AND TO SHARE WITH MY TEAMTake full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.InstallationInstall thePyPI package:pip install zboardFor Usage Go to the Original Author Page:https://github.com/boppreh/keyboard/
zbookmarks
Install$pipinstallzbookmarksUsageA simple python package for loading / dumping Chrome HTML bookmarks. Born out of necessity to fix my own bookmarks.importzbookmarks# Loadwithopen("chrome_bookmarks.html","r")asf:bookmarks=zbookmarks.load_chrome(f.read())# Printprint(bookmarks)# Dumpwithopen("output.html","w")asf:zbookmarks.dump_chrome(bookmarks,f)How it worksI made this package by examining my own Chrome bookmark files and extrapolating. The general rules are:dldenotes a list of bookmark items and folders.dtdenotes either a bookmark item or folder:If it's a bookmark item,dthas a singleatag child, which gives the bookmark attributes (href, title, etc.).If it's a bookmark folder,dthas 3 children:Ah3tag containing the folder attributes (title, etc.)Adltag containing the folder's contents.A uselesspchild tag.I found it easier to come up with these rules after visualizing the DOM tree of a Chrome bookmarks file:You can try it out on your own bookmark file by running:#Youneedtoinstallgraphviz(dot)inordertorunthescript$sudoapt-getinstall-ygraphviz$poetryinstall$python3scripts/visualize_dom.py<my_bookmarks_file.html>
zbot
NAMEZBOT - python3 irc botSYNOPSISzbot <cmd> [key=val] [key==val] zbot [-a] [-c] [-d] [-h] [-v] [-w] options are: -a load all modules -c start console -d start daemon -h display help -v use verboseDESCRIPTIONZBOT is a python3 irc bot, it can connect to IRC, fetch and display RSS feeds, take todo notes, keep a shopping list and log text. You can also copy/paste the service file and run it under systemd for 24/7 presence in a IRC channel. ZBOT users BOTL, containing all the python3 code to program a unix cli program, such as disk perisistence for configuration files, event handler to handle the client/server connection, code to introspect modules for commands, deferred exception handling to not crash on an error, a parser to parse commandline options and values, etc. ZBOT uses OBJX, an module that allows for easy json save//load to/from disk of objects. It provides an "clean namespace" Object class that only has dunder methods, so the namespace is not cluttered with method names. This makes storing and reading to/from json possible. ZBOT is Public Domain.USAGEwithout any argument the program does nothing $ zbot $ see list of commands $ zbot cmd cmd,err,mod,req,thr,ver list of modules $ zbot mod cmd,err,fnd,irc,log,mod,req,rss,tdo,thr use -c to start a console $ zbot -c use mod=<name1,name2> to load additional modules $ zbot -c mod=irc,rss > use -v for verbose $ zbot -cv mod=irc ZBOT started CV started Sat Dec 2 17:53:24 2023 >CONFIGURATION$ zbot cfg channel=#zbot commands=True nick=zbot port=6667 server=localhost irc $ zbot cfg server=<server> $ zbot cfg channel=<channel> $ zbot cfg nick=<nick> sasl $ zbot pwd <nsvnick> <nspass> $ zbot cfg password=<frompwd> rss $ zbot rss <url> $ zbot dpl <url> <item1,item2> $ zbot rem <url> $ zbot nme <url> <name>COMMANDScmd - commands cfg - irc configuration dlt - remove a user dpl - sets display items fnd - find objects log - log some text met - add a user mre - displays cached output pwd - sasl nickserv name/pass rem - removes a rss feed rss - add a feed thr - show the running threadsSYSTEMDsave the following it in /etc/systems/system/zbot.service and replace "<user>" with the user running pipx [Unit] Description=python3 irc bot Requires=network-online.target After=network-online.target [Service] Type=simple User=<user> Group=<user> WorkingDirectory=/home/<user>/.zbot ExecStart=/home/<user>/.local/pipx/venvs/zbot/bin/zbot -d RemainAfterExit=yes [Install] WantedBy=multi-user.target then run this $ mkdir ~/.zbot $ sudo systemctl enable zbot --now default channel/server is #zbot on localhostFILES~/.zbot ~/.local/bin/zbot ~/.local/pipx/venvs/zbot/AUTHORBart Thate <[email protected]>COPYRIGHTZBOT is Public Domain.
zbox
zbox is a tiny library to help me usetoolzandcytoolz. I frequently usetoolzand would like to usecytoolzif it’s available, but don’t want to put atry/exceptin all my projects. By importingtoolzfromzboxI always getcytoolzifcytoolzis installed and otherwise I gettoolz.Installationzbox is on PyPI, install it with:pip install zbox. zbox works on Python 2 and Python 3.Usagefrom zbox import toolzIfcytoolzis installedtoolzwill becytoolz, otherwise it will betoolz.genfrom zbox import gengenis a function that converts any iterable into a Python generator object. I use this with Pandas, which sometimes doesn’t expand iterables unless they are first converted to a generator.
z-box
No description available on PyPI.
zboxfs
ZboxFS binding for PythonWIP
zbpp-light
Light-weight Library of Zero Bubble Pipeline ParallelismHow to useInstall bypip install zbpp_lightInsert the following code snippet to your training script at the very beginning:importzbpp_lightzbpp_light.patch_megatron()# Your original training script starts hereimportmegatron,etcSupported FrameworksMegatron-LMMegatron-DeepSpeedCurrent LimitationsOnly supports ZB-H1 schedule, which reduces 2/3 1F1B bubble with same memory and communication cost.
zbpy
zbpy: official Zetabase client for PythonThezbpypackage provides a pure-Python Zetabase client and reference implementation of the Zetabase protocol, along with integrations for commonly used Python tools like Numpy/Pandas.For more complete documentation, please refer to the main documentation section on the Zetabase website:Python quick startPython library referenceZetabase main documentationPrerequisites and external dependenciesPython 3.6 or highergccor equivalent compiler (except Windows)gmplibrary and headers (except Windows)Note: a C compiler is not required when runningzbpyon Windows. However, all requests made with ECDSA on Windows will be slightly slower when compared to other operating systems due to limitations of the platform. We recommend that heavy workloads on Windows use JWT authentication when possible.Installing gmp (if needed)OSX:brew install gmpUbuntu:apt-get install libgmp3-devCentos:yum install gmp gmp-devel gmp-statusNot required for Windows OS.InstallationRun the following to install:pip3installzbpyYou may get an error indicating you need to installcython. In this case, simply run the following:pip3installcythonAnd then re-runpip3 install zbpy.Creating an accountIf you do not have an account already you can easily create one through the Python client module. If you are using Juptyer notebooks, simply use the Jupyter account creation magic:fromzbpyimportclient%createaccountThe%createaccountmagic will run you through an interactive wizard to create a new Zetabase user identity.Otherwise, run the following code within the Python interactive shell to go through the same wizard on the console:fromzbpyimportutilutil.new_account_interactive()Answer the prompts that will appear, and if the account is created successfully, three files will be created in your current directory. These are:your private key;your public key; andan identity file containing both keys along with your user ID.Test your installationTo test that everything has installed correctly run thetest_zbpymethod fromzbpy.utilin Jupyter or the Python interactive shell:fromzbpyimportutilutil.test_zbpy()Library usageCreating a Zetabase clientWhen you created your identity, you were assigned a user id (a uuid, or random-looking string of letters and numbers). use this to instantiate your client.fromzbpyimportclientzb_client=client.ZetabaseClient('YOUR USER ID')Connecting your client to ZetabaseTo use JWT authentication for all requestsWhen you created your identity, you created a "name" (handle) and administrator password. You can use these instead of your public and private keys if your tables are configured to allow it.zb.login_jwt('YOUR USERNAME','YOUR PASSWORD')To use ECDSA authentication for all requestszb_client.setup_ecdsa('FILEPATH TO PRIVATE KEY','FILEPATH TO PUBLIC KEY')Creating TablesWith PandasNote: There are two methods to create tables using zbpy. There are two optional parameters with both of the methods:perms: used to specify the permissions of the table (can also be added to an existing table using theadd_perm()method)allow_jwt: if true, allows data to be put into the table using JWT authentication.If you are creating a table to hold a Pandas dataframe, the easiest way is to use the following function. This will create a table with indexed fields that match the names and types of the columns of your dataframe, and then it inserts your dataframe into the given table using some given "dataframe key" to identify it.zb_client.put_dataframe_new_table('TABLE ID',YOURDATAFRAME,'YOUR DF KEY')If you would like a subset of the DataFrame's columns to be turned into indexed fields in the table use the 'specify_fields' parameter.zb_client.put_dataframe_new_table('Table ID',YOURDATAFRAME,'YOUR DF KEY',specify_fields=['age','height'])This field can be[]to not index any fields (i.e. if you have no intention of querying the table based on field values).Custom tables (no Pandas)In this case, we create a new table by passing in a set of zero or more fields to index and some given list of permissions, e.g.:fromzbpy.indexedfieldentityimportIndexedFieldfromzbpyimportzb_protocol_pb2aszbindex_age=IndexedField('age',zb.QueryOrdering.INTEGRAL_NUMBERS)index_height=IndexedField('height',zb.QueryOrdering.REAL_NUMBERS)zb_client.create_table('TABLE ID',zb.TableDataFormat.JSON,[index_age,index_height],[OPTIONALPERMS],allow_jwt=True)Creating permissions and adding them to existing tablesfromzbpy.permissionentityimportPermEntryfromzbpyimportzb_protocol_pb2aszbperm=PermEntry(zb.PermissionLevel.READ,zb.PermissionAudienceType.PUBLIC,'')zb_client.add_permission('TABLE ID',perm)Retrieving data and PaginationWhen using the functionslist_keys(),get(), andquery(), the data is returned as aGetPagesobject. AGetPagesobjects can be iterated over or turned into a Pandas dataframes using theto_dataframe()method (both demonstrated below).Retrieving keys from tablelist_keys=zb_client.list_keys('TABLE ID')keys=[keyforkeyinlist_keys]Retrieving data by keyresult=zb_client.get('TABLE ID',['KEY 1','KEY 2','KEY 3','etc.'])dataframe=result.to_dataframe()Retrieving data as objectsThereturn_prettymethod will pre-parse JSON objects for you.result=zb_client.get('TABLE ID',['KEY 1','KEY 2','KEY 3','etc.'])result.return_pretty()foriinresult:print(i)Retrieving data by queryTo query data from Zetabase, we have a Python-based DSL ("domain-specific language") that allows you to express queries. The idea is to useFieldobjects to represent indexed fields and to build queries based on them. We can then use comparison operators on each field to create a subquery, and we can combine subquery with logical operators. Seethe documentation for more information.The example below assumes that a table exists with indexed fields 'age' and 'name'. Queries use '&' and '|' for 'and' and 'or' operators -- for that reason, use parentheses to avoid operator precedence issues.fromzbpyimportqueriesage=Field('age')name=Field('name')query=((age==19)|((age>25)&(age<=27)))&(name=='Austin')result=zb_client.query('TABLE ID',query)foriinresult:print(i)Inserting dataTo insert a Pandas dataframe into an existing table, use theput_dataframe()method. Each row of the dataframe will be inserted as its own object, the collection of which is identified by a key: thedf_keyparameter. Dataframes can be appended to one another by simply storing a new dataframe using the samedf_keyon the same table as an existing dataframe.zb_client.put_dataframe('TABLE ID',YOURDATAFRAME,'YOUR DF KEY')To insert data without Pandas, we can useput_datafor a single object, orput_multifor a list of objects:zb_client.put_data('TABLE ID','DATA KEY',DATAASBYTES)zb_client.put_multi('TABLE ID',['KEY 1','KEY 2','KEY 3','etc.'],[DATA1ASBYTES,DATA2ASBYTES,etc.])NotesFor performance reasons, to insert multiple pieces of data, it is suggested to use theput_multi()method.When possible, if storing large quantities of data, it is faster to use JWT over ECDSA if possible.
zbr
zbr: Zuul Build ReproducterTBH, don't install it that's just a placeholderInstallingpip install zbrUsageSo use it just runzbr.
zbrac
zBrac : A multilanguage tool for zTreeCreated by Ali Seyhun Saral and Anna SchroeterLicensed under GNU General Public License v3.0About the projectzBrac is a tool designed for easy modification of the text in z-Tree treatment files. With zBrac, you can export specified text intoa language fileand import it back after the text modification or translation.The main advantage of using zBrac for z-Tree experiment development is that that the text in zTree files can be modified easily at any time, which means the coding process and the text design/translation process can be independently done.zBrac's design is specifically tailored for multicultural studies: By using the software, you can code your experiment once and send the original language file for translation. zBrac also tries to tackle encoding issues special characters in z-Tree by offering different encoding options.zBrac is particularly useful when the treatment file contains the same piece of text several times. Such duplicate text is very common in z-Tree programming as it is often needed to copy-paste stage tree elements. zBrac recognizes each unique key as a single key and it would be enough to provide the text to replace for this key at once. For an example, please see below for the Holt and Laury measure example.**zBrac is free/open-source software (See GNU GPL-3 Licence). You can use, modify and distribute it. It is not obligatory to cite the software, although it is highly appreciated. (see below about citing the paper) **Citing the softwareCurrently, a paper about zBrac is submitted to a scientific journal. If you use the software and would like to cite the paper, please visit this page or contact us before you share your manuscript to check the status of the paper.For more information, visit project page:www.zbrac.com
zbredis
Python function to connect to redis by uri
zb-restqa
A package containing the framework for REST API testing. This version requires Python 2.7 or later
zbridge
Installation (Windows):download package (.zip archive)open cmdrun “pip install zbridge-<version>.zip”extract “examples” and “data” to working directory
zbrojarzpdf
This is the homepafe of our project
zbrojiMiGa-fsucic
No description available on PyPI.
zbrowser
zbrowserZen browser library.
zbsmsa
ZimmerBiomet Surgery Management System Automation
zbs-pkgs
Failed to fetch description. HTTP Status Code: 404
zbspy
No description available on PyPI.
zbs.zest
ZestA function-oriented testing framework for Python 3.Written by Zack Booth Simpson, 2020Available as a pip package:pip install zbs.zestMotivationPython's default unittest module is a class-oriented approach that does not lend itself well to recursive setup and teardown.Zest uses a recursive function-based approach best demonstrated with examples.########################################### some_module.pydef_say_hello():print("Hello")defunit_under_test(a):ifa<=0:raiseValueError("a should be positive")_say_hello()returna+1########################################### zest_some_module.pyfromzestimportzestimportsome_moduledefzest_unit_under_test():# This is a root-level zest because it starts with "zest_"defit_raises_on_non_positive():defit_raises_on_negative():withzest.raises(ValueError):some_module.unit_under_test(-1)defit_raises_on_zero():withzest.raises(ValueError):some_module.unit_under_test(0)zest()# Note this call which tells zest to run the above two testsdefit_calls_say_hello_once():withzest.mock(some_module._say_hello)asm_say_hello:some_module.unit_under_test(0)assertm_say_hello.called_once()zest()# Same here, this will cause it_raises_on_non_positive and it_calls_say_hello_once to runThe zest() function uses stack reflection to call each function that it finds in the caller's stack-frame. However, it only calls functions that do not start with an underscore.Two special functions are reserved: _before() and _after() which are called before/aftereachtest function in the scope.For example, often you may want to set up some complex state.defzest_my_test():state=Nonedef_before():nonlocalstatestate=State(1,2,3)defit_raises_if_bad():withzest.raises(Exception):unit_under_test(state)defit_modifies_state_on_1():unit_under_test(state,1)assertstate.foo==1defit_modifies_state_on_2():unit_under_test(state,2)assertstate.foo==2ExamplesSee./zests/zest_examples.pyfor more examples.UsageSearch recursively all directories for def zest_*() functions and execute them.$zestShow progress$zest--verbose=0# Show no progress$zest--verbose=1# Show "dot" progress (default)$zest--verbose=2# Show hierarchical full progressSearch only inside the specific dirs$zest--include_dirs=./abc:./defRun only tests that are in the "integration" or "slow" groups$zest--groups=integration:slowRun only tests that contain the string "foobar". This will also run any parent test needed to execute the match.$zestfoobarDisable test order shuffling which is on by default to increase the liklihood that accidental order-dependencies are manifest.$zest--disable_shuffleHelpersExpected exceptionsdefzest_foobar_should_raise_on_no_arguments():withzest.raises(ValueError):foobar()Sometimes you may wish to check a property of the trapped exceptiondefzest_foobar_should_raise_on_no_arguments():withzest.raises(ValueError)ase:foobar()asserte.exception.args==("bad juju",)Often you may wish to check only for a string of a property of the trapped exception in which case you can use the in_* argument to the raises.defzest_foobar_should_raise_on_no_arguments():withzest.raises(ValueError,in_args="bad juju")ase:foobar()Mocksimportunit_under_testdefzest_foobar():withzest.mock(unit_under_test.bar)asm_bar:# Suppose unit_under_test.foobar() calls bar()m_bar.returns(0)unit_under_test.foobar()assertm_bar.called_once_with(0)Seezest.MockFunctionfor a complete MockFunction API.GotchasDon't forget to put the zest() call at each level of the test. If you forget, the zest runner will throw an error along the lines of: "function did not terminate with a call to zest()..."defzest_something():defit_foos():foo()defit_bars():bar()# WRONG! zest() wasn't called here. Error will be thrown when the test is run.Do not mock outside of test functions:defzest_something():withzest.mock(...):defit_does_something():assertsomethingdefit_does_something_else():assertsomething# The zest() will execute outside of the above "with" statement so# the two tests will not inherit the mock as expected.zest()Rather, put the zest() inside the "with mock":defzest_something():withzest.mock(...):defit_does_something():assertsomethingdefit_does_something_else():assertsomething# This is fine because zest() was called INSIDE the withzest()Don't have more than one zest() call in the same scope.defzest_something():withzest.mock(...):defit_does_something():assertsomethingdefit_does_something_else():assertsomething# Like above example; so far, so good, but watch out...zest()withzest.mock(...):defit_does_yet_another_thing():assertsomething# WRONG! A second call to zest() will RE-EXECUTE the above two tests# (it_does_something and it_does_something_else) because this# second call to zest() doesn't know that it is inside of a with statement.# The "with" scope makes it look different but really the following# call to zest() and the call to zest above are actually in the same scope.zest()When asserting on properties of an expected exception, be sure to do assert outside the scope of the "with" as demonstrated:Wrong:withzest.raises(SomeException)ase:something_that_raises()asserte.exception.property=="something"# The above "assert" will NOT be run because the exception thrown by# something_that_raises() will be caught and never get to execute the assert!Right:withzest.raises(SomeException)ase:something_that_raises()asserte.exception.property=="something"# (Note the reference to "e.exception." as opposed to "e."Remember that the exception returned from a zest.raises() isnotof the type you are expecting but rather of a wrapper class calledTrappedException. To get to the properties of interest you need to usee.exception.*.Wrong:withzest.raises(SomeException)ase:something_that_raises()asserte.property=="something"# Wrong! e is of type TrappedException therefore the above will not work as expected.Right:withzest.raises(SomeException)ase:something_that_raises()asserte.exception.property=="something"# Correct, .exception reference to get original exception from the `e` TrappedException wrapper.DevelopmentRun in development modepipenvshell pipenvsync# Run all the example tests (which actually test the tester itself).$./zest.shDeploy$./deploy.shYou will need the user and password and credentials for Pypi.orgTODOConvert over to using logging correctlyWhen debug mode is on in ui, and a test runs, you don't see the success increment--ui fails is brokenWhen match string matches nothing it is confusing. Need "nothing was run"Add a "slowest last" to UIAdd "raises" to mock and stack mock. And error if BOTh returns and raises are setAdd --rng_seed optionMake searches more clear -- currently hard-coded to only search "zests" directoriesHarden failed imports on zest runner AST importMirror debugger-like stack introspection into a set of check-like helpers for type, arrays, etc.Add a zest internal test that _after is called even if the subsequent test exceptions (that is, _after is in a finally block)Add coverage
zb-test-pkg
Example PackageThis is a simple example package. You can use [github-flavored markdown] (https://guides. github. com/features/mastering-markdown/) to write your content.
zbuild
No description available on PyPI.
zbuilder
Zbuilder: Building VMs and applying ansible playbooksZBuilder is a tool to help you build VMs ready to be transfered to ansible. By using ansible as a library, it has access to all ansible variables. This way it achieves high integration with ansible.InstallationInstall and update using:pip3 install --user --upgrade zbuilderLinksDocumentationReleasesCode
zbus
UNKNOWN
zbuspy
No description available on PyPI.
zbx2slack
Zabbix Alert Notification Script for Slack. by pure python.Can use by “Remote command”. But can’t use by “Media type”.if use by python2.6 (like CentOS6.x), installargparsemodule. ex,$sudoyuminstallpython-argparseScreenshotNotification example.InstallIn your zabbix server,$pipinstallzbx2slackor you can download directly usingwget,curl.$wgethttps://raw.githubusercontent.com/laughk/zbx2slack/master/zbx2slack.py$chmod+xzbx2slack.py(if necessary, usesudo. )set this script your zabbix server.put file and add mode to execute.Usageget incoming-webhook url for your slack. fromincoming webhook integration.In the WebUI of your zabbix server.[Configureation][Action]Choose ‘Trigger’ at Event source and Create Action.if “Recovery message” checked, Uncheck the checkbox.At [Conditions] tab, addTrigger value = OKto Conditions.Trigger value = OKandTrigger value = PROBLEMare in Conditions.At [Operations] tab, addRemote CommandOperation type : Remote CommandTargeta list : any host (ex. Current host)Type : Custom scriptExecute on : Zabbix serverCommands:(if directly download, replacezbx2slacktozbx2slack.py.)zbx2slack\--zabbix-server-url"http://zabbix.example.com/zabbix"\--slack-botname"Zabbix Alert"\--slack-incoming-webhook-url"https://hooks.slack.com/services/xxxxxxxxx/xxxxxxxxx/...."\--trigger-id"{TRIGGER.ID}"\--trigger-name"{TRIGGER.NAME}"\--trigger-status"{TRIGGER.STATUS}"\--trigger-severity"{TRIGGER.SEVERITY}"\--event-id"{EVENT.ID}"\--item"{HOST.NAME1}|{ITEM.NAME1}|{ITEM.KEY1}|{ITEM.VALUE1}|{ITEM.ID1}"\--item"{HOST.NAME2}|{ITEM.NAME2}|{ITEM.KEY2}|{ITEM.VALUE2}|{ITEM.ID2}"\--item"{HOST.NAME3}|{ITEM.NAME3}|{ITEM.KEY3}|{ITEM.VALUE3}|{ITEM.ID3}"LICENSEMITAUTHORKei Iwasaki <[email protected]>
zbxapi
Zabbix api wrapper
zbx-dashboard
zbx_dashboardzbx_dashboardis a simple Django applicattion that provides an alternative to the Zabbix screens. It allows users who are not registered in Zabbix being able to view the graphs and (in the future) more data from Zabbix.PrerequisitesDjango 1.5.*, 1.6.*, 1.7.*Python 2.6.8+, 2.7.*Main featuresGroup graphs in separate dashboardsRearrange graphs on the dashboardEach dashboard and the graph can be provided a brief descriptionDashboards may belong to different groups of usersInstallationInstall latest stable version from PyPI:$ pip install zbx-dashboardOr latest stable version from GitHub:$ pip install -e git+https://github.com/banzayats/zbx-dashboard@stable#egg=zbx-dashboardEdit your projects’ Django settings:INSTALLED_APPS=('admin_tools','admin_tools.theming','admin_tools.menu','admin_tools.dashboard','tinymce','widget_tweaks','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','zbx_dashboard',)STATIC_ROOT=os.path.join(BASE_DIR,'static')TEMPLATE_CONTEXT_PROCESSORS=('django.contrib.auth.context_processors.auth','django.core.context_processors.debug','django.core.context_processors.i18n','django.core.context_processors.request','django.core.context_processors.static','django.contrib.messages.context_processors.messages',)LOGIN_REDIRECT_URL='/boards'# Set up your Zabbix server credentialsZABBIX_URL='https://zabbix.org/zabbix/'ZABBIX_USER='guest'ZABBIX_PASS=''# TinyMCETINYMCE_DEFAULT_CONFIG={'mode':'exact','theme':"advanced",'relative_urls':False,'width':400,'height':200,'plugins':'inlinepopups,preview,media,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras','theme_advanced_buttons1':'fullscreen,|,bold,italic,underline,strikethrough,|,sub,sup,|,bullist,numlist,|,outdent,indent,|,formatselect,removeformat,|,preview,code','theme_simple_toolbar_location':'top','theme_advanced_toolbar_align':'left',}LOCALE_PATHS=(os.path.join(BASE_DIR,'locale'),)Add to urls.py:fromdjango.contrib.auth.viewsimportlogin,logouturlpatterns=patterns('',# ...url(r'^admin_tools/',include('admin_tools.urls')),url(r'^boards/',include('zbx_dashboard.urls',namespace="boards")),url(r'^accounts/login/$',login,name='login'),url(r'^accounts/logout/$',logout,name='logout'),url(r'^tinymce/',include('tinymce.urls')),)Run:$ python manage.py syncdbThis creates a few tables in your database that are necessary for operation.Makestaticdirectory in your projects’ root directory and run:$ python manage.py collectstaticTest the application. Run the development server:$ python manage.py runserver 0.0.0.0:5000DemoDemo site:http://boyard.pp.ualogin: admin, password: admin
zbxnotifier
No description available on PyPI.
zbxsend
Sample usage::>>> from zbxsend import Metric, send_to_zabbix >>> send_to_zabbix([Metric('localhost', 'bucks_earned', 99999)], 'localhost', 10051)
zbx-statsd
Introductionzbx-statsd is a clone of Etsy’s statsd and Steve Ivy’s py-statsd designed to work with Zabbix as stats collection and graphing backend. Based on sources of pystatsd.pystatsdhttps://github.com/sivy/py-statsd/Graphitehttp://graphite.wikidot.comStatsdcode:https://github.com/etsy/statsdblog post:http://codeascraft.etsy.com/2011/02/15/measure-anything-measure-everything/UsageClient:from zbx-statsd import Client, Serversc = Client(‘example.org’,8125, ‘zabbix_name_of_this_machine’)sc.timing(‘python_test.time’,500) sc.increment(‘python_test.inc_int’) sc.decrement(‘python_test.decr_int’)Server:srvr = Server(debug=True) srvr.serve()
zbxtool
Failed to fetch description. HTTP Status Code: 404
zbxtool-cfomp
No description available on PyPI.
zbzdata
long description
zc
No description available on PyPI.
zca
ZCA whitening in Python with a Scikit-Learn like interface.UsagefromzcaimportZCAimportnumpyasnpX=np.random.random((10000,15))# data arraytrf=ZCA().fit(X)X_whitened=trf.transform(X)X_reconstructed=trf.inverse_transform(X_whitened)assert(np.allclose(X,X_reconstructed))# TrueInstallationpipinstall-UzcaLicenceGPLv3Authorszcawas written byMaarten Versteegh.
zcache
PyZCache is dependency free python key value cache based file storage and json serialize.extra features:limit able stack cacheoption to add ttl (time to life) in cache contentsmart requestInstallationpip install zcacheexamplebasic example:fromzcacheimportCacheimporttimec=Cache(path="/tmp")print("set foo=bar: ",c.set("foo","bar"))print("c size:",c.size())print("c has foo: ",c.has("foo"))print("c get foo: ",c.get("foo"))print("c delete foo: ",c.delete("foo"))print("c has foo: ",c.has("foo"))print("c has spam:",c.has("spam"))print("c set spam=eggs, ttl=3: ",c.set("spam","eggs",ttl=3))# cache with ttlprint("c has spam:",c.has("spam"))print("sleep 3")time.sleep(3)print("c has spam:",c.has("spam"))print("c size:",c.size())example with limited stack:fromzcacheimportCached=Cache(path="/tmp",limit=2)d.reset()# reset cache stack to 0print(d.set("one",1))# Trueprint(d.set("two",2))# Trueprint(d.set("three",3))# False out of stack limitd.delete("one")# delete one item from stackprint(d.set("three",3))# TrueSmartRequestSmartRequestis Simple HTTP Client with smart caching system provide byzcache.example usage ofSmartRequest(url, cache_path, cache_time, offline_ttl):fromzcacheimportSmartRequestreq=SmartRequest("https://www.example.com",cache_path="/tmp/request1.cache")print(req.is_loaded_from_cache)# check is response loaded from cacheresponse_headers=req.response.get('headers')response_body=req.response.get('body')to make advance request you can create costum url object with other library, for example:fromzcacheimportSmartRequestimportrequestsclassMyRequest:url="https://www.example.com"defget():"""this method called by SmartRequest to retrieve content.you can put request logic get, post etc and return tuple(headers=dict, body=str)"""ret=requests.get(MyRequest.url)returndict(ret.headers),ret.textreq=SmartRequest(MyRequest,cache_path="/tmp/request2.cache")note: caching for request media/binary content is possible withbase64encode.LicenseMIT
zc.ajaxform
********************Ajax Support********************The zc.ajaxform package provides framework to support:- A single-class application model- Nested-application support- Integration with zope.formlib.. contents::Detailed Documentation**********************Application support===================The zc.ajaxform.application module provides support for writing ajax[#ajax]_ applications. This framework started out as an experiment insimplifying writing applications with Zope 3. I was frustrated withZCML situps and generally too much indirection. I ended up with amodel that I'm pretty happy with. It might not be for everybody. :)The basic idea is that an application can be provided using a singleZope 3 view plus necessary resource-library definitions. This viewhas a URL. It typically provides many ajax methods whose URLs have theview URL as a base.Many applications can be implemented using a simple class that can beregistered as a view.Let's look at a simple stupid application. :)::import zc.ajaxform.applicationimport zope.exceptionsclass Calculator(zc.ajaxform.application.Trusted,zc.ajaxform.application.Application):resource_library_name = [email protected] about(self):return 'Calculator 1.0'@zc.ajaxform.application.jsonpagedef operations(self):return ['add', "subtract"]@zc.ajaxform.application.jsonpagedef value(self):return dict(value=getattr(self.context, 'calculator_value', 0))def do_add(self, value):value += getattr(self.context, 'calculator_value', 0)self.context.calculator_value = valuereturn dict(value=value)@zc.ajaxform.application.jsonpagedef add(self, value):if not isinstance(value, int):return dict(error="The value must be an integer!")return self.do_add(value)@zc.ajaxform.application.jsonpagedef subtract(self, value):if not isinstance(value, int):raise zope.exceptions.UserError("The value must be an integer!")return self.do_add(-value)@zc.ajaxform.application.jsonpagedef noop(self):[email protected] none(self):return "null"@zc.ajaxform.application.jsonpagedef echo_form(self):def maybe_file(v):if hasattr(v, 'read'):return ("<File upload name=%r content-type=%r size=%r>"% (v.filename, v.headers['content-type'], len(v.read())))else:return vreturn dict((name, maybe_file(v))for (name, v) in self.request.form.items())@zc.ajaxform.application.jsonpagedef doh(self):raise TypeError("Doh!")We subclass zc.ajaxform.application.Trusted. This is a minimalbase class that provides a constructor that takes a context and arequest and removes the security proxy from the context. Itoverrides the constructor from zc.ajaxform.application.Application.We also subclass zc.ajaxform.application.Application. This is a baseclass that provides:- a basic constructor that takes context and request arguments and setscorresponding attributes,- traversal to attributes that provide IBrowserPublisher withconversion of dots to underscores,- a default "page" named index.html,- a template method that returns an HTML page with an empty head.- an index_html method that loads a resource library and calls thetemplate,- an interface declaration that it provides IBrowserPublisher, and- an adapter declaration that adaptszope.traversing.interfaces.IContainmentRoot andzope.publisher.interfaces.browser.IBrowserRequest.The main goals of this base class are to make it easy to loadJavascript and to make it easy to define ajax methods to support theJavascript. For that reason, we provide a traverser that traverses toobject attributes that provide IBrowserPublisher. Thezc.ajaxform.application.jsonpage decorator is also an important part ofthis. It makes methods accessible and automatically marshals theirresult to JSON [#jsoninput]_. There's also azc.ajaxform.application.page decorator that makes methods accessiblewithout the automatic marshalling. The use of a default page, ratherthan just a __call__ method is to cause the URL base to be the view,rather than the view's context. This allows the Javascript code touse relative URLs to refer to the ajax methods.The class expects subclasses to define a resource_library_nameattribute [#missing_resource_library_name]_. For these applications,you pretty much always want to use an associated Javascript file andother resources (supporting JS, CSS, etc.). You can suppress the useof the resource library by setting the value of this attribute toNone.For applications that build pages totally in Javascript, the defaulttemplate is adequate. For applications that need to supportnon-Javascript-enabled browsers, that want to support search-engineoptimization [#sso]_, or that want to provide some Javascript dataduring the initial page load, a custom template can be provided bysimply overriding the template method with a page template or a methodthat calls one.The view can be registered with a simple adapter registration:::<configure xmlns="http://namespaces.zope.org/zope"><adapter name="calculator.html"factory="zc.ajaxform.calculator_example.Calculator"permission="zope.View"/></configure>If we wanted to register it for an object other than the anIContainmentRoot, we could just provide specifically adapted interfacesor classes in the registration.Let's access the calculator with a test browser>>> import zope.testbrowser.testing>>> browser = zope.testbrowser.testing.Browser()>>> browser.open('http://localhost/')Traceback (most recent call last):...HTTPError: HTTP Error 401: UnauthorizedBecause our view was registered to require zope.View, the request wasunauthorized. Let's login. In the demo setup, we login by justproviding a login form variable.>>> browser.open('http://localhost/calculator.html?login')>>> print browser.contents # doctest: +NORMALIZE_WHITESPACE<html><head><base href="http://localhost/calculator.html/index.html" /></head></html>We registered our view as calculator.html. Because of the way it sets thebrowser default page for itself, it becomes the base href for thepage. This allows us to access ajax methods using relative URLs.Our calculator view provides a value method. It uses thezc.ajaxform.application.jsonpage decorator. This does 2 things:- Arranges that the method can be traversed to,- marshals the result to JSON.The way results are marshalled to JSON deserves someexplanation. To support automation of ajax calls, we:- Always return objects- If there is an error, we include:- an error property providing an error messahe, and/or- when handling form submissions, an errors property with am object valuemapping field names to field-specific error messages.::>>> import simplejson>>> browser.open('http://localhost/@@calculator.html/value')>>> simplejson.loads(browser.contents){u'value': 0}>>> browser.open('http://localhost/@@calculator.html/add?value=hi')>>> simplejson.loads(browser.contents){u'error': u'The value must be an integer!'}Things other than a dictionary can be returned:>>> browser.open('http://localhost/@@calculator.html/about')>>> simplejson.loads(browser.contents)u'Calculator 1.0'>>> browser.open('http://localhost/@@calculator.html/operations')>>> simplejson.loads(browser.contents)[u'add', u'subtract']If you want to marshal JSON yourself, you can use thezc.ajaxform.application.jsonpage decorator:>>> browser.open('http://localhost/@@calculator.html/none')An alternative way to return errors is to raise user errors, as isdone by the subtract method in our example:>>> browser.open('http://localhost/@@calculator.html/subtract?value=hi')>>> simplejson.loads(browser.contents){u'error': u'The value must be an integer!'}This works because there is a view registered forzope.exceptions.interfaces.IUserError, andzc.ajaxform.interfaces.IAjaxRequest.Testing support===============zc.ajaxform.testing has some helper functions to make it easier to testajax calls.The zc.ajaxform.testing.FormServer class provides some convenience formaking ajax calls in which data are sent as form data and returned asJSON. The class takes a browser and returns an object that can becalled to make server calls:>>> import zc.ajaxform.testing, pprint>>> server = zc.ajaxform.testing.FormServer(browser)>>> pprint.pprint(server('/calculator.html/echo_form',... {'a': 1.0}, b=[1, 2, 3], c=True, d='d', e=u'e\u1234'... ), width=1){u'a': u'1.0',u'b': [u'1',u'2',u'3'],u'c': u'1',u'd': u'd',u'e': u'e\u1234'}When we call the server, we pass a URL to invoke, which may berelative, a optional dictionary of parameter values, and optionalkeyword arguments.Note that the application will recieve data as strings, which is whatwe see echoed back in the example above.If the application is written using Zope, then we can enable Zope formmarshalling, by passing a True value when we create the server:>>> server = zc.ajaxform.testing.FormServer(browser, True)>>> pprint.pprint(server('/calculator.html/echo_form',... {'a': 1.0}, b=[1, 2, 3], c=True, d='d', e=u'e\u1234'... ), width=1){u'a': 1.0,u'b': [1,2,3],u'c': True,u'd': u'd',u'e': u'e\u1234'}>>> pprint.pprint(server('/calculator.html/add', {'value': 1}), width=1){u'value': 1}>>> pprint.pprint(server('/calculator.html/add', value=1), width=1){u'value': 2}The methods called are assumed to return JSON and the resulting datais converted back into Python.The function pprint method combines pprint and calling:>>> server.pprint('/calculator.html/add', {'value': 1}){u'value': 3}>>> server.pprint('/calculator.html/add', value=1){u'value': 4}>>> server.pprint('/calculator.html/echo_form',... {'a': 1.0}, b=[1, 2, 3], c=True, d='d', e=u'e\u1234'... ){u'a': 1.0,u'b': [1,2,3],u'c': True,u'd': u'd',u'e': u'e\u1234'}In the future, there will be versions of these functions that senddata as JSON.We can include file-upload data by including a 3-tuple with a filename, a content type, and a data string:>>> server.pprint('/calculator.html/echo_form',... b=[1, 2, 3], c=True, d='d',... file=('foo.xml', 'test/xml', '<foo></foo>'),... ){u'b': [1,2,3],u'c': True,u'd': u'd',u'file': u"<File upload name=u'foo.xml' content-type='test/xml' size=11>"}as a convenience, you can pass a URL string to the server constructor,which will create a browser for you that has opened that URL. You canalso omit the brower and an unopened browser will be created.>>> server = zc.ajaxform.testing.FormServer(... 'http://localhost/calculator.html?login')>>> server.browser.url'http://localhost/calculator.html?login'>>> server.pprint('/calculator.html/echo_form', x=1){u'x': u'1'}>>> server = zc.ajaxform.testing.FormServer(zope_form_marshalling=True)>>> server.browser.open('http://localhost/calculator.html?login')>>> server.pprint('/calculator.html/echo_form', x=1){u'x': 1}In the example above, we didn't provide a browser, but we provided thezope_form_marshalling flag as a keyword option... Edge case: we can't traverse to undecorated methods:>>> server.pprint('/calculator.html/do_add', value=1)Traceback (most recent call last):...HTTPError: HTTP Error 404: Not Found"Library" applications======================The "application" model described above is pretty appealing in itssimplicity -- at least to me. :) Usually, we'd like to make outapplications a bit more flexible in their use. In particular, weoften want to assemble applications together. At the Javascript level,this often means having an application return a panel that can be usedin some higher-level layout. At the server level, we need to providea way to access application logic within some larger context. Thereare two parts to this:1. The containing application needs to support traversal to thesub-application.2. The subapplication needs to know how it was traversed to, at leastif it generates URLs. For example, the form machinery [#forms]_generates URLs for action handlers.Sub-application should expose the URL needed to access then as abase_href attribute. This is usually a relative URL relative to the baseapplication.There are a number of classes defined in zc.ajaxform.application thathelp with creating sub-applications:SubApplicationThis class, which Application subclasses, provides traversal toattributes that provide IBrowserPublisher. It also stampsIAjaxRequest on the request object when an object is traversed[#iajaxrequest]_ .(Maybe this request stamping should be done further down thetraversal chain or perhaps only done if X-Requested-With isxmlhttprequest.)PublicTraversableThis class provides security declarations that allow objects to betraversable publically. This is appropriate for sub-applicationsthat want the same protections as the object being traversed.Let's look at our calculator example as a subapplication:::import zc.ajaxform.applicationimport zope.exceptionsclass Container(zc.ajaxform.application.Application):resource_library_name = None@propertydef calc(self):return Calculator(self.context, self.request, base_href='calc')class Calculator(zc.ajaxform.application.Trusted,zc.ajaxform.application.SubApplication,zc.ajaxform.application.PublicTraversable,):@zc.ajaxform.application.jsonpagedef operations(self):return [['add', self.base_href+'/add'],['add', self.base_href+'/subtract'],]@zc.ajaxform.application.jsonpagedef value(self):return dict(value=getattr(self.context, 'calculator_value', 0))def do_add(self, value):value += getattr(self.context, 'calculator_value', 0)self.context.calculator_value = valuereturn dict(value=value)@zc.ajaxform.application.jsonpagedef add(self, value):if not isinstance(value, int):return dict(error="The value must be an integer!")return self.do_add(value)@zc.ajaxform.application.jsonpagedef subtract(self, value):if not isinstance(value, int):raise zope.exceptions.UserError("The value must be an integer!")return self.do_add(-value)Here, we've defined a container application that simply providestraversal to a calculator subapplication as a static property. Itcreates the calculator with the application's context and request. Itpasses a base_href as a keyword argument, which SubApplication'sconstructor accepts. Our ZCML configuration is pretty simple:::<configure xmlns="http://namespaces.zope.org/zope"><include package="zope.app.component" file="meta.zcml" /><adapter name="container.html"factory="zc.ajaxform.calculator_subapplication_example.Container"permission="zope.View"/></configure>Using the container application, we access the calculator via thecontainer:>>> server.pprint('http://localhost/@@container.html/calc/add', value=1){u'value': 5}We've updated the operations method to include the URL for eachoperation, which is computed based on the base_href:>>> server.pprint('http://localhost/@@container.html/calc/operations')[[u'add',u'calc/add'],[u'add',u'calc/subtract']]Note that we didn't make any security declarations for the Calculatorclass. We're relying on the protection for the container. If werestart the browser, we see, indeed, that we can't access thecalculator:>>> server = zc.ajaxform.testing.FormServer()>>> server.pprint('http://localhost/@@container.html/calc/operations'){u'session_expired': True}Dynamic Traversal=================In the previous example, we traversed to a sub-application using astatic property. Sometimes, we need to traverse dynamically. Wemight have a container application with a variable number ofsubapplications. Examples include a portlet container and a system formanaging user-defined data types. In the later case, as users definenew data types, one or more applications get defined for each type.zc.ajaxform.application provides a helper descriptor that allows customtraversers to be implemented with simple Python methods. Let's lookat a simple example.>>> import zc.ajaxform.application>>> class Foo:... def __str__(self):... return 'a '+self.__class__.__name__...... @zc.ajaxform.application.traverser... def demo_traverse(self, request, name):... return "traverse: %s %s %s" % (self, request, name)This is a rather silly traverser for demonstration purposes that justreturnes a transformed name.>>> foo = Foo()>>> foo.demo_traverse.publishTraverse("a request", "xxx")'traverse: a Foo a request xxx'We can still call the method:>>> foo.demo_traverse("a request", "xxx")'traverse: a Foo a request xxx'The method provides IBrowserPublisher:>>> import zope.publisher.interfaces.browser>>> zope.publisher.interfaces.browser.IBrowserPublisher.providedBy(... foo.demo_traverse)TrueThe descriptor has a security declaration that allows it to betraversed but not called from untrusted code:>>> import zope.security.checker>>> checker = zope.security.checker.getChecker(... zope.security.checker.ProxyFactory(foo.demo_traverse))>>> checker.get_permissions{'publishTraverse': Global(CheckerPublic,zope.security.checker)}>>> checker.set_permissions{}Acquisition===========Applications and sub-applications have __parent__ properties thatreturn their context. This is to support frameworks that ise__parent__ to perform acquisition.>>> class MyApp(zc.ajaxform.application.Application):... pass>>> myapp = MyApp(foo, None)>>> myapp.__parent__ is fooTrue>>> class MySubApp(zc.ajaxform.application.SubApplication):... pass>>> mysubapp = MySubApp(foo, None)>>> mysubapp.__parent__ is fooTrueSystem Errors=============System errors will be rendered as json.>>> server = zc.ajaxform.testing.FormServer(... 'http://localhost/calculator.html?login')>>> server('/calculator.html/doh')Traceback (most recent call last):...HTTPError: HTTP Error 500: Internal Server Error>>> pprint.pprint(simplejson.loads(server.browser.contents), width=1){u'error': u'TypeError: Doh!'}.. [#ajax] Technically, these aren't really AJAX applications, sincewe rarely. if ever, use XML as a serialization format. Toemphasize this I'll use lower-case "ajax" to refer to the genericapproach of making low-level calls from Javascript rather thandoing page loads... [#jsoninput] In the near future, there will also be support forJSON method input. This will provide a number of benefits:- It will provide more automatic marshaling of non-stringdata. Now, we either have to de-marshal in the server applicationcode or embed marshaling data into parameter names in clientcode.- It will allow richer data structures than is practical with form data.- It will probably allow faster ajax requests because:- Server-side de-marshalling is done with highly optimized codein simplejson.- We will assume that data passed are valid method arguments andavoid method introspection... [#missing_resource_library_name] A custom attribute error messageis used if this attribute is missing that tries to be moreinformative than the default attribute error... [#sso] For search-engine optimization, one generally wants acontent page to actually contain its content. If one depends onJavascript-enabled browsers, one can improve performance andsearch-engine optimization by adding ancilary data in Javascript,so as not to dilute the content... [#forms] See form.txt... [#iajaxrequest] Traversing into a subapplication adds IAjaxRequest to thelist of interfaces provided by the request.>>> import zc.ajaxform.application>>> import zc.ajaxform.interfaces>>> import zope.publisher.browser>>> request = zope.publisher.browser.TestRequest()>>> class SubApp(zc.ajaxform.application.SubApplication):... @zc.ajaxform.application.jsonpage... def foo(self):... return 'bar'>>> subapp = SubApp(object(), request)Now let's try traversing into the subapplication:>>> zc.ajaxform.interfaces.IAjaxRequest.providedBy(request)False>>> subapp.publishTraverse(request, 'foo')()'"bar"'>>> zc.ajaxform.interfaces.IAjaxRequest.providedBy(request)TrueNote that the request keeps any provided interfaces:>>> request = zope.publisher.browser.TestRequest()>>> class IMyInterface(zope.interface.Interface):... pass>>> zope.interface.directlyProvides(request, IMyInterface)>>> subapp.publishTraverse(request, 'foo')()'"bar"'>>> IMyInterface.providedBy(request)TrueSystem Error Logging====================When an error is generated, zope.app.publishing checks to see if theerror handler provides the System Error interface. If so, zope.app.publishinglogs the error.Rather than use this indirect method of logging, there is an explicitstatement in ExceptionView that imports the logging module and logs and erroritself. We can test this with the zope.testing.loggingsupport functions.First we set up loggingsupport. This keeps track of all error messageswritten via the module passed as the parameter. In this case, zc.ajaxform.>>> import logging>>> import zope.testing.loggingsupport>>> log_handler = zope.testing.loggingsupport.InstalledHandler('zc.ajaxform')Then we create an error.>>> server = zc.ajaxform.testing.FormServer(... 'http://localhost/calculator.html?login')>>> server('/calculator.html/doh')Traceback (most recent call last):...HTTPError: HTTP Error 500: Internal Server Error...And check to see that it was logged.>>> print log_handlerzc.ajaxform.application ERRORSysError created by zc.ajaxformForm Processing===============zc.ajaxform.form provides support for server-generated forms based onthe zope.formlib library.Forms are meant to be used as parts of larger applications. A formprovides output of JSON data for building javascript forms. Forms alsoprovide validation and call actions with validated data to performactions on form submit.To create a form, just create a form class as a subclass ofzc.ajaxform.form.Form. This base class provides:- an ajax __call__ method that returns a form definition,- traversal to form actions, in much the same way thatzc.ajaxform.application.Application [#application]_ provides traversalto json methods,- a definitions method that can be used by ajax methods to get a formdefinition as Python data, and- a getObjectData method for getting initial form data from anexisting object.Here's a simple example:::import zc.ajaxform.applicationimport zc.ajaxform.interfacesimport zc.ajaxform.widgetsimport zc.ajaxform.formimport zope.componentimport zope.interfaceimport zope.formlibimport zope.schemaclass IAddress(zope.interface.Interface):street = zope.schema.TextLine(title = u"Street",description = u"The street",)city = zope.schema.TextLine(title = u"City",description = u"The city",)awesomeness = zope.schema.Int(title = u"Awesomeness",description = u"The awesomeness on a scale of 1 to 10",min = 1,max = 10,)class Pets(zc.sourcefactory.basic.BasicSourceFactory):def getValues(self):return (u'Dog', u'Cat', u'Fish')class Pet(zope.schema.TextLine):"""A textline representing a pet.This is just a textline, but we also have a source of common pets thatthe user can choose from."""class IPerson(zope.interface.Interface):first_name = zope.schema.TextLine(title = u"First name",description = u"Given name.",default= u'Happy')last_name = zope.schema.TextLine(title = u"Last name",description = u"Family name.",default= u'Camper')favorite_color = zope.schema.TextLine(title = u"Favorite color",required = False,default= u'Blue')age = zope.schema.Int(title = u"Age",description = u"Age in years",min = 0,max = 200,default= 23)happy = zope.schema.Bool(title = u"Happy",description = u"Are they happy?",default= True)pet = Pet(title=u'Pet',description=u'This person\'s best friend.',required=False,)temperment = zope.schema.Choice(title = u"Temperment",description = u"What is the person like?",values = ['Nice', 'Mean', 'Ornery', 'Right Neighborly'],default = u'Right Neighborly')weight = zope.schema.Decimal(title = u"Weight",description = u"Weight in lbs?")description = zope.schema.Text(title = u"Description",description = u"What do they look like?",default = u'10ft tall\nRazor sharp scales.')secret = zope.schema.TextLine(title = u"Secret Key",description = u"Don't tell anybody",default = u'5ecret sauce')siblings = zope.schema.Int(title = u"Siblings",description = u"Number of siblings",min = 0,max = 8,default = 1)addresses = zope.schema.List(title = u'Addresses',description = u"All my wonderful homes",value_type = zope.schema.Object(schema=IAddress),default= [{'street':'123 fake street','city': 'fakeville','awesomeness': '9'},{'street':'345 false street','city': 'falsetown','awesomeness': '9001'}])other = zope.schema.Text(title = u"Other",description = u"Any other notes",default = u"I've got a magic toenail")class Person:zope.interface.implements(IPerson)def __init__(self, first_name, last_name, favorite_color, age, happy,pet, temperment, weight, description, secret, siblings,addresses, other):self.first_name = first_nameself.last_name = last_nameself.favorite_color = favorite_colorself.age = ageself.happy = happyself.pet = petself.temperment = tempermentself.weight = weightself.description = descriptionself.secret = secretself.siblings = siblingsself.addresses = addressesself.other = otherclass FormExample(zc.ajaxform.application.Application):resource_library_name = Noneclass ExampleForm(zc.ajaxform.form.Form):leftFields = ('first_name', 'last_name', 'age', 'other')form_fields = zope.formlib.form.Fields(IPerson)form_fields['secret'].custom_widget = zc.ajaxform.widgets.Hiddenform_fields['siblings'].custom_widget = [email protected]("Register")def register(self, action, data):person = Person(**data)return dict(data = data,self_class_name = self.__class__.__name__,self_app_class_name = self.app.__class__.__name__,self_context_class_name = self.context.__class__.__name__)class PetWidget(zc.ajaxform.widgets.ComboBox):zope.component.adapts(Pet,zc.ajaxform.interfaces.IAjaxRequest)zope.interface.implements(zc.ajaxform.interfaces.IInputWidget)def __init__(self, context, request):super(PetWidget, self).__init__(context, Pets(), request)Note that we've nested our form definition in an application. We candefine the form class elsewhere and use it, but if a form is only usedin an application, then it's often easiest to define it within anapplication class. Forms are instantiated by calling them with asingle argument. This argument, the application, becomes the form's `app`attribute. The application's context becomes the form's context. Formclasses are automatically instantiated when a form class is assigned toan attribute in a class and accessed through an instance[#form_classes_are_descriptors]_.Let's try accessing our form, which can be found in its python formin form_example.py:>>> import zope.testbrowser.testing>>> from zc.ajaxform.testing import call_form, print_form>>> browser = zope.testbrowser.testing.Browser()>>> browser.open('http://localhost/form.html?login')>>> print_form(browser, 'http://localhost/form.html/ExampleForm'){u'definition': {u'actions': [{u'label': u'Register',u'name': u'ExampleForm.actions.register',u'url': u'ExampleForm/register'}],u'left_fields': {u'addresses': False,u'age': True,u'description': False,u'favorite_color': False,u'first_name': True,u'happy': False,u'last_name': True,u'other': True,u'pet': False,u'secret': False,u'siblings': False,u'temperment': False,u'weight': False},u'prefix': u'ExampleForm',u'widgets': [{u'fieldHint': u'Given name.',u'fieldLabel': u'First name',u'id': u'first_name',u'minLength': 0,u'name': u'first_name',u'required': True,u'value': u'Happy',u'widget_constructor': u'zope.schema.TextLine'},{u'fieldHint': u'Family name.',u'fieldLabel': u'Last name',u'id': u'last_name',u'minLength': 0,u'name': u'last_name',u'required': True,u'value': u'Camper',u'widget_constructor': u'zope.schema.TextLine'},{u'fieldHint': u'',u'fieldLabel': u'Favorite color',u'id': u'favorite_color',u'minLength': 0,u'name': u'favorite_color',u'required': False,u'value': u'Blue',u'widget_constructor': u'zope.schema.TextLine'},{u'allowBlank': False,u'fieldHint': u'Age in years',u'fieldLabel': u'Age',u'field_max': 200,u'field_min': 0,u'id': u'age',u'name': u'age',u'required': True,u'value': u'23',u'widget_constructor': u'zope.schema.Int'},{u'fieldHint': u'Are they happy?',u'fieldLabel': u'Happy',u'id': u'happy',u'name': u'happy',u'required': True,u'value': True,u'widget_constructor': u'zope.schema.Bool'},{u'fieldHint': u"This person's best friend.",u'fieldLabel': u'Pet',u'id': u'pet',u'name': u'pet',u'required': False,u'values': [[u'c935d187f0b998ef720390f85014ed1e',u'Dog'],[u'fa3ebd6742c360b2d9652b7f78d9bd7d',u'Cat'],[u'071642fa72ba780ee90ed36350d82745',u'Fish']],u'widget_constructor': u'zc.ajaxform.widgets.ComboBox'},{u'allowBlank': False,u'fieldHint': u'What is the person like?',u'fieldLabel': u'Temperment',u'hiddenName': u'temperment.value',u'id': u'temperment',u'name': u'temperment',u'required': True,u'value': u'Right Neighborly',u'values': [[u'Nice',u'Nice'],[u'Mean',u'Mean'],[u'Ornery',u'Ornery'],[u'Right Neighborly',u'Right Neighborly']],u'widget_constructor': u'zope.schema.Choice'},{u'allowBlank': False,u'fieldHint': u'Weight in lbs?',u'fieldLabel': u'Weight',u'id': u'weight',u'name': u'weight',u'required': True,u'widget_constructor': u'zope.schema.Decimal'},{u'fieldHint': u'What do they look like?',u'fieldLabel': u'Description',u'id': u'description',u'minLength': 0,u'name': u'description',u'required': True,u'value': u'10ft tall\nRazor sharp scales.',u'widget_constructor': u'zope.schema.Text'},{u'fieldHint': u"Don't tell anybody",u'fieldLabel': u'Secret Key',u'id': u'secret',u'name': u'secret',u'required': True,u'value': u'5ecret sauce',u'widget_constructor': u'zc.ajaxform.widgets.Hidden'},{u'allowBlank': False,u'fieldHint': u'Number of siblings',u'fieldLabel': u'Siblings',u'field_max': 8,u'field_min': 0,u'id': u'siblings',u'name': u'siblings',u'required': True,u'value': u'1',u'widget_constructor': u'zc.ajaxform.widgets.NumberSpinner'},{u'fieldHint': u'All my wonderful homes',u'fieldLabel': u'Addresses',u'id': u'addresses',u'name': u'addresses',u'record_schema': {u'readonly': False,u'widgets': [{u'fieldHint': u'The street',u'fieldLabel': u'Street',u'id': u'street',u'minLength': 0,u'name': u'street',u'required': True,u'widget_constructor': u'zope.schema.TextLine'},{u'fieldHint': u'The city',u'fieldLabel': u'City',u'id': u'city',u'minLength': 0,u'name': u'city',u'required': True,u'widget_constructor': u'zope.schema.TextLine'},{u'allowBlank': False,u'fieldHint': u'The awesomeness on a scale of 1 to 10',u'fieldLabel': u'Awesomeness',u'field_max': 10,u'field_min': 1,u'id': u'awesomeness',u'name': u'awesomeness',u'required': True,u'widget_constructor': u'zope.schema.Int'}]},u'required': True,u'value': [{u'awesomeness': u'9',u'city': u'fakeville',u'street': u'123 fake street'},{u'awesomeness': u'9001',u'city': u'falsetown',u'street': u'345 false street'}],u'widget_constructor': u'zope.schema.List'},{u'fieldHint': u'Any other notes',u'fieldLabel': u'Other',u'id': u'other',u'minLength': 0,u'name': u'other',u'required': True,u'value': u"I've got a magic toenail",u'widget_constructor': u'zope.schema.Text'}]}}Our application is at: "http://localhost/form.html". The form isexposed as an ajax method named "ExampleForm", which comes from the attributename in the class definition.The form definition contains both action definitions and widgetdefinitions. The widget definitions may be full js field definitionsor name a widget_constructor, which is a Javascript helper provided bythe zc.ajaxform resource library that provides additional information,like Javascript validators, that can't be expressed in JSON.There is an action definition for each action defined in the form. Theaction information includes the url to post the result to, relative tothe application.Note that the name of the form class is used as the form prefix andthat the form prefix is used as the prefix for widget and action namesand ids [#actionids]_.Let's post a result back:>>> print_form(browser, 'http://localhost/form.html/ExampleForm/register',... {'first_name': 'Bob',... 'last_name': '',... 'favorite_color': '',... 'age': '-1',... }){u'errors': {u'addresses': u'Addresses: Missing Input',u'age': u'Value is too small',u'description': u'Description: Missing Input',u'last_name': u'Last name: Missing Input',u'other': u'Other: Missing Input',u'secret': u'Secret Key: Missing Input',u'siblings': u'Siblings: Missing Input',u'temperment': u'Temperment: Missing Input',u'weight': u'Weight: Missing Input'}}The result had 9 problems:- We didn't provide a last name, description, secret key,number of siblings, temperment, or weight, which are all required- In the form we did not specify deleting either of our two currentaddress records, but also ommitted their data, and the first of themreported a missing field. Following this we will delete them both andadd a new record.- We specified an invalid age.Let's pass valid data:>>> print_form(browser, 'http://localhost/form.html/ExampleForm/register',... {'first_name': 'Bob',... 'last_name': 'Zope',... 'favorite_color': '',... 'age': '11',... 'addresses.street.0': '123 Fake Ln.',... 'addresses.city.0': 'Fakeville',... 'addresses.awesomeness.0': 7,... 'description': 'Hello',... 'other': 'So nice to meet you',... 'secret': 'Oh nothing',... 'siblings': 1,... 'temperment': 'Nice',... 'weight': '170.5',... 'pet': 'Carrier Pigeon'... }){u'data': {u'addresses': [{u'awesomeness': 7,u'city': u'Fakeville',u'street': u'123 Fake Ln.'}],u'age': 11,u'description': u'Hello',u'favorite_color': u'',u'first_name': u'Bob',u'happy': False,u'last_name': u'Zope',u'other': u'So nice to meet you',u'pet': u'Carrier Pigeon',u'secret': u'Oh nothing',u'siblings': 1,u'temperment': u'Nice',u'weight': u'170.5'},u'self_app_class_name': u'FormExample',u'self_class_name': u'ExampleForm',u'self_context_class_name': u'Folder'}Here we get a successful result. Our contrived action in the examplesimply echoed back the data it was passed, Note, in particular that:- the data keys have the form prefix removed, and- the value of the age key is an integer, since the field was aninteger field.Note that for the list field, the original request added a prefix of the listfield name to prevent collisions with a field with the same name in anotherlist field (if it existed).The action also prints out the classes of its self argument, its appand its context. Actions are methods of forms so their `self` argument is theform. The form's `app` is the app through which it is accessed and`context` is the app's context.For list widgets if a field in its record is missing and it is required, theerror reported lists the field name:>>> print_form(browser, 'http://localhost/form.html/ExampleForm/register',... {'first_name': 'Bob',... 'last_name': 'Zope',... 'favorite_color': '',... 'age': '11',... 'addresses.street.0': '123 Fake Ln.',... 'addresses.city.0': 'Fakeville',... 'addresses.awesomeness.0': 7,... 'addresses.street.1': 'The 2nd Missing field St.',... 'addresses.awesomeness.1': 3,... 'description': 'Hello',... 'other': 'So nice to meet you',... 'secret': 'Oh nothing',... 'siblings': 1,... 'temperment': 'Nice',... 'weight': '170.5',... 'pet': 'Carrier Pigeon'... }){u'errors': {u'addresses': u'City: Missing Input'}}Let's provide this value now:>>> print_form(browser, 'http://localhost/form.html/ExampleForm/register',... {'first_name': 'Bob',... 'last_name': 'Zope',... 'favorite_color': '',... 'age': '11',... 'addresses.street.0': '123 Fake Ln.',... 'addresses.city.0': 'Fakeville',... 'addresses.awesomeness.0': 7,... 'addresses.street.1': 'The 2nd Missing field St.',... 'addresses.city.1': 'A Void',... 'addresses.awesomeness.1': '3',... 'description': 'Hello',... 'other': 'So nice to meet you',... 'secret': 'Oh nothing',... 'siblings': 1,... 'temperment': 'Nice',... 'weight': '170.5',... 'pet': 'Carrier Pigeon'... }){u'data': {u'addresses': [{u'awesomeness': 7,u'city': u'Fakeville',u'street': u'123 Fake Ln.'},{u'awesomeness': 3,u'city': u'A Void',u'street': u'The 2nd Missing field St.'}],u'age': 11,u'description': u'Hello',u'favorite_color': u'',u'first_name': u'Bob',u'happy': False,u'last_name': u'Zope',u'other': u'So nice to meet you',u'pet': u'Carrier Pigeon',u'secret': u'Oh nothing',u'siblings': 1,u'temperment': u'Nice',u'weight': u'170.5'},u'self_app_class_name': u'FormExample',u'self_class_name': u'ExampleForm',u'self_context_class_name': u'Folder'}Reordering items in a list is accomplished by reordering the suffix for therecord fields:>>> print_form(browser, 'http://localhost/form.html/ExampleForm/register',... {'first_name': 'Bob',... 'last_name': 'Zope',... 'favorite_color': '',... 'age': '11',... 'addresses.street.1': '123 Fake Ln.',... 'addresses.city.1': 'Fakeville',... 'addresses.awesomeness.1': 7,... 'addresses.street.0': 'The 2nd Missing field St.',... 'addresses.city.0': 'A Void',... 'addresses.awesomeness.0': 3,... 'description': 'Hello',... 'other': 'So nice to meet you',... 'secret': 'Oh nothing',... 'siblings': 1,... 'temperment': 'Nice',... 'weight': '170.5',... 'pet': 'Carrier Pigeon'... }){u'data': {u'addresses': [{u'awesomeness': 3,u'city': u'A Void',u'street': u'The 2nd Missing field St.'},{u'awesomeness': 7,u'city': u'Fakeville',u'street': u'123 Fake Ln.'}],u'age': 11,u'description': u'Hello',u'favorite_color': u'',u'first_name': u'Bob',u'happy': False,u'last_name': u'Zope',u'other': u'So nice to meet you',u'pet': u'Carrier Pigeon',u'secret': u'Oh nothing',u'siblings': 1,u'temperment': u'Nice',u'weight': u'170.5'},u'self_app_class_name': u'FormExample',u'self_class_name': u'ExampleForm',u'self_context_class_name': u'Folder'}Getting definitions from Python-------------------------------Sometimes we want to get form definitions from Python. The form__call__ method returns a JSON string. We can get Python data bycalling get_definition.>>> import zc.ajaxform.form_example>>> import zope.publisher.browser>>> request = zope.publisher.browser.TestRequest()>>> import zc.ajaxform.interfaces>>> import zope.interface>>> zope.interface.alsoProvides(... request, zc.ajaxform.interfaces.IAjaxRequest)>>> ex = zc.ajaxform.form_example.FormExample(None, request)>>> from pprint import pprint>>> pprint(ex.ExampleForm.get_definition(), width=1){'actions': [{'label': 'Register','name': u'ExampleForm.actions.register','url': u'ExampleForm/register'}],'left_fields': {'addresses': False,'age': True,'description': False,'favorite_color': False,'first_name': True,'happy': False,'last_name': True,'other': True,'pet': False,'secret': False,'siblings': False,'temperment': False,'weight': False},'prefix': 'ExampleForm','widgets': [{'fieldHint': u'Given name.','fieldLabel': u'First name','id': 'first_name','minLength': 0,'name': 'first_name','required': True,'value': u'Happy','widget_constructor': 'zope.schema.TextLine'},{'fieldHint': u'Family name.','fieldLabel': u'Last name','id': 'last_name','minLength': 0,'name': 'last_name','required': True,'value': u'Camper','widget_constructor': 'zope.schema.TextLine'},{'fieldHint': u'','fieldLabel': u'Favorite color','id': 'favorite_color','minLength': 0,'name': 'favorite_color','required': False,'value': u'Blue','widget_constructor': 'zope.schema.TextLine'},{'allowBlank': False,'fieldHint': u'Age in years','fieldLabel': u'Age','field_max': 200,'field_min': 0,'id': 'age','name': 'age','required': True,'value': u'23','widget_constructor': 'zope.schema.Int'},{'fieldHint': u'Are they happy?','fieldLabel': u'Happy','id': 'happy','name': 'happy','required': True,'value': True,'widget_constructor': 'zope.schema.Bool'},{'fieldHint': u"This person's best friend.",'fieldLabel': u'Pet','id': 'pet','name': 'pet','required': False,'values': [['c935d187f0b998ef720390f85014ed1e',u'Dog'],['fa3ebd6742c360b2d9652b7f78d9bd7d',u'Cat'],['071642fa72ba780ee90ed36350d82745',u'Fish']],'widget_constructor': 'zc.ajaxform.widgets.ComboBox'},{'allowBlank': False,'fieldHint': u'What is the person like?','fieldLabel': u'Temperment','hiddenName': 'temperment.value','id': 'temperment','name': 'temperment','required': True,'value': 'Right Neighborly','values': [['Nice',u'Nice'],['Mean',u'Mean'],['Ornery',u'Ornery'],['Right Neighborly',u'Right Neighborly']],'widget_constructor': 'zope.schema.Choice'},{'allowBlank': False,'fieldHint': u'Weight in lbs?','fieldLabel': u'Weight','id': 'weight','name': 'weight','required': True,'widget_constructor': 'zope.schema.Decimal'},{'fieldHint': u'What do they look like?','fieldLabel': u'Description','id': 'description','minLength': 0,'name': 'description','required': True,'value': u'10ft tall\nRazor sharp scales.','widget_constructor': 'zope.schema.Text'},{'fieldHint': u"Don't tell anybody",'fieldLabel': u'Secret Key','id': 'secret','name': 'secret','required': True,'value': u'5ecret sauce','widget_constructor': 'zc.ajaxform.widgets.Hidden'},{'allowBlank': False,'fieldHint': u'Number of siblings','fieldLabel': u'Siblings','field_max': 8,'field_min': 0,'id': 'siblings','name': 'siblings','required': True,'value': u'1','widget_constructor': 'zc.ajaxform.widgets.NumberSpinner'},{'fieldHint': u'All my wonderful homes','fieldLabel': u'Addresses','id': 'addresses','name': 'addresses','record_schema': {'readonly': False,'widgets': [{'fieldHint': u'The street','fieldLabel': u'Street','id': 'street','minLength': 0,'name': 'street','required': True,'widget_constructor': 'zope.schema.TextLine'},{'fieldHint': u'The city','fieldLabel': u'City','id': 'city','minLength': 0,'name': 'city','required': True,'widget_constructor': 'zope.schema.TextLine'},{'allowBlank': False,'fieldHint': u'The awesomeness on a scale of 1 to 10','fieldLabel': u'Awesomeness','field_max': 10,'field_min': 1,'id': 'awesomeness','name': 'awesomeness','required': True,'widget_constructor': 'zope.schema.Int'}]},'required': True,'value': [{'awesomeness': u'9','city': u'fakeville','street': u'123 fake street'},{'awesomeness': u'9001','city': u'falsetown','street': u'345 false street'}],'widget_constructor': 'zope.schema.List'},{'fieldHint': u'Any other notes','fieldLabel': u'Other','id': 'other','minLength': 0,'name': 'other','required': True,'value': u"I've got a magic toenail",'widget_constructor': 'zope.schema.Text'}]}Note that we had to stamp the request with IAjaxRequest. This is doneduring application traversal. We need it so widgets can get lookedup.Base and prefix---------------Forms have base_href and prefix variables. The base_href is used to computeURLs for form actions. A form's base_href defaults to its class name.The form's base_href also includes the base_href of its app, if its app hasa base_href. This is useful for sub-applications. Let's give our sampleapplication a base_href attribute as if it were a sub-application:>>> ex = zc.ajaxform.form_example.FormExample(None, request)>>> ex.base_href = 'sample'>>> ex.ExampleForm.base_href'sample/ExampleForm'>>> pprint(ex.ExampleForm.get_definition(), width=1){'actions': [{'label': 'Register','name': u'sample.ExampleForm.actions.register','url': u'sample/ExampleForm/register'}],'left_fields': {'addresses': False,'age': True,'description': False,'favorite_color': False,'first_name': True,'happy': False,'last_name': True,'other': True,'pet': False,'secret': False,'siblings': False,'temperment': False,'weight': False},'prefix': 'sample.ExampleForm','widgets': [{'fieldHint': u'Given name.','fieldLabel': u'First name','id': 'first_name','minLength': 0,'name': 'first_name','required': True,'value': u'Happy','widget_constructor': 'zope.schema.TextLine'},{'fieldHint': u'Family name.','fieldLabel': u'Last name','id': 'last_name','minLength': 0,'name': 'last_name','required': True,'value': u'Camper','widget_constructor': 'zope.schema.TextLine'},{'fieldHint': u'','fieldLabel': u'Favorite color','id': 'favorite_color','minLength': 0,'name': 'favorite_color','required': False,'value': u'Blue','widget_constructor': 'zope.schema.TextLine'},{'allowBlank': False,'fieldHint': u'Age in years','fieldLabel': u'Age','field_max': 200,'field_min': 0,'id': 'age','name': 'age','required': True,'value': u'23','widget_constructor': 'zope.schema.Int'},{'fieldHint': u'Are they happy?','fieldLabel': u'Happy','id': 'happy','name': 'happy','required': True,'value': True,'widget_constructor': 'zope.schema.Bool'},{'fieldHint': u"This person's best friend.",'fieldLabel': u'Pet','id': 'pet','name': 'pet','required': False,'values': [['c935d187f0b998ef720390f85014ed1e',u'Dog'],['fa3ebd6742c360b2d9652b7f78d9bd7d',u'Cat'],['071642fa72ba780ee90ed36350d82745',u'Fish']],'widget_constructor': 'zc.ajaxform.widgets.ComboBox'},{'allowBlank': False,'fieldHint': u'What is the person like?','fieldLabel': u'Temperment','hiddenName': 'temperment.value','id': 'temperment','name': 'temperment','required': True,'value': 'Right Neighborly','values': [['Nice',u'Nice'],['Mean',u'Mean'],['Ornery',u'Ornery'],['Right Neighborly',u'Right Neighborly']],'widget_constructor': 'zope.schema.Choice'},{'allowBlank': False,'fieldHint': u'Weight in lbs?','fieldLabel': u'Weight','id': 'weight','name': 'weight','required': True,'widget_constructor': 'zope.schema.Decimal'},{'fieldHint': u'What do they look like?','fieldLabel': u'Description','id': 'description','minLength': 0,'name': 'description','required': True,'value': u'10ft tall\nRazor sharp scales.','widget_constructor': 'zope.schema.Text'},{'fieldHint': u"Don't tell anybody",'fieldLabel': u'Secret Key','id': 'secret','name': 'secret','required': True,'value': u'5ecret sauce','widget_constructor': 'zc.ajaxform.widgets.Hidden'},{'allowBlank': False,'fieldHint': u'Number of siblings','fieldLabel': u'Siblings','field_max': 8,'field_min': 0,'id': 'siblings','name': 'siblings','required': True,'value': u'1','widget_constructor': 'zc.ajaxform.widgets.NumberSpinner'},{'fieldHint': u'All my wonderful homes','fieldLabel': u'Addresses','id': 'addresses','name': 'addresses','record_schema': {'readonly': False,'widgets': [{'fieldHint': u'The street','fieldLabel': u'Street','id': 'street','minLength': 0,'name': 'street','required': True,'widget_constructor': 'zope.schema.TextLine'},{'fieldHint': u'The city','fieldLabel': u'City','id': 'city','minLength': 0,'name': 'city','required': True,'widget_constructor': 'zope.schema.TextLine'},{'allowBlank': False,'fieldHint': u'The awesomeness on a scale of 1 to 10','fieldLabel': u'Awesomeness','field_max': 10,'field_min': 1,'id': 'awesomeness','name': 'awesomeness','required': True,'widget_constructor': 'zope.schema.Int'}]},'required': True,'value': [{'awesomeness': u'9','city': u'fakeville','street': u'123 fake street'},{'awesomeness': u'9001','city': u'falsetown','street': u'345 false street'}],'widget_constructor': 'zope.schema.List'},{'fieldHint': u'Any other notes','fieldLabel': u'Other','id': 'other','minLength': 0,'name': 'other','required': True,'value': u"I've got a magic toenail",'widget_constructor': 'zope.schema.Text'}]}Note that the action URL now includes "sample/" as a prefix. Alsonote that the widget and action names have "" as a prefix. Theform prefix is simply its base with "/"s converted to "."s.>>> ex.ExampleForm.prefix'sample.ExampleForm'Form data---------Ajax forms are a bit different from normal web forms because the dataand the form definition can be fetched separately. For example, wemay use the same form to edit multiple objects. Form objects have agetObjectData method that returns data suitable for editing form fieldvalues. Let's create a person and use out form to get data for them:>>> bob = zc.ajaxform.form_example.Person(... first_name='bob',... last_name='smith',... favorite_color=None,... age=11,... happy=True,... pet=u'Cockatiel',... temperment='Nice',... weight = 175.5,... description = 'A real cool guy',... secret = 'Noone knows!',... siblings = 1,... addresses = [],... other = 'stuff')>>> pprint(ex.ExampleForm.getObjectData(bob), width=1){'addresses': [],'age': u'11','description': u'A real cool guy','first_name': u'bob','happy': True,'last_name': u'smith','other': u'stuff','pet': u'Cockatiel','secret': u'Noone knows!','siblings': u'1','temperment': 'Nice','weight': u'175.5'}We didn't set the favorite_color for the person, so it is ommittedfrom the data.We can pass in a dictionary of values that take precedence over object data:>>> pprint(ex.ExampleForm.getObjectData(... bob, {'age': u'1'}),... width=1){'addresses': [],'age': u'1','description': u'A real cool guy','first_name': u'bob','happy': True,'last_name': u'smith','other': u'stuff','pet': u'Cockatiel','secret': u'Noone knows!','siblings': u'1','temperment': 'Nice','weight': u'175.5'}Display Options---------------Additional display options may be sent in the widget definition if the widgetcan be adapted to `IDisplayOptions`. The result of the adaptation only needbe JSON serializable.>>> import zope.app.form.interfaces>>> def example_options(widget):... field, name = widget.context, widget.context.__name__... if name == 'favorite_color':... return {'picker': 'crayons'}... elif name == 'secret':... return 'super-secret'... else:... return None>>> site_manager = zope.component.getSiteManager()>>> site_manager.registerAdapter(... example_options,... required=(zope.app.form.interfaces.IWidget,),... provided=zc.ajaxform.interfaces.IDisplayOptions)>>> result = call_form(... browser, 'http://localhost/form.html/ExampleForm')>>> widgets = result['definition']['widgets']>>> for widget in widgets:... if widget.get('display_options'):... print widget['name'] + ':', widget['display_options']favorite_color: {u'picker': u'crayons'}secret: super-secretFinally, clean up.>>> site_manager.unregisterAdapter(... example_options,... required=(zope.app.form.interfaces.IWidget,),... provided=zc.ajaxform.interfaces.IDisplayOptions)TrueTo-do (maybe)-------------More widgets!Interface invariantsActions:- conditions- validators- failure handlers.. [#application] See application.txt.. [#form_classes_are_descriptors] Form classes are alsodescriptors. They get called with the instance they're accessedthrough... [#actionids] The Javascript code that sets up action buttons usesaction name as the button's ID.Download********
zcash-service-status
Zcash Service Status LibraryWant to know about Zcash network and its services? Use this library!pip install zcash-service-status==0.1.2 from zcash_service_status import communities_and_forums_response_time communities_and_forums_response_time.communities_and_forums_response_time()
zcash-service-status-MANAN-MONGA
Zcash Service Status LibraryWant to know about Zcash network and its services? Use this library!
zca_snippets
zca-listzca-snippetszca-list$zca-listpyramid.interfacespyramid.interfaces:ITranslationDirectoriespyramid.interfaces:INewRequestpyramid.interfaces:IRootFactorypyramid.interfaces:IDefaultRootFactorypyramid.interfaces:IViewMapperFactorypyramid.interfaces:IBeforeRender## ..snippyramid.interfaces:IExceptionViewClassifierpyramid.interfaces:ILocaleNegotiatorpyramid.interfaces:IMultiDictpyramid.interfaces:IAuthenticationPolicyzca-snippets$zca-snippetspyramid.interfaces:IAuthenticationPolicyfromzope.interfaceimportimplementerfrompyramid.interfacesimportIAuthenticationPolicy## see: pyramid.interfaces:IAuthenticationPolicy@implementer(IAuthenticationPolicy)classAuthenticationPolicy(object):defremember(self,request,principal,**kw):passdefeffective_principals(self,request):passdefforget(self,request):passdefauthenticated_userid(self,request):passdefunauthenticated_userid(self,request):pass$zca-snippets-qpyramid.interfaces:IAuthorizationPolicy## see: pyramid.interfaces:IAuthorizationPolicy@implementer(IAuthorizationPolicy)classAuthorizationPolicy(object):defprincipals_allowed_by_permission(self,context,permission):passdefpermits(self,context,principals,permission):pass
zc.async
What is it?Thezc.asyncpackage providesan easy-to-use Python tool that schedules work persistently and reliably across multiple processes and machines.For instance…Web apps: maybe your web application lets users request the creation of a large PDF, or some other expensive task.Postponed work: maybe you have a job that needs to be done at a certain time, not right now.Parallel processing: maybe you have a long-running problem that can be made to complete faster by splitting it up into discrete parts, each performed in parallel, across multiple machines.Serial processing: maybe you want to decompose and serialize a job.High-level features include the following:easy to use;flexible configuration, changeable dynamically in production;reliable;supports high availability;good debugging tools;well-tested; andfriendly to testing.While developed as part of the Zope project, zc.async can be used stand-alone.How does it work?The system uses the Zope Object Database (ZODB), a transactional, pickle-based Python object database, for communication and coordination among participating processes.zc.async participants can each run in their own process, or share a process (run in threads) with other code.The Twisted framework supplies some code (failures and reactor implementations, primarily) and some concepts to the package.Where can I read more?Quickstarts and in-depth documentation are available in the package and in thenew and exciting on-line documentation.Changes1.5.4 (2011-03-03)Rearrange ftesting.setUp to avoid provoking a DemoStorage bug present in ZODB <= 3.9.3.Resolved the following testing issues: signal handlers weren’t cleaned up properly in some tests, Twisted was leaking file descriptors during ftesting tearDown (http://twistedmatrix.com/trac/ticket/3063), and the twisted.txt regression test was not repeatable due to Twisted’s recalcitrance when it comes to stopping and subsequently starting a reactor instance.Fix two undefined variables that could trigger exceptions in corner cases.1.5.3 (2009-11-15)Made zc.async.subscribers.ThreadedDispatcherInstaller keep track of signal handlers it installs in a module global “signal_handlers.”Made zc.async.ftesting.tearDown restore the signal handlers that were replaced by ThreadedDispatcherInstaller.Fix a bug in zc.async.ftesting.setUp and zc.async.testing.print_logs which would result in the default argument for log_file becoming “fixated” with an incorrect value across tests.Make the ftesting.txt test exercise the ‘zc.async’ logger in addition to ‘zc.async.event’.zc.async.utils.dt_to_long coerces return value to long (test pass on 64-bit Python).Tests pass on Python 2.6The callable of a zc.async.job.Job (or one of its subclasses) can be a method on the Job itself.1.5.2 (2009-07-22)Fix a bug where zc.async.testing._datetime.now did not accept the same keyword arguments as datetime.datetime, added tests.Fix a bug where zc.async.testing._datetime.astimezone did not accept the same keyword arguments as datetime.datetime, added tests.1.5.1 (2008-10-13)Add a performance optimization withisinstancebeforeprovidedBy.Add support for filters toAgentInstaller.Fix a bug which caused a condition to be always true inmonitor.Encoder.1.5.0 (2008-09-21)Documentation improvements. Converted documentation into Sphinx system.Made “other” commit errors for theRetryCommonForeverretry policy have an incremental backoff. By default, this starts at 0 seconds, and increments by a second to a maximum of 60 seconds.Work around a memory leak in zope.i18nmessageid (https://bugs.launchpad.net/zope3/+bug/257657). The change should be backward-compatible. It also will produce slightly smaller pickles for Jobs, but that was really not a particular goal.Added zc.async.partial.Partial for backward compatibility purposes.Fix support for Twisted installed reactor.Fix retry behavior for parallel and serial jobsTweaked the uuid.txt to mention zdaemon/supervisor rather than Zope 3.Fixed some bugs in egg creation.Changed quotas to not use a container that has conflict resolution, since these values should be a strict maximum.We only want to claim a job if we are activated. Make the agent check theactivatedanddeadattributes of the parent dispatcher before claiming.When activating, also clean out jobs from the dispatcher’s agents, just as with deactivating. This should protect from unusual race conditions in which the dispatcher got a job after being deactivated.Change dispatcher to ping before claiming jobs.when a ping reactivates a dispatcher, use new methodreactivaterather thanactivate. This fires a newDispatcherReactivatedevent.It’s still theoretically possible (for instance, with a badly-behaved long commit that causes a sibling to believe that the process is dead) that an async worker process would be working on a job that it shouldn’t be. For instance, the job has been taken away, and is another process’ responsibility now. Now, whenever a process is about to start any work (especially a retry), it should double-check that the job is registered as being performed by itself. If not, the process should abort the transaction, make an error log, and give up on the job. Write conflict errors on the job should protect us from the edge cases in this story.The dispatcher’sgetActiveJobsmethod now actually tells you information about what’s going on in the threads at this instant, rather than what’s going on in the database. The poll’sactive jobskeys continues to report what was truein the databaseas ofthe last poll. This change also affects theasync jobsmonitor command.The dispatcher methodgetJobInfo(and the monitor commandasync job) now returns the name of the queue for the job, the name of the agent for the job, and whether the job has been, or was reassigned.zc.async events inherit from ‘zc.component.interfaces.IObjectEvent’ instead of a zc.async specific IObjectEvent (thanks to Satchit Haridas).Added new monitoring and introspection tools: theasyncdbzc.monitor command (and, for Python, the code in monitordb.py). This code provides easy spellings to examine the database’s view of what is happening in zc.async. Because it is the database, it also has a much longer historical view than theasynctools. The best way to learn about these tools is to read the extensive documentation provided within zc.monitor by usingasyncdb helpandasyncdb help <TOOL NAME>.Added new preferred way of filtering agent choices: the newfilterattribute. Using filters, rather than “choosers,” allows severalasyncdbtools to filter pending jobs based on what an agent is willing to do. It also is a smaller contract, and so a filter requires less code than a chooser in the common case. On the other hand, using a filter alone doesn’t allow the agent to try toprefercertain tasks.Deprecated agent.chooseFirst. It is no longer necesary, since an agent without a chooser and with a filter of None has the same behavior. It is retained for legacy databases.Moved deprecated legacy code to newlegacymodule.Tried to be significantly reduce the chance of spurious timing errors in the tests, at the expense of causing the tests to take longer to run.monitoring support depends on the new zc.monitor package, which is not Zope specific. This means non-Zope 3 apps can take advantage of the monitoring support. To use, use the [monitor] target; this only adds simplejson, zc.ngi, and zc.monitor to the basic dependencies.Make ftesting try to join worker threads, in addition to polling thread, to try to eliminate intermittent test-runner warnings in ftests that a thread is left behind. If the threads do not end, inform the user what jobs are not letting go. (thanks to Patrick Strawderman)1.4.2 (2009-07-17)Fix a bug where zc.async.testing._datetime.now did not accept the same keyword arguments as datetime.datetime, added tests.1.4.1 (2008-07-30)The newserialandparallelhelpers did not allow thepostprocessargument to be a partial closure, and were being naughty. Fixed.Added tests and demos for advanced features ofserialandparallel.More tweaks to the new Quickstart S5 document.1.4.0 (2008-07-30)Mentioned in ftesting.txt that Zope 3 users should uses zope.app.testing 3.4.2 or newer. Also added a summary section at the beginning of that file.Added logging of critical messages to __stdout__ forftesting.setUp. This can help discovering problems in callback transactions. This uses a new helper function ,print_logs, in zc.async.testing, which is primarily intended to be used for quick and dirty debuggingChanged testing.wait_for_result and testing.wait_for_annotation to ignore ReadConflictErrors, so they can be used more reliably in tests that use MappingStorage, and other storages without MVCC.Support <type ‘builtin_function_or_method’> for adaptation to Job.Add warning about long commits to tips and tricks.After complaining about a polling dispatcher that is deactivated not really being dead in the logs, reactivate.No longer use intermediate job to implement the success/failure addCallbacks behavior. Introduce an ICallbackProxy that can be used for this kind of behavior instead. This change was driven by two desires.Don’t log the intermediate result. It makes logs harder to read with unnecessary duplications of pertinent data hidden within unimportant differences in the log entries.Don’t unnecessarily remember errors in success/failure callbacks. This can cause unnecessary failures in unusual situations.The callback proxy accepts callbacks, which are added to the selected job (success or failure) when the job is selected.This change introduces some hopefully trivial incompatibilities, which basically come down to the callback being a proxy, not a real job. Use the convenience propertiessuccessandfailureon the proxy to look at the respective jobs. After the proxy is evaluated, thejobattribute will hold the job that was actually run.statusandresultare conveniences to get the status and result of the selected job.Addparallelandserialconvenience functions to zc.async.job to make it trivial to schedule and process decomposed jobs.Addstartconvenience function to zc.async.configure to make it trivial to start up a common-case configuration of a zc.async dispatcher.No longer use protected attributes of callbacks inresumeCallbacks.The “local” code is now moved out from the dispatcher module to threadlocal. This is to recognize that the local code is now modified outside of the dispatcher module, as described in the next bullet.Jobs, when called, are responsible for setting the “local” job value. This means that zc.async.local.getJob() always returns the currently running job, whether it is a top-level job (as before) or a callback (now).Start on S5 QuickStart presentation (see QUICKSTART_1_VIRTUALENV.txt in package).1.3 (2008-07-04)added “Tips and Tricks” and incorporated into the PyPI page.addedsetUpandtearDownhooks to Job class so that code can run before and after the main job’s code. The output ofsetUpis passed as an argument totearDownso that one can pass state to the other, if needed.setUpis run immediately before the actual job call.tearDownruns after the transaction is committed, or after it was aborted if there was a failure. A retry requested by a retry policy causes the methods to be run again. A failure insetUpis considered to be a failure in the job, as far as the retryPolicy is concerned (i.e., the job calls the retry policy’sjobErrormethod). IfsetUpfails, the job is not called, bittearDownis.tearDownwill fail with a critical log message, but then processing will continue.using the newsetUpandtearDownhooks, added a Zope 3-specific Job subclass (see zc.async.z3.Job) that remembers the zope.app.component site and interaction participants when instantiated. These can be mutated. Then, when the job is run, thesetUpsets up the site and a security interaction with the old participants, and then thetearDowntears it all down after the transaction has committed.changed retry policy logs to “WARNING” level, from “INFO” level.changed many dispatcher errors to “CRITICAL” level from “ERROR” level.added “CRITICAL” level logs for “other” commit retries on the RetryCommonForever retry policy.addedremovemethod on queue.added helpers for setting up and tearing down Zope 3 functional tests (ftesting.py), and a discussion of how to write Zope 3 functional tests with layers (zope.app.testing.functional) in ftesting.txt.remove obsolete retry approach for success/failure callbacks (completeStartedJobArguments): it is now handled by retry policies.remove odd full-path self-references within the utils module.renamedzc.async.utils.try_transaction_five_timestozc.async.utils.try_five_times.doc improvements and fixes (thanks to Zvezdan Petkovic and Gintautas Miliauskas).thez3“extra” distutils target now explicitly depends on zope.security, zope.app.security, and zope.app.component. This almost certainly does not increase the practical dependencies of thez3extras, but it does reflect new direct dependencies of the z3-specific modules in the package.1.2 (2008-06-20)made the log for finding an activated agent report the pertinent queue’s oid as an unpacked integer, rather than the packed string blob. UseZODB.utils.p64to convert back to an oid that the ZODB will recognize.Bugfix: in failing a job, the job thought it was in its old agent, and thefailcall failed. This is now tested by the first example in new doctestcatastrophes.txt.jobs no longer default to abegin_byvalue of one hour after thebegin_after. The default now is no limit.Made dispatcher much more robust to transaction errors and ZEO ClientDisconnected errors.Jobs now use an IRetryPolicy to decide what to do on failure within a job, within the commit of the result, and if the job is interrupted. This allows support of transactional jobs, transactional jobs that critically must be run to completion, and non-transactional jobs such as communicating with an external service.The default retry policy supports retries for ClientDisconnected errors, transaction errors, and interruptions.job.txthas been expanded significantly to show error handling and the use of retry policies. New filecatastrophes.txtshows handling of other catastrophes, such as interruptions to polling.job errors now go in the main zc.async.event log rather than in the zc.async.trace log. Successes continue to go in the trace log.callback failures go to the main log as a CRITICAL error, by default.handleInterruptis the new protocol on jobs to inform them that they were active in a dispatcher that is now dead. They either fail or reschedule, depending on the associated IRetryPolicy for the job. If they reschedule, this should either be a datetime or timedelta. The job calls the agent’sreschedulemethod. If the timedelta is empty or negative, or the datetime is earlier than now, the job is put back in the queue with a newputBackmethod on the queue. This is intended to be the opposite ofclaim. Jobs put in the queue withputBackwill be pulled out before any others.convert to using zope.minmax rather than locally definedAtom.Fix (and simplify) last_ping code so as to reduce unnecessarily writing the state of the parent DispatcherAgents collection to the database whenever the atom changed.Depends on new release of zc.twist (1.3)Switched dispatcher’s in-memory storage of job and poll information to be per job or per poll, respectively, rather than per time period, so as to try and make memory usage more predictable (for instance, whether a dispatcher is whipping through lots of jobs quickly, or doing work more slowly).1.1.1 (2008-05-14)more README tweaks.converted all reports from the dispatcher, including the monitor output, to use “unpacked” integer oids. This addresses a problem that simplejson was having in trying to interpret the packed string blobs as unicode, and then making zc.ngi fall over. To get the object, then, you’ll need to useZODB.utils.p64, like this:connection.get(ZODB.utils.p64(INTEGER_OID)), whereINTEGER_OIDindicates the integer oid of the object you want to examine.added several more tests for the monitor code.made theasync jobsmonitor command be “up to the minute”. Before, it included all of the new and active jobs from the previous poll; now, it also filters out those that have since completed.Theasync jobcommand was broken, as revealed by a new monitor test. Fixed, which also means we need a new version of zope.bforest (1.2) for a new feature there.1.1 (2008-04-24)Fired events when the IQueues and IQueue objects are installed by the QueueInstaller (thanks to Fred Drake).Dispatchers make agent threads keep their connections, so each connection’s object cache use is optimized if the agent regularly requests jobs with the same objects.README improved (thanks to Benji York and Sebastian Ware).Callbacks are logged at start in the trace log.All job results (including callbacks) are logged, including verbose tracebacks if the callback generated a failure.Had the ThreadedDispatcherInstaller subscriber stash the thread on the dispatcher, so you can shut down tests like this:>>> import zc.async.dispatcher >>> dispatcher = zc.async.dispatcher.get() >>> dispatcher.reactor.callFromThread(dispatcher.reactor.stop) >>> dispatcher.thread.join(3)AddedgetQueueto zc.async.local as a convenience (it does what you could already do:zc.async.local.getJob().queue).Clarified thatIQueue.pullis the approved way of removing scheduled jobs from a queue in interfaces and README.reports in the logs of a job’s success or failure come before callbacks are started.Added a section showing how the basic_dispatcher_policy.zcml worked, which then pushed the former README_3 examples into README_3b.Put ZPL everywhere I was supposed to.Moved a number of helpful testing functions out of footnotes and into zc.async.testing, both so that zc.async tests don’t have to redefine them and client packages can reuse them.1.0 (2008-04-09)Initial release.
zcatalyst-cliq
ZCatalyst Cliq SDKThe official python sdk for integrating Zoho Catalyst with Zoho Cliq.ZCatalyst Cliq SDK helps you to work with Python for handling Zoho Cliq extensions using Zoho Catalyst.PrerequisitesTo start working with this SDK you need to sign up withcatalystandcliqThen you need to install suitable version ofPythonandpipInstallingThe ZCatalyst Cliq SDK is a pip package and can be found as zcatalyst-cliq on PyPI:python-mpipinstallzcatalyst-cliqUsing zcatalyst-cliqAfter installing zcatalyst-cliq, you can initialize it in your catalyst's cliq integration functions as:importzcatalyst_cliq# your cliq handler files's mapping should be given hereconfig={"ZohoCliq":{"handlers":{"bot_handler":"handlers/bot_handler.py","function_handler":"handlers/function_handler.py","installation_validator":"handlers/installation_validator.py","command_handler":"handlers/command_handler.py","widget_handler":"handlers/widget_handler.py","messageaction_handler":"handlers/message_action_handler.py","installation_handler":"handlers/installation_handler.py"}},}defhandler(request,response):handler_resp=zcatalyst_cliq.execute(request,config)response.set_content_type('application/json')response.send(handler_resp)DocumentationFor documentation and further queries kindly [email protected]
zcatalyst-runtime-39
Catalyst by Zoho - Python 3.9 runtimeThis project is for internal use withzcatalyst-clionly.ContactFor any queries, kindly [email protected]
zcatalyst-sdk
ZCatalyst SDKThe official python sdk of Catalyst by ZohoZCatalyst Python SDK bundles all the features of Zoho Catalyst and provides access to various Catalyst services and their respective components, which helps you build robust Catalyst applications and microservices.PrerequisitesTo start working with this SDK you need a catalyst accountSign UpThen you need to install suitable version ofPythonandpipInstallingThe ZCatalyst Python SDK is a pip package and can be found as zcatalyst on PyPI:python-mpipinstallzcatalyst-sdkUsing zcatalystAfter installing zcatalyst, you can initialize it in your catalyst functions as:importzcatalyst_sdkcatalyst_app=zcatalyst_sdk.initialize()DocumentationFor documentation and further clarifications kindly [email protected]
zc.authorizedotnet
Authorize.Net provides credit card (henceforth “CC”) processing via a protocol on top of HTTPS. Authorize.Net’s customers are “merchants”. The merchant is the entity accepting a CC as payment. This package provides a simple interface to Authorize.Net’s “Advanced Integration Method” (AIM).Several terms used in this document:authorize: check validity of CC information and for sufficient balancecapture: the approval of transfer of funds from the CC holder to the merchantsettlement: the actual transfer of funds from the CC holder to the merchantcredit: issuing a refund from the merchant to the card holdervoiding: canceling a previous transactionSettlement is performed in daily batches. The cut-off time for which is specified in the merchant’s settings available on the Authorize.Net merchant interface.There are many other settings which can be configured via the merchant interface, but this module attempts to work independently of most of them. Where specific settings are required they will be marked with the phrase “required merchant interface setting”.Transaction KeysEach AIM transaction must be accompanied by a merchant login and a “transaction key”. This key is obtained from the merchant interface. After importing the CcProcessor class you must pass it your login and transaction key:>>> from zc.authorizedotnet.processing import CcProcessor >>> from zc.creditcard import (AMEX, DISCOVER, MASTERCARD, ... VISA, UNKNOWN_CARD_TYPE) >>> cc = CcProcessor(server=SERVER_NAME, login=LOGIN, key=KEY)AuthorizingTo authorize a charge use theauthorizemethod. It returns aTransactionobject.>>> result = cc.authorize(amount='2.00', card_num='4007000000027', ... exp_date='0530')The result object contains details about the transaction.>>> result.response 'approved' >>> result.response_reason 'This transaction has been approved.' >>> result.approval_code '123456' >>> auth_trans_id = result.trans_id >>> result.trans_id '123456789'When the card_num is sent in, the result also contains the type of credit card:>>> result.card_type == VISA TrueIf no credit card number is provided, card_type is None:>>> result2 = cc.authorize(amount='2.00', exp_date='0530') >>> result2.card_type == None True>>> result2 = cc.authorize(amount='2.00', card_num='', exp_date='0530') >>> result2.card_type == None TrueCapturing Authorized TransactionsNow if we want to capture the transaction that was previously authorized, we can do so.>>> result = cc.captureAuthorized(trans_id=result.trans_id) >>> result.response 'approved'Credit (refund) transactionsA previosly credited transaction can be refunded. The amount of the refund cannot exceed the amount captured. At least the last four digits of the credit card number must be provided, along with the transaction id.Credit will only work when the transaction has been settled by the banks, that is if we try refunding immediately, it will fail:>>> result = cc.credit(trans_id=auth_trans_id, ... card_num='4007000000027', ... exp_date='0530', ... amount='1.00', ... ) >>> result.response_reason 'The referenced transaction does not meet the criteria for issuing a credit.' >>> result.response 'error'Voiding TransactionsIf we need to stop a transaction that has not yet been completed (like the crediting of the captured transaction above) we can do so with thevoidmethod.>>> result = cc.void(trans_id=auth_trans_id) >>> result.response 'approved'Transaction ErrorsIf something about the transaction is erroneous, the transaction results indicate so.>>> result = cc.authorize(amount='2.50', card_num='4007000000027', ... exp_date='0599')The result object reflecs the error.>>> result.response 'error' >>> result.response_reason 'The credit card has expired.'The valid values for theresponseattribute are ‘approved’, ‘declined’, and ‘error’.Address Verification System (AVS)AVS is used to assert that the billing information provided for a transaction must match (to some degree or another) the cardholder’s actual billing data. The gateway can be configured to disallow transactions that don’t meet certain AVS criteria.>>> result = cc.authorize(amount='27.00', card_num='4222222222222', ... exp_date='0530', address='000 Bad Street', ... zip='90210') >>> result.response 'declined' >>> result.response_reason 'The transaction resulted in an AVS mismatch...'Duplicate WindowThe gateway provides a way to detect and reject duplicate transactions within a certain time window. Any transaction with the same CC information (card number and expiration date) and amount duplicated within the window will be rejected.The first transaction will work.>>> result = cc.authorize(amount='3.00', card_num='4007000000027', ... exp_date='0530', invoice_num='123') >>> result.response 'approved'A duplicate transaction will fail with an appropriate message.>>> result2 = cc.authorize(amount='3.00', card_num='4007000000027', ... exp_date='0530', invoice_num='123') >>> result2.response 'error' >>> result2.response_reason 'A duplicate transaction has been submitted.'Similar transactions can be unaliased by including a unique invoice_num field:>>> result3 = cc.authorize(amount='3.00', card_num='4007000000027', ... exp_date='0530', invoice_num='124') >>> result3.response 'approved'The default window size is 120 seconds, but any other value (including 0) can be provided by passingduplicate_windowto the transaction method.>>> cc.captureAuthorized(trans_id=result.trans_id).response 'approved'>>> cc.captureAuthorized(trans_id=result.trans_id).response_reason 'This transaction has already been captured.'>>> cc.captureAuthorized(trans_id=result.trans_id, duplicate_window=0 ... ).response 'approved'But voiding doesn’t report errors if the same transaction is voided inside the duplicate window.>>> cc.void(trans_id=result.trans_id).response 'approved'>>> cc.void(trans_id=result.trans_id).response 'approved'Line itemsAn itemized listing of the order can be included in the authorization data as a sequcence of sequences.>>> result = cc.authorize(amount='2.98', card_num='4007000000027', ... exp_date='0530', ... line_items=[ ... # id name description qty unit price tax ... ('1', 'G-1000', 'Gadget', '1', '1.99', 'Y'), ... ('2', 'A-150', 'Accessory','1', '0.99', 'Y'), ... ]) >>> result.response 'approved'the result will have a card_type attribute.>>> result.card_type == VISA TrueThe MD5 Hash Security FeatureAuthorize.Net provides for validating transaction responses via an MD5 hash. The required merchant interface setting to use this feature is under “Settings and Profile” and then “MD5 Hash”. Enter a “salt” value in the fields provided and submit the form. You may then provide thesaltparameter to the CcProcessor constructor to enable response validation.WARNING: The format of the “amount” field is very important for this feature to work correctly. The field must be formatted in the “canonical” way for the currency in use. For the US dollar that means no leading zeros and two (and only two) decimal places. If the amount is not formatted properly in the request, the hashes will not match and the transaction will raise an exception.If you want to enable hash checking, provide asaltvalue to theCcProcessorconstructor. If an incorrect salt value is used, or the hash given in the transaction doesn’t match the true hash value an exception is raised.>>> cc = CcProcessor(server=SERVER_NAME, login=LOGIN, key=KEY, ... salt='wrong') >>> result = cc.authorize(amount='10.00', card_num='4007000000027', ... exp_date='0530') Traceback (most recent call last): ... ValueError: MD5 hash is not valid (trans_id = ...)Error CheckingIf you don’t pass a string for the amount when doing an authorization, an exception will be raised. This is to avoid charging the wrong amount due to floating point representation issues.>>> cc.authorize(amount=5.00, number='4007000000027', expiration='0530') Traceback (most recent call last): ... ValueError: amount must be a string
zcb-dbutils
dbutils使用方法fromzcb_dbutilsimportDBConnectionimportloggingimportpandasaspdlogging.basicConfig(level=logging.DEBUG,format='%(asctime)s%(filename)s[line:%(lineno)d]%(levelname)s%(message)s',datefmt='%d%b %Y,%a%H:%M:%S',#日 月 年 ,星期 时 分 秒)dbconn=DBConnection(host='localhost',port=3306,user='root',password='',database='basic')ret=dbconn.fetch_one("select * from tb_user1 where id = 1000")print(ret)ret=dbconn.showtable('basic','tb_user')print(pd.DataFrame.from_dict(ret))ret=dbconn.show_table_index('basic','tb_user')print(pd.DataFrame.from_dict(ret))rows=dbconn.fetch_list('select user_id,id from tb_user')print(rows)id=dbconn.insert('insert into tb_role (role_name,role_type,remark_info,created,updated) value (%s,1,%s,0,0)',('xxx','xxxx'))dbconn.commit()print(id)
zcbe
zcbeIntroductionThe Z cross build environment is a tool for managing cross-compile environments. It comes with concurrent building, dependency tracking and other useful features.UsageTutorialTODOCLI Usageusage: zcbe [-h] [-w] [-W WARNING] [-B] [-C CHDIR] [-o FILE] [-e FILE] [-f FILE] [-j JOBS] [-a] [-s] [-n] [-u] [-H ABOUT] [PROJ ...] The Z Cross Build Environment positional arguments: PROJ List of projects to build optional arguments: -h, --help show this help message and exit -w Suppress all warnings -W WARNING Modify warning behavior -B, --rebuild, --always-make, --always-build Force build requested projects and dependencies -C CHDIR, --chdir CHDIR, --directory CHDIR Change directory to -o FILE, --stdout-to FILE Redirect stdout to FILE ('{n}' expands to the name of the project) -e FILE, --stderr-to FILE Redirect stderr to FILE ('{n}' expands to the name of the project) -f FILE, --file FILE, --build-toml FILE Read FILE as build.toml -j JOBS, --jobs JOBS Number of maximum concurrent jobs -a, --all Build all projects in mapping.toml -s, --silent Silence make standard output(short for -o /dev/null) -n, --dry-run, --just-print, --recon Don't actually run any commands -u, --show-unbuilt List unbuilt projects and exit -H ABOUT, --about ABOUT Help on a topic("topics" for a list of topics)
zc.beforestorage
Before StorageZODB storages typically store multiple object revisions to support features such as multi-version concurrency control and undo. In the case of the mod popular storage implementation, old revisions aren’t discarded until a pack. This feature has often been exploited to perform time travel, allowing one to look at a database as it existed in at some point in time. In the past, this has been possible with file storage by specifying a time at which to open the file storage. This works fairly well, but is very slow for large databases because existing index files can’t easily be used. Time travel is also supported for individual objects through the ZODB history mechanism.The introduction of multi-version concurrency control provided new opertunities for time travel. Using the storage loadBefore method, one can load transaction records written before a given time. ZODB 3.9 will provide an option to the database open method for opening connections as of a point in time.Demo storage can be quite useful for testing, and especially staging applications. In a common configuration, they allow for storing changes to a base database without changing the underlying database. Zope functional testing frameworks leverage demo storages to easily roll-back database state after a test to a non-empty state before a test. A significant limitation of demo storages is that they can’t be used with base storages that change. This means that they generaly can’t be used with ZEO. It isn’t enough to have a read-only connections, if the underlying database is still being changed by other clients.The “before” storage provides another way to leverage the loadBefore method to support time travel and a means to provide an unchanging view into a ZEO server. A before storage is a database adapter that provides a read-only view of an underlying storage as of a particular point in time.ContentsBefore StorageUsing ZConfig to configure Before storages“before” option“before-from-file” optionDemonstration (doctest)Blob SupportCHANGES1.0 (2023-02-09)0.6 (2020-05-14)0.5.1 (2013-10-25)0.5.0 (2013-10-25)0.4.0 (2010-12-09)0.3.2 (2008-12-05)0.3.1 (2008-12-01)0.3.0 (2008-12-01)0.2.0 (2008-03-05)0.1.1 (2008-02-07)0.1 (2008-01-??)Using ZConfig to configure Before storages“before” optionTo use before storages from ZConfig configuration files, you need to import zc.beforestorage and then use a before storage section.>>> import ZODB.config >>> storage = ZODB.config.storageFromString(""" ... ... %import zc.beforestorage ... ... <before> ... before 2008-01-21 ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """)>>> storage <Before: my.fs before 2008-01-21 00:00:00.000000>>>> storage.close()If we leave off the before option, we’ll use the current time:>>> storage = ZODB.config.storageFromString(""" ... ... %import zc.beforestorage ... ... <before> ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """)>>> storage <Before: my.fs before 2008-01-21 18:22:49.000000>>>> storage.close()We can also give the option ‘now’ and get the current time.>>> import ZODB.config >>> storage = ZODB.config.storageFromString(""" ... ... %import zc.beforestorage ... ... <before> ... before now ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """)>>> storage <Before: my.fs before 2008-01-21 18:22:53.000000>>>> storage.close()We can give the option ‘startup’ and get the time at startup.>>> import ZODB.config >>> storage = ZODB.config.storageFromString(""" ... ... %import zc.beforestorage ... ... <before> ... before startup ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """)>>> storage <Before: my.fs before 2008-01-21 18:22:43.000000> >>> import zc.beforestorage >>> import ZODB.TimeStamp >>> print( ... str(zc.beforestorage.startup_time_stamp)) 2008-01-21 18:22:43.000000 >>> storage.close()“before-from-file” optionThe “before-from-file” option can be used to preserve the changes file between restarts. It’s value is the absolute path to a file. If the file exists, the “before” time will be read from that file. If the file does not exist, it will be created and the current UTC time will be written to itWhen used with a Changes file that does NOT have the “create=true” option set, the database will be preserved between restarts.>>> import os.path >>> import tempfile>>> tempdir = tempfile.mkdtemp() >>> before_file = os.path.join(tempdir, 'before-file')Currently the file does not exist. So it’ll be created and written with the current time. In order to make this repeatable, we “monkeypatch” the “get_now” function in the module to return a fixed value:>>> import datetime >>> import zc.beforestorage>>> def fake_get_utcnow(): ... return datetime.datetime(2008, 1, 1, 15, 0) >>> orig_get_utcnow = zc.beforestorage.get_utcnow >>> zc.beforestorage.get_utcnow = fake_get_utcnow>>> os.path.exists(before_file) False>>> storage = ZODB.config.storageFromString(""" ... ... %%import zc.beforestorage ... ... <before> ... before-from-file %s ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """ % before_file)>>> storage <Before: my.fs before 2008-01-01 15:00:00.000000>>>> storage.close()The file will now have been created:>>> os.path.exists(before_file) True>>> f = open(before_file) >>> f.read() == fake_get_utcnow().replace(microsecond=0).isoformat() TrueIf we now write a new value to the file, the storage will be started with that time.>>> f = open(before_file, 'w') >>> _ = f.write('1990-01-01T11:11') >>> f.close()>>> storage = ZODB.config.storageFromString(""" ... ... %%import zc.beforestorage ... ... <before> ... before-from-file %s ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """ % before_file)>>> storage <Before: my.fs before 1990-01-01 11:11:00.000000>>>> storage.close()If we restart the storage, the value from the file will be used.>>> storage = ZODB.config.storageFromString(""" ... ... %%import zc.beforestorage ... ... <before> ... before-from-file %s ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """ % before_file)>>> storage <Before: my.fs before 1990-01-01 11:11:00.000000>>>> storage.close()This will continue to happen until we remove the file. The “before_from_file” path is stored on the storage itself, so applications that use it have access to it.>>> os.remove(storage.before_from_file)>>> os.path.exists(before_file) FalseIf we restart the storage again, a new file will be created.>>> storage = ZODB.config.storageFromString(""" ... ... %%import zc.beforestorage ... ... <before> ... before-from-file %s ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """ % before_file)>>> storage <Before: my.fs before 2008-01-01 15:00:00.000000>>>> storage.close()Note that unlike the “before” option, the “before-from-file” file cannot contain special values such as “now” or “startup”.>>> f = open(before_file, 'w') >>> _ = f.write('now') >>> f.close()>>> storage = ZODB.config.storageFromString(""" ... ... %%import zc.beforestorage ... ... <before> ... before-from-file %s ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """ % before_file) Traceback (most recent call last): ... ValueError: 8-byte array expectedNote that only one of “before” or “before-from-file” options can be specified, not both:>>> storage = ZODB.config.storageFromString(""" ... ... %%import zc.beforestorage ... ... <before> ... before 2008-01-01 ... before-from-file %s ... <filestorage> ... path my.fs ... </filestorage> ... </before> ... """ % before_file) Traceback (most recent call last): ... ValueError: Only one of "before" or "before-from-file" options can be specified, not bothCleanup…>>> import shutil >>> shutil.rmtree(tempdir)>>> zc.beforestorage.get_utcnow = orig_get_utcnowDemonstration (doctest)Note that most people will configure the storage through ZConfig. If you are one of those people, you may want to stop here. :) The examples below show you how to use the storage from Python, but they also exercise lots of details you might not be interested in.To see how this works at the Python level, we’ll create a file storage, and use a before storage to provide views on it.>>> import ZODB.FileStorage >>> fs = ZODB.FileStorage.FileStorage('Data.fs') >>> from ZODB.DB import DB >>> db = DB(fs) >>> conn = db.open() >>> root = conn.root() >>> import persistent.mappingWe’ll record transaction identifiers, which we’ll use to when opening the before storage.>>> import transaction >>> transactions = [root._p_serial] >>> for i in range(1, 11): ... root[i] = persistent.mapping.PersistentMapping() ... transaction.get().note("trans %s" % i) ... transaction.commit() ... transactions.append(root._p_serial)We create a before storage by calling the Before constructer with an existing storage and a timestamp:>>> import zc.beforestorage >>> b5 = zc.beforestorage.Before(fs, transactions[5]) >>> db5 = DB(b5) >>> conn5 = db5.open() >>> root5 = conn5.root() >>> len(root5) 4here we see the database as it was before the 5th transaction was committed. If we try to access a later object, we’ll get a ReadConflictError:>>> conn5.get(root[5]._p_oid) Traceback (most recent call last): ... ZODB.POSException.ReadConflictError: b'\x00\x00\x00\x00\x00\x00\x00\x05'Similarly, while we can access earlier object revisions, we can’t access revisions at the before time or later:>>> _ = b5.loadSerial(root._p_oid, transactions[2])>>> b5.loadSerial(root._p_oid, transactions[5]) Traceback (most recent call last): ... POSKeyError: 0x00Let’s run through the storage methods:>>> (b5.getName() == ... 'Data.fs before %s' % ZODB.TimeStamp.TimeStamp(transactions[5])) True>>> b5.getSize() == fs.getSize() True>>> for hd in b5.history(root._p_oid, size=3): ... print(hd['description'].decode('utf-8')) trans 4 trans 3 trans 2>>> b5.isReadOnly() True>>> transactions[4] <= b5.lastTransaction() < transactions[5] True>>> len(b5) == len(fs) True>>> p, s1, s2 = b5.loadBefore(root._p_oid, transactions[5]) >>> p == fs.loadSerial(root._p_oid, transactions[4]) True >>> s1 == transactions[4] True >>> s2 is None True>>> p, s1, s2 = b5.loadBefore(root._p_oid, transactions[4]) >>> p == fs.loadSerial(root._p_oid, transactions[3]) True >>> s1 == transactions[3] True >>> s2 == transactions[4] True>>> b5.getTid(root._p_oid) == transactions[4] True>>> b5.tpc_transaction()>>> try: ... b5.new_oid() ... except Exception as e: # Workaround http://bugs.python.org/issue19138 ... print(e.__class__.__name__) ReadOnlyError>>> from ZODB.TimeStamp import TimeStamp >>> try: ... b5.pack(TimeStamp(transactions[3]).timeTime(), lambda p: []) ... except Exception as e: ... print(e.__class__.__name__) ReadOnlyError>>> b5.registerDB(db5)>>> b5.sortKey() == fs.sortKey() True>>> try: ... b5.tpc_begin(transaction.get()) ... except Exception as e: ... print(e.__class__.__name__) ReadOnlyError>>> b5.store(root._p_oid, transactions[4], b5.load(root._p_oid)[0], '', ... transaction.get()) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... StorageTransactionError: ...>>> b5.tpc_vote(transaction.get()) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ZODB.POSException.StorageTransactionError: ...>>> b5.tpc_finish(transaction) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ZODB.POSException.StorageTransactionError: ...>>> b5.tpc_transaction() >>> b5.tpc_abort(transaction)Before storages don’t support undo:>>> b5.supportsUndo Traceback (most recent call last): ... AttributeError: 'Before' object has no attribute 'supportsUndo'(Don’t even ask about versions. :)Closing a before storage closes the underlying storage:>>> b5.close() >>> fs.load(root._p_oid, '') # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...If we ommit a timestamp when creating a before storage, the current time will be used:>>> fs = ZODB.FileStorage.FileStorage('Data.fs') >>> from ZODB.DB import DB >>> db = DB(fs) >>> conn = db.open() >>> root = conn.root()>>> bnow = zc.beforestorage.Before(fs) >>> dbnow = DB(bnow) >>> connnow = dbnow.open() >>> rootnow = connnow.root()>>> for i in range(1, 11): ... root[i] = persistent.mapping.PersistentMapping() ... transaction.get().note("trans %s" % i) ... transaction.commit() ... transactions.append(root._p_serial)>>> len(rootnow) 10>>> dbnow.close()The timestamp may be passed directory, or as an ISO time. For example:>>> fs = ZODB.FileStorage.FileStorage('Data.fs') >>> iso = 'T'.join(str(ZODB.TimeStamp.TimeStamp(transactions[5])).split() ... )[:19] >>> b5 = zc.beforestorage.Before(fs, iso) >>> db5 = DB(b5) >>> conn5 = db5.open() >>> root5 = conn5.root() >>> len(root5) 4>>> b5.close()Blob SupportBefore storage supports blobs if the storage it wraps supports blobs, and, in fact, it simply exposes the underlying storages loadBlob and temporaryDirectory methods.>>> fs = ZODB.FileStorage.FileStorage('Data.fs') >>> import ZODB.blob >>> bs = ZODB.blob.BlobStorage('blobs', fs) >>> db = ZODB.DB(bs) >>> conn = db.open() >>> conn.root()['blob'] = ZODB.blob.Blob() >>> _ = conn.root()['blob'].open('w').write(b'data1') >>> transaction.commit()>>> bnow = zc.beforestorage.Before(bs) >>> dbnow = DB(bnow) >>> connnow = dbnow.open() >>> rootnow = connnow.root()>>> _ = conn.root()['blob'].open('w').write(b'data2') >>> transaction.commit()>>> print(rootnow['blob'].open().read().decode('utf-8')) data1>>> bnow.temporaryDirectory() == bs.temporaryDirectory() True>>> import ZODB.interfaces, zope.interface.verify >>> zope.interface.verify.verifyObject( ... ZODB.interfaces.IBlobStorage, bnow) True>>> bnow.close()CHANGES1.0 (2023-02-09)Add support for Python 3.9, 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.0.6 (2020-05-14)Add support for Python 3.5 through 3.8.Drop support for Python 3.3 and 3.4.Fix a long-standing bug in loadBefore´. The bug was revealed by testing against ZODB 5, for which loadBefore plays a bigger role.0.5.1 (2013-10-25)Fix broken release0.5.0 (2013-10-25)Added ZODB4 and Python 3 support.0.4.0 (2010-12-09)Added a “before-from-file” option that can be used if the application wants to preserve beforestorage state between application restarts.0.3.2 (2008-12-05)Updated to work with both ZODB 3.8 and 3.9.0.3.1 (2008-12-01)Renamed lastTid to getTid to conform to the ZEO.interfaces.IServeable interface.0.3.0 (2008-12-01)Added Blob support.0.2.0 (2008-03-05)Added support for “now” and “startup” values to the before option when using ZConfig. The “now” value indicates that the before storage should provide a view of the base storage as of the time the storage is created. The “startup” value indicates that the before storage should provide a view of the base stoage as of process startup time. The later is especially useful when setting up more than once before storage in a single application, as it allows you to arrange that all of the storages provide consistent views without having to specify a time.0.1.1 (2008-02-07)Fixed a packaging bug that caused some files to be omitted.0.1 (2008-01-??)Initial release.
zcb-gz
No description available on PyPI.
zcbin
Failed to fetch description. HTTP Status Code: 404
zc.blist
ContentsOverviewDifferences from Python’s ListSlices are IteratorsAdditional Iteration MethodsCheapcopyMechanismPerformance CharacteristicsThe GoodThe So-SoThe BadChanges1.0b2 (2009-03-12)1.0b1 (2008-10-06)OverviewThe sequence in this package has a list-like API, but stores its values in individual buckets. This means that, for small changes in large sequences, the sequence could be a big win. For instance, an ordered BTree-based container might want to store order in a sequence, so that moves only cause a bucket or two–around 50 strings or less–to be rewritten in the database, rather than the entire contents (which might be thousands of strings, for instance).If the sequence is most often completely rearranged, the complexity of the code in this package is not desirable. It only makes sense if changes most frequently are fairly small.One downside is that reading and writing is more work than with a normal list. If this were to actually gain traction, perhaps writing some or all of it in C would be helpful. However, it still seems pretty snappy.Another downside is the corollary of the bucket advantage listed initially: with more persistent objects, iterating over it will fill a lot of ZODB’s object cache (which is based on the number of objects cached, rather than the size). Consider specifying a big object cache if you are using these to store a lot of data and are frequently iterating or changing.These sequences return slices as iterators, and add some helpful iteration methods. It adds acopymethod that provides a cheap copy of the blist that shares all buckets and indexes until a write happens, at which point it copies and mutates the affected indexes and buckets.We’ll take a glance at how these differences work, and then describe the implementation’s basic mechanism, and close with a brief discussion of performance characteristics in the abstract.Differences from Python’s ListSlices are IteratorsThis doesn’t need much discussion. Getting slices of all sorts returns iterators.>>> from zc.blist import BList >>> l = BList(range(1000)) >>> l[345:351] # doctest: +ELLIPSIS <generator object at ...> >>> list(l[345:351]) [345, 346, 347, 348, 349, 350]>>> l[351:345:-1] # doctest: +ELLIPSIS <generator object at ...> >>> list(l[351:345:-1]) [351, 350, 349, 348, 347, 346]>>> l[345:351:2] # doctest: +ELLIPSIS <generator object at ...> >>> list(l[345:351:2]) [345, 347, 349]Additional Iteration MethodsiterReversedlets you iterate over the list in reverse order, efficiently, with a given start point. It is used for slices that proceed with a step of -1.>>> i = l.iterReversed() >>> i.next() 999 >>> i.next() 998 >>> list(i)[-10:] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]iterSlicelets you iterate over the list with a slice. It is equivalent to using a slice with __getitem__.>>> i = l.iterSlice(345, 351, 2) >>> i # doctest: +ELLIPSIS <generator object at ...> >>> list(i) [345, 347, 349]CheapcopyThecopymethod produces a cheap copy of the given blist. All buckets and indexes are shared until a change is made to either side. Copies can safely be made of other copies.>>> c = l.copy() >>> l == c True >>> list(c) == list(l) True >>> del c[10:] >>> list(l) == range(1000) True >>> list(c) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> l == c False >>> c2 = c.copy() >>> c2 == c True >>> list(c2) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]MechanismIn its implementation, the sequence is an adapted B+ tree. Indexes are keys, but each bucket or branch starts at 0. For instance, a perfectly-balanced bucket sequence with 16 items, and a limit of 3 entries in a bucket or branch, would have “keys” like this. In the diagram, the top three rows are indexes, and the bottom row consists of buckets:0 8 0 4 0 4 0 2 0 2 0 2 0 2 01 01 01 01 01 01 01 01So, for instance, you would get the value at position 5 using this process:In the top index (the top row, with keys of 0 and 8), find the largest key that is lower than the desired position, and use the associated value (index or bucket, which is in this case the index represented by the first pair of 0 and 4 in the second row) for the next step. In this case, the top index has keys of 0 and 8, so the largest key lower than position 5 is 0. Subtract this key from the position for the next step. This difference will be used as the position for the next step. In this case, the next position will be (5-0=) 5.The next index has keys of 0 and 4. The largest key lower than 5 is 4. Use the child index associated with the 4 key for the next step (the second pair of 0 and 2 in the third row), and subtract the key (4) from the position (5) for the position to be used in the next step (=1).The next index (the second pair of 0 and 2 in the third row) needs to find position 1. This will return the third pair of 0 1 in the last row. The new position will be (1-0=) 1.Finally, position 1 in the bottom bucket stores the actual desired value.This arrangement minimizes the changes to keys necessary when a new value is inserted low in the sequence: ignoring balancing the tree, only parents and their subsequent siblings must be adjusted. For instance, inserting a new value in the 0 position of the bucketsequence described above (the worst case for the algorithm, in terms of the number of objects touched) would result in the following tree:0 9 0 5 0 4 0 3 0 2 0 2 0 2 012 01 01 01 01 01 01 01Performance CharacteristicsThe Good__getitem__is efficient, not loading unnecessary buckets. It handles slices pretty well too, not even loading intermediary buckets if the slice is very large. Slices currently return iterables rather than lists; this may switch to a view of some sort. All that should be assumed right now is that you can iterate over the result of a slice.__setitem__and all the write methods do a pretty good job in terms of efficient loading of buckets, and only writing what they need to. It supports full Python slice semantics.copyis cheap: it reuses buckets and indexes so that new inner components are created lazily when they mutate.While__contains__,__iter__,indexand other methods are brute force and written in Python, they might not load all buckets and items, while with a normal list or tuple, they always will. See alsoiter,iterReversed, anditerSlice.The So-Socount,__eq__, and other methods load all buckets and items, and are brute force, and in Python. In contrast, lists and tuples will load all items (worse), and is brute force in C (better, but not algorithmically).The BadThis will create a lot of Persistent objects for one blist, which may cause cache eviction problems depending on circumstances and usage.Did I mention that this was in Python, not C? That’s fixable, at least, and in fact doesn’t appear to be too problematic at the moment, at least for the author’s usage.Changes1.0b2 (2009-03-12)fixed: internal data structures were not stored correctly in the ZODB, so BLists loaded from a fresh DB connection would break.removed unused code and the dependency on rwpropertyimproved test coverage of the BList API, fixed access to items at index -1 or at the ends of the valid index range1.0b1 (2008-10-06)Initial release.
zcbor
zcborzcbor is a low footprintCBORlibrary in the C language (C++ compatible), tailored for use in microcontrollers. It comes with a schema-driven script tool that can validate your data, or even generate code. The schema language (CDDL) allows creating very advanced and detailed schemas.The validation and conversion part of the tool works with YAML and JSON data, in addition to CBOR. It can for example validate a YAML file against a schema and convert it into CBOR.The code generation part of the tool generates C code based on the given schema. The generated code performs CBOR encoding and decoding using the C library, while also validating the data against all the rules in the schema.The schema language used by zcbor is CDDL (Concise Data Definition Language) which is a powerful human-readable data description language defined inIETF RFC 8610.FeaturesHere are some possible ways zcbor can be used:C code:As a low-footprint CBOR decoding/encoding library similar to TinyCBOR/QCBOR/NanoCBOR. The library can be used independently of the Python script. (More information)To generate C code (using the Python script) for validating and decoding or encoding CBOR, for use in optimized or constrained environments, such as microcontrollers. (More information)Python script and module (More information):Validate a YAML/JSON file and translate it into CBOR e.g. for transmission.Validate a YAML/JSON/CBOR file before processing it with some other toolDecode and validate incoming CBOR data into human-readable YAML/JSON.As part of a python script that processes YAML/JSON/CBOR files.Uses the same internal representation used by the PyYAML/json/cbor2 libraries.Do validation against a CDDL schema.Create a read-only representation via named tuples (with names taken from the CDDL schema).Getting startedThere are samples in thesamplesdirectory that demonstrate different ways to use zcbor, both the script tool and the C code.Thehello_world sampleis a minimum examples of encoding and decoding using the C library.Thepet sampleshows a how to use the C library together with generated code, and how to use the script tool to do code generation and data conversion.Thetestsalso demonstrate how to use zcbor in different ways. Theencoding,decoding, andunittests run usingZephyr(the samples do not use Zephyr).Should I use code generation or the library directly?The benefit of using code generation is greater for decoding than encoding. This is because decoding is generally more complex than encoding, since when decoding you have to gracefully handle all possible payloads. The code generation will provide a number of checks that are tedious to write manually. These checks ensure that the payload is well-formed.CBOR decoding/encoding libraryThe CBOR library can be found ininclude/andsrc/and can be used directly, by including the files in your project. If using zcbor with Zephyr, the library will be available when theCONFIG_ZCBORconfig is enabled.The library is also used by generated code. See theCode generationsection for more info about code generation.The C library is C++ compatible.The zcbor state objectTo do encoding or decoding with the library, instantiate azcbor_state_tobject, which is most easily done using theZCBOR_STATE_*()macros, look below or in thehello_worldsample for example code.Theelem_countmember refers to the number of encoded objects in the current list or map.elem_countstarts again when entering a nested list or map, and is restored when exiting.elem_countis one reason for needing "backup" states (the other is to allow rollback of the payload). Backups are needed fordecodingif there are any lists, maps, or CBOR-encoded strings (zcbor_bstr_*_decode) in the data. Backups are needed forencodingif there are any lists or mapsandyou are using canonical encoding (ZCBOR_CANONICAL), or when using thezcbor_bstr_*_encodefunctions./** Initialize a decoding state (could include an array of backup states).* After calling this, decode_state[0] is ready to be used with the decoding APIs. */ZCBOR_STATE_D(decode_state,n,payload,payload_len,elem_count,n_flags);/** Initialize an encoding state (could include an array of backup states).* After calling this, encode_state[0] is ready to be used with the encoding APIs. */ZCBOR_STATE_E(encode_state,n,payload,payload_len,0);ConfigurationThe C library has a few compile-time configuration options. These configuration options can be enabled by adding them as compile definitions to the build. If using zcbor with Zephyr, use theKconfig optionsinstead.NameDescriptionZCBOR_CANONICALAssume canonical encoding (AKA "deterministically encoded CBOR"). When encoding lists and maps, do not use indefinite length encoding. EnablingZCBOR_CANONICALincreases code size and makes the encoding library more often use state backups. When decoding, ensure that the incoming data conforms to canonical encoding, i.e. no indefinite length encoding, and always using minimal length encoding (e.g. not using 16 bits to encode a value < 256). Note: the map ordering constraint in canonical encoding is not checked.ZCBOR_VERBOSEPrint log messages on encoding/decoding errors (zcbor_log()), and also a trace message (zcbor_trace()) for each decoded value, and in each generated function (when using code generation).ZCBOR_ASSERTSEnable asserts (zcbor_assert()). When they fail, the assert statements instruct the current function to return aZCBOR_ERR_ASSERTIONerror. IfZCBOR_VERBOSEis enabled, a message is printed.ZCBOR_STOP_ON_ERROREnable thestop_on_errorfunctionality. This makes all functions abort their execution if called when an error has already happened.ZCBOR_BIG_ENDIANAll decoded values are returned as big-endian. The default is little-endian.ZCBOR_MAP_SMART_SEARCHApplies to decoding of unordered maps. When enabled, a flag is kept for each element in an array, ensuring it is not processed twice. If disabled, a count is kept for map as a whole. Enabling increases code size and memory usage, and requires the state variable to possess the memory necessary for the flags.Python script and moduleThe zcbor.py script can directly read CBOR, YAML, or JSON data and validate it against a CDDL description. It can also freely convert the data between CBOR/YAML/JSON. It can also output the data to a C file formatted as a byte array.Invoking zcbor.py from the command linezcbor.py can be installed viapip, or alternatively invoked directly from its location in this repo.Following are some generalized examples for validating, and for converting (which also validates) data from the command line. The script infers the data format from the file extension, but the format can also be specified explicitly. Seezcbor validate --helpandzcbor convert --helpfor more information.zcborvalidate-c<CDDLdescriptionfile>-t<whichCDDLtypetoexpect>-i<inputdatafile> zcborconvert-c<CDDLdescriptionfile>-t<whichCDDLtypetoexpect>-i<inputdatafile>-o<outputdatafile>Or directly from within the repo.python3<zcborbase>/zcbor/zcbor.pyvalidate-c<CDDLdescriptionfile>-t<whichCDDLtypetoexpect>-i<inputdatafile> python3<zcborbase>/zcbor/zcbor.pyconvert-c<CDDLdescriptionfile>-t<whichCDDLtypetoexpect>-i<inputdatafile>-o<outputdatafile>Importing zcbor in a Python scriptImporting zcbor gives access to the DataTranslator class which is used to implement the command line conversion features. DataTranslator can be used to programmatically perform the translations, or to manipulate the data. When accessing the data, you can choose between two internal formats:The format provided by thecbor2,yaml (PyYAML), andjsonpackages. This is a format where the serialization types (map, list, string, number etc.) are mapped directly to the corresponding Python types. This format is common between these packages, which makes translation very simple. When returning this format, DataTranslator hides the idiomatic representations for bytestrings, tags, and non-text keys described above.A custom format which allows accessing the data via the names from the CDDL description file. This format is implemented using named tuples, and is immutable, meaning that it can be used for inspecting data, but not for changing or creating data.Making CBOR YAML-/JSON-compatibleSince CBOR supports more data types than YAML and JSON, zcbor can optionally use a bespoke format when converting to/from YAML/JSON. This is controlled with the--yaml-compatibilityoption toconvertandvalidate. This is relevant when handling YAML/JSON conversions of data that uses the unsupported features. The following data types are supported by CBOR, but not by YAML (or JSON which is a subset of YAML):bytestrings: YAML supports only text strings. In YAML, bytestrings are represented as{"zcbor_bstr": "<hex-formatted bytestring>"}, or as{"zcbor_bstr": <any type>}if the CBOR bytestring contains CBOR-formatted data, in which the data is decoded into<any type>.map keys other than text string: In YAML, such key value pairs are represented as{"zcbor_keyval<unique int>": {"key": <key, not text>, "val": <value>}}.tags: In cbor2, tags are represented by a special type,cbor2.CBORTag. In YAML, these are represented as{"zcbor_tag": <tag number>, "zcbor_tag_val": <tagged data>}.undefined: In cbor2, undefined has its own valuecbor2.types.undefined. In YAML, undefined is represented as:["zcbor_undefined"].You can see an example of the conversions intests/cases/yaml_compatibility.yamland its CDDL filetests/cases/yaml_compatibility.cddl.Code generationCode generation is invoked with thezcbor codecommand:zcborcode<--decodeor--encodeorboth>-c<CDDLdescriptionfile(s)>-t<whichCDDLtype(s)toexposeintheAPI>--output-cmake<pathtoplacethegeneratedCMakefileat> zcborcode<--decodeor--encodeorboth>-c<CDDLdescriptionfile(s)>-t<whichCDDLtype(s)toexposeintheAPI>--oc<pathtothegeneratedCfile>--oh<pathtothegeneratedheaderfile>--oht<pathtothegeneratedtypesheader>When you call this, zcbor reads the CDDL files and creates C struct types to match the types described in the CDDL. It then creates code that uses the C library to decode CBOR data into the structs, and/or encode CBOR from the data in the structs. Finally, it takes the "entry types" (-t) and creates a public API function for each of them. While doing these things, it will make a number of optimizations, e.g. inlining code for small types and removing unused functions. It outputs the generated code into header and source files and optionally creates a CMake file to build them.Thezcbor codecommand reads one or more CDDL file(s) and generates some or all of these files:A header file with types (always)A header file with declarations for decoding functions (if--decode/-dis specified)A C file with decoding functions (if--decode/-dis specified)A header file with declarations for encoding functions (if--encode/-eis specified)A C file with encoding functions (if--encode/-eis specified)A CMake file that creates a library with the generated code and the C library (if--output-cmakeis specified).CDDL allows placing restrictions on the members of your data. Restrictions can be on type (int/string/list/bool etc.), on content (e.g. values/sizes of ints or strings), and repetition (e.g. the number of members in a list). The generated code will validate the input, which means that it will check all the restriction set in the CDDL description, and fail if a restriction is broken.There are tests for the code generation intests/decodeandtests/encode. The tests requireZephyr(if your system is set up to build Zephyr samples, the tests should also build).The generated C code is C++ compatible.Build systemWhen calling zcbor with the argument--output-cmake <file path>, a CMake file will be created at that location. The generated CMake file creates a target library and adds the generated and non-generated source files as well as required include directories to it. This CMake file can then be included in your project'sCMakeLists.txtfile, and the target can be linked into your project. This is demonstrated in the tests, e.g. attests/decode/test3_simple/CMakeLists.txt. zcbor can be instructed to copy the non-generated sources to the same location as the generated sources with--copy-sources.Usage ExampleThere are buildable examples in thesamplesdirectory.To see how to use the C library directly, see thehello_worldsample, or thepetsample (look for calls to functions prefixed withzcbor_).To see how to use code generation, see thepetsample.Look at theCMakeLists.txtfile to see how zcbor is invoked for code generation (and for conversion).To see how to do conversion, see thepetsample.Below are some additional examples of how to invoke zcbor for code generation and for converting/validatingCode generationpython3<zcborbase>/zcbor/zcbor.pycode-cpet.cddl-d-tPet--ocpet_decode.c--ohpet_decode.h# orzcborcode-cpet.cddl-d-tPet--ocpet_decode.c--ohpet_decode.hConvertingHere is an example call for converting from YAML to CBOR:python3<zcborbase>/zcbor/zcbor.pyconvert-cpet.cddl-tPet-imypet.yaml-omypet.cbor# orzcborconvert-cpet.cddl-tPet-imypet.yaml-omypet.cborWhich takes a yaml structure from mypet.yaml, validates it against the Pet type in the CDDL description in pet.cddl, and writes binary CBOR data to mypet.cbor.ValidatingHere is an example call for validating a JSON file:python3<zcborbase>/zcbor/zcbor.pyvalidate-cpet.cddl-tPet--yaml-compatibility-imypet.json# orzcborvalidate-cpet.cddl-tPet--yaml-compatibility-imypet.jsonWhich takes the json structure in mypet.json, converts anyyaml-compatiblevalues to their original form, and validates that against the Pet type in the CDDL description in pet.cddl.Running testsThe tests for the generated code are based on the Zephyr ztest library. These tests can be found intests/decodeandtests/encode. To set up the environment to run the ztest tests, followZephyr's Getting Started Guide, or see the workflow in the.githubdirectory.Tests forconvertandverifyare implemented with the unittest module. These tests can be found intests/scripts/test_zcbor.py. In this file there are also tests for code style of all python scripts, using thepycodestylelibrary.Tests for the docs, samples, etc. can be found intests/scripts/test_repo_files.py.For running the tests locally, there istests/test.shwhich runs all above tests.Introduction to CDDLIn CDDL you define types from other types. Types can be defined from base types, or from other types you define. Types are declared with '=', e.g.Foo = intwhich declares the typeFooto be an integer, analogous totypedef int Foo;in C. CDDL defines the following base types (this is not an exhaustive list):int: Positive or negative integeruint: Positive integerbstr: Byte stringtstr: Text stringbool: Booleannil: Nil/Null valuefloat: Floating point valueany: Any single elementCDDL allows creating aggregate types:[]: List. Elements don't need to have the same type.{}: Map. Key/value pairs as are declared as<key> => <value>or<key>: <value>. Note that:is also used for labels.(): Groups. Grouping with no enclosing type, which means that e.g.Foo = [(int, bstr)]is equivalent toFoo = [int, bstr]./: Unions. Analogous to unions in C. E.g.Foo = int/bstr/Barwhere Foo is either an int, a bstr, or Bar (some custom type).Literals can be used instead of the base type names:Number:Foo = 3, where Foo is a uint with the additional requirement that it must have the value 3.Number range:Foo = -100..100, where Foo is an int with value between -100 and 100.Text string:Foo = "hello", where Foo is a tstr with the requirement that it must be "hello".True/False:Foo = false, where Foo is a bool which is always false.Base types can also be restricted in other ways:.size: Works for integers and strings. E.g.Foo = uint .size 4where Foo is a uint exactly 4 bytes long..cbor/.cborseq: E.g.Foo = bstr .cbor Barwhere Foo is a bstr whose contents must be CBOR data decodable as the Bar type.An element can be repeated:?: 0 or 1 time. E.g.Foo = [int, ?bstr], where Foo is a list with an int possibly followed by a bstr.*: 0 or more times. E.g.Foo = [*tstr], where Foo is a list containing 0 or more tstrs.+: 1 or more times. E.g.Foo = [+Bar].x*y: Between x and y times, inclusive. E.g.Foo = {4*8(int => bstr)}where Foo is a map with 4 to 8 key/value pairs where each key is an int and each value is a bstr.Note that in the zcbor script and its generated code, the number of entries supported via*and+is affected by the default_max_qty value.Any element can be labeled with:. The label is only for readability and does not impact the data structure in any way. E.g.Foo = [name: tstr, age: uint]is equivalent toFoo = [tstr, uint].Seepet.cddlfor CDDL example code.Introduction to CBORCBOR's format is described well onWikipedia, but here's a synopsis:Encoded CBOR data elements look like this.| Header | Value | Payload | | 1 byte | 0, 1, 2, 4, or 8 bytes | 0 - 2^64-1 bytes/elements | | 3 bits | 5 bits | | Major Type | Additional Info |The available major types can be seen inzcbor_major_type_t.For all major types, Values 0-23 are encoded directly in theAdditional info, meaning that theValuefield is 0 bytes long. IfAdditional infois 24, 25, 26, or 27, theValuefield is 1, 2, 4, or 8 bytes long, respectively.Major typespint(0),nint(1),tag(6), andsimple(7) elements have no payload, onlyValue.pint: Interpret theValueas a positive integer.nint: Interpret theValueas a positive integer, then multiply by -1 and subtract 1.tag: TheValuesays something about the next non-tag element. See theCBOR tag documentationfor details.simple: DifferentAdditional infomean different things:0-19: Unassigned simple values.20:falsesimple value21:truesimple value22:nullsimple value23:undefinedsimple value24: Interpret theValueas a 1 byte simple value. These simple values are currently unassigned.25: Interpret theValueas an IEEE 754 float16.26: Interpret theValueas an IEEE 754 float32.27: Interpret theValueas an IEEE 754 float64.31: End of an indefinite-lengthlistormap.Forbstr(2),tstr(3),list(4), andmap(5), theValuedescribes the length of thePayload. Forbstrandtstr, the length is in bytes, forlist, the length is in number of elements, and formap, the length is in number of key/value element pairs.Forlistandmap, sub elements are regular CBOR elements with their ownHeader,ValueandPayload.lists andmaps can be recursively encoded. If alistormaphasAdditional info31, it is "indefinite-length", which means it has an "unknown" number of elements. Instead, its end is marked by asimplewithAdditional info31 (byte value 0xFF).Historyzcbor (then "cddl-gen") was initially conceived as a code generation project. It was inspired by the need to securely decode the complex manifest data structures in theIETF SUIT specification. This is reflected in the fact that there are multiple zcbor tests that use the CDDL and examples from various revisions of that specification. Decoding/deserializing data securely requires doing some quite repetitive checks on each data element, to be sure that you are not decoding gibberish. This is where code generation could pull a lot of weight. Later it was discovered that the CBOR library that was designed to used by generated code could be useful by itself. The script was also expanded so it could directly manipulate CBOR data. Since CBOR, YAML, and JSON are all represented in roughly the same way internally in Python, it was easy to expand that data manipulation to support YAML and JSON.Some places where zcbor is currently used:MCUboot's serial recovery mechanismZephyr's mcumgrZephyr's LwM2M SenMLnRF Connect SDK's full modem update mechanismnRF Connect SDK's nrf_rpcCommand line documentationAdded viaadd_helptext.pyzcbor --helpusage: zcbor [-h] [--version] {code,validate,convert} ... Parse a CDDL file and validate/convert between YAML, JSON, and CBOR. Can also generate C code for validation/encoding/decoding of CBOR. positional arguments: {code,validate,convert} options: -h, --help show this help message and exit --version show program's version number and exitzcbor code --helpusage: zcbor code [-h] -c CDDL [--no-prelude] [-v] [--default-max-qty DEFAULT_MAX_QTY] [--output-c OUTPUT_C] [--output-h OUTPUT_H] [--output-h-types OUTPUT_H_TYPES] [--copy-sources] [--output-cmake OUTPUT_CMAKE] -t ENTRY_TYPES [ENTRY_TYPES ...] [-d] [-e] [--time-header] [--git-sha-header] [-b {32,64}] [--include-prefix INCLUDE_PREFIX] [-s] [--file-header FILE_HEADER] Parse a CDDL file and produce C code that validates and xcodes CBOR. The output from this script is a C file and a header file. The header file contains typedefs for all the types specified in the cddl input file, as well as declarations to xcode functions for the types designated as entry types when running the script. The c file contains all the code for decoding and validating the types in the CDDL input file. All types are validated as they are xcoded. Where a `bstr .cbor <Type>` is specified in the CDDL, AND the Type is an entry type, the xcoder will not xcode the string, only provide a pointer into the payload buffer. This is useful to reduce the size of typedefs, or to break up decoding. Using this mechanism is necessary when the CDDL contains self- referencing types, since the C type cannot be self referencing. This script requires 'regex' for lookaround functionality not present in 're'. options: -h, --help show this help message and exit -c CDDL, --cddl CDDL Path to one or more input CDDL file(s). Passing multiple files is equivalent to concatenating them. --no-prelude Exclude the standard CDDL prelude from the build. The prelude can be viewed at zcbor/prelude.cddl in the repo, or together with the script. -v, --verbose Print more information while parsing CDDL and generating code. --default-max-qty DEFAULT_MAX_QTY, --dq DEFAULT_MAX_QTY Default maximum number of repetitions when no maximum is specified. This is needed to construct complete C types. The default_max_qty can usually be set to a text symbol if desired, to allow it to be configurable when building the code. This is not always possible, as sometimes the value is needed for internal computations. If so, the script will raise an exception. --output-c OUTPUT_C, --oc OUTPUT_C Path to output C file. If both --decode and --encode are specified, _decode and _encode will be appended to the filename when creating the two files. If not specified, the path and name will be based on the --output-cmake file. A 'src' directory will be created next to the cmake file, and the C file will be placed there with the same name (except the file extension) as the cmake file. --output-h OUTPUT_H, --oh OUTPUT_H Path to output header file. If both --decode and --encode are specified, _decode and _encode will be appended to the filename when creating the two files. If not specified, the path and name will be based on the --output-cmake file. An 'include' directory will be created next to the cmake file, and the C file will be placed there with the same name (except the file extension) as the cmake file. --output-h-types OUTPUT_H_TYPES, --oht OUTPUT_H_TYPES Path to output header file with typedefs (shared between decode and encode). If not specified, the path and name will be taken from the output header file (--output-h), with '_types' added to the file name. --copy-sources Copy the non-generated source files (zcbor_*.c/h) into the same directories as the generated files. --output-cmake OUTPUT_CMAKE Path to output CMake file. The filename of the CMake file without '.cmake' is used as the name of the CMake target in the file. The CMake file defines a CMake target with the zcbor source files and the generated file as sources, and the zcbor header files' and generated header files' folders as include_directories. Add it to your project via include() in your CMakeLists.txt file, and link the target to your program. This option works with or without the --copy-sources option. -t ENTRY_TYPES [ENTRY_TYPES ...], --entry-types ENTRY_TYPES [ENTRY_TYPES ...] Names of the types which should have their xcode functions exposed. -d, --decode Generate decoding code. Either --decode or --encode or both must be specified. -e, --encode Generate encoding code. Either --decode or --encode or both must be specified. --time-header Put the current time in a comment in the generated files. --git-sha-header Put the current git sha of zcbor in a comment in the generated files. -b {32,64}, --default-bit-size {32,64} Default bit size of integers in code. When integers have no explicit bounds, assume they have this bit width. Should follow the bit width of the architecture the code will be running on. --include-prefix INCLUDE_PREFIX When #include'ing generated files, add this path prefix to the filename. -s, --short-names Attempt to make most generated struct member names shorter. This might make some names identical which will cause a compile error. If so, tweak the CDDL labels or layout, or disable this option. This might also make enum names different from the corresponding union members. --file-header FILE_HEADER Header to be included in the comment at the top of generated C files, e.g. copyright.zcbor validate --helpusage: zcbor validate [-h] -c CDDL [--no-prelude] [-v] -i INPUT [--input-as {yaml,json,cbor,cborhex}] -t ENTRY_TYPE [--default-max-qty DEFAULT_MAX_QTY] [--yaml-compatibility] Read CBOR, YAML, or JSON data from file or stdin and validate it against a CDDL schema file. options: -h, --help show this help message and exit -c CDDL, --cddl CDDL Path to one or more input CDDL file(s). Passing multiple files is equivalent to concatenating them. --no-prelude Exclude the standard CDDL prelude from the build. The prelude can be viewed at zcbor/prelude.cddl in the repo, or together with the script. -v, --verbose Print more information while parsing CDDL and generating code. -i INPUT, --input INPUT Input data file. The option --input-as specifies how to interpret the contents. Use "-" to indicate stdin. --input-as {yaml,json,cbor,cborhex} Which format to interpret the input file as. If omitted, the format is inferred from the file name. .yaml, .yml => YAML, .json => JSON, .cborhex => CBOR as hex string, everything else => CBOR -t ENTRY_TYPE, --entry-type ENTRY_TYPE Name of the type (from the CDDL) to interpret the data as. --default-max-qty DEFAULT_MAX_QTY, --dq DEFAULT_MAX_QTY Default maximum number of repetitions when no maximum is specified. It is only relevant when handling data that will be decoded by generated code. If omitted, a large number will be used. --yaml-compatibility Whether to convert CBOR-only values to YAML-compatible ones (when converting from CBOR), or vice versa (when converting to CBOR). When this is enabled, all CBOR data is guaranteed to convert into YAML/JSON. JSON and YAML do not support all data types that CBOR/CDDL supports. bytestrings (BSTR), tags, undefined, and maps with non-text keys need special handling. See the zcbor README for more information.zcbor convert --helpusage: zcbor convert [-h] -c CDDL [--no-prelude] [-v] -i INPUT [--input-as {yaml,json,cbor,cborhex}] -t ENTRY_TYPE [--default-max-qty DEFAULT_MAX_QTY] [--yaml-compatibility] -o OUTPUT [--output-as {yaml,json,cbor,cborhex,c_code}] [--c-code-var-name C_CODE_VAR_NAME] [--c-code-columns C_CODE_COLUMNS] Parse a CDDL file and validate/convert between CBOR and YAML/JSON. The script decodes the CBOR/YAML/JSON data from a file or stdin and verifies that it conforms to the CDDL description. The script fails if the data does not conform. 'zcbor validate' can be used if only validate is needed. options: -h, --help show this help message and exit -c CDDL, --cddl CDDL Path to one or more input CDDL file(s). Passing multiple files is equivalent to concatenating them. --no-prelude Exclude the standard CDDL prelude from the build. The prelude can be viewed at zcbor/prelude.cddl in the repo, or together with the script. -v, --verbose Print more information while parsing CDDL and generating code. -i INPUT, --input INPUT Input data file. The option --input-as specifies how to interpret the contents. Use "-" to indicate stdin. --input-as {yaml,json,cbor,cborhex} Which format to interpret the input file as. If omitted, the format is inferred from the file name. .yaml, .yml => YAML, .json => JSON, .cborhex => CBOR as hex string, everything else => CBOR -t ENTRY_TYPE, --entry-type ENTRY_TYPE Name of the type (from the CDDL) to interpret the data as. --default-max-qty DEFAULT_MAX_QTY, --dq DEFAULT_MAX_QTY Default maximum number of repetitions when no maximum is specified. It is only relevant when handling data that will be decoded by generated code. If omitted, a large number will be used. --yaml-compatibility Whether to convert CBOR-only values to YAML-compatible ones (when converting from CBOR), or vice versa (when converting to CBOR). When this is enabled, all CBOR data is guaranteed to convert into YAML/JSON. JSON and YAML do not support all data types that CBOR/CDDL supports. bytestrings (BSTR), tags, undefined, and maps with non-text keys need special handling. See the zcbor README for more information. -o OUTPUT, --output OUTPUT Output data file. The option --output-as specifies how to interpret the contents. Use "-" to indicate stdout. --output-as {yaml,json,cbor,cborhex,c_code} Which format to interpret the output file as. If omitted, the format is inferred from the file name. .yaml, .yml => YAML, .json => JSON, .c, .h => C code, .cborhex => CBOR as hex string, everything else => CBOR --c-code-var-name C_CODE_VAR_NAME Only relevant together with '--output-as c_code' or .c files. --c-code-columns C_CODE_COLUMNS Only relevant together with '--output-as c_code' or .c files. The number of bytes per line in the variable instantiation. If omitted, the entire declaration is a single line.
zcbot-celery-sdk
pip uninstall zcbot-celery-sdkpip install –upgrade zcbot-celery-sdk -ihttps://pypi.python.org/simplepip show zcbot-celery-sdk
zcbot-crawl-core
pip uninstall zcbot-crawl-corepip install –upgrade zcbot-crawl-core -ihttps://pypi.python.org/simplepip show zcbot-crawl-core
zcbot-crawl-sdk
pip uninstall zcbot-crawl-sdkpip install –upgrade zcbot-crawl-sdk -ihttps://pypi.python.org/simplepip show zcbot-crawl-sdk
zc.botokeyring
Note: My hope is that this package will become redundant by integrating something very similar into boto itself.Boto is awesome for controlling AWS. Unfortunately, there are times when specifying credentials is awkward. Typically, one has to either:includint the AWS password (aws_secret_access_key) in a clear text dot file, which is insecure, orsetting an environment variable with the password, which is inconvenient and insecure on multi-user systems.It would be better to use a secure keyring to store the password. zc.botokeyring provides exactlly that capability. To use it, set aws_access_key_id in the Credentials section of your boto configuration filem as usual, and instead of setting aws_secret_access_key, set keyring to the name of a keyring containing the password:[Credentials] aws_access_key_id = 1234 keyring = testChanges0.1.0 (2012-12-02)Initial release
zcbot-predict-sdk
pip uninstall zcbot-predict-sdkpip install –upgrade zcbot-predict-sdk -ihttps://pypi.python.org/simplepip show zcbot-predict-sdk
zcbot-scrapy-redis
Scrapy-RedisRedis-based components for Scrapy.Usage:https://github.com/rmax/scrapy-redis/wiki/UsageDocumentation:https://github.com/rmax/scrapy-redis/wiki.Release:https://github.com/rmax/scrapy-redis/wiki/HistoryContribution:https://github.com/rmax/scrapy-redis/wiki/Getting-StartedLICENSE: MIT licenseFeaturesDistributed crawling/scrapingYou can start multiple spider instances that share a single redis queue. Best suitable for broad multi-domain crawls.Distributed post-processingScraped items gets pushed into a redis queued meaning that you can start as many as needed post-processing processes sharing the items queue.Scrapy plug-and-play componentsScheduler + Duplication Filter, Item Pipeline, Base Spiders.In this forked version: addedjsonsupported data in Redisdata containsurl,`meta`and other optional parameters.metais a nested json which contains sub-data. this function extract this data and send another FormRequest withurl,metaand additionformdata.For example:{"url":"https://exaple.com","meta":{"job-id":"123xsd","start-date":"dd/mm/yy"},"url_cookie_key":"fertxsas"}this data can be accessed inscrapy spiderthrough response. like:request.url,request.meta,request.cookiesNoteThis features cover the basic case of distributing the workload across multiple workers. If you need more features like URL expiration, advanced URL prioritization, etc., we suggest you to take a look at theFronteraproject.RequirementsPython 3.7+Redis >= 5.0Scrapy>= 2.0redis-py>= 4.0InstallationFrom pippipinstallscrapy-redisFrom GitHubgitclonehttps://github.com/darkrho/scrapy-redis.gitcdscrapy-redispythonsetup.pyinstallNoteFor using this json supported data feature, please make sure you have not installed the scrapy-redis through pip. If you already did it, you first uninstall that one.pipuninstallscrapy-redisAlternative ChoiceFronterais a web crawling framework consisting ofcrawl frontier, and distribution/scaling primitives, allowing to build a large scale online web crawler.History0.7.3 (2022-07-21)Move docs to GitHub WikiUpdate tox and support dynamic testsUpdate support for json dataRefactor max idle timeAdd support for python3.7~python3.10Deprecate python2.x support0.7.2 (2021-12-27)Fix RedisStatsCollector._get_key()Fix redis-py dependency versionAdded maximum idle waiting time MAX_IDLE_TIME_BEFORE_CLOSE0.7.1 (2021-03-27)Fixes datetime parse error for redis-py 3.x.Add support for stats extensions.0.7.1-rc1 (2021-03-27)Fixes datetime parse error for redis-py 3.x.0.7.1-b1 (2021-03-22)Add support for stats extensions.0.7.0-dev (unreleased)Unreleased.0.6.8 (2017-02-14)Fixed automated release due to not matching registered email.0.6.7 (2016-12-27)Fixes bad formatting in logging message.0.6.6 (2016-12-20)Fixes wrong message on dupefilter duplicates.0.6.5 (2016-12-19)Fixed typo in default settings.0.6.4 (2016-12-18)Fixed data decoding in Python 3.x.AddedREDIS_ENCODINGsetting (defaultutf-8).Default toCONCURRENT_REQUESTSvalue forREDIS_START_URLS_BATCH_SIZE.Renamed queue classes to a proper naming conventiong (backwards compatible).0.6.3 (2016-07-03)AddedREDIS_START_URLS_KEYsetting.Fixed spider methodfrom_crawlersignature.0.6.2 (2016-06-26)Supportredis_clsparameter inREDIS_PARAMSsetting.Python 3.x compatibility fixed.AddedSCHEDULER_SERIALIZERsetting.0.6.1 (2016-06-25)Backwards incompatible change:Require explicitDUPEFILTER_CLASSsetting.AddedSCHEDULER_FLUSH_ON_STARTsetting.AddedREDIS_START_URLS_AS_SETsetting.AddedREDIS_ITEMS_KEYsetting.AddedREDIS_ITEMS_SERIALIZERsetting.AddedREDIS_PARAMSsetting.AddedREDIS_START_URLS_BATCH_SIZEspider attribute to read start urls in batches.AddedRedisCrawlSpider.0.6.0 (2015-07-05)Updated code to be compatible with Scrapy 1.0.Added-a domain=…option for example spiders.0.5.0 (2013-09-02)AddedREDIS_URLsetting to support Redis connection string.AddedSCHEDULER_IDLE_BEFORE_CLOSEsetting to prevent the spider closing too quickly when the queue is empty. Default value is zero keeping the previous behavior.Schedule preemptively requests on item scraped.This version is the latest release compatible with Scrapy 0.24.x.0.4.0 (2013-04-19)AddedRedisSpiderandRedisMixinclasses as building blocks for spiders to be fed through a redis queue.Added redis queue stats.Let the encoder handle the item as it comes instead converting it to a dict.0.3.0 (2013-02-18)Added support for different queue classes.Changed requests serialization frommarshaltocPickle.0.2.0 (2013-02-17)Improved backward compatibility.Added example project.0.1.0 (2011-09-01)First release on PyPI.
zcbot-shop-parser
pip uninstall zcbot-shop-parserpip install –upgrade zcbot-shop-parser -ihttps://pypi.python.org/simplepip show zcbot-shop-parser
zcbot-url-parser
pip uninstall zcbot-url-parserpip install –upgrade zcbot-url-parser -ihttps://pypi.python.org/simplepip show zcbot-url-parser
zcbot-web-core
pip uninstall zcbot-web-corepip install –upgrade zcbot-web-core -ihttps://pypi.python.org/simplepip show zcbot-web-core
zc.buildout
Buildout is a project designed to solve 2 problems:Application-centric assembly and deploymentAssemblyruns the gamut from stitching together libraries to create a running program, to production deployment configuration of applications, and associated systems and tools (e.g. run-control scripts, cron jobs, logs, service registration, etc.).Buildout might be confused with build tools like make or ant, but it is a little higher level and might invoke systems like make or ant to get its work done.Buildout might be confused with systems like puppet or chef, but it is more application focused. Systems like puppet or chef might use buildout to get their work done.Buildout is also somewhat Python-centric, even though it can be used to assemble and deploy non-python applications. It has some special features for assembling Python programs. It’s scripted with Python, unlike, say puppet or chef, which are scripted with Ruby.Repeatable assembly of programs from Python software distributionsBuildout puts great effort toward making program assembly a highly repeatable process, whether in a very open-ended development mode, where dependency versions aren’t locked down, or in a deployment environment where dependency versions are fully specified. You should be able to check buildout into a VCS and later check it out. Two checkouts built at the same time in the same environment should always give the same result, regardless of their history. Among other things, after a buildout, all dependencies should be at the most recent version consistent with any version specifications expressed in the buildout.Buildout supports applications consisting of multiple programs, with different programs in an application free to use different versions of Python distributions. This is in contrast with a Python installation (real or virtual), where, for any given distribution, there can only be one installed.To learn more about buildout, including how to use it, seehttp://docs.buildout.org/.Change History3.0.1 (2022-11-08)Bug fixes:Fixed import of packaging.markers. [maurits] (#621)3.0.0 (2022-11-07)New features:Add support for PEP 508 markers in section condition expressions. For example:[versions:python_version <= "3.9"]. [maurits] (#621)Bug fixes:Command-line ‘extends’ now works with dirs in file names [gotcha] (cli-extends)Add support for python311-315 in conditional section expressions. (#311)Make compatible with pip 22.2+, restoring Requires-Python functionality there. Fixesissue 613. [maurits] (#613)3.0.0rc3 (2022-04-07)Bug fixes:FixTypeError: dist must be a Distribution instancedue to issue betweensetuptoolsandpip. (#600)3.0.0rc2 (2022-03-04)New features:add support for PEP496 environment markers (pep496)Bug fixes:Fix TypeError for missing requireduse_deprecated_html5libwith pip 22. Keep compatible with earlier pip versions. (#598)3.0.0rc1 (2021-12-16)Bug fixes:Call pip viapython -m pip. (#569)3.0.0b5 (2021-11-29)Bug fixes:Fix when c extension implements namespace packages without the corresponding directories. (#589)Honor command-line buildout:extends (#592)3.0.0b4 (2021-11-25)New features:Allow to run buildout in FIPS enabled environments. (#570)Proper error message if extends-cache tries to expand ${section:variable} (#585)Bug fixes:Forward verbose option to pip (#576)Check that file top_level.txt exists before opening. Add check for other files as well. (#582)Return code of pip install subprocess is now properly returned to buildout. (#586)3.0.0b3 (2021-10-08)New features:Improve warning message when a section contains unused options. (#483)Bug fixes:Fix support ofpip>=21.1(#567)Fix confusion when using multiple Python versions and installing packages with C extensions without proper binary wheel available. (#574)Development:Avoid broken jobs on Travis because of security on PRs (travis-pr)3.0.0b2 (2021-03-09)New features:Improve error message when a package version is not pinned andallow-picked-versions = false. (#481)Bug fixes:Fix FileNotFoundError when installing eggs with top-level directory without code (like doc). (#556)Development:Login to docker hub to avoid pull limits (travis)Initialize towncrier (#519)3.0.0b1 (2021-03-07)Fix issue with combination of>specs andextrasand recentsetuptools.Fix issue with incrementing options from.buildout/default.cfg.Support python37, python38 and python39 in conditional section expressions.Fix bootstrapping for python27 and python35.3.0.0a2 (2020-05-25)Ignore.gitwhen computing signature of a recipe develop eggWarn when the name passed tozc.recipe.egg:scriptsis not defined in egg entry points.Show pip warning about Python version only once.Better patch forpkg_resources.Distribution.hashcmpperformance.3.0.0a1 (2020-05-17)Scripts: ensure eggs are inserted beforesite-packagesinsys.path.Fix forever loop when changingzc.buildoutversion viabuildout.Add support forRequires-Pythonmetadata. Fragile monkeypatch that relies onpip._internal. Emits a warning when support is disabled due to changes inpip.Usepip installinstead of deprecatedsetuptools.easy_install.Patchpkg_resources.Distributionto make install of unpinned versions quicker. Most obvious withsetuptools.2.13.3 (2020-02-11)Fix DeprecationWarning about MutableMapping. (#484)2.13.2 (2019-07-03)Fixed DeprecationWarning on python 3.7: “‘U’ mode is deprecated”.2.13.1 (2019-01-29)Documentation update for the newbuildout querycommand.2.13.0 (2019-01-17)Get information about the configuration with new commandbuildout query.2.12.2 (2018-09-04)Upon an error, buildout exits with a non-zero exit code. This now also works when running with-D.Fixed most ‘Deprecation’ and ‘Resource’ warnings.2.12.1 (2018-07-02)zc.buildout now explicitly requests zc.recipe.egg >=2.0.6 now.2.12.0 (2018-07-02)Add a new buildout optionallow-unknown-extrasto enable installing requirements that specify extras that do not exist. This needs a corresponding update to zc.recipe.egg. Seeissue 457.zc.recipe.egg has been updated to 2.0.6 for this change.2.11.5 (2018-06-19)Fix forissue 295. On windows, deletion of temporary egg files is more robust now.2.11.4 (2018-05-14)Fix forissue 451: distributions with a version number that normalizes to a shorter version number (3.3.0 to 3.3, for instance) can be installed now.2.11.3 (2018-04-13)Update to use the new PyPI athttps://pypi.org/.2.11.2 (2018-03-19)Fix for the #442 issue: AttributeError onpkg_resources.SetuptoolsVersion.2.11.1 (2018-03-01)Made upgrade check more robust. When using extensions, the improvement introduced in 2.11 could prevent buildout from restarting itself when it upgraded setuptools.2.11.0 (2018-01-21)Installed packages are added to the working set immediately. This helps in some corner cases that occur when system packages have versions that conflict with our specified versions.2.10.0 (2017-12-04)Setuptools 38.2.0 started supporting wheels. Through setuptools, buildout now also supports wheels! You need at least version 38.2.3 to get proper namespace support.This setuptools change interfered with buildout’s recent support forbuildout.wheel, resulting in a sudden “Wheels are not supported” error message (seeissue 435). Fixed by making setuptools the default, though you can still use the buildout.wheel if you want.2.9.6 (2017-12-01)Fixed: could not install eggs when sdist file name and package name had different case.2.9.5 (2017-09-22)Use HTTPS for PyPI’s index. PyPI redirects HTTP to HTTPS by default now so using HTTPS directly avoids the potential for that redirect being modified in flight.2.9.4 (2017-06-20)Sort the distributions used to compute__buildout_signature__to ensure reproducibility under Python 3 or under Python 2 when-Ris used onPYTHONHASHSEEDis set torandom. Fixesissue 392.NOTE: This may cause existing.installed.cfgto be considered outdated and lead to parts being reinstalled spuriously under Python 2.Add support code for doctests to be able to easily measure code coverage. Seeissue 397.2.9.3 (2017-03-30)Add more verbosity toannotateresults with-vSelect one or more sections with arguments afterbuildout annotate.2.9.2 (2017-03-06)Fixed: We unnecessarily used a function from newer versions of setuptools that caused problems when older setuptools or pkg_resources installs were present (as in travis.ci).2.9.1 (2017-03-06)Fixed a minor packaging bug that broke the PyPI page.2.9.0 (2017-03-06)Added new syntax to explicitly declare that a part depends on other part. Seehttp://docs.buildout.org/en/latest/topics/implicit-parts.htmlInternal refactoring to work withbuildout.wheel.Fixed a bugs inzc.buildout.testing.Buildout. It was loading user-default configuration. It didn’t support calling thecreatedmethod on its sections.Fixed a bug (windows, py 3.4) When processing metadata on “old-style” distutils scripts, .exe stubs appeared inmetadata_listdir, in turn reading those burped withUnicodeDecodeError. Skipping .exe stubs now.2.8.0 (2017-02-13)Added a hook to enable a soon-to-be-released buildout extension to provide wheel support.2.7.1 (2017-01-31)Fixed a bug introduced in 2.6.0: zc.buildout and its dependeoncies were reported as picked even when their versions were fixed in aversionssection. Worse, when theupdate-versions-fileoption was used, theversionssection was updated needlessly on every run.2.7.0 (2017-01-30)Added a buildout option,abi-tag-eggsthat, when true, causes theABI tagfor the buildout environment to be added to the eggs directory name.This is useful when switching Python implementations (e.g. CPython vs PyPI or debug builds vs regular builds), especially when environment differences aren’t reflected in egg names. It also has the side benefit of making eggs directories smaller, because eggs for different Python versions are in different directories.2.6.0 (2017-01-29)Updated to work with the latest setuptools.Added (verified) Python 3.6 support.2.5.3 (2016-09-05)After a dist is fetched and put into its final place, compile its python files. No longer wait with compiling until all dists are in place. This is related to the change below about not removing an existing egg. [maurits]Do not remove an existing egg. When installing an egg to a location that already exists, keep the current location (directory or file). This can only happen when the location at first did not exist and this changed during the buildout run. We used to remove the previous location, but this could cause problems when running two buildouts at the same time, when they try to install the same new egg. Fixes #307. [maurits]Inzc.buildout.testing.system, setTERM=dumbin the environment. This avoids invisible control characters popping up in some terminals, likexterm. Note that this may affect tests by buildout recipes. [maurits]Removed Python 2.6 and 3.2 support. [do3cc]2.5.2 (2016-06-07)Fixed-=and+=when extending sections. See #161. [puittenbroek]2.5.1 (2016-04-06)Fix python 2 for downloading external config files with basic auth in the URL. Fixes #257.2.5.0 (2015-11-16)Added more elaborate version and requirement information when there’s a version conflict. Previously, you could get a report of a version conflict without information about which dependency requested the conflicing requirement.Now all this information is logged and displayed in case of an error. [reinout]Dropped 3.2 support (at least in the automatic tests) as setuptools will soon stop supporting it. Added python 3.5 to the automatic tests. [reinout]2.4.7 (2015-10-29)Fix for #279. Distutils script detection previously broke on windows with python 3 because it errored on.exefiles. [reinout]2.4.6 (2015-10-28)Relative paths are now also correctly generated for the current directory (“develop = .”). [youngking]2.4.5 (2015-10-14)More complete fix for #24. Distutils scripts are now also generated for develop eggs. [reinout]2.4.4 (2015-10-02)zc.buildout is now also released as a wheel. (Note: buildout itself doesn’t support installing wheels yet.) [graingert]2.4.3 (2015-09-03)Added nested directory creation support [guyzmo]2.4.2 (2015-08-26)If a downloaded config file in the “extends-cache” gets corrupted, buildout now tells you the filename in the cache. Handy for troubleshooting. [reinout]2.4.1 (2015-08-08)Check theuse-dependency-linksoption earlier. This can give a small speed increase. [maurits]When using python 2, urllib2 is used to work around Python issue 24599, which affects downloading from behind a proxy. [stefano-m]2.4.0 (2015-07-01)Buildout no longer breaks on packages that contain a file with a non-ascii filename. Fixes #89 and #148. [reinout]Undo breakage on Windows machines wheresys.prefixcan also be asite-packagesdirectory: don’t remove it fromsys.path. Seehttps://github.com/buildout/buildout/issues/217.Remove assumption thatpkg_resourcesis a module (untrue since release ofsetuptools 8.3`). Seehttps://github.com/buildout/buildout/issues/227.Fix for #212. For certain kinds of conflict errors you’d get an UnpackError when rendering the error message. Instead of a nicely formatted version conflict message. [reinout]Making sure we use the correct easy_install when setuptools is installed globally. Seehttps://github.com/buildout/buildout/pull/232andhttps://github.com/buildout/buildout/pull/222. [lrowe]Updated buildout’stravis-ciconfiguration so that tests run much quicker so that buildout is easier and quicker to develop. [reinout]Note: zc.recipe.egg has also been updated to 2.0.2 together with this zc.buildout release. Fixed: Inzc.recipe.egg#customrecipe’srpathsupport, don’t assume path elements are buildout-relative if they start with one of the “special” tokens (e.g.,$ORIGIN). See:https://github.com/buildout/buildout/issues/225. [tseaver]download-cache,eggs-directoryandextends-cacheare now automatically created if their parent directory exists. Also they can be relative directories (relative to the location of the buildout config file that defines them). Also they can now be in the form~/subdir, with the usual convention that the~char means the home directory of the user running buildout. [lelit]A new bootstrap.py file is released (version 2015-07-01).When bootstrapping, thedevelop-eggs/directory is first removed. This prevents old left-over.egg-linkfiles from breaking buildout’s careful package collection mechanism. [reinout]The bootstrap script now accepts--to-dir. Setuptools is installed there. If already available there, it is reused. This can be used to bootstrap buildout without internet access. Similarly, a localez_setup.pyis used when available instead of it being downloaded. You need setuptools 14.0 or higher for this functionality. [lrowe]The bootstrap script now uses--buildout-versioninstead of--versionto pick a specific buildout version. [reinout]The bootstrap script now accepts--versionwhich prints the bootstrap version. This version is the date the bootstrap.py was last changed. A date is handier or less confusing than either tracking zc.buildout’s version or having a separate bootstrap version number. [reinout]2.3.1 (2014-12-16)Fixed: Buildout merged single-version requirements with version-range requirements in a way that caused it to think there wasn’t a single-version requirement. IOW, buildout through that versions were being picked when they weren’t.Suppress spurious (and possibly non-spurious) version-parsing warnings.2.3.0 (2014-12-14)Buildout is now compatible with (and requires) setuptools 8.2.2.5 (2014-11-04)Improved fix for #198: when bootstrapping with an extension, buildout was too strict on itself, resulting in an inability to upgrade or downgrade its own version. [reinout]Setuptools must be at 3.3 or higher now. If you use the latest bootstrap fromhttp://downloads.buildout.org/2/bootstrap.pyyou’re all set. [reinout]Installingrecipesthat themselves have dependencies used to fail with a VersionConflict if such a dependency was installed globally with a lower version. Buildout now ignores the version conflict in those cases and simply installs the correct version. [reinout]2.2.4 (2014-11-01)Fix for #198: buildout 2.2.3 caused a version conflict when bootstrapping a buildout with a version pinned to an earlier one. Same version conflict could occur with system-wide installed packages that were newer than the pinned version. [reinout]2.2.3 (2014-10-30)Fix #197, Python 3 regression [aclark4life]2.2.2 (2014-10-30)Open files forexec()in universal newlines mode. Seehttps://github.com/buildout/buildout/issues/130AddBUILDOUT_HOMEas an alternate way to control how the user default configuration is found.Close various files when finished writing to them. This avoids ResourceWarnings on Python 3, and better supports doctests under PyPy.Introduce improved easy_install Install.install function. This is present in 1.5.X and 1.7X but was never merged into 2.X somehow.2.2.1 (2013-09-05)distutilsscripts: correct order of operations onfrom ... importlines (seehttps://github.com/buildout/buildout/issues/134).Add an--allow-site-packgesoption tobootstrap.py, defaulting to False. If the value is false, strip any “site packages” (as defined by thesitemodule) fromsys.pathbefore attempting to importsetuptools/pkg_resources.Updated the URL used to fetchez_setup.pyto the official, non-version- pinned version.2.2.0 (2013-07-05)Handle both addition and subtraction of elements (+= and -=) on the same key in the same section. Forward-ported from buildout 1.6.Suppress the uselessLink to <URL>***BLOCKED***by--allow-hostserror message being emitted by distribute / setuptools.Extend distutils script generation to support module docstrings and __future__ imports.Refactored picked versions logic to make it easier to use for plugins.Useget_win_launcherAPI to find Windows launcher (falling back toresource_stringforcli.exe).Removedata_filesfromsetup.py: it was installingREADME.txtin current directory during installation (merged from 1.x branch).Switch dependency fromdistribute 0.6.xtosetuptools 0.7.x.2.1.0 (2013-03-23)Meta-recipe supportConditional sectionsBuildout now accepts a--versioncommand-line option to print its version.Fixed: Builout didn’t exit with a non-zero exit status if there was afailure in combination with an upgrade.Fixed: We now fail with an informative error when an old bootstrapscript causes buildout 2 to be used with setuptools.Fixed: An error incorrectly suggested that buildout 2 implemented allof the functionality of dumppickedversions.Fixed: Buildout generated bad scripts when no eggs needed to be addedtosys.path.Fixed: Buildout didn’t honour Unix umask when generating scripts.https://bugs.launchpad.net/zc.buildout/+bug/180705Fixed:update-versions-filedidn’t work unlessshow-picked-versionswas also set.https://github.com/buildout/buildout/issues/712.0.1 (2013-02-16)Fixed: buildout didn’t honor umask settings when creating scripts.Fix for distutils scripts installation on Python 3, related to__pycache__directories.Fixed: encoding data in non-entry-point-based scripts was lost.
zc.buildout.languageserver
ALanguage Serverforzc.buildout.This language server is implemented usingpygls.InstallationStandaloneNeeds a python >= 3.8.python-mpipinstallzc.buildout.languageserverThen configure your editor to runbuildoutls( orpython3 -m buildoutls).From vscode extensionOn activation, the extension automatically installs the extension on the python configured in the extension preferences.The automatic installation does not seem to work with theia and the python egg has to be installed beforehand.FeaturesCompletions${complete sections.${section:completesection's options. Ifsectionuses a known recipe, dynamic options from the recipe are also completed.${buildout:extends}completes filenames.${buildout:parts}and<=option completes parts.Diagnosticsnon existant section and options in${section:option}references.required options not defined for a a few "known recipes".python package listed in[versions]with known vulnerabilitiesSymbolsSections and options are shown are displayed in outline as symbols.Links${buildout:extends}are links.Go to definitionsfrom${section:options}we can go to the location whereoptionis defined insection, or tosectionheader if it's not defined.from<= sectionwe can go tosection.from${buildout:extends}we can go to the extended profile.HoverHover on an option show the option value.Find referencesFind references of the current symbol. A bit simple, it only look for references and does not check if profiles reallyextendseach other. It does not look in templates either.Code actionsupdate a python package from[versions]to its latest version on pypicompute themd5sumof an urlTemplate support"current" buildout profile is guessed, then completions and diagnostics should work on any files.Jinja2 supportJinja syntax is syntax highlighted and jinja syntax markers are ignored when parsing buildout.SlapOS supportSlapOS instance buildout (ie. buildout generated by buildout) is understood,${and$${are treated separatly for completions and diagnostics.ChangelogAll notable changes to this project will be documented in this file.The format is based onKeep a Changelog, and this project adheres toSemantic Versioning.Unreleased0.12.0- 2023-10-08support python 3.12version up dependenciesFixedhover: fix crash when opening instance.cfg.in without opening a folder (by updating pygls)0.11.0- 2023-10-04Addedcode actions: support cancellation of md5sum commandFixedhover: fix crash when opening instance.cfg.in outside of workspace folder0.10.1- 2023-09-20Fixedrevert: code actions: support cancellation of md5sum command, this needs an unreleased pygls0.10.0- 2023-09-20Addedcode actions: support cancellation of md5sum commandreferences: support cancellation0.9.3- 2023-09-19Fixedserver: Fix crash when hover .cfg.in in gitlens viewsclient,server: update dependencies0.9.2- 2023-02-24Fixedserver: fixed definition ofpython_requires0.9.1- 2023-02-24Addedclient: version up dependencies0.9.0- 2023-01-01Addedupdate to pygls 1.00.8.3- 2022-11-06Fixedclient: revert to older vscode and vscode-languageclient dependenciesAddedserver: support more slapos recipes0.8.2- 2022-10-29Fixed:client: install with requirements.txt to install a fixed versionAdded:client: version up dependenciesserver: support python 3.110.8.1- 2022-07-03Fixed:code_actions: fix visit project on pypi when invoked from option keyaiohttp: don't set global timeout0.8.0- 2022-07-02Added:switch fromrequeststoaiohttp. Doing http requests asynchronously and in the case of pypi diagnostics, concurrently.diagnostic: lower severity of option redefined to same value to information leveldiagnostic: add hint level diagnostic for every redefined valuecli: new--log-pyglsflag to include pygls logs. By default they are not included.diagnostic: report unknown pypi projects or versionsFixed:pypi: fix a crash when unknown project is listed inversionsdiagnostic: don't emit false positives for profiles generated with jinjafix crash with empty${buildout:extends}0.7.1- 2022-05-08Added:recipe: support defining deprecated optionsrecipe: supportslapos.recipe.templateversion 0.5Fixed:recipe: fix some markdown syntax in recipe docs0.7.0- 2022-04-03Added:code actions: report progress when updating md5sumexpose commands to start & stop profiling.Fixed:significantly improve performance by implementing .copy() method and using an intermediate cache.fix crash when completing option made only of spacefix crash when completing after ${}0.6.2- 2022-01-06Fixed:fix a packaging mistake with the vscode extension0.6.1- 2022-01-04Fixed:fix problems with automatic publishing of packages0.6.0- 2022-01-04Added:diagnostic: report versions with known vulnerabilitiescode action: update a python package listed inversionsto latest versioncode action: view a python package page on pypicode action: compute md5sum of an urlRemovedsupport for python 3.6, minimal supported version is now 3.7Fixed:completions: don't offer completions in commentsfix performance issues by cancelling pending tasksactually the fix was wrong0.5.0- 2021-03-28Added:diagnostic: warn when options are redefining the current valuecompletions: complete existing options of current sectionsdiagnostic: support recipes with arbitrary options (like slapos.recipe.build)diagnostic: report error when existing non existant profilesFixed:stop emitting false positives diagnostics with multi line jinjastop emitting false positives diagnostics for missing sections/options when extending dynamic profilefixed "add line comment" action0.4.0- 2020-10-08Fixed:don't skip lines containing jinja expressions. This was causing some missing options when jinja was used in optiondiagnostic: tolerate unknown part when extends jinja0.3.0- 2020-02-23Added:support http URLs in${buildout:extends}0.2.1- 2020-04-25Fixedreferences: consider listing a section in${buildout:parts}as a reference.completions: usetextEditto properly overwrite exiting text.all: debounce protocol functions to accept cancellations.all: fix errors when opening profiles outside of workspace.0.2.0- 2020-02-12Added:support running with buildout < 2.9.3initial support ofinstance.cfgdefined usingslapos.recipe.template:jinja2Fixedfixed broken v0.1.1 release, it could not be installed from pypi.diagnostics: prevent "missing required options" false positive on sections used only as macros.diagnostic: Correctly analyze sections with.or-in their namesdiagnostic: Fix false positives on${buildout:parts}with extended sectionsdiagnostic: Fix false positives on${buildout:parts}when dynamically adding parts with jinja.0.1.1- 2020-01-30Addeddefinitions: paths from${buildout:extends}can also be opened with jump to definition.completions: fix insertText with-.diagnostics: detect missing non existant sections listed in${buildout:parts}.diagnostics: detect sections without recipe listed in${buildout:parts}.0.1.0 - 2020-01-04Initial Version
zc.buildoutsftp
The zc.buildoutsftp package provides a zc.buildout extension that provides support for SFTP. To use it, simply provide the option:extensions = zc.buildoutsftpin your buildout section. Then you can use sftp URLs for find-links or index URLs.An SFTP URL is similar to an FTP URL and is of the form:sftp://user:password@hostname:port/pathwhere the user name, password, and port are optional. Here are some examples:The following URL accesses the path /distribution on download.zope.org:sftp://download.zope.org/distributionThe following URL accesses the path /distribution on download.zope.org using the user id jim:sftp://[email protected]/distributionThe following URL accesses the path /distribution on download.zope.org using the user id jim and password 123:sftp://jim:[email protected]/distributionThe following url accesses the path /distribution on download.zope.org using an ssh server running on port 1022:sftp://download.zope.org:1022/distributionThe buildout extension actually installs a urllib2 handler for the “sftp” protocol. This handler is actually setuptools specific because it generates HTML directory listings, needed by setuptools and makes no effort to make directory listings useful for anything else. It is possible that, in the future, setuptools will provide it’s own extension mechanism for handling alternate protocols, in which case, we might bypass the urllib2 extension mechanism.SSH CompatibilityThe extension works with Open SSH on unix-based systems and PuTTY on Windows. Unless a password is given in the URL, private keys are contained from ssh agent (pagent on Windows).Status and Change HistoryThis package has been used for years on Linux and Mac OS X. The author doesn’t use it on Windows, but, presumably, other people do.0.11.0 (2013/08/01)Compatibility fix for setuptools 0.7 and later.0.10.0 (2013/05/22)Compatibility fix for paramiko 1.10.x0.9.0 (2012/09/13)Removed beta label.0.9.0b1 (2012/06/29)Added support for:Global-configuration settings.Global known-hosts files.Host-specific ssh keys.Added mock-based tests for unix-like systems. Unfortunately, these tests will fail for Windows and windows support, while present, is untested.0.6.1 (2010/03/17)Fixed documentation typo.0.6.0 (2009/06/22)Added an unload entry point. This is necessary so we don’t hang when the buildout process exits due to non-daemonic paramiko connection threads.0.5.0 (2008/12/08)Added connection pooling. This speeds up multiple downloads from the same server substantially.Adjust the paramiko logging level relative to the buildout logging level to make it less chatty.0.4.0 (2007/12/6)Now reads user definitions from ~/.ssh/config, if possible.0.3.2 (2007/03/22)Fixed a serious bug that caused files to be downloaded incompletely.0.3.1 (2007/03/22)Fixed a serious bug that caused files read to be truncated to 0 bytes.0.3 (2007/03/22)Added debug logging to help diagnose problems.Close transports after use to prevent leakage.0.2.2Fixed a bug in handling multiple host keys for a given host.0.2.1Fixed a bug in handling multiple user keys.0.2Added missing entry point.Adjusted content-type information to work with setuptools.0.1Initial release
zcc
UNKNOWN
zc.cacheheaders
UNKNOWN
zc.catalog
zc.catalog is an extension to the Zope 3 catalog, Zope 3’s indexing and search facility. zc.catalog contains a number of extensions to the Zope 3 catalog, such as some new indexes, improved globbing and stemming support, and an alternative catalog implementation.ContentsCHANGES3.0 (2019-03-21)2.0.1 (2017-06-15)2.0.0 (2017-05-09)1.6 (2013-07-04)1.5.1 (2012-01-20)1.5 (2010-10-19)1.4.5 (2010-10-05)1.4.4 (2010-07-06)1.4.3 (2010-03-09)1.4.2 (2010-01-20)1.4.1 (2009-02-27)1.4.0 (2009-02-07)1.3.0 (2008-09-10)1.2.0 (2007-11-03)1.1.1 (2007-3-17)1.1 (2007-01-06)1.0 (2007-01-05)0.2 (2006-11-22)Value IndexSorting Value IndexesSet IndexNormalized IndexSortingExtent CatalogCatalog with a filter extentSelf-populating extentsStemmerSupport for legacy dataGlobberCallable Wrapperzc.catalog Browser SupportSetIndexValueIndexCHANGES3.0 (2019-03-21)Drop support for Python 3.4 as it reached its end of life.Add support for Python 3.7 and 3.8a2.2.0.1 (2017-06-15)Add Python 3 compatibility for thezopyx.txng3.extstemmer. See#4.2.0.0 (2017-05-09)Add support for Python 3.4, 3.5, 3.6 and PyPy. Note that thezopyx.txng3.extstemmer is not available on Python 3.Remove test dependency on zope.app.zcmlfiles and zope.app.testing, among others.1.6 (2013-07-04)Using Python’sdoctestmodule instead of deprecatedzope.testing.doctest.Movezope.intidto dependencies.1.5.1 (2012-01-20)Fix the extent catalog’ssearchResultsmethod to work when using a local uid source.Replaced a testing dependency onzope.app.authenticationwithzope.password.Removedzope.app.servertest dependency.1.5 (2010-10-19)The package’sconfigure.zcmldoes not include the browser subpackage’sconfigure.zcmlanymore.This, together withbrowserandtest_browserextras_require, decouples the browser view registrations from the main code. As a result projects that do not need the ZMI views to be registered are not pulling in the zope.app.* dependencies anymore.To enable the ZMI views for your project, you will have to do two things:listzc.catalog [browser]as ainstall_requires.have your project’sconfigure.zcmlinclude thezc.catalog.browsersubpackage.Only include the browser tests whenever the dependencies for the browser tests are available.Python2.7 test fix.1.4.5 (2010-10-05)Remove implicit test dependency on zope.app.dublincore, that was not needed in the first place.1.4.4 (2010-07-06)Fixed test-failure happening with more recentmechanize(>=2.0).1.4.3 (2010-03-09)Try to import the stemmer from the zopyx.txng3.ext package first, which as of 3.3.2 contains stability and memory leak fixes.1.4.2 (2010-01-20)Fix missing testing dependencies when using ZTK by adding zope.login.1.4.1 (2009-02-27)Add FieldIndex-like sorting support for the ValueIndex.Add sorting indexes support for the NormalizationWrapper.1.4.0 (2009-02-07)Fixed a typo in ValueIndex addform and addMenuItemUsezope.containerinstead ofzope.app.container.Usezope.keyreferenceinstead ofzope.app.keyreference.Usezope.intidinstead ofzope.app.intid.Usezope.cataloginstead ofzope.app.catalog.1.3.0 (2008-09-10)Added hook point to allow extent catalog to be used with local UID sources.1.2.0 (2007-11-03)Updated package meta-data.zc.catalog now can use 64-bit BTrees (“L”) as provided by ZODB 3.8.Albertas Agejavas ([email protected]) included the new CallableWrapper, for when the typical Zope 3 index-by-adapter story (zope.app.catalog.attribute) is unnecessary trouble, and you just want to use a callable. See callablewrapper.txt. This can also be used for other indexes based on the zope.index interfaces.Extents now have a __len__. The current implementation defers to the standard BTree len implementation, and shares its performance characteristics: it needs to wake up all of the buckets, but if all of the buckets are awake it is a fairly quick operation.A simple ISelfPoulatingExtent was added to the extentcatalog module for which populating is a no-op. This is directly useful for catalogs that are used as implementation details of a component, in which objects are indexed explicitly by your own calls rather than by the usual subscribers. It is also potentially slightly useful as a base for other self-populating extents.1.1.1 (2007-3-17)‘all_of’ would return all results when one of the values had no results. Reported, with test and fix provided, by Nando Quintana.1.1 (2007-01-06)Features removedThe queueing of events in the extent catalog has been entirely removed. Subtransactions caused significant problems to the code introduced in 1.0. Other solutions also have significant problems, and the win of this kind of queueing is qustionable. Here is a run down of the approaches rejected for getting the queueing to work:_p_invalidate (used in 1.0). Not really designed for use within a transaction, and reverts to last savepoint, rather than the beginning of the transaction. Could monkeypatch savepoints to iterate over precommit transaction hooks but that just smells too bad._p_resolveConflict. Requires application software to exist in ZEO and even ZRS installations, which is counter to our software deployment goals. Also causes useless repeated writes of empty queue to database, but that’s not the showstopper.vague hand-wavy ideas for separate storages or transaction managers for the queue. Never panned out in discussion.1.0 (2007-01-05)Bugs fixedadjusted extentcatalog tests to trigger (and discuss and test) the queueing behavior.fixed problem with excessive conflict errors due to queueing code.updated stemming to work with newest version of TextIndexNG’s extensions.omitted stemming test when TextIndexNG’s extensions are unavailable, so tests pass without it. Since TextIndexNG’s extensions are optional, this seems reasonable.removed use of zapi in extentcatalog.0.2 (2006-11-22)Features addedFirst release on Cheeseshop.Value IndexThe valueindex is an index similar to, but more flexible than a standard Zope field index. The index allows searches for documents that contain any of a set of values; between a set of values; any (non-None) values; and any empty values.Additionally, the index supports an interface that allows examination of the indexed values.It is as policy-free as possible, and is intended to be the engine for indexes with more policy, as well as being useful itself.On creation, the index has no wordCount, no documentCount, and is, as expected, fairly empty.>>> from zc.catalog.index import ValueIndex >>> index = ValueIndex() >>> index.documentCount() 0 >>> index.wordCount() 0 >>> index.maxValue() # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:... >>> index.minValue() # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:... >>> list(index.values()) [] >>> len(index.apply({'any_of': (5,)})) 0The index supports indexing any value. All values within a given index must sort consistently across Python versions.>>> data = {1: 'a', ... 2: 'b', ... 3: 'a', ... 4: 'c', ... 5: 'd', ... 6: 'c', ... 7: 'c', ... 8: 'b', ... 9: 'c', ... } >>> for k, v in data.items(): ... index.index_doc(k, v) ...After indexing, the statistics and values match the newly entered content.>>> list(index.values()) ['a', 'b', 'c', 'd'] >>> index.documentCount() 9 >>> index.wordCount() 4 >>> index.maxValue() 'd' >>> index.minValue() 'a' >>> list(index.ids()) [1, 2, 3, 4, 5, 6, 7, 8, 9]The index supports four types of query. The first is ‘any_of’. It takes an iterable of values, and returns an iterable of document ids that contain any of the values. The results are not weighted.>>> list(index.apply({'any_of': ('b', 'c')})) [2, 4, 6, 7, 8, 9] >>> list(index.apply({'any_of': ('b',)})) [2, 8] >>> list(index.apply({'any_of': ('d',)})) [5] >>> bool(index.apply({'any_of': (42,)})) FalseAnother query is ‘any’, If the key is None, all indexed document ids with any values are returned. If the key is an extent, the intersection of the extent and all document ids with any values is returned.>>> list(index.apply({'any': None})) [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> from zc.catalog.extentcatalog import FilterExtent >>> extent = FilterExtent(lambda extent, uid, obj: True) >>> for i in range(15): ... extent.add(i, i) ... >>> list(index.apply({'any': extent})) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> limited_extent = FilterExtent(lambda extent, uid, obj: True) >>> for i in range(5): ... limited_extent.add(i, i) ... >>> list(index.apply({'any': limited_extent})) [1, 2, 3, 4]The ‘between’ argument takes from 1 to four values. The first is the minimum, and defaults to None, indicating no minimum; the second is the maximum, and defaults to None, indicating no maximum; the next is a boolean for whether the minimum value should be excluded, and defaults to False; and the last is a boolean for whether the maximum value should be excluded, and also defaults to False. The results are not weighted.>>> list(index.apply({'between': ('b', 'd')})) [2, 4, 5, 6, 7, 8, 9] >>> list(index.apply({'between': ('c', None)})) [4, 5, 6, 7, 9] >>> list(index.apply({'between': ('c',)})) [4, 5, 6, 7, 9] >>> list(index.apply({'between': ('b', 'd', True, True)})) [4, 6, 7, 9]Using an invalid (non-comparable on Python 3) argument to between produces nothing:>>> list(index.apply({'between': (1, 5)})) []The ‘none’ argument takes an extent and returns the ids in the extent that are not indexed; it is intended to be used to return docids that have no (or empty) values.>>> list(index.apply({'none': extent})) [0, 10, 11, 12, 13, 14]Trying to use more than one of these at a time generates an error.>>> index.apply({'between': (5,), 'any_of': (3,)}) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:...Using none of them simply returns None.>>> index.apply({}) # returns NoneInvalid query names cause ValueErrors.>>> index.apply({'foo': ()}) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:...When you unindex a document, the searches and statistics should be updated.>>> index.unindex_doc(5) >>> len(index.apply({'any_of': ('d',)})) 0 >>> index.documentCount() 8 >>> index.wordCount() 3 >>> list(index.values()) ['a', 'b', 'c'] >>> list(index.ids()) [1, 2, 3, 4, 6, 7, 8, 9]Reindexing a document that has a changed value also is reflected in subsequent searches and statistic checks.>>> list(index.apply({'any_of': ('b',)})) [2, 8] >>> data[8] = 'e' >>> index.index_doc(8, data[8]) >>> index.documentCount() 8 >>> index.wordCount() 4 >>> list(index.apply({'any_of': ('e',)})) [8] >>> list(index.apply({'any_of': ('b',)})) [2] >>> data[2] = 'e' >>> index.index_doc(2, data[2]) >>> index.documentCount() 8 >>> index.wordCount() 3 >>> list(index.apply({'any_of': ('e',)})) [2, 8] >>> list(index.apply({'any_of': ('b',)})) []Reindexing a document for which the value is now None causes it to be removed from the statistics.>>> data[3] = None >>> index.index_doc(3, data[3]) >>> index.documentCount() 7 >>> index.wordCount() 3 >>> list(index.ids()) [1, 2, 4, 6, 7, 8, 9]This affects both ways of determining the ids that are and are not in the index (that do and do not have values).>>> list(index.apply({'any': None})) [1, 2, 4, 6, 7, 8, 9] >>> list(index.apply({'any': extent})) [1, 2, 4, 6, 7, 8, 9] >>> list(index.apply({'none': extent})) [0, 3, 5, 10, 11, 12, 13, 14]The values method can be used to examine the indexed values for a given document id. For a valueindex, the “values” for a given doc_id will always have a length of 0 or 1.>>> index.values(doc_id=8) ('e',)And the containsValue method provides a way of determining membership in the values.>>> index.containsValue('a') True >>> index.containsValue('q') FalseSorting Value IndexesValue indexes supports sorting, just like zope.index.field.FieldIndex.>>> index.clear()>>> index.index_doc(1, 9) >>> index.index_doc(2, 8) >>> index.index_doc(3, 7) >>> index.index_doc(4, 6) >>> index.index_doc(5, 5) >>> index.index_doc(6, 4) >>> index.index_doc(7, 3) >>> index.index_doc(8, 2) >>> index.index_doc(9, 1)>>> list(index.sort([4, 2, 9, 7, 3, 1, 5])) [9, 7, 5, 4, 3, 2, 1]We can also specify thereverseargument to reverse results:>>> list(index.sort([4, 2, 9, 7, 3, 1, 5], reverse=True)) [1, 2, 3, 4, 5, 7, 9]And as per IIndexSort, we can limit results by specifying thelimitargument:>>> list(index.sort([4, 2, 9, 7, 3, 1, 5], limit=3)) [9, 7, 5]If we pass an id that is not indexed by this index, it won’t be included in the result.>>> list(index.sort([2, 10])) [2]Set IndexThe setindex is an index similar to, but more general than a traditional keyword index. The values indexed are expected to be iterables; the index allows searches for documents that contain any of a set of values; all of a set of values; or between a set of values.Additionally, the index supports an interface that allows examination of the indexed values.It is as policy-free as possible, and is intended to be the engine for indexes with more policy, as well as being useful itself.On creation, the index has no wordCount, no documentCount, and is, as expected, fairly empty.>>> from zc.catalog.index import SetIndex >>> index = SetIndex() >>> index.documentCount() 0 >>> index.wordCount() 0 >>> index.maxValue() # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:... >>> index.minValue() # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:... >>> list(index.values()) [] >>> len(index.apply({'any_of': (5,)})) 0The index supports indexing any value. All values within a given index must sort consistently across Python versions. In practice, in Python 3 this means that the values need to be homogeneous.>>> data = {1: ['a', '1'], ... 2: ['b', 'a', '3', '4', '7'], ... 3: ['1'], ... 4: ['1', '4', 'c'], ... 5: ['7'], ... 6: ['5', '6', '7'], ... 7: ['c'], ... 8: ['1', '6'], ... 9: ['a', 'c', '2', '3', '4', '6',], ... } >>> for k, v in data.items(): ... index.index_doc(k, v) ...After indexing, the statistics and values match the newly entered content.>>> list(index.values()) ['1', '2', '3', '4', '5', '6', '7', 'a', 'b', 'c'] >>> index.documentCount() 9 >>> index.wordCount() 10 >>> index.maxValue() 'c' >>> index.minValue() '1' >>> list(index.ids()) [1, 2, 3, 4, 5, 6, 7, 8, 9]The index supports five types of query. The first is ‘any_of’. It takes an iterable of values, and returns an iterable of document ids that contain any of the values. The results are weighted.>>> list(index.apply({'any_of': ('b', '1', '5')})) [1, 2, 3, 4, 6, 8] >>> list(index.apply({'any_of': ('b', '1', '5')})) [1, 2, 3, 4, 6, 8] >>> list(index.apply({'any_of': ('42',)})) [] >>> index.apply({'any_of': ('a', '3', '7')}) # doctest: +ELLIPSIS BTrees...FBucket([(1, 1.0), (2, 3.0), (5, 1.0), (6, 1.0), (9, 2.0)])Using an invalid (non-comparable on Python 3) argument is ignored:>>> list(index.apply({'any_of': (1,)})) [] >>> list(index.apply({'any_of': (1, '1')})) [1, 3, 4, 8]Another query is ‘any’. If the key is None, all indexed document ids with any values are returned. If the key is an extent, the intersection of the extent and all document ids with any values is returned.>>> list(index.apply({'any': None})) [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> from zc.catalog.extentcatalog import FilterExtent >>> extent = FilterExtent(lambda extent, uid, obj: True) >>> for i in range(15): ... extent.add(i, i) ... >>> list(index.apply({'any': extent})) [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> limited_extent = FilterExtent(lambda extent, uid, obj: True) >>> for i in range(5): ... limited_extent.add(i, i) ... >>> list(index.apply({'any': limited_extent})) [1, 2, 3, 4]The ‘all_of’ argument also takes an iterable of values, but returns an iterable of document ids that contains all of the values. The results are not weighted.>>> list(index.apply({'all_of': ('a',)})) [1, 2, 9] >>> list(index.apply({'all_of': ('3', '4')})) [2, 9] >>> list(index.apply({'all_of': (3, '4')})) [] >>> list(index.apply({'all_of': ('3', 4)})) []These tests illustrate two related reported errors that have been fixed.>>> list(index.apply({'all_of': ('z', '3', '4')})) [] >>> list(index.apply({'all_of': ('3', '4', 'z')})) []The ‘between’ argument takes from 1 to four values. The first is the minimum, and defaults to None, indicating no minimum; the second is the maximum, and defaults to None, indicating no maximum; the next is a boolean for whether the minimum value should be excluded, and defaults to False; and the last is a boolean for whether the maximum value should be excluded, and also defaults to False. The results are weighted.>>> list(index.apply({'between': ('1', '7')})) [1, 2, 3, 4, 5, 6, 8, 9] >>> list(index.apply({'between': ('b', None)})) [2, 4, 7, 9] >>> list(index.apply({'between': ('b',)})) [2, 4, 7, 9] >>> list(index.apply({'between': ('1', '7', True, True)})) [2, 4, 6, 8, 9] >>> index.apply({'between': ('2', '6')}) # doctest: +ELLIPSIS BTrees...FBucket([(2, 2.0), (4, 1.0), (6, 2.0), (8, 1.0), (9, 4.0)])Using invalid (non-comparable on Python 3) arguments produces no results:>>> list(index.apply({'between': (1, 7)})) []The ‘none’ argument takes an extent and returns the ids in the extent that are not indexed; it is intended to be used to return docids that have no (or empty) values.>>> list(index.apply({'none': extent})) [0, 10, 11, 12, 13, 14]Trying to use more than one of these at a time generates an error.>>> index.apply({'all_of': ('5',), 'any_of': ('3',)}) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:...Using none of them simply returns None.>>> index.apply({}) # returns NoneInvalid query names cause ValueErrors.>>> index.apply({'foo': ()}) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError:...When you unindex a document, the searches and statistics should be updated.>>> index.unindex_doc(6) >>> len(index.apply({'any_of': ('5',)})) 0 >>> index.documentCount() 8 >>> index.wordCount() 9 >>> list(index.values()) ['1', '2', '3', '4', '6', '7', 'a', 'b', 'c'] >>> list(index.ids()) [1, 2, 3, 4, 5, 7, 8, 9]Reindexing a document that has new additional values also is reflected in subsequent searches and statistic checks.>>> data[8].extend(['5', 'c']) >>> index.index_doc(8, data[8]) >>> index.documentCount() 8 >>> index.wordCount() 10 >>> list(index.apply({'any_of': ('5',)})) [8] >>> list(index.apply({'any_of': ('c',)})) [4, 7, 8, 9]The same is true for reindexing a document with both additions and removals.>>> 2 in set(index.apply({'any_of': ('7',)})) True >>> 2 in set(index.apply({'any_of': ('2',)})) False >>> data[2].pop() '7' >>> data[2].append('2') >>> index.index_doc(2, data[2]) >>> 2 in set(index.apply({'any_of': ('7',)})) False >>> 2 in set(index.apply({'any_of': ('2',)})) TrueReindexing a document that no longer has any values causes it to be removed from the statistics.>>> del data[2][:] >>> index.index_doc(2, data[2]) >>> index.documentCount() 7 >>> index.wordCount() 9 >>> list(index.ids()) [1, 3, 4, 5, 7, 8, 9]This affects both ways of determining the ids that are and are not in the index (that do and do not have values).>>> list(index.apply({'any': None})) [1, 3, 4, 5, 7, 8, 9] >>> list(index.apply({'none': extent})) [0, 2, 6, 10, 11, 12, 13, 14]The values method can be used to examine the indexed values for a given document id.>>> set(index.values(doc_id=8)) == set(['1', '5', '6', 'c']) TrueAnd the containsValue method provides a way of determining membership in the values.>>> index.containsValue('5') True >>> index.containsValue(5) False >>> index.containsValue('20') FalseNormalized IndexThe index module provides a normalizing wrapper, a DateTime normalizer, and a set index and a value index normalized with the DateTime normalizer.The normalizing wrapper implements a full complement of index interfaces– zope.index.interfaces.IInjection, zope.index.interfaces.IIndexSearch, zope.index.interfaces.IStatistics, and zc.catalog.interfaces.IIndexValues– and delegates all of the behavior to the wrapped index, normalizing values using the normalizer before the index sees them.The normalizing wrapper currently only supports queries offered by zc.catalog.interfaces.ISetIndex and zc.catalog.interfaces.IValueIndex.The normalizer interface requires the following methods, as defined in the interface:def value(value):“””normalize or check constraints for an input value; raise an error or return the value to be indexed.”””def any(value, index):“””normalize a query value for a “any_of” search; return a sequence of values.”””def all(value, index):“””Normalize a query value for an “all_of” search; return the value for query”””def minimum(value, index):“””normalize a query value for minimum of a range; return the value for query”””def maximum(value, index):“””normalize a query value for maximum of a range; return the value for query”””The DateTime normalizer performs the following normalizations and validations. Whenever a timezone is needed, it tries to get a request from the current interaction and adapt it to zope.interface.common.idatetime.ITZInfo; failing that (no request or no adapter) it uses the system local timezone.input values must be datetimes with a timezone. They are normalized to the resolution specified when the normalizer is created: a resolution of 0 normalizes values to days; a resolution of 1 to hours; 2 to minutes; 3 to seconds; and 4 to microseconds.‘any’ values may be timezone-aware datetimes, timezone-naive datetimes, or dates. dates are converted to any value from the start to the end of the given date in the found timezone, as described above. timezone-naive datetimes get the found timezone.‘all’ values may be timezone-aware datetimes or timezone-naive datetimes. timezone-naive datetimes get the found timezone.‘minimum’ values may be timezone-aware datetimes, timezone-naive datetimes, or dates. dates are converted to the start of the given date in the found timezone, as described above. timezone-naive datetimes get the found timezone.‘maximum’ values may be timezone-aware datetimes, timezone-naive datetimes, or dates. dates are converted to the end of the given date in the found timezone, as described above. timezone-naive datetimes get the found timezone.Let’s look at the DateTime normalizer first, and then an integration of it with the normalizing wrapper and the value and set indexes.The indexed values are parsed with ‘value’.>>> from zc.catalog.index import DateTimeNormalizer >>> n = DateTimeNormalizer() # defaults to minutes >>> import datetime >>> import pytz >>> naive_datetime = datetime.datetime(2005, 7, 15, 11, 21, 32, 104) >>> date = naive_datetime.date() >>> aware_datetime = naive_datetime.replace( ... tzinfo=pytz.timezone('US/Eastern')) >>> n.value(naive_datetime) Traceback (most recent call last): ... ValueError: This index only indexes timezone-aware datetimes. >>> n.value(date) Traceback (most recent call last): ... ValueError: This index only indexes timezone-aware datetimes. >>> n.value(aware_datetime) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, tzinfo=<DstTzInfo 'US/Eastern'...>)If we specify a different resolution, the results are different.>>> another = DateTimeNormalizer(1) # hours >>> another.value(aware_datetime) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 0, tzinfo=<DstTzInfo 'US/Eastern'...>)Note that changing the resolution of an indexed value may create surprising results, because queries do not change their resolution. Therefore, if you index something with a datetime with a finer resolution that the normalizer’s, then searching for that datetime will not find the doc_id.Values in an ‘any_of’ query are parsed with ‘any’. ‘any’ should return a sequence of values. It requires an index, which we will mock up here.>>> class DummyIndex(object): ... def values(self, start, stop, exclude_start, exclude_stop): ... assert not exclude_start and exclude_stop ... six_hours = datetime.timedelta(hours=6) ... res = [] ... dt = start ... while dt < stop: ... res.append(dt) ... dt += six_hours ... return res ... >>> index = DummyIndex() >>> tuple(n.any(naive_datetime, index)) # doctest: +ELLIPSIS (datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Local...>),) >>> tuple(n.any(aware_datetime, index)) # doctest: +ELLIPSIS (datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Eastern...>),) >>> tuple(n.any(date, index)) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS (datetime.datetime(2005, 7, 15, 0, 0, tzinfo=<...Local...>), datetime.datetime(2005, 7, 15, 6, 0, tzinfo=<...Local...>), datetime.datetime(2005, 7, 15, 12, 0, tzinfo=<...Local...>), datetime.datetime(2005, 7, 15, 18, 0, tzinfo=<...Local...>))Values in an ‘all_of’ query are parsed with ‘all’.>>> n.all(naive_datetime, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Local...>) >>> n.all(aware_datetime, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Eastern...>) >>> n.all(date, index) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...Minimum values in a ‘between’ query as well as those in other methods are parsed with ‘minimum’. They also take an optional exclude boolean, which indicates whether the minimum is to be excluded. For datetimes, it only makes a difference if you pass in a date.>>> n.minimum(naive_datetime, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Local...>) >>> n.minimum(naive_datetime, index, exclude=True) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Local...>)>>> n.minimum(aware_datetime, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Eastern...>) >>> n.minimum(aware_datetime, index, True) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Eastern...>)>>> n.minimum(date, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 0, 0, tzinfo=<...Local...>) >>> n.minimum(date, index, True) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 23, 59, 59, 999999, tzinfo=<...Local...>)Maximum values in a ‘between’ query as well as those in other methods are parsed with ‘maximum’. They also take an optional exclude boolean, which indicates whether the maximum is to be excluded. For datetimes, it only makes a difference if you pass in a date.>>> n.maximum(naive_datetime, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Local...>) >>> n.maximum(naive_datetime, index, exclude=True) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Local...>)>>> n.maximum(aware_datetime, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Eastern...>) >>> n.maximum(aware_datetime, index, True) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, 32, 104, tzinfo=<...Eastern...>)>>> n.maximum(date, index) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 23, 59, 59, 999999, tzinfo=<...Local...>) >>> n.maximum(date, index, True) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 0, 0, tzinfo=<...Local...>)Now let’s examine these normalizers in the context of a real index.>>> from zc.catalog.index import DateTimeValueIndex, DateTimeSetIndex >>> setindex = DateTimeSetIndex() # minutes resolution >>> data = [] # generate some data >>> def date_gen( ... start=aware_datetime, ... count=12, ... period=datetime.timedelta(hours=10)): ... dt = start ... ix = 0 ... while ix < count: ... yield dt ... dt += period ... ix += 1 ... >>> gen = date_gen() >>> count = 0 >>> while True: ... try: ... next_ = [next(gen) for i in range(6)] ... except StopIteration: ... break ... data.append((count, next_[0:1])) ... count += 1 ... data.append((count, next_[1:3])) ... count += 1 ... data.append((count, next_[3:6])) ... count += 1 ... >>> print(data) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE [(0, [datetime.datetime(2005, 7, 15, 11, 21, 32, 104, ...<...Eastern...>)]), (1, [datetime.datetime(2005, 7, 15, 21, 21, 32, 104, ...<...Eastern...>), datetime.datetime(2005, 7, 16, 7, 21, 32, 104, ...<...Eastern...>)]), (2, [datetime.datetime(2005, 7, 16, 17, 21, 32, 104, ...<...Eastern...>), datetime.datetime(2005, 7, 17, 3, 21, 32, 104, ...<...Eastern...>), datetime.datetime(2005, 7, 17, 13, 21, 32, 104, ...<...Eastern...>)]), (3, [datetime.datetime(2005, 7, 17, 23, 21, 32, 104, ...<...Eastern...>)]), (4, [datetime.datetime(2005, 7, 18, 9, 21, 32, 104, ...<...Eastern...>), datetime.datetime(2005, 7, 18, 19, 21, 32, 104, ...<...Eastern...>)]), (5, [datetime.datetime(2005, 7, 19, 5, 21, 32, 104, ...<...Eastern...>), datetime.datetime(2005, 7, 19, 15, 21, 32, 104, ...<...Eastern...>), datetime.datetime(2005, 7, 20, 1, 21, 32, 104, ...<...Eastern...>)])] >>> data_dict = dict(data) >>> for doc_id, value in data: ... setindex.index_doc(doc_id, value) ... >>> list(setindex.ids()) [0, 1, 2, 3, 4, 5] >>> set(setindex.values()) == set( ... setindex.normalizer.value(v) for v in date_gen()) TrueFor the searches, we will actually use a request and interaction, with an adapter that returns the Eastern timezone. This makes the examples less dependent on the machine that they use.>>> import zope.security.management >>> import zope.publisher.browser >>> import zope.interface.common.idatetime >>> import zope.publisher.interfaces >>> request = zope.publisher.browser.TestRequest() >>> zope.security.management.newInteraction(request) >>> from zope import interface, component >>> @interface.implementer(zope.interface.common.idatetime.ITZInfo) ... @component.adapter(zope.publisher.interfaces.IRequest) ... def tzinfo(req): ... return pytz.timezone('US/Eastern') ... >>> component.provideAdapter(tzinfo) >>> n.all(naive_datetime, index).tzinfo is pytz.timezone('US/Eastern') True>>> set(setindex.apply({'any_of': (datetime.date(2005, 7, 17), ... datetime.date(2005, 7, 20), ... datetime.date(2005, 12, 31))})) == set( ... (2, 3, 5)) TrueNote that this search is using the normalized values.>>> set(setindex.apply({'all_of': ( ... datetime.datetime( ... 2005, 7, 16, 7, 21, tzinfo=pytz.timezone('US/Eastern')), ... datetime.datetime( ... 2005, 7, 15, 21, 21, tzinfo=pytz.timezone('US/Eastern')),)}) ... ) == set((1,)) True >>> list(setindex.apply({'any': None})) [0, 1, 2, 3, 4, 5] >>> set(setindex.apply({'between': ( ... datetime.datetime(2005, 4, 1, 12), datetime.datetime(2006, 5, 1))}) ... ) == set((0, 1, 2, 3, 4, 5)) True >>> set(setindex.apply({'between': ( ... datetime.datetime(2005, 4, 1, 12), datetime.datetime(2006, 5, 1), ... True, True)}) ... ) == set((0, 1, 2, 3, 4, 5)) True‘between’ searches should deal with dates well.>>> set(setindex.apply({'between': ( ... datetime.date(2005, 7, 16), datetime.date(2005, 7, 17))}) ... ) == set((1, 2, 3)) True >>> len(setindex.apply({'between': ( ... datetime.date(2005, 7, 16), datetime.date(2005, 7, 17))}) ... ) == len(setindex.apply({'between': ( ... datetime.date(2005, 7, 15), datetime.date(2005, 7, 18), ... True, True)}) ... ) TrueRemoving docs works as usual.>>> setindex.unindex_doc(1) >>> list(setindex.ids()) [0, 2, 3, 4, 5]Value, Minvalue and Maxvalue can take timezone-less datetimes and dates.>>> setindex.minValue() # doctest: +ELLIPSIS datetime.datetime(2005, 7, 15, 11, 21, ...<...Eastern...>) >>> setindex.minValue(datetime.date(2005, 7, 17)) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 17, 3, 21, ...<...Eastern...>)>>> setindex.maxValue() # doctest: +ELLIPSIS datetime.datetime(2005, 7, 20, 1, 21, ...<...Eastern...>) >>> setindex.maxValue(datetime.date(2005, 7, 17)) # doctest: +ELLIPSIS datetime.datetime(2005, 7, 17, 23, 21, ...<...Eastern...>)>>> list(setindex.values( ... datetime.date(2005, 7, 17), datetime.date(2005, 7, 17))) ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE [datetime.datetime(2005, 7, 17, 3, 21, ...<...Eastern...>), datetime.datetime(2005, 7, 17, 13, 21, ...<...Eastern...>), datetime.datetime(2005, 7, 17, 23, 21, ...<...Eastern...>)]>>> zope.security.management.endInteraction() # TODO put in tests tearDownSortingThe normalization wrapper provides the zope.index.interfaces.IIndexSort interface if its upstream index provides it. For example, the DateTimeValueIndex will provide IIndexSort, because ValueIndex provides sorting. It will also delegate thesortmethod to the value index.>>> from zc.catalog.index import DateTimeValueIndex >>> from zope.index.interfaces import IIndexSort>>> ix = DateTimeValueIndex() >>> IIndexSort.providedBy(ix.index) True >>> IIndexSort.providedBy(ix) True >>> ix.sort.__self__ is ix.index TrueBut it won’t work for indexes that doesn’t do sorting, for example DateTimeSetIndex.>>> ix = DateTimeSetIndex() >>> IIndexSort.providedBy(ix.index) False >>> IIndexSort.providedBy(ix) False >>> ix.sort Traceback (most recent call last): ... AttributeError: 'SetIndex' object has no attribute 'sort'Extent CatalogAn extent catalog is very similar to a normal catalog except that it only indexes items addable to its extent. The extent is both a filter and a set that may be merged with other result sets. The filtering is an additional feature we will discuss below; we’ll begin with a simple “do nothing” extent that only supports the second use case.We create the state that the text needs here.>>> import zope.keyreference.persistent >>> import zope.component >>> import zope.intid >>> import zope.component >>> import zope.interface.interfaces >>> import zope.component.persistentregistry >>> from ZODB.MappingStorage import DB >>> import transaction>>> zope.component.provideAdapter( ... zope.keyreference.persistent.KeyReferenceToPersistent, ... adapts=(zope.interface.Interface,)) >>> zope.component.provideAdapter( ... zope.keyreference.persistent.connectionOfPersistent, ... adapts=(zope.interface.Interface,))>>> site_manager = None >>> def getSiteManager(context=None): ... if context is None: ... if site_manager is None: ... return zope.component.getGlobalSiteManager() ... else: ... return site_manager ... else: ... try: ... return zope.interface.interfaces.IComponentLookup(context) ... except TypeError as error: ... raise zope.component.ComponentLookupError(*error.args) ... >>> def setSiteManager(sm): ... global site_manager ... site_manager = sm ... if sm is None: ... zope.component.getSiteManager.reset() ... else: ... zope.component.getSiteManager.sethook(getSiteManager) ... >>> def makeRoot(): ... db = DB() ... conn = db.open() ... root = conn.root() ... site_manager = root['components'] = ( ... zope.component.persistentregistry.PersistentComponents()) ... site_manager.__bases__ = (zope.component.getGlobalSiteManager(),) ... site_manager.registerUtility( ... zope.intid.IntIds(family=btrees_family), ... provided=zope.intid.interfaces.IIntIds) ... setSiteManager(site_manager) ... transaction.commit() ... return root ...>>> @zope.component.adapter(zope.interface.Interface) ... @zope.interface.implementer(zope.interface.interfaces.IComponentLookup) ... def getComponentLookup(obj): ... return obj._p_jar.root()['components'] ... >>> zope.component.provideAdapter(getComponentLookup)To show the extent catalog at work, we need an intid utility, an index, some items to index. We’ll do this within a real ZODB and a real intid utility.>>> import zc.catalog >>> import zc.catalog.interfaces >>> from zc.catalog import interfaces, extentcatalog >>> from zope import interface, component >>> from zope.interface import verify >>> import persistent >>> import BTrees.IFBTree>>> root = makeRoot() >>> intid = zope.component.getUtility( ... zope.intid.interfaces.IIntIds, context=root) >>> TreeSet = btrees_family.IF.TreeSet>>> from zope.container.interfaces import IContained >>> @interface.implementer(IContained) ... class DummyIndex(persistent.Persistent): ... __parent__ = __name__ = None ... def __init__(self): ... self.uids = TreeSet() ... def unindex_doc(self, uid): ... if uid in self.uids: ... self.uids.remove(uid) ... def index_doc(self, uid, obj): ... self.uids.insert(uid) ... def clear(self): ... self.uids.clear() ... def apply(self, query): ... return [uid for uid in self.uids if uid <= query] ... >>> class DummyContent(persistent.Persistent): ... def __init__(self, name, parent): ... self.id = name ... self.__parent__ = parent ...>>> extent = extentcatalog.Extent(family=btrees_family) >>> verify.verifyObject(interfaces.IExtent, extent) True >>> root['catalog'] = catalog = extentcatalog.Catalog(extent) >>> verify.verifyObject(interfaces.IExtentCatalog, catalog) True >>> index = DummyIndex() >>> catalog['index'] = index >>> transaction.commit()Now we have a catalog set up with an index and an extent. We can add some data to the extent:>>> matches = [] >>> for i in range(100): ... c = DummyContent(i, root) ... root[i] = c ... doc_id = intid.register(c) ... catalog.index_doc(doc_id, c) ... matches.append(doc_id) >>> matches.sort() >>> sorted(extent) == sorted(index.uids) == matches TrueWe can get the size of the extent.>>> len(extent) 100Unindexing an object that is in the catalog should simply remove it from the catalog and index as usual.>>> matches[0] in catalog.extent True >>> matches[0] in catalog['index'].uids True >>> catalog.unindex_doc(matches[0]) >>> matches[0] in catalog.extent False >>> matches[0] in catalog['index'].uids False >>> doc_id = matches.pop(0) >>> sorted(extent) == sorted(index.uids) == matches TrueClearing the catalog clears both the extent and the contained indexes.>>> catalog.clear() >>> list(catalog.extent) == list(catalog['index'].uids) == [] TrueUpdating all indexes and an individual index both also update the extent.>>> catalog.updateIndexes() >>> matches.insert(0, doc_id) >>> sorted(extent) == sorted(index.uids) == matches True>>> index2 = DummyIndex() >>> catalog['index2'] = index2 >>> index2.__parent__ == catalog True >>> index.uids.remove(matches[0]) # to confirm that only index 2 is touched >>> catalog.updateIndex(index2) >>> sorted(extent) == sorted(index2.uids) == matches True >>> matches[0] in index.uids False >>> matches[0] in index2.uids True >>> res = index.uids.insert(matches[0])But so why have an extent in the first place? It allows indices to operate against a reliable collection of the full indexed data; therefore, it allows the indices in zc.catalog to perform NOT operations.The extent itself provides a number of merging features to allow its values to be merged with other BTrees.IFBTree data structures. These include intersection, union, difference, and reverse difference. Given an extent named ‘extent’ and another IFBTree data structure named ‘data’, intersections can be spelled “extent & data” or “data & extent”; unions can be spelled “extent | data” or “data | extent”; differences can be spelled “extent - data”; and reverse differences can be spelled “data - extent”. Unions and intersections are weighted.>>> extent = extentcatalog.Extent(family=btrees_family) >>> for i in range(1, 100, 2): ... extent.add(i, None) ... >>> alt_set = TreeSet() >>> _ = alt_set.update(range(0, 166, 33)) # return value is unimportant here >>> sorted(alt_set) [0, 33, 66, 99, 132, 165] >>> sorted(extent & alt_set) [33, 99] >>> sorted(alt_set & extent) [33, 99] >>> sorted(extent.intersection(alt_set)) [33, 99] >>> original = set(extent) >>> union_matches = original.copy() >>> union_matches.update(alt_set) >>> union_matches = sorted(union_matches) >>> sorted(alt_set | extent) == union_matches True >>> sorted(extent | alt_set) == union_matches True >>> sorted(extent.union(alt_set)) == union_matches True >>> sorted(alt_set - extent) [0, 66, 132, 165] >>> sorted(extent.rdifference(alt_set)) [0, 66, 132, 165] >>> original.remove(33) >>> original.remove(99) >>> set(extent - alt_set) == original True >>> set(extent.difference(alt_set)) == original TrueWe can pass our own instantiated UID utility to extentcatalog.Catalog.>>> extent = extentcatalog.Extent(family=btrees_family) >>> uidutil = zope.intid.IntIds() >>> cat = extentcatalog.Catalog(extent, uidutil) >>> cat["index"] = DummyIndex() >>> cat.UIDSource is uidutil True>>> cat._getUIDSource() is uidutil TrueThe ResultSet instance returned by the catalog’ssearchResultsmethod uses our UID utility.>>> obj = DummyContent(43, root) >>> uid = uidutil.register(obj) >>> cat.index_doc(uid, obj) >>> res = cat.searchResults(index=uid) >>> res.uidutil is uidutil True>>> list(res) == [obj] TruesearchResultsmay also return None.>>> cat.searchResults() is None TrueCallingupdateIndexandupdateIndexeswhen the catalog has its uid source set works as well.>>> cat.clear() >>> uid in cat.extent FalseAll objects in the uid utility are indexed.>>> cat.updateIndexes() >>> uid in cat.extent True>>> len(cat.extent) 1>>> obj2 = DummyContent(44, root) >>> uid2 = uidutil.register(obj2) >>> cat.updateIndexes() >>> len(cat.extent) 2>>> uid2 in cat.extent True>>> uidutil.unregister(obj2)>>> cat.clear() >>> uid in cat.extent False >>> cat.updateIndex(cat["index"]) >>> uid in cat.extent TrueWith a self-populating extent, callingupdateIndexorupdateIndexesmeans only the objects whose ids are in the extent are updated/reindexed; if present, the catalog will use its uid source to look up the objects by id.>>> extent = extentcatalog.NonPopulatingExtent(family=btrees_family) >>> cat = extentcatalog.Catalog(extent, uidutil) >>> cat["index"] = DummyIndex()>>> extent.add(uid, obj) >>> uid in cat["index"].uids False>>> cat.updateIndexes() >>> uid in cat["index"].uids True>>> cat.clear() >>> uid in cat["index"].uids False>>> uid in cat.extent False>>> cat.extent.add(uid, obj) >>> cat.updateIndex(cat["index"]) >>> uid in cat["index"].uids TrueUnregister the objects of the previous tests from intid utility:>>> intid = zope.component.getUtility( ... zope.intid.interfaces.IIntIds, context=root) >>> for doc_id in matches: ... intid.unregister(intid.queryObject(doc_id))Catalog with a filter extentAs discussed at the beginning of this document, extents can not only help with index operations, but also act as a filter, so that a given catalog can answer questions about a subset of the objects contained in the intids.The filter extent only stores objects that match a given filter.>>> def filter(extent, uid, ob): ... assert interfaces.IFilterExtent.providedBy(extent) ... # This is an extent of objects with odd-numbered uids without a ... # True ignore attribute ... return uid % 2 and not getattr(ob, 'ignore', False) ... >>> extent = extentcatalog.FilterExtent(filter, family=btrees_family) >>> verify.verifyObject(interfaces.IFilterExtent, extent) True >>> root['catalog1'] = catalog = extentcatalog.Catalog(extent) >>> verify.verifyObject(interfaces.IExtentCatalog, catalog) True >>> index = DummyIndex() >>> catalog['index'] = index >>> transaction.commit()Now we have a catalog set up with an index and an extent. If we create some content and ask the catalog to index it, only the ones that match the filter will be in the extent and in the index.>>> matches = [] >>> fails = [] >>> i = 0 >>> while True: ... c = DummyContent(i, root) ... root[i] = c ... doc_id = intid.register(c) ... catalog.index_doc(doc_id, c) ... if filter(extent, doc_id, c): ... matches.append(doc_id) ... else: ... fails.append(doc_id) ... i += 1 ... if i > 99 and len(matches) > 4: ... break ... >>> matches.sort() >>> sorted(extent) == sorted(index.uids) == matches TrueIf a content object is indexed that used to match the filter but no longer does, it should be removed from the extent and indexes.>>> matches[0] in catalog.extent True >>> obj = intid.getObject(matches[0]) >>> obj.ignore = True >>> filter(extent, matches[0], obj) False >>> catalog.index_doc(matches[0], obj) >>> doc_id = matches.pop(0) >>> doc_id in catalog.extent False >>> sorted(extent) == sorted(index.uids) == matches TrueUnindexing an object that is not in the catalog should be a no-op.>>> fails[0] in catalog.extent False >>> catalog.unindex_doc(fails[0]) >>> fails[0] in catalog.extent False >>> sorted(extent) == sorted(index.uids) == matches TrueUpdating all indexes and an individual index both also update the extent.>>> index2 = DummyIndex() >>> catalog['index2'] = index2 >>> index2.__parent__ == catalog True >>> index.uids.remove(matches[0]) # to confirm that only index 2 is touched >>> catalog.updateIndex(index2) >>> sorted(extent) == sorted(index2.uids) True >>> matches[0] in index.uids False >>> matches[0] in index2.uids True >>> res = index.uids.insert(matches[0])If you update a single index and an object is no longer a member of the extent, it is removed from all indexes.>>> matches[0] in catalog.extent True >>> matches[0] in index.uids True >>> matches[0] in index2.uids True >>> obj = intid.getObject(matches[0]) >>> obj.ignore = True >>> catalog.updateIndex(index2) >>> matches[0] in catalog.extent False >>> matches[0] in index.uids False >>> matches[0] in index2.uids False >>> doc_id = matches.pop(0) >>> (matches == sorted(catalog.extent) == sorted(index.uids) ... == sorted(index2.uids)) TrueSelf-populating extentsAn extent may know how to populate itself; this is especially useful if the catalog can be initialized with fewer items than those available in the IIntIds utility that are also within the nearest Zope 3 site (the policy coded in the basic Zope 3 catalog).Such an extent must implement theISelfPopulatingExtentinterface, which requires two attributes. Let’s use theFilterExtentclass as a base for implementing such an extent, with a method that selects content item 0 (created and registered above):>>> class PopulatingExtent( ... extentcatalog.FilterExtent, ... extentcatalog.NonPopulatingExtent): ... ... def populate(self): ... if self.populated: ... return ... self.add(intid.getId(root[0]), root[0]) ... super(PopulatingExtent, self).populate()Creating a catalog based on this extent ignores objects in the database already:>>> def accept_any(extent, uid, ob): ... return True >>> extent = PopulatingExtent(accept_any, family=btrees_family) >>> catalog = extentcatalog.Catalog(extent) >>> index = DummyIndex() >>> catalog['index'] = index >>> root['catalog2'] = catalog >>> transaction.commit()At this point, our extent remains unpopulated:>>> extent.populated FalseIterating over the extent does not cause it to be automatically populated:>>> list(extent) []Causing our new index to be filled will cause thepopulate()method to be called, setting thepopulateflag as a side-effect:>>> catalog.updateIndex(index) >>> extent.populated True >>> list(extent) == [intid.getId(root[0])] TrueThe index has been updated with the documents identified by the extent:>>> list(index.uids) == [intid.getId(root[0])] TrueUpdating the same index repeatedly will continue to use the extent as the source of documents to include:>>> catalog.updateIndex(index) >>> list(extent) == [intid.getId(root[0])] True >>> list(index.uids) == [intid.getId(root[0])] TrueTheupdateIndexes()method has a similar behavior. If we add an additional index to the catalog, we see that it indexes only those objects from the extent:>>> index2 = DummyIndex() >>> catalog['index2'] = index2 >>> catalog.updateIndexes() >>> list(extent) == [intid.getId(root[0])] True >>> list(index.uids) == [intid.getId(root[0])] True >>> list(index2.uids) == [intid.getId(root[0])] TrueWhen we have fresh catalog and extent (not yet populated), we see thatupdateIndexes()will cause the extent to be populated:>>> extent = PopulatingExtent(accept_any, family=btrees_family) >>> root['catalog3'] = catalog = extentcatalog.Catalog(extent) >>> index1 = DummyIndex() >>> index2 = DummyIndex() >>> catalog['index1'] = index1 >>> catalog['index2'] = index2 >>> transaction.commit() >>> extent.populated False >>> catalog.updateIndexes() >>> extent.populated True >>> list(extent) == [intid.getId(root[0])] True >>> list(index1.uids) == [intid.getId(root[0])] True >>> list(index2.uids) == [intid.getId(root[0])] TrueWe’ll make sure everything can be safely committed.>>> transaction.commit() >>> setSiteManager(None)StemmerThe stemmer uses Andreas Jung’s stemmer code, which is a Python wrapper of M. F. Porter’s Snowball project (http://snowball.tartarus.org/index.php). It is designed to be used as part of a pipeline in a zope/index/text/ lexicon, after a splitter. This enables getting the relevance ranking of the zope/index/text code with the splitting functionality of TextIndexNG 3.x.It requires that the TextIndexNG extensions–specifically txngstemmer–have been compiled and installed in your Python installation. Inclusion of the textindexng package is not necessary.As of this writing (Jan 3, 2007), installing the necessary extensions can be done with the following steps:svn co https://svn.sourceforge.net/svnroot/textindexng/extension_modules/trunk ext_modcd ext_mod(using the python you use for Zope)python setup.py installAnother approach is to simply install TextIndexNG (seehttp://opensource.zopyx.com/software/textindexng3)The stemmer must be instantiated with the language for which stemming is desired. It defaults to ‘english’. For what it is worth, other languages supported as of this writing, using the strings that the stemmer expects, include the following: ‘danish’, ‘dutch’, ‘english’, ‘finnish’, ‘french’, ‘german’, ‘italian’, ‘norwegian’, ‘portuguese’, ‘russian’, ‘spanish’, and ‘swedish’.For instance, let’s build an index with an english stemmer.>>> from zope.index.text import textindex, lexicon >>> import zc.catalog.stemmer >>> lex = lexicon.Lexicon( ... lexicon.Splitter(), lexicon.CaseNormalizer(), ... lexicon.StopWordRemover(), zc.catalog.stemmer.Stemmer('english')) >>> ix = textindex.TextIndex(lex) >>> data = [ ... (0, 'consigned consistency consoles the constables'), ... (1, 'knaves kneeled and knocked knees, knowing no knights')] >>> for doc_id, text in data: ... ix.index_doc(doc_id, text) ... >>> list(ix.apply('consoling a constable')) [0] >>> list(ix.apply('knightly kneel')) [1]Note that query terms with globbing characters are not stemmed.>>> list(ix.apply('constables*')) []Support for legacy dataPrior to the introduction of btree “families” and theBTrees.Interfaces.IBTreeFamilyinterface, the indexes defined by thezc.catalog.indexmodule used the instance attributesbtreemoduleandIOBTree, initialized in the constructor, and theBTreeAPIproperty. These are replaced by thefamilyattribute in the current implementation.This is a white-box test that verifies that the supported values in existing data structures (loaded from pickles) can be used effectively with the current implementation.There are two supported sets of values; one for 32-bit btrees:>>> import BTrees.IOBTree >>> legacy32 = { ... "btreemodule": "BTrees.IFBTree", ... "IOBTree": BTrees.IOBTree.IOBTree, ... }and another for 64-bit btrees:>>> import BTrees.LOBTree >>> legacy64 = { ... "btreemodule": "BTrees.LFBTree", ... "IOBTree": BTrees.LOBTree.LOBTree, ... }In each case, actual legacy structures will also include index structures that match the right integer size:>>> import BTrees.OOBTree >>> import BTrees.Length >>> legacy32["values_to_documents"] = BTrees.OOBTree.OOBTree() >>> legacy32["documents_to_values"] = BTrees.IOBTree.IOBTree() >>> legacy32["documentCount"] = BTrees.Length.Length(0) >>> legacy32["wordCount"] = BTrees.Length.Length(0) >>> legacy64["values_to_documents"] = BTrees.OOBTree.OOBTree() >>> legacy64["documents_to_values"] = BTrees.LOBTree.LOBTree() >>> legacy64["documentCount"] = BTrees.Length.Length(0) >>> legacy64["wordCount"] = BTrees.Length.Length(0)What we want to do is verify that thefamilyattribute is properly computed for instances loaded from legacy data, and ensure that the structure is updated cleanly without providing cause for a read-only transaction to become a write-transaction. We’ll need to create instances that conform to the old data structures, pickle them, and show that unpickling them produces instances that use the correct families.Let’s create new instances, and force the internal data to match the old structures:>>> import pickle >>> import zc.catalog.index >>> vi32 = zc.catalog.index.ValueIndex() >>> vi32.__dict__ = legacy32.copy() >>> legacy32_pickle = pickle.dumps(vi32) >>> vi64 = zc.catalog.index.ValueIndex() >>> vi64.__dict__ = legacy64.copy() >>> legacy64_pickle = pickle.dumps(vi64)Now, let’s unpickle these structures and verify the structures. We’ll start with the 32-bit variety:>>> vi32 = pickle.loads(legacy32_pickle) >>> vi32.__dict__["btreemodule"] 'BTrees.IFBTree' >>> vi32.__dict__["IOBTree"] <type 'BTrees.IOBTree.IOBTree'> >>> "family" in vi32.__dict__ False >>> vi32._p_changed FalseThefamilyproperty returns theBTrees.family32singleton:>>> vi32.family is BTrees.family32 TrueOnce accessed, the legacy values have been cleaned out from the instance dictionary:>>> "btreemodule" in vi32.__dict__ False >>> "IOBTree" in vi32.__dict__ False >>> "BTreeAPI" in vi32.__dict__ FalseAccessing these attributes as attributes provides the proper values anyway:>>> vi32.btreemodule 'BTrees.IFBTree' >>> vi32.IOBTree <type 'BTrees.IOBTree.IOBTree'> >>> vi32.BTreeAPI <module 'BTrees.IFBTree' from ...>Even though the instance dictionary has been cleaned up, the change flag hasn’t been set. This is handled this way to avoid turning a read-only transaction into a write-transaction:>>> vi32._p_changed FalseThe 64-bit variation provides equivalent behavior:>>> vi64 = pickle.loads(legacy64_pickle) >>> vi64.__dict__["btreemodule"] 'BTrees.LFBTree' >>> vi64.__dict__["IOBTree"] <type 'BTrees.LOBTree.LOBTree'> >>> "family" in vi64.__dict__ False >>> vi64._p_changed False >>> vi64.family is BTrees.family64 True >>> "btreemodule" in vi64.__dict__ False >>> "IOBTree" in vi64.__dict__ False >>> "BTreeAPI" in vi64.__dict__ False >>> vi64.btreemodule 'BTrees.LFBTree' >>> vi64.IOBTree <type 'BTrees.LOBTree.LOBTree'> >>> vi64.BTreeAPI <module 'BTrees.LFBTree' from ...> >>> vi64._p_changed FalseNow, if we have a legacy structure and explicitly set thefamilyattribute, the old data structures will be cleared and replaced with the new structure. If the object is associated with a data manager, the changed flag will be set as well:>>> class DataManager(object): ... def register(self, ob): ... pass >>> vi64 = pickle.loads(legacy64_pickle) >>> vi64._p_jar = DataManager() >>> vi64.family = BTrees.family64 >>> vi64._p_changed True >>> "btreemodule" in vi64.__dict__ False >>> "IOBTree" in vi64.__dict__ False >>> "BTreeAPI" in vi64.__dict__ False >>> "family" in vi64.__dict__ True >>> vi64.family is BTrees.family64 True >>> vi64.btreemodule 'BTrees.LFBTree' >>> vi64.IOBTree <type 'BTrees.LOBTree.LOBTree'> >>> vi64.BTreeAPI <module 'BTrees.LFBTree' from ...>GlobberThe globber takes a query and makes any term that isn’t already a glob into something that ends in a star. It was originally envisioned as averylow- rent stemming hack. The author now questions its value, and hopes that the new stemming pipeline option can be used instead. Nonetheless, here is an example of it at work.>>> from zope.index.text import textindex >>> index = textindex.TextIndex() >>> lex = index.lexicon >>> from zc.catalog import globber >>> globber.glob('foo bar and baz or (b?ng not boo)', lex) '(((foo* and bar*) and baz*) or (b?ng and not boo*))'Callable WrapperIf we want to index some value that is easily derivable from a document, we have to define an interface with this value as an attribute, and create an adapter that calculates this value and implements this interface. All this is too much hassle if the want to store a single easily derivable value. CallableWrapper solves this problem, by converting the document to the indexed value with a callable converter.Here’s a contrived example. Suppose we have cars that know their mileage expressed in miles per gallon, but we want to index their economy in litres per 100 km.>>> class Car(object): ... def __init__(self, mpg): ... self.mpg = mpg>>> def mpg2lp100(car): ... return 100.0/(1.609344/3.7854118 * car.mpg)Let’s create an index that would index cars’ l/100 km rating.>>> from zc.catalog import index, catalogindex >>> idx = catalogindex.CallableWrapper(index.ValueIndex(), mpg2lp100)Let’s add a couple of cars to the index!>>> hummer = Car(10.0) >>> beamer = Car(22.0) >>> civic = Car(45.0)>>> idx.index_doc(1, hummer) >>> idx.index_doc(2, beamer) >>> idx.index_doc(3, civic)The indexed values should be the converted l/100 km ratings:>>> list(idx.values()) # doctest: +ELLIPSIS [5.22699076283393..., 10.691572014887601, 23.521458432752723]We can query for cars that consume fuel in some range:>>> list(idx.apply({'between': (5.0, 7.0)})) [3]zc.catalog Browser SupportThe zc.catalog.browser package adds simple TTW addition/inspection for SetIndex and ValueIndex.First, we need a browser so we can test the web UI.>>> from zope.testbrowser.wsgi import Browser >>> browser = Browser() >>> browser.handleErrors = False >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.addHeader('Accept-Language', 'en-US') >>> browser.open('http://localhost/')Now we need to add the catalog that these indexes are going to reside within.>>> browser.open('http://localhost/++etc++site/default/@@+/') >>> browser.getControl('Catalog').click() >>> browser.getControl(name='id').value = 'catalog' >>> browser.getControl('Add').click()SetIndexAdd the SetIndex to the catalog.>>> browser.open(browser.getLink('Add').url + '/') >>> browser.getControl('Set Index').click() >>> browser.getControl(name='id').value = 'set_index' >>> browser.getControl('Add').click()The add form needs values for what interface to adapt candidate objects to, and what field name to use, and whether-or-not that field is a callable. (We’ll use a simple interfaces for demonstration purposes, it’s not really significant.)>>> browser.getControl('Interface', index=0).displayValue = [ ... 'zope.size.interfaces.ISized'] >>> browser.getControl('Field Name').value = 'sizeForDisplay' >>> browser.getControl('Field Callable').click() >>> browser.getControl(name='add_input_name').value = 'set_index' >>> browser.getControl('Add').click()Now we can look at the index and see how is is configured.>>> browser.getLink('set_index').click() >>> print(browser.contents) <... ...Interface...zope.size.interfaces.ISized... ...Field Name...sizeForDisplay... ...Field Callable...True...We need to go back to the catalog so we can add a different index.>>> browser.open('/++etc++site/default/catalog/@@contents.html')ValueIndexAdd the ValueIndex to the catalog.>>> browser.open(browser.getLink('Add').url + '/') >>> browser.getControl('Value Index').click() >>> browser.getControl(name='id').value = 'value_index' >>> browser.getControl('Add').click()The add form needs values for what interface to adapt candidate objects to, and what field name to use, and whether-or-not that field is a callable. (We’ll use a simple interfaces for demonstration purposes, it’s not really significant.)>>> browser.getControl('Interface', index=0).displayValue = [ ... 'zope.size.interfaces.ISized'] >>> browser.getControl('Field Name').value = 'sizeForDisplay' >>> browser.getControl('Field Callable').click() >>> browser.getControl(name='add_input_name').value = 'value_index' >>> browser.getControl('Add').click()Now we can look at the index and see how is is configured.>>> browser.getLink('value_index').click() >>> print(browser.contents) <... ...Interface...zope.size.interfaces.ISized... ...Field Name...sizeForDisplay... ...Field Callable...True...
zc.catalogqueue
A catalog queue provides a queue for catalog indexing. The basic idea is to queue catalog operations so:Operations can be batched for greater efficiencyApplication requests don’t have to wait for indexing to be doneThe benefits of queueing are especially significant when text indexes are used.ContentsDetailed DocumentationUsing QueuesEdgecaseDownloadDetailed DocumentationUsing QueuesA queue is created by instantiating a zc.catalogqueue.queue.CatalogQueue object:>>> import zc.catalogqueue.queue >>> queue = zc.catalogqueue.queue.CatalogQueue()We can pass a queue size. It should be a prime number. The default is 1009, which is a bit large.>>> queue = zc.catalogqueue.queue.CatalogQueue(11)Typically, queues are registered as zc.catalogqueue.interfaces.ICatalogQueue utilities.>>> import zope.interface, pprint >>> pprint.pprint(sorted(zope.interface.providedBy(queue)), width=1) [<InterfaceClass zc.catalogqueue.interfaces.ICatalogQueue>, <InterfaceClass persistent.interfaces.IPersistent>]There are some bits of information that the queue maintains regarding its own processing state. The time of last processing and the total number of cataloging events processed are available. Since this queue hasn’t been processed yet, these have some initial values:>>> print queue.lastProcessedTime None >>> queue.totalProcessed 0The length of the queue provides access to the number of pending cataloging events:>>> len(queue) 0Queues are used in 2 ways. As content are modified, we call add, update, and remove methods on the queue:>>> queue.add(1) >>> queue.update(1) >>> queue.remove(1)>>> queue.update(2) >>> queue.update(2)>>> queue.add(3) >>> queue.update(3) >>> queue.add(3) Traceback (most recent call last): ... TypeError: Attempt to add an object that is already in the catalog>>> queue.update(4) >>> queue.update(4) >>> queue.update(4)>>> queue.remove(5) >>> queue.update(5) Traceback (most recent call last): ... TypeError: Attempt to change an object that has been removed>>> queue.update(0) >>> queue.update(0)At this point, we’ve added several events, but haven’t processed the queue, so we expectlastProcessedTime,totalProcessedto be unchanged, but the queue length to reflect the pending tasks:>>> print queue.lastProcessedTime None >>> queue.totalProcessed 0 >>> len(queue) 6Periodically, we call process on the queue. We need to pass an ids object and a collection of injection (catalog) objects:>>> class Ids: ... def queryObject(self, id, default=None): ... if not id: ... return default ... return "object %s" % id>>> class Injection: ... def __init__(self, name): ... self.name = name ... def index_doc(self, docid, value): ... print self.name, 'indexing', docid, value ... def unindex_doc(self, docid): ... print self.name, 'unindexing', docid>>> queue.process(Ids(), [Injection('cat1'), Injection('cat2')], 10) cat1 unindexing 1 cat2 unindexing 1 cat1 indexing 2 object 2 cat2 indexing 2 object 2 cat1 indexing 3 object 3 cat2 indexing 3 object 3 cat1 indexing 4 object 4 cat2 indexing 4 object 4 cat1 unindexing 5 cat2 unindexing 5 6There are a number of things to note about this example:Each object is processed only once.What happens depends on the last event.Object 0 wasn’t indexed because queryObject returned None. We ignore events for objects that have been removed from the intid utility.The number of objects processed is returned.The processing information has been updated on the queue:>>> queue.lastProcessedTime # doctest: +ELLIPSIS datetime.datetime(... tzinfo=<UTC>) >>> queue.totalProcessed 6>>> previous_time = queue.lastProcessedTimeThe length of the queue now indicates that no further events are pending:>>> len(queue) 0If we process the queue without additional events, we’ll just get 0 back:>>> queue.process(Ids(), [Injection('cat1'), Injection('cat2')], 10) 0The historical processing information is updated:>>> queue.lastProcessedTime # doctest: +ELLIPSIS datetime.datetime(... tzinfo=<UTC>) >>> queue.lastProcessedTime > previous_time True >>> queue.totalProcessed 6>>> len(queue) 0Of course, the limit argument limits how many events we process:>>> for i in range(10): ... queue.update(i) >>> len(queue) 10 >>> queue.process(Ids(), [Injection('cat1')], 5) cat1 indexing 1 object 1 cat1 indexing 2 object 2 cat1 indexing 3 object 3 cat1 indexing 4 object 4 5 >>> queue.totalProcessed 11 >>> len(queue) 5>>> queue.process(Ids(), [Injection('cat1')], 5) cat1 indexing 5 object 5 cat1 indexing 6 object 6 cat1 indexing 7 object 7 cat1 indexing 8 object 8 cat1 indexing 9 object 9 5 >>> queue.totalProcessed 16 >>> len(queue) 0(Remember that 0 isn’t processed because it can’t be found.)When an object can’t be found, a warning is logged:>>> import zope.testing.loggingsupport >>> handler = zope.testing.loggingsupport.InstalledHandler('zc') >>> queue.update(0) >>> queue.process(Ids(), [Injection('cat1')], 5) 1>>> print handler zc.catalogqueue.queue WARNING Couldn't find object for 0>>> handler.uninstall()EdgecaseIf a “old” state has two ‘ADDED’ events, and the committed state processes the queue, and the “new” state modifies one of the objects marked for addition, the code marks the other for removal.>>> from zc.catalogqueue.CatalogEventQueue import ( ... CatalogEventQueue, ADDED, REMOVED, CHANGED, CHANGED_ADDED) >>> cq = CatalogEventQueue()>>> def resolve(old, committed, new): ... return sorted(cq._p_resolveConflict( ... {'_conflict_policy': 0, '_data': old}, ... {'_conflict_policy': 0, '_data': committed}, ... {'_conflict_policy': 0, '_data': new} ... )['_data'].items())>>> resolve({1: (1, ADDED), 2: (1, ADDED)}, {}, ... {1: (1, ADDED), 2: (3, REMOVED), 3: (1, ADDED)}) [(2, (3, 0)), (3, (1, 1))]Download
zcc-helper
ZCC-HELPERThe ZIMI library is a basic python API and command line tool that supports the zimi Cloud Connect device to manage Powermesh home network equipment.InstallationYou can install zimi from PyPi:pip install zcc-helperThe module is only supported in python3.How to useThe module can be used both as part of an embedded python program and as a command line tool.Embedded ProgramIn order to control the zimi Cloud Connect (ZCC) and associated devices your program should create an instance of a ControlPoint object which will be used to manipulate the associated devices. There is a multi-step process to do so described below.Step One - discover details of the Zimi Controller and create a ControlPointDescription objectIf you are connected to the local LAN with the Zimi Controller, then you can auto discover the ZCC otherwise you need to know the IP address and port number of the ZCC.To discover ZCC and devices on the local LAN use the ControlPointDiscoveryService.discover() async method to obtain a ControlPointDescription object with details of host, port etc as per the code snippet below:importasynciofromzccimportControlPoint,ControlPointDescription,ControlPointDiscoveryServiceasyncdefdiscover():returnawaitControlPointDiscoveryService().discover()asyncdefmain():controller_description=awaitdiscover()print(controller_description)asyncio.run(main())When this is run it produces output like:ControlPointDescription(brand='zimi',product='zcc',mac='c4ffbc90bf73',host='192.168.1.105',port=5003,available_tcps=6)Step Two - Create a ControlPoint object and connect to the controllerOnce you have discovered details of the ZIMI controller your program should create a ControlPoint instance and use the async connect() method to authorise and start a session with the ZIMI controller as well as build a catalogue of all associated devices.Use some code as per the snippet below:importasynciofromzccimportControlPoint,ControlPointDescription,ControlPointDiscoveryServiceasyncdefdiscover():returnawaitControlPointDiscoveryService().discover()asyncdefmain():description=awaitdiscover()controller=ControlPoint(description=description)awaitcontroller.connect()controller.print_description()asyncio.run(main())When this is run it produces output like:+----------------------------------------------------------------------------------------------------------------------------------+ | ControlPoint: c4ffbc90bf73 zcc zimi 59 devices 192.168.1.105:5003 6 Tcps | +----------------------------------------------------------------------------------------------------------------------------------+ bddf0500-4d15-4457-b063-c12ed208a0b0_3 Study Pendant/Upstairs switch Off { TurnOn TurnOff } bddf0500-4d15-4457-b063-c12ed208a0b0_4 Lounge/Upstairs switch Off { TurnOn TurnOff } 37bd164e-d867-4ba7-b64c-e7d4c4d0f418_1 Kitchen Downlights/Kitchen switch Off { TurnOn TurnOff }It is also possible to connect to a known ZCC host with ip address and port number wrapped in a ControlPointDescription object:controller=ControlPoint(description=ControlPointDescription(host='192.168.1.105',port=5003))Step Three - Control devices connected to the controllerOnce the device ID is known then it can be used to control a particular device by using the controller.devices[device_id] instance that represents an individual device.>>>dev=zcc.devices['bddf0500-4d15-4457-b063-c12ed208a0b0_3']>>>print(dev){'actions':{'actions':{'TurnOff':{'actionParams':{}},'TurnOn':{'actionParams':{}}}},'controller':<zcc.controller.ControlPointobjectat0x7f70a9f117f0>,'identifier':'bddf0500-4d15-4457-b063-c12ed208a0b0_3','properties':{'controlPointType':'switch','name':'Study Pendant','roomId':5,'roomName':'Up Stairs Passage'},'states':{'controlState':{'switch':{'isOn':False}},'isConnected':True}}>>>dev.turn_on()>>>print(dev){'actions':{'actions':{'TurnOff':{'actionParams':{}},'TurnOn':{'actionParams':{}}}},'controller':<zcc.controller.ControlPointobjectat0x7f70a9f117f0>,'identifier':'bddf0500-4d15-4457-b063-c12ed208a0b0_3','properties':{'controlPointType':'switch','name':'Study Pendant','roomId':5,'roomName':'Up Stairs Passage'},'states':{'controlState':{'switch':{'isOn':True}},'isConnected':True}}>>>dev.turn_off()Depending upon the type of device it will support various actions as defined in ControlPointDevice.Available actions include:asyncdefclose_door(self):'''CloseDoor if the action is supported'''asyncdeffade(self,brightness,timeperiod):'''SetBrightness if the action is supported'''asyncdefopen_door(self):'''OpenDoor if the action is supported'''asyncdefopen_to_percentage(self,percentage):'''OpenToPercentage if the action is supported'''asyncdefset_brightness(self,brightness):'''SetBrightness if the action is supported'''asyncdefset_fanspeed(self,fanspeed):'''SetFanSpeed if the action is supported'''asyncdefturn_on(self):'''TurnOn the device if the action is supported'''asyncdefturn_off(self):'''TurnOff the device if the action is supported'''Available properties include:defbattery_level(self)->int|None:'''Return the battery level of an attached sensor.'''defbrightness(self)->int|None:'''Returns brightness from 0 to 100 or None.'''defdoor_temp(self)->int|None:'''Return the external temperature of an attached sensor.'''deffanspeed(self)->int|None:'''Returns fanspeed from 0 to 7 or None.'''defgarage_humidity(self)->int|None:'''Return the internal garage humidity of an attached sensor.'''defgarage_temp(self)->int|None:'''Return the internal garage temperature of an attached sensor.'''defis_closing(self)->bool:'''Returns True if door is closing.'''defis_closed(self)->bool:'''Returns True if door is closed.'''defis_connected(self)->bool:'''Returns True if connected is on.When a device has been disconnected from the mesh it show False.'''defis_off(self)->bool:'''Returns True if status is off.'''defis_on(self)->bool:'''Returns True if status is on.'''defis_opening(self)->bool:'''Returns True if door is opening.'''defis_open(self)->bool'''Returns True if door is open.'''deflocation(self)->str:'''Gets a descriptive string of the device location'''defname(self)->str:'''Gets a descriptive string of the device name'''defpercentage(self)->int|None:'''Return the open to percentage'''defroom(self)->str:'''Gets a descriptive string of the device room'''deftype(self)->str:'''Gets a descriptive string of the device type'''In addition, you can subscribe to a notification for changes to the device state by using the following methods of the device object.defsubscribe(self,observer):'''Subscribe an observer object for state changes.Observer object must include notify(self, observable, *args, **kwargs) method.'''defunsubscribe(self,observer):'''Unsubscribe an observer object.'''The observer object must have a notify(observable) method.Finally, you can initiate a watchdog function that will periodically refresh the device states from the ZCC. This can be useful for long lived connections that may time-out as it will trigger a re-connection if needed.defstart_watchdog(self,timer:int):'''Start a periodic timeout that resets every time a status update is received.'''defstop_watchdog(self):'''Stop the periodic timeout.'''Command Line ProgramZCC can also be used as a command line tool to discover ZCC devices and/or execute actions upon them.$ python3 -m zcc usage: zcc [-h] [--verbosity VERBOSITY] (--discover | --execute) [--host HOST] [--port PORT] [--timeout TIMEOUT] [--device DEVICE] [--action {CloseDoor,OpenDoor,TurnOn,TurnOff,OpenToPercentage,SetBrightness,SetFanSpeed}] [--value VALUE] zcc: error: one of the arguments --discover --execute is requiredTo discover devices use:$ python -m zcc --discover +-----------------------------------------------------------------------------------------------------------------+ | ControlPoint: c4ffbc90bf73 zcc zimi 34 devices 192.168.1.105:5003 6 Tcps | +-----------------------------------------------------------------------------------------------------------------+ 0a872922-73e0-4699-89c5-29156f0686f8_1 LED strip/Lounge dimmer Off { TurnOn TurnOff SetBrightness } 0da922e4-1f04-4a80-b267-ade8529194c9_1 Water Feature Pu switch { TurnOn TurnOff }To execute an action use:python -m zcc --execute --device 'bddf0500-4d15-4457-b063-c12ed208a0b0_3' --action 'TurnOn'This version of the command is relatively slow as it first of all discovers the ZCC on the local LAN, builds a device inventory and then executes the action.
zcc-Math
No description available on PyPI.
zc.comment
A simple package to support a list of comments for an object.Detailed DocumentationCommentsThe comment package is a simple way to add comments to anyIAnnotatableZope content. The datetime and current principals are stamped on to the comment. The comment body is currently simply unicode text but intended to be html snippets (“rich text”) at a later date.The inclusion of current principals requires an interaction, which is what we need to set up before we can use the system here. Below, we set up a dummy interaction with dummy participants, create some content that isIAttributeAnnotatable, and then finally show the system in use.In order to create a participation, we need a few principals:>>> import zope.security.management >>> import zope.security.interfaces >>> from zope import interface >>> class Principal(object): ... interface.implements(zope.security.interfaces.IPrincipal) ... ... def __init__(self, id, title, description): ... self.id = id ... self.title = title ... self.description = description ... ... def __repr__(self): ... return '<%s %r>' %(self.__class__.__name__, self.id)>>> alice = Principal('alice', 'Alice Aal', 'first principal') >>> betty = Principal('betty', 'Betty Barnes', 'second principal')Now we can create a participation:>>> class Participation(object): ... zope.interface.implements( ... zope.security.interfaces.IParticipation, ... zope.publisher.interfaces.IRequest) ... interaction = principal = None ... ... def __init__(self, principal): ... self.principal = principal ... ... def __repr__(self): ... return '<%s %r>' %(self.__class__.__name__, self.principal)Next we need to make sute the annotation mechanism is setup, because the comments adapter needs to be able to annotate the adapted object:>>> import zope.component >>> import zope.annotation >>> zope.component.provideAdapter( ... zope.annotation.attribute.AttributeAnnotations)Let’s now make sure that all commentable objects can receive comments:>>> from zc.comment import comment >>> zope.component.provideAdapter(comment.CommentsFactory)Now that we have everything setup, let’s have a look at how it works. First we need a simple content component:>>> class SimpleContent(object): ... interface.implements( ... zope.annotation.interfaces.IAttributeAnnotatable) ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return '<%s %r>' %(self.__class__.__name__, self.name) >>> content = SimpleContent(u'content')In order to play with the comments, we now have to register a new participation. In our case, Alice wants to create a comment:>>> zope.security.management.endInteraction() >>> zope.security.management.newInteraction(Participation(alice))We can access the comments of an object by adapting toIComments:>>> from zc.comment import interfaces >>> comments = interfaces.IComments(content) Traceback (most recent call last): ... TypeError: ('Could not adapt', <SimpleContent u'content'>, <InterfaceClass zc.comment.interfaces.IComments>)Initially, the component is not commentable, because it does not provide the correct interface:>>> zope.interface.directlyProvides(content, interfaces.ICommentable)>>> comments = interfaces.IComments(content) >>> comments <Comments (0) for <SimpleContent u'content'>>Let’s now add a comment:>>> import datetime, pytz >>> before = datetime.datetime.now(pytz.utc)>>> comments.add(u"Foo! Bar!")>>> after = datetime.datetime.now(pytz.utc)As you can see it was not necessary to create the comments object manually, but simply pass in the text. Clearly a comment has been added:>>> len(comments) 1Let’s now make sure that the data was set correctly:>>> comments[0].body u'Foo! Bar!' >>> before <= comments[0].date <= after True >>> comments[0].principal_ids ('alice',)Let’s now log in as Betty:>>> zope.security.management.endInteraction() >>> zope.security.management.newInteraction(Participation(betty))Betty can also add a comment:>>> comments = interfaces.IComments(content) >>> before = datetime.datetime.now(pytz.utc) >>> comments.add(u"Shazam") >>> after = datetime.datetime.now(pytz.utc) >>> len(comments) 2And her comment is also correctly stored:>>> comments[1].body u'Shazam' >>> before <= comments[1].date <= after True >>> comments[1].principal_ids ('betty',)Let’s now make sure that if multiple participants are in the interaction that all of them get picked up:>>> zope.security.management.endInteraction() >>> zope.security.management.newInteraction( ... Participation(alice), Participation(betty))>>> comments.add(u"Boom.") >>> len(comments) 3 >>> comments[2].body u'Boom.' >>> comments[2].principal_ids ('alice', 'betty')Finally, note that we can only add unicode text as a valid comment:>>> comments.add(42) Traceback (most recent call last): ... WrongType: (42, <type 'unicode'>)If you like, you can always clear all comments:>>> comments.clear() >>> len(comments) 0And of course some cleanup:>>> zope.security.management.endInteraction()Commenting UICreate the browser object we’ll be using.>>> from zope.testbrowser.testing import Browser >>> browser = Browser() >>> browser.addHeader('Accept-Language', 'test')To see how comments work, we’ll create an instance of a simple content object:>>> browser.open('http://localhost/@@contents.html') >>> browser.getLink('[[zope][[top]]]').click() >>> browser.getLink('[[zc.comment][Content]]').click() >>> browser.getControl(name='new_value').value = 'number' >>> browser.getControl('[[zope][container-apply-button (Apply)]]').click()Let’s visit the object and click on the comments tab:>>> browser.handleErrors = False >>> browser.getLink('number').click() >>> browser.getLink('[[zc.comment][Comments]]').click()We see that no comments have been made yet:>>> '[[zc.intranet][No comments have been made.]]' in browser.contents TrueLet’s add a new multi-line comment:>>> browser.getControl('[[zc.comment][New Comment]]').value = '''\ ... I give my pledge, as an Earthling ... to save, and faithfully defend from waste ... the natural resources of my planet. ... It's soils, minerals, forests, waters, and wildlife. ... '''>>> browser.getControl('[[zc.comment][Add Comment]]').click()Now, we get a table that displays the comment with it’s date, text, and the user who made it:>>> print browser.contents <... <th> ...[[zc.comment][comment_column-date (Date)]]... </th> <th> ...[[zc.comment][comment_column-principals (Principals)]]... </th> <th> [[zc.comment][comment_column-comment (Comment)]] </th> ... <td> 2005 11 14 12:00:55 -500 </td> <td> Unauthenticated User </td> <td> I give my pledge, as an Earthling<br /> to save, and faithfully defend from waste<br /> the natural resources of my planet.<br /> It's soils, minerals, forests, waters, and wildlife.<br /> ... <label for="form.comment"> <span class="required">*</span><span>[[zc.comment][New Comment]]</span> </label> ...<textarea class="zc-comment-text" style="width: 50ex; height: 6em;" cols="60" id="form.comment" name="form.comment" rows="15" ></textarea></div> ... <input type="submit" id="form.actions.41646420436f6d6d656e74" name="form.actions.41646420436f6d6d656e74" value="[[zc.comment][Add Comment]]" class="button" /> ...Now, we’ll add another comment.>>> browser.getControl('[[zc.comment][New Comment]]' ... ).value = 'another comment' >>> browser.getControl('[[zc.comment][Add Comment]]').click() >>> print browser.contents <... <th> ...[[zc.comment][comment_column-date (Date)]]... </th> <th> ...[[zc.comment][comment_column-principals (Principals)]]... </th> <th> [[zc.comment][comment_column-comment (Comment)]] </th> </tr> ... <td> 2005 11 14 12:10:18 -500 </td> <td> Unauthenticated User </td> <td> I give my pledge, as an Earthling<br /> to save, and faithfully defend from waste<br /> the natural resources of my planet.<br /> It's soils, minerals, forests, waters, and wildlife.<br /> <BLANKLINE> </td> </tr> ... <td> 2005 11 14 12:10:18 -500 </td> <td> Unauthenticated User </td> <td> another comment </td> </tr> ... <label for="form.comment"> <span class="required">*</span><span>[[zc.comment][New Comment]]</span> </label> ... ...<textarea class="zc-comment-text" style="width: 50ex; height: 6em;" cols="60" id="form.comment" name="form.comment" rows="15" ></textarea>... <input type="submit" id="form.actions.41646420436f6d6d656e74" name="form.actions.41646420436f6d6d656e74" value="[[zc.comment][Add Comment]]" class="button" /> ...CHANGES0.1.0 (2008-04-21)Initial Release
zc-common
No description available on PyPI.
zc.configuration
******************************************************************zope.configuration extensions to filter out unwanted configuration******************************************************************.. contents::CHANGES*******1.2.0 (2017-04-17)------------------- Added ``MANIFEST.in``.- Using Python's ``doctest`` module instead of depreacted``zope.testing.doctest``.1.1 (2009-02-26)----------------- Move the ``exclude`` directive into the original ``zope.configuration``package.So, this package is currently contains only a backward-compatibilityimport for ``exclude`` directive and is not useful anymore. Howeverit's intended to contain miscellaneous extensions to the configurationframework and may contain more in future, so we are not marking isas deprecated for now.1.0 (2007-09-29)----------------Initial release.Detailed Documentation**********************Configuration Extensions for Filtering or Inhibiting Configuration==================================================================The zc.configuration package used to provide the ``exclude`` directivefor inhibiting configuration. It was included in the zope.configurationand this package currently provides a backward-compatibility importsand tests that ensure that it will work for people who are alreadyusing zc.configuration and not the newer zope.configuration.This package may contain more configuration extensions in future, butcurrently, it's not useful anymore as the only feature it provided,the ``exclude`` directive was merged into the original``zope.configuration`` package.First, let's look at an example. The zc.configuration.demo packagehas a ZCML configuration that includes some other configuration files.We'll set a log handler so we can see what's going on:>>> import logging, sys>>> logger = logging.getLogger('config')>>> oldlevel = logger.level>>> logger.setLevel(logging.DEBUG)>>> handler = logging.StreamHandler(sys.stdout)>>> logger.addHandler(handler)Now, we'll include the zc.configuration.demo config:>>> from zope.configuration import xmlconfig>>> _ = xmlconfig.string('<include package="zc.configuration.demo" />')include /zc.configuration/src/zc/configuration/demo/configure.zcmlinclude /zc.configuration/src/zc/configuration/demo/sub/configure.zcmlinclude /zc.configuration/src/zc/configuration/demo/spam.zcmlEach run of the configuration machinery runs with fresh state, sorerunning gives the same thing:>>> _ = xmlconfig.string('<include package="zc.configuration.demo" />')include /zc.configuration/src/zc/configuration/demo/configure.zcmlinclude /zc.configuration/src/zc/configuration/demo/sub/configure.zcmlinclude /zc.configuration/src/zc/configuration/demo/spam.zcmlNow, we'll load the zc.configuration meta.zcml and use the excludedirective to exclude the two files included by the configuration filein zc.configuration.demo:>>> _ = xmlconfig.string(... '''... <configure xmlns="http://namespaces.zope.org/zope">... <include package="zc.configuration" file="meta.zcml" />... <exclude package="zc.configuration.demo.sub" />... <exclude package="zc.configuration.demo" file="spam.zcml" />... <include package="zc.configuration.demo" />... </configure>... ''')include /zc.configuration/src/zc/configuration/meta.zcmlinclude /zc.configuration/src/zc/configuration/demo/configure.zcml.. cleanup>>> logger.setLevel(oldlevel)>>> logger.removeHandler(handler)Download********
zc.copy
This package used to provide a pluggable replacement of ObjectCopier class and locationCopy function from zope.copypastemove and zope.location respectively. Currently, all its functionality is merged to those packages and the new zope.copy package is provided that contains the actual pluggable copying mechanism used to be in this package with no dependencies except zope.interface.This package now only provides backward-compatibility imports and should not be used for new developments.
zc.creditcard
UNKNOWN
zc.customdoctests
doctest (and recently manuel) provide hooks for using custom doctest parsers.zc.customdoctestshelps to leverage this to support other languages, such as JavaScript:js> function double (x) { ... return x*2; ... } js> double(2) 4And withmanuel, it facilitates doctests that mix multiple languages, such as Python, JavaScript, and sh.ContentsDetailed documentationCustom doctest parsersJavascript and Python-Spidermonkey supportChangelog1.0.1 (2013-02-14)1.0.0 (2013-02-13)0.1.0 (2011-05-19)Detailed documentationCustom doctest parserszc.customdoctests provides a little bit of help with creating custom doctest parsers that work pretty muct like regular doctests, but that use an alternate means of evaluating examples. To use it, you call zc.customdoctests.DocTestParser and pass any of the following options:ps1The first-line prompt, which defaultd to'>>>'.This must be a regular expression that matches exactly 3 characters.(Note that you can’t override the second-line prompt.)comment_prefixThe comment prefix regular expression, which defaults to ‘#’.transformA function used to transform example source, which defaults to a no-operation function.The js module provides support for using JavaScript in doctests usingpython-spidermonkey. It provides some examples of defining custom doctest parsers.Javascript and Python-Spidermonkey supportTo wire this up, you’d use something like:import doctest, zc.customdoctests.js test_suite = doctest.DocTestSuite( parser=zc.customdoctests.js.parser, setUp=zc.customdoctests.js.spidermonkeySetUp)Or, with manuel:test_suite = manuel.testing.TestSuite( manuel.doctest.Manuel(parser=zc.customdoctests.js.parser) + manuel.doctest.Manuel(parser=zc.customdoctests.js.eq_parser) + manuel.doctest.Manuel() + manuel.capture.Manuel(), 'spidermonkey.txt', setUp=zc.customdoctests.js.spidermonkeySetUp)Note that zc.customdoctests doesn’t require spidermonkey, so you need to install spidermonkey seperately if you want to use it.An advantage of using manuel is that you can use multiple parsers in the same document. In the example, above, 2 javascript example syntaxes (described below) as well as the standard doctest syntax are supported. This document is run with manuel to allow all 3 syntaxes.For the rest of this document, we’ll show examples of JavaScript doctests as well as helper APIs used to support JavaScript and to integrate JavaScript and Python.Javascript doctests use a “js>” prompt (as used in rhino and the spidermonkey interpreter):js> 2 + ... 'Hi world' // doctest: +ELLIPSIS u'2Hi...Assignments return values. This can generate annoying output in doctests:js> ob = {a: 1, b: 2} [object Object]If you’re using manuel, you can avoid this by using js!:js! x = 3which suppresses expression values.load and print functions (similar to those found in rhino) are provided. For example, given a javascript file, double.js:function double (x) { return x*2; }We can load the file:js> load('double.js') js> double(10) 20We can print values:js> print('Hi') HiA python object provides access to the open function and the os module:js> python.os.path.exists('double.js') True js! f = python.open('double.js') js> print(f.read()) function double (x) { return x*2; } <BLANKLINE> js> f.close()If you’re using manuel, you can intermix Python and and JavaScript examples and there are a number of APIs to facilitate using Python and JavaScript together.There’s an add_js_global function to copy data from Python:>>> add_js_global('y', 1) js> y 1There’s also a js object that provides attribute access to js globals:>>> js.x 3 >>> js.z = 4 js> z 4You can also call this to run JS code without returning the resulting value:>>> js('a = x + y') js> a 4Changelog1.0.1 (2013-02-14)Fixed ReStructuredText errors on the PyPI page.1.0.0 (2013-02-13)Added Python 3.3 support.Cleanupsetup.py, addtox.iniand manifest.0.1.0 (2011-05-19)Initial release
zcc-utils
zcc_utils介绍Accumulated tool modules Currently there are:Convert JSON string to custom typeGet the number after the decimal point, 1.2 = > 2Get the number after the decimal point, 1.2 = > 0.2Seconds to minutesSecond to hourThe hour to time type of float type, 12.99 hours = > 12:59:24安装说明pip install -i https://pypi.Python.org/simple/ zcc-utils --trusted-host pypi.Python.org
zc.datetimewidget
There are two types of widgets provided by this package, a date widget and a datetime widget.ContentsDatetime and Date WidgetsDate WidgetDatetime WidgetCalendar WidgetConfigurationDumping JavaScriptDate set widgetDatetime Widget DemoCHANGES0.8.0 (2016-01-12)0.7.0 (2011-06-07)0.6.4 (2009-10-20)0.6.3 (2009-08-24)0.6.2 (2009-05-20)0.6.1 (2008-05-29)0.5.2 (2007-11-03)0.5.1 (2006-06-15)0.5.0 (2006-05-24)Datetime and Date WidgetsThere are two types of widgets provided by this package, a date widget and a datetime widget.Date WidgetThe date widget only handles datetime.date objects, which are not timezone aware. We use the demo package here to have a content class.>>> from zope import component >>> from datetime import datetime, date >>> from zc.datetimewidget import datetimewidget >>> from zc.datetimewidget.demo.content import DemoContent >>> from zc.datetimewidget.demo.interfaces import IDemoContent >>> from zope.publisher.browser import TestRequest, BrowserLanguages >>> component.provideAdapter(BrowserLanguages) >>> request = TestRequest(HTTP_ACCEPT_LANGUAGE='en-US') >>> field = IDemoContent['startDate'] >>> widget = datetimewidget.DateWidget(field,request) >>> widget._toFormValue(None) u''Now let us convert a real date.>>> d = date(2006,5,1) >>> formValue = widget._toFormValue(d) >>> formValue '2006-05-01'>>> parsedValue = widget._toFieldValue(formValue) >>> parsedValue datetime.date(2006, 5, 1)The widget handles the same date notations as zope’s default datewidget.>>> widget._toFieldValue('2006/12/31') datetime.date(2006, 12, 31)Datetime WidgetDatetimes are always stored timezone aware, and by default the utc timezone is used.In order to handle timezones correctly the zope instance has to provide an adapter from IBrowserRequest to ITZInfo. It is up to the instance what kind of implementation it uses. For this test, we just use the implementation of the demo.timezone module which always returns Europe/Vienna as timezone.The field’s missing value results in an empty string.>>> import pytz >>> from zc.datetimewidget.demo import timezone >>> component.provideAdapter(timezone.tzinfo) >>> tz = pytz.timezone('Europe/Vienna') >>> request = TestRequest(HTTP_ACCEPT_LANGUAGE='en-US') >>> field = IDemoContent['startDatetime'] >>> widget = datetimewidget.DatetimeWidget(field,request)>>> widget._toFormValue(None) u''Now let us convert a real datetime.>>> dt = datetime(2006,5,1,12,tzinfo=pytz.utc) >>> formValue = widget._toFormValue(dt) >>> formValue '2006-05-01 14:00:00' >>> parsedValue = widget._toFieldValue(formValue) >>> parsedValue datetime.datetime(2006, 5, 1, 12, 0, tzinfo=<UTC>)The datetime might also be an naive one (without time zone) but it gets saved with UTC timezone information.>>> naive_dt = datetime(2006,5,1,12) >>> formValue = widget._toFormValue(naive_dt) >>> formValue '2006-05-01 12:00:00' >>> parsedValue = widget._toFieldValue(formValue) >>> parsedValue datetime.datetime(2006, 5, 1, 10, 0, tzinfo=<UTC>)While the widget tries to parse dates in the form ‘%Y-%m-%d %H:%M:%S’ first, it will fall through to the locale-specific parsing of the core datetimewidget.>>> widget._toFieldValue('May 1, 2006 2:00:00 PM') datetime.datetime(2006, 5, 1, 12, 0, tzinfo=<UTC>)Calendar WidgetConfiguration>>> from zope.interface.verify import verifyObject >>> from zc.datetimewidget.datetimewidget import ( ... CalendarWidgetConfiguration, ICalendarWidgetConfiguration)Let’s create a standard configuration object:>>> conf = CalendarWidgetConfiguration('field.x') >>> verifyObject(ICalendarWidgetConfiguration, conf) TrueFields have their default values:>>> conf.daFormat u'%Y/%m/%d' >>> conf.singleClick True >>> print conf.flat NoneWe can customize some attributes during instantiation:>>> import datetime >>> conf = CalendarWidgetConfiguration('x', date=datetime.date(2006, 8, 25)) >>> conf.date datetime.date(2006, 8, 25)Dumping JavaScriptConfiguration can be dumped as JavaScript. First an empty configuration:>>> print CalendarWidgetConfiguration('field.x').dumpJS() Calendar.setup({ <BLANKLINE> });Now let’s add a few customizations:>>> conf = CalendarWidgetConfiguration('x', daFormat=u'%m-%d', ... inputField='inp', eventName=None, date=conf.date) >>> print conf.dumpJS() Calendar.setup({ inputField: 'inp', eventName: null, daFormat: '%m-%d', date: new Date(2006, 7, 25) });Invalid arguments are not accepted:>>> conf = CalendarWidgetConfiguration('x', foo='bar') Traceback (most recent call last): ... ValueError: unknown arguments: fooDate set widget>>> from zc.datetimewidget.datetimewidget import DateSetWidget >>> from zope.schema import Set >>> from zope.publisher.browser import TestRequest>>> class Context(object): ... somedates = set() >>> context = Context()>>> request = TestRequest() >>> field = Set(__name__='somedates') >>> field.set(context, set([datetime.date(2006, 12, 6), ... datetime.date(2006, 12, 7)])) >>> field = field.bind(context) >>> widget = DateSetWidget(field, object(), request)>>> print widget() # doctest: +REPORT_NDIFF <BLANKLINE> <input class="textType" id="field.somedates" name="field.somedates" size="30" type="text" value="" /> <input type="button" value="..." id="field.somedates_trigger"> <script type="text/javascript"> <BLANKLINE> var multi_field_somedates = [new Date(2006, 11, 6), new Date(2006, 11, 7)]; Calendar.setup({ inputField: 'field.somedates', button: 'field.somedates_trigger', ifFormat: '%Y-%m-%d', onClose: getMultipleDateClosedHandler("field.somedates", multi_field_somedates), multiple: multi_field_somedates }); <BLANKLINE> </script> <BLANKLINE>>>> print widget.hidden() # doctest: +REPORT_NDIFF <input class="hiddenType" id="field.somedates" name="field.somedates" type="hidden" value="" /> <input type="button" value="..." id="field.somedates_trigger"> <script type="text/javascript"> <BLANKLINE> var multi_field_somedates = [new Date(2006, 11, 6), new Date(2006, 11, 7)]; Calendar.setup({ inputField: 'field.somedates', button: 'field.somedates_trigger', ifFormat: '%Y-%m-%d', onClose: getMultipleDateClosedHandler("field.somedates", multi_field_somedates), multiple: multi_field_somedates }); <BLANKLINE> </script>Datetime Widget DemoThis demo packe provides a simple content class which uses the zc.datetimewidget>>> from zope.testbrowser.testing import Browser >>> browser = Browser() >>> browser.handleErrors = False >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.open('http://localhost/@@contents.html')It can be added by clicking on the “Datetimewidget Demo” link in the add menu. And giving it a name.>>> link = browser.getLink('Datetimewidget Demo') >>> link.click() >>> nameCtrl = browser.getControl(name='new_value') >>> nameCtrl.value = 'mydemo' >>> applyCtrl = browser.getControl('Apply') >>> applyCtrl.click() >>> link = browser.getLink('mydemo') >>> link.click() >>> browser.url 'http://localhost/mydemo/@@edit.html'We can fill in the values>>> browser.getControl('Start Date').value = '2006-11-15' >>> browser.getControl('End Date').value = '2006-11-16' >>> browser.getControl('Start Datetime').value = '2006-11-15T07:49:31Z' >>> browser.getControl('End Datetime').value = '2006-11-16T19:46:00Z' >>> browser.getControl('Several dates').value = '2006-11-20 2006-11-21 2006-11-22' >>> browser.getControl('Change').click()And they will be saved:>>> 'Required input is missing' in browser.contents False>>> '2006-11-15' in browser.contents True >>> '2006-11-16' in browser.contents True >>> '07:49' in browser.contents True >>> '19:46' in browser.contents True >>> '2006-11-20 2006-11-21 2006-11-22' in browser.contents TrueIf we do not fill some fields, we get missing value errors>>> browser.getControl('Start Date').value = '' >>> browser.getControl('Change').click() >>> 'Required input is missing' in browser.contents TrueLet’s step back:>>> browser.getControl('Start Date').value = '2006-11-15' >>> browser.getControl('Change').click() >>> 'Required input is missing' in browser.contents FalseNow let’s try not filling a date set field:>>> browser.getControl('Several dates').value = '' >>> browser.getControl('Change').click() >>> 'Required input is missing' in browser.contents TrueCHANGES0.8.0 (2016-01-12)Get rid of thezope.app.formdependency by usingzope.formlib>= 4.0.0.7.0 (2011-06-07)Fix tests using a newer zope.publisher that requires zope.login.Fix tests by not using deprecatedzope.app.securitypolicyRemove test dependencyzope.app.serverandzope.app.authentication. Usezope.passwordinstead.No longer using deprecatedzope.testing.doctestunit. Use python’s build-indoctestinstead.0.6.4 (2009-10-20)Make Calendar pop-up and drag behavior more consistent across browser modes in IE.0.6.3 (2009-08-24)Fixed handling of naive datetime objects, they no longer result in an exception but are displayed unchanged. When they get saved again they are saved with UTC timezone like all other ones.Addeddatetimewidget.txtdoctest tolong_descriptionto show up on pypi home page.Fixed home page name insetup.py.Added coverage analysis tools to buildout.Removed deprecated zpkg and zcml slugs.0.6.2 (2009-05-20)Using++resource++instead of@@/to load resources.Renaming “lang” directory (ZPublishergets confused because of a view with the same name exists inzope.traversing.namespace).Seegocept.datetimewidgetfor more details on how to use zc.datetimewidget with zope2.0.6.1 (2008-05-29)Unchanged from 0.5.2, but released with a new version number thanks to a package with an 0.6.1dev-rBFN revision found in the wild.0.5.2 (2007-11-03)Improve package data.Developed proper package dependencies.Merged functional tests intotests.py.0.5.1 (2006-06-15)Include license and copyright headers.0.5.0 (2006-05-24)Initial release.
zc.demostorage2
The zc.demostorage2 module provides a storage implementation that wraps two storages, a base storage and a storage to hold changes. The base storage is never written to. All new records are written to the changes storage. Both storages are expected to:Use packed 64-bit unsigned integers as object ids,Allocate object ids sequentially, starting from 0, andin the case of the changes storage, accept object ids assigned externally.In addition, it is assumed that less than 2**63 object ids have been allocated in the first storage.Note that DemoStorage also assumes that it’s base storage uses 64-bit unsigned integer object ids allocated sequentially.ContentsChange History0.1.1 (2008-02-07)0.1 (2008-02-04)ConfigurationDemo (doctest)DownloadChange History0.1.1 (2008-02-07)Fixed a packaging bug that caused some files to be omitted.0.1 (2008-02-04)Initial release.ConfigurationThe section below shows how to create zc.demostorage2 storages from Python. If you’re using ZConfig, you need to:import zc.demostroage2include a demostroage2 sectionHere’s an example that shows how to configure demo storage and how to use the configuration from python:>>> import ZODB.config >>> storage = ZODB.config.storageFromString(""" ... ... %import zc.demostorage2 ... ... <demostorage2> ... <filestorage base> ... path base.fs ... </filestorage> ... <filestorage changes> ... path changes.fs ... </filestorage> ... </demostorage2> ... """)This creates a demo storage that gets base data from a file storage named base.fs and stores changes in a file storage named changes.fs.>>> storage <DemoStorage2: DemoStorage2(base.fs, changes.fs)>>>> storage.close()Demo (doctest)Note that most people will configure the storage through ZConfig. If you are one of those people, you may want to stop here. :) The examples below show you how to use the storage from Python, but they also exercise lots of details you might not be interested in.To see how this works, we’ll start by creating a base storage and puting an object (in addition to the root object) in it:>>> from ZODB.FileStorage import FileStorage >>> base = FileStorage('base.fs') >>> from ZODB.DB import DB >>> db = DB(base) >>> from persistent.mapping import PersistentMapping >>> conn = db.open() >>> conn.root()['1'] = PersistentMapping({'a': 1, 'b':2}) >>> import transaction >>> transaction.commit() >>> db.close() >>> import os >>> original_size = os.path.getsize('base.fs')Now, lets reopen the base storage in read-only mode:>>> base = FileStorage('base.fs', read_only=True)And open a new storage to store changes:>>> changes = FileStorage('changes.fs')and combine the 2 in a demofilestorage:>>> from zc.demostorage2 import DemoStorage2 >>> storage = DemoStorage2(base, changes)If there are no transactions, the storage reports the lastTransaction of the base database:>>> storage.lastTransaction() == base.lastTransaction() TrueLet’s add some data:>>> db = DB(storage) >>> conn = db.open() >>> items = conn.root()['1'].items() >>> items.sort() >>> items [('a', 1), ('b', 2)]>>> conn.root()['2'] = PersistentMapping({'a': 3, 'b':4}) >>> transaction.commit()>>> conn.root()['2']['c'] = 5 >>> transaction.commit()Here we can see that we haven’t modified the base storage:>>> original_size == os.path.getsize('base.fs') TrueBut we have modified the changes database:>>> len(changes) 2Our lastTransaction reflects the lastTransaction of the changes:>>> storage.lastTransaction() > base.lastTransaction() True>>> storage.lastTransaction() == changes.lastTransaction() TrueLet’s walk over some of the methods so ewe can see how we delegate to the new oderlying storages:>>> from ZODB.utils import p64, u64 >>> storage.load(p64(0), '') == changes.load(p64(0), '') True >>> storage.load(p64(0), '') == base.load(p64(0), '') False >>> storage.load(p64(1), '') == base.load(p64(1), '') True>>> serial = base.getTid(p64(0)) >>> storage.loadSerial(p64(0), serial) == base.loadSerial(p64(0), serial) True>>> serial = changes.getTid(p64(0)) >>> storage.loadSerial(p64(0), serial) == changes.loadSerial(p64(0), ... serial) TrueThe object id of the new object is quite large:>>> u64(conn.root()['2']._p_oid) 4611686018427387905LLet’s look at some other methods:>>> storage.getName() 'DemoStorage2(base.fs, changes.fs)'>>> storage.sortKey() == changes.sortKey() True>>> storage.getSize() == changes.getSize() True>>> len(storage) == len(changes) TrueUndo methods are simply copied from the changes storage:>>> [getattr(storage, name) == getattr(changes, name) ... for name in ('supportsUndo', 'undo', 'undoLog', 'undoInfo') ... ] [True, True, True, True]Download
zc.dict
An efficient, persistent and subclassable dictPersistentDict is very inefficient if it contains more than a couple of values, and BTrees are not recommended to inherit from.This class is a simple wrapper over a BTree. It retains the efficiency of BTrees and is safe to use as a base class. Also, it implements the full Python dict interface.>>> from zc.dict import Dict >>> d = Dict() >>> d <zc.dict.dict.Dict object at ...>>>> d['foo'] = 'bar' >>> len(d) 1>>> d['bar'] = 'baz' >>> len(d) 2Note that an important difference between the Python dict and this Dict is that the Python dict uses hashes, and this uses BTree comparisons. Practically, this means that your keys should be of homogenous types. We use strings in these examples.Length is maintained separately, because len on a BTree is inefficient, as it has to wake up all buckets in the tree from the database.>>> d._len <BTrees.Length.Length object at ...> >>> d._len() 2In order to keep updates efficient for small changes, we unroll them as a series of setitems.>>> d.update({'bar': 'moo', 'ding': 'dong', 'beep': 'beep'}) >>> len(d) 4The Dict supports the fullupdateinterface.>>> d.update([['sha', 'zam'], ['ka', 'pow']]) >>> len(d) 6 >>> d['ka'] 'pow' >>> d.update(left='hook', right='jab') >>> len(d) 8 >>> d['left'] 'hook'popneeds to update the length.>>> d.pop('sha') 'zam' >>> d.pop('ka') 'pow' >>> d.pop('left') 'hook' >>> d.pop('right') 'jab' >>> len(d) 4…except when it doesn’t.>>> d.pop('nonexistent') Traceback (most recent call last): ... KeyError: 'nonexistent' >>> d.pop('nonexistent', 42) 42 >>> len(d) 4setdefaultalso sometimes needs to update the length.>>> len(d) 4 >>> d.setdefault('newly created', 'value') 'value' >>> d['newly created'] 'value' >>> len(d) 5>>> d.setdefault('newly created', 'other') 'value' >>> d['newly created'] 'value' >>> len(d) 5>>> del d['newly created'] # set things back to the way they were...keys,valuesanditemsreturn normal Python lists. Because of the underlying BTree, these are always in sort order of the keys.>>> d.keys() ['bar', 'beep', 'ding', 'foo']>>> d.values() ['moo', 'beep', 'dong', 'bar']>>> d.items() [('bar', 'moo'), ('beep', 'beep'), ('ding', 'dong'), ('foo', 'bar')]However, efficient BTree iterators are available via the iter methods:>>> iter(d) <OO-iterator object at ...> >>> d.iterkeys() <OO-iterator object at ...>>>> d.iteritems() <OO-iterator object at ...>>>> d.itervalues() <OO-iterator object at ...>popitem removes from the dict and returns a key-value pair:>>> len(d) 4>>> d.popitem() ('bar', 'moo')>>> len(d) 3The copy method creates a copy of a Dict:>>> c = d.copy() >>> c.items() == d.items() TrueHowever we don’t support comparison, except for identity, because of cowardice:>>> c == d False >>> Dict() == {} False >>> d == d Trueclear removes all the keys from the dict:>>> d.clear() >>> d.keys() [] >>> len(d) 0The rest of the dict methods are delegated to the underlying BTree:>>> c.has_key('beep') True >>> 'BEEP' in c False >>> c.get('nonexistent', 'default') 'default'SubclassingFor easy subclassing, the dict is intended to have three important characteristics:All addition is done with __setitem__ so overriding it will control addition.All removal is done with eitherpoporclearso overriding these methods will control removal.Calling __init__ without passing an argument will not try to access theupdatemethod.Let’s demonstrate these with a quick subclass.>>> class Demo(Dict): ... def __setitem__(self, key, value): ... print '__setitem__', key, value ... super(Demo, self).__setitem__(key, value) ... def pop(self, key, *args): ... print 'pop', key, args and arg[0] or '---' ... return super(Demo, self).pop(key, *args) ... def update(self, *args, **kwargs): ... print 'update' ... super(Demo, self).update(*args, **kwargs) ... def clear(self): ... print 'clear' ... super(Demo, self).clear() ...>>> demo1 = Demo() >>> demo2 = Demo([['foo', 'bar'], ['bing', 'baz']], sha='zam') update __setitem__ foo bar __setitem__ bing baz __setitem__ sha zam >>> demo2.setdefault('babble') __setitem__ babble None >>> del demo2['bing'] pop bing --- >>> demo2.popitem() pop babble --- ('babble', None) >>> demo2.clear() clearRegression testsWhen setting an item that’s already in the dict, the length is not increased:>>> d.clear() >>> d['foo'] = 'bar' >>> d['foo'] = 'baz' >>> len(d) 1Ordered Dict: An persistent container that maintains orderAn OrderedDict provides most of the functionality of a Dict, with the additional feature that it remembers the order in which items were added. It also provides the API to reorder the items.Importantly, the OrderedDict currently uses a PersistentList to store the order, which does not have good behavior for large collections, because the entire collection of keys must be pickled every time any key, or ordering, changes. A BList would be a preferred data structure, but that has not yet been released.>>> from zc.dict import OrderedDict >>> d = OrderedDict() >>> d <zc.dict.dict.OrderedDict object at ...>>>> d['foo'] = 'bar' >>> len(d) 1>>> d['bar'] = 'baz' >>> len(d) 2>>> d['foo'] 'bar' >>> d['bar'] 'baz'The keys are currently in the order added.>>> list(d) ['foo', 'bar']Note that an important difference between the Python dict and the OrderedDict is that the Python dict uses hashes, and this uses BTree comparisons. Practically, this means that your keys should be of homogenous types. We use strings in these examples.Length is maintained separately, because len on a BTree is inefficient, as it has to wake up all buckets in the tree from the database.>>> d._len <BTrees.Length.Length object at ...> >>> d._len() 2In order to keep updates efficient for small changes, we unroll them as a series of setitems.>>> d.update({'bar': 'moo', 'ding': 'dong', 'beep': 'beep'}) >>> len(d) 4Note that the result of an update of multiple new items in a data structure without order will add the new items to the end of the ordered dict in an undefined order. To set our order, we need to introduce a new method:updateOrder. This method is a heavy-handed approach to changing the order: supply a new one.>>> list(d) == ['bar', 'beep', 'ding', 'foo'] False >>> d.updateOrder(('bar', 'beep', 'ding', 'foo')) >>> d.keys() ['bar', 'beep', 'ding', 'foo']updateOrderexpects the entire list of keys in the new order>>> d.updateOrder(['bar', 'beep', 'ding']) Traceback (most recent call last): ... ValueError: Incompatible key set.>>> d.updateOrder(['bar', 'beep', 'ding', 'sha', 'foo']) Traceback (most recent call last): ... ValueError: Incompatible key set.>>> d.updateOrder(['bar', 'beep', 'ding', 'sha']) Traceback (most recent call last): ... ValueError: Incompatible key set.>>> d.updateOrder(['bar', 'beep', 'ding', 'ding']) Traceback (most recent call last): ... ValueError: Duplicate keys in order.The Dict supports the fullupdateinterface. If the input values are ordered, the result will be as well.>>> d.update([['sha', 'zam'], ['ka', 'pow']]) >>> len(d) 6 >>> d['ka'] 'pow' >>> d.keys() ['bar', 'beep', 'ding', 'foo', 'sha', 'ka']If keyword arguments are used, no order to the new items is implied, but it otherwise works as expected.>>> d.update(left='hook', right='jab') >>> len(d) 8 >>> d['left'] 'hook'popneeds to update the length, and maintain the order.>>> d.pop('sha') 'zam' >>> d.pop('ka') 'pow' >>> d.pop('left') 'hook' >>> d.pop('right') 'jab' >>> len(d) 4 >>> d.keys() ['bar', 'beep', 'ding', 'foo']…except when it doesn’t.>>> d.pop('nonexistent') Traceback (most recent call last): ... KeyError: 'nonexistent' >>> d.pop('nonexistent', 42) 42 >>> len(d) 4setdefaultalso sometimes needs to update the length.>>> len(d) 4 >>> d.setdefault('newly created', 'value') 'value' >>> d['newly created'] 'value' >>> len(d) 5 >>> d.keys() ['bar', 'beep', 'ding', 'foo', 'newly created']>>> d.setdefault('newly created', 'other') 'value' >>> d['newly created'] 'value' >>> len(d) 5>>> del d['newly created'] # set things back to the way they were...keys,valuesanditemsreturn normal Python lists. Because of the underlying BTree, these are always in sort order of the keys.>>> d.keys() ['bar', 'beep', 'ding', 'foo']>>> d.values() ['moo', 'beep', 'dong', 'bar']>>> d.items() [('bar', 'moo'), ('beep', 'beep'), ('ding', 'dong'), ('foo', 'bar')]However, efficient iterators are available via the iter methods:>>> iter(d) <iterator object at ...> >>> d.iterkeys() <iterator object at ...>>>> d.iteritems() <generator object at ...>>>> d.itervalues() <generator object at ...>popitem removes an item from the dict and returns a key-value pair:>>> len(d) 4>>> d.popitem() ('bar', 'moo')>>> len(d) 3The copy method creates a copy of a Dict:>>> c = d.copy() >>> c.items() == d.items() TrueHowever we don’t support comparison, except for identity, because of cowardice:>>> c == d False >>> OrderedDict() == {} False >>> d == d Trueclear removes all the keys from the dict:>>> d.clear() >>> d.keys() [] >>> len(d) 0The rest of the dict methods are delegated to the underlying BTree:>>> c.has_key('beep') True >>> 'BEEP' in c False >>> c.get('nonexistent', 'default') 'default'SubclassingFor easy subclassing, the ordered dict is intended to have three important characteristics:All addition is done with __setitem__ so overriding it will control addition.All removal is done with eitherpoporclearso overriding these methods will control removal.Calling __init__ without passing an argument will not try to access theupdatemethod.Let’s demonstrate these with a quick subclass.>>> class Demo(OrderedDict): ... def __setitem__(self, key, value): ... print '__setitem__', key, value ... super(Demo, self).__setitem__(key, value) ... def pop(self, key, *args): ... print 'pop', key, args and arg[0] or '---' ... return super(Demo, self).pop(key, *args) ... def update(self, *args, **kwargs): ... print 'update' ... super(Demo, self).update(*args, **kwargs) ... def clear(self): ... print 'clear' ... super(Demo, self).clear() ...>>> demo1 = Demo() >>> demo2 = Demo([['foo', 'bar'], ['bing', 'baz']], sha='zam') update __setitem__ foo bar __setitem__ bing baz __setitem__ sha zam >>> demo2.setdefault('babble') __setitem__ babble None >>> del demo2['bing'] pop bing --- >>> demo2.popitem() pop babble --- ('babble', None) >>> demo2.clear() clearRegression testsWhen setting an item that’s already in the dict, the length is not increased:>>> d.clear() >>> d['foo'] = 'bar' >>> d['foo'] = 'baz' >>> len(d) 1Legacy testsOld databases may need to find something importable from zc.dict.ordered.>>> from zc.dict.ordered import OrderedDict as Olde >>> Olde is OrderedDict True
zc.displayname
AdaptersDefault Display Name GeneratorThe default display name generator simply takes a Dublin Core title or a __name__ and returns it, truncated if desired. It uses a helper function intended to make writing other display name generators easier, convertName.No help is offered yet for using HTML with the IBrowserDisplayNameGenerator interface.Given an ILocation that can be adapted to zope.dublincore.interfaces.IDCDescriptiveProperties, and that actually has a value for it, it returns the DC title; otherwise, it uses __name__.>>> import zope.dublincore.interfaces >>> import zope.location.interfaces >>> from zc.displayname import interfaces, adapters >>> from zope.interface import verify >>> from zope import interface >>> class Dummy(object): ... interface.implements(zope.location.interfaces.ILocation) ... def __init__(self, parent, name): ... self.__parent__ = parent ... self.__name__ = name ... >>> d = Dummy('parent', 'a name') >>> from zope.publisher.browser import TestRequest >>> g = adapters.DefaultDisplayNameGenerator(d, TestRequest()) >>> verify.verifyObject(interfaces.IDisplayNameGenerator, g) True >>> g() 'a name' >>> g('foo') Traceback (most recent call last): ... TypeError: ('maxlength must be int', 'foo') >>> g(-1) Traceback (most recent call last): ... ValueError: ('maxlength must be 0 or greater', -1) >>> g(4) 'a...' >>> g(6) 'a name' >>> g(2) '??' >>> interface.directlyProvides( ... d, zope.dublincore.interfaces.IDCDescriptiveProperties) >>> d.title = 'My Special Dummy' >>> d.description = 'My interface said I had to have this' >>> verify.verifyObject( ... zope.dublincore.interfaces.IDCDescriptiveProperties, d) True >>> g() 'My Special Dummy' >>> g(0) '' >>> g(100) 'My Special Dummy' >>> g(16) 'My Special Dummy' >>> g(15) 'My Special D...'Breadcrumbszc.displayname also provides an interface and some basic adapters that provide breadcrumb functionality. This breadcrumb functionality is notably different from the standard Zope 3 breadcrumbs in two ways: the breadcrumbs are not connected to the IAbsoluteURL interface, and the breadcrumbs take advantage of the display name generator.To use the breadcrumbs, register the appropriate adapters, and get breadcrumbs for an ILocation within a hierarchy with an IContainmentRoot as a root node.>>> from zope.traversing.interfaces import IContainmentRoot >>> class DummyContainmentRoot(object): ... zope.interface.implements(IContainmentRoot) ... >>> root = DummyContainmentRoot() >>> child = Dummy(root, 'foo') >>> grandchild = Dummy(child, 'bar baz bing') >>> d.__parent__ = grandchild >>> from zope import component >>> component.provideAdapter(adapters.Breadcrumbs) >>> component.provideAdapter(adapters.TerminalBreadcrumbs) >>> component.provideAdapter(adapters.DefaultDisplayNameGenerator) >>> component.provideAdapter(adapters.SiteDisplayNameGenerator) >>> from zope.publisher.interfaces.http import IHTTPRequest >>> from zope.traversing.browser.interfaces import IAbsoluteURL >>> from zope.traversing import browser >>> component.provideAdapter( ... browser.AbsoluteURL, adapts=(None, IHTTPRequest), ... provides=IAbsoluteURL) >>> component.provideAdapter( ... browser.SiteAbsoluteURL, adapts=(IContainmentRoot, IHTTPRequest), ... provides=IAbsoluteURL) >>> component.provideAdapter( ... browser.AbsoluteURL, adapts=(None, IHTTPRequest), ... provides=interface.Interface, name='absolute_url') >>> component.provideAdapter( ... browser.SiteAbsoluteURL, adapts=(IContainmentRoot, IHTTPRequest), ... provides=interface.Interface, name='absolute_url') >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> bc = component.getMultiAdapter((d, request), interfaces.IBreadcrumbs) >>> import pprint >>> pprint.pprint(bc()) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ({'name': u'[root]', 'name_gen': <...SiteDisplayNameGenerator...>, 'object': <DummyContainmentRoot...>, 'url': 'http://127.0.0.1'}, {'name': 'foo', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy... 'url': 'http://127.0.0.1/foo'}, {'name': 'bar baz bing', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing'}, {'name': 'My Special Dummy', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing/a%20name'}) >>> pprint.pprint(bc(6)) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ({'name': u'[root]', 'name_gen': <...SiteDisplayNameGenerator...>, 'object': <DummyContainmentRoot...>, 'url': 'http://127.0.0.1'}, {'name': 'foo', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy... 'url': 'http://127.0.0.1/foo'}, {'name': 'bar...', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing'}, {'name': 'My ...', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing/a%20name'})The package also offers a hidden breadcrumb implementation. This enables usecases that involve objects that are in the traversal path but are for which no breadcrumbs are desired. For some sites, an IAdding is such an object. Here is an example of hiding the IAdding from the breadcrumbs.>>> import zope.app.container.interfaces >>> component.provideAdapter( ... adapters.HiddenBreadcrumbs, ... adapts=(zope.app.container.interfaces.IAdding, IHTTPRequest)) >>> from zope.app.container.browser.adding import Adding >>> adding = Adding(d, request) >>> bc = component.getMultiAdapter( ... (adding, request), interfaces.IBreadcrumbs) >>> pprint.pprint(bc()) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ({'name': u'[root]', 'name_gen': <...SiteDisplayNameGenerator...>, 'object': <DummyContainmentRoot...>, 'url': 'http://127.0.0.1'}, {'name': 'foo', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy... 'url': 'http://127.0.0.1/foo'}, {'name': 'bar baz bing', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing'}, {'name': 'My Special Dummy', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing/a%20name'})For ease of use within page templates, the adapters module also offers two views that can be used to get breadcrumbs directly. They simply get the adapter and call it, either with no argument, or with the maxlength argument of 20. Register one of these, or another one with a similar pattern, for your application’sbreadcrumbsview.>>> pprint.pprint(adapters.breadcrumbs(adding, request)) ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ({'name': u'[root]', 'name_gen': <...SiteDisplayNameGenerator...>, 'object': <DummyContainmentRoot...>, 'url': 'http://127.0.0.1'}, {'name': 'foo', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy... 'url': 'http://127.0.0.1/foo'}, {'name': 'bar baz bing', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing'}, {'name': 'My Special Dummy', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing/a%20name'}) >>> d.title = "My Special Dummy With a Really Long Title" >>> pprint.pprint(adapters.breadcrumbs20char(adding, request)) ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ({'name': u'[root]', 'name_gen': <...SiteDisplayNameGenerator...>, 'object': <DummyContainmentRoot...>, 'url': 'http://127.0.0.1'}, {'name': 'foo', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy... 'url': 'http://127.0.0.1/foo'}, {'name': 'bar baz bing', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing'}, {'name': 'My Special Dummy ...', 'name_gen': <...DefaultDisplayNameGenerator...>, 'object': <Dummy...>, 'url': 'http://127.0.0.1/foo/bar%20baz%20bing/a%20name'})
zc.dojoform
UNKNOWN
zc-events
No description available on PyPI.
zc.extrinsicreference
Extrinsic Key ReferencesSeesrc/zc/extrinsicreference/README.txtfor details.Detailed DocumentationExtrinsic ReferencesExtrinsic reference registries record a key and one or more values to which they refer. The key and all values must be adaptable to zope.app.keyreference.interfaces.IKeyReference.>>> import zc.extrinsicreference >>> references = zc.extrinsicreference.ExtrinsicReferences() >>> references.add(1, 2) Traceback (most recent call last): ... TypeError: ('Could not adapt', 1... >>> from zope import interface, component >>> from zope.app.keyreference.interfaces import IKeyReference >>> class IMyObject(interface.Interface): ... "An interface for which we register an IKeyReference adapter" ... id = interface.Attribute("An id unique to IMyObject instances") ... >>> class MyObject(object): ... interface.implements(IMyObject) ... _id_counter = 0 ... @classmethod ... def _getId(cls): ... val = cls._id_counter ... cls._id_counter += 1 ... return val ... def __init__(self): ... self.id = self._getId() ... >>> class DummyKeyReference(object): ... interface.implements(IKeyReference) ... component.adapts(IMyObject) ... key_type_id = 'zc.extrinsicreference.doctest' ... def __init__(self, obj): ... self.object = obj ... def __call__(self): ... """Get the object this reference is linking to. ... """ ... return self.object ... def __hash__(self): ... """Get a unique identifier of the referenced object. ... """ ... return hash(self.object.id) ... def __cmp__(self, other): ... """Compare the reference to another reference. ... """ ... if self.key_type_id == other.key_type_id: ... return cmp(self.object.id, other.object.id) ... return cmp(self.key_type_id, other.key_type_id) ... >>> component.provideAdapter(DummyKeyReference) >>> object1 = MyObject() >>> references.add(object1, 2) Traceback (most recent call last): ... TypeError: ('Could not adapt', 2... >>> value1 = MyObject() >>> value2 = MyObject() >>> references.add(object1, value1) >>> references.add(object1, value2)Values can be retrieved by their key:>>> set(references.get(object1)) == set((value1, value2)) TrueReferences can be removed:>>> references.remove(object1, value1) >>> list(references.get(object1)) == [value2] TrueBut if the reference is not registered, removing it raises a KeyError.>>> references.remove(object1, value1) Traceback (most recent call last): ... KeyError:... >>> object2 = MyObject() >>> references.remove(object2, value2) Traceback (most recent call last): ... KeyError:...If you prefer to silently ignore these errors, usediscard.>>> references.discard(object1, value1) >>> references.discard(object2, value2)Otherwise, you can usecontainsto determine if the reference exists:>>> references.contains(object1, value1) False >>> references.contains(object2, value2) False >>> references.contains(object1, value2) TrueIf a key has no associated values, an empty iterable is returned:>>> references.discard(object1, value2) >>> list(references.get(object1)) []Adding a value more than once does not cause the value to be included in the result sequence more than once:>>> references.add(object1, value1) >>> references.add(object1, value1) >>> list(references.get(object1)) == [value1] TrueThesetmethod destructively sets the given values for the object. Repeated objects are collapsed to a single instance.>>> references.set(object1, (value2, object2, value2, value2, object2)) >>> references.contains(object1, value1) False >>> len(list(references.get(object1))) 2 >>> set(references.get(object1)) == set((value2, object2)) True >>> references.set(object1, ()) >>> len(list(references.get(object1))) 0Theupdatemethod adds values to the previous values, non-destructively.>>> references.add(object1, value1) >>> references.update(object1, (value2, object2, value2)) >>> len(list(references.get(object1))) 3 >>> set(references.get(object1)) == set((value1, value2, object2)) TrueCHANGES0.3.0 (2009-08-27)Fix errors introduced in 0.2.0 refactoring:Stop referring to extrinsicreference module from ZCML. The code is now in__init__.py.RevertregisterShortcutandunregisterShortcutchanges. These two functions are handlers intrack_shortcuts.zcml.Add more package infrastructure, such as this file.0.2.0 (2009-08-26)Refactored an existing stable code.Initial release as an egg.
zcfd-validate
This package provides a cli to check that a zCFD input dictionary correctly validates against the schema provided for the latest version of zCFD (https://zcfd.zenotech.com/)
zc.FileStorage
UNKNOWN
zc.form
The zc.form package is a possibly temporary appendage used to hold extra browser widgets and alternative approaches to code found in the zope.formlib package. Most or all of the code is created by Zope Corporation and is intended for eventual folding into the main Zope 3 release.ContentsChanges2.0 (2023-02-06)1.1 (2019-02-11)1.0 (2019-01-11)FeaturesBugfixesCaveats0.5 (2016-08-02)0.4 (2016-01-12)0.3 (2014-04-23)0.2 (2011-09-24)0.1CombinationWidgetMost Recently Used (MRU) Source WidgetChanges2.0 (2023-02-06)Add support for Python 3.8, 3.9, 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.1.1 (2019-02-11)Fix ZCML configuration issue if the[mruwidget]extra was not installed.1.0 (2019-01-11)FeaturesClaim support for Python 3.5, 3.6, 3.7, PyPy and PyPy3.BugfixesFix aNameErrorinBaseVocabularyDisplay.render().Actually pass amissing_valueset on theCombinationfield to the containing fields.CaveatsInstallation ofMruSourceInputWidgetandTimeZoneWidgetrequires the[mruwidget]extra to break dependency onzc.resourcelibraryfor projects which do not need it.0.5 (2016-08-02)Bind fields that are contained in azc.form.field.Combinationto fix thecontextof those fields.0.4 (2016-01-12)Get rid of thezope.app.pagetemplatedependency.0.3 (2014-04-23)Remove requirement, thatzc.form.field.Combinationneeds at least two subfields.0.2 (2011-09-24)Got rid ofzope.app.formdependency by requiring at leastzope.formlib4.0.Got rid ofzope.app.componentdependency by requiring at leastzope.component3.8.Depending onzope.cataloginstead ofzope.app.catalog.Depending onzope.securityinstead ofzope.app.security.Depending onzope.app.wsgi>=3.7 instead ofzope.app.testingfor test setup.Depending onzope.browserpageandzope.containerinstead ofzope.app.publisher.Got rid of the following dependencies:zope.app.basicskinzope.app.securitypolicyzope.app.zapizope.app.zcmlfilesFixed tests to run withzope.schema>= 3.6.Made package fit to run on ZTK 1.1.Moved test dependencies totestextra.Using Python’sdoctestmodule instead of deprecatedzope.testing.doctest.0.1Exception views are now unicode aware. They used to break on translated content.Added use_default_for_not_selected to Union field to use default value even if sub field is not selected.CombinationWidgetThe combinationwidget collects two or more subfields to provide a convenient way to specify a sequence of values.Rendering the widget returns a table with the subfields:>>> from zc.form.browser.combinationwidget import ( ... CombinationWidget, CombinationDisplayWidget, default_template) >>> from zope import component, interface >>> component.provideAdapter(default_template, name='default') >>> from zc.form.field import Combination, OrderedCombinationConstraint >>> from zope.schema import Int >>> from zope.schema.interfaces import IInt >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> from zope.formlib.interfaces import IInputWidget >>> from zope.formlib.textwidgets import IntWidget >>> component.provideAdapter( ... IntWidget, (IInt, IBrowserRequest), IInputWidget) >>> from zope import interface >>> class IDemo(interface.Interface): ... acceptable_count = Combination( ... (Int(title=u'Minimum', required=True, min=0), ... Int(title=u'Maximum', required=False)), ... title=u'Acceptable Count', ... required=False, ... constraints=(OrderedCombinationConstraint(),)) ... >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> widget = CombinationWidget(IDemo['acceptable_count'], request) >>> widget.setPrefix('field') >>> widget.loadValueFromRequest() # None >>> print(widget()) <input type='hidden' name='field.acceptable_count-marker' value='x' /> <table class="combinationFieldWidget"> <tr> <td class="label"> <label for="field.acceptable_count.combination_00"> <span class="required">*</span><span>Minimum</span> </label> </td> <td class="field"> <div class="widget"><input class="textType" id="field.acceptable_count.combination_00" name="field.acceptable_count.combination_00" size="10" type="text" value="" /> </div> </td> </tr> <tr> <td class="label"> <label for="field.acceptable_count.combination_01"> <span>Maximum</span> </label> </td> <td class="field"> <div class="widget"><input class="textType" id="field.acceptable_count.combination_01" name="field.acceptable_count.combination_01" size="10" type="text" value="" /> </div> </td> </tr> </table>Setting the appropriate values in the Request lets the widget correctly read the specified value:>>> request.form['field.acceptable_count-marker'] = 'x' >>> request.form['field.acceptable_count.combination_00'] = '10' >>> request.form['field.acceptable_count.combination_01'] = '' >>> widget = CombinationWidget(IDemo['acceptable_count'], request) >>> widget.setPrefix('field') >>> widget.getInputValue() (10, None) >>> print(widget()) <... ...<input class="textType" id="field.acceptable_count.combination_00" name="field.acceptable_count.combination_00" size="10" type="text" value="10" />... ...<input class="textType" id="field.acceptable_count.combination_01" name="field.acceptable_count.combination_01" size="10" type="text" value="" />...The field is fine with empty values, because it is not required:>>> request.form['field.acceptable_count-marker'] = 'x' >>> request.form['field.acceptable_count.combination_00'] = '' >>> request.form['field.acceptable_count.combination_01'] = '' >>> widget = CombinationWidget(IDemo['acceptable_count'], request) >>> widget.setPrefix('field') >>> widget.getInputValue() # None >>> print(widget()) <... ...<input class="textType" id="field.acceptable_count.combination_00" name="field.acceptable_count.combination_00" size="10" type="text" value="" />... ...<input class="textType" id="field.acceptable_count.combination_01" name="field.acceptable_count.combination_01" size="10" type="text" value="" />... >>> bool(widget.error()) False >>> bool(widget.widgets[0].error()) FalseIf the optional value is filled in and the required one is not, though, there are errors:>>> request.form['field.acceptable_count-marker'] = 'x' >>> request.form['field.acceptable_count.combination_00'] = '' >>> request.form['field.acceptable_count.combination_01'] = '10' >>> widget = CombinationWidget(IDemo['acceptable_count'], request) >>> widget.setPrefix('field') >>> widget.getInputValue() Traceback (most recent call last): WidgetInputError: ('acceptable_count', u'Acceptable Count', WidgetInputError('combination_00', u'Minimum', RequiredMissing('combination_00'))) >>> import zope.formlib.interfaces >>> import zope.publisher.interfaces.browser >>> @interface.implementer(zope.formlib.interfaces.IWidgetInputErrorView) ... @component.adapter(zope.formlib.interfaces.WidgetInputError, ... zope.publisher.interfaces.browser.IBrowserRequest) ... class SnippetView(object): ... ... def __init__(self, context, request): ... self.context = context ... self.request = request ... def snippet(self): ... return self.context.doc() ... >>> component.provideAdapter(SnippetView) >>> print(widget()) <... ...<input class="textType" id="field.acceptable_count.combination_00" name="field.acceptable_count.combination_00" size="10" type="text" value="" />... ...Required input is missing... ...<input class="textType" id="field.acceptable_count.combination_01" name="field.acceptable_count.combination_01" size="10" type="text" value="10" />... >>> print(widget.error()) Required input is missing. >>> print(widget.widgets[0].error()) Required input is missing.Similarly, if the field’s constraints are not met, the widget shows errors:>>> request.form['field.acceptable_count-marker'] = 'x' >>> request.form['field.acceptable_count.combination_00'] = '20' >>> request.form['field.acceptable_count.combination_01'] = '10' >>> widget = CombinationWidget(IDemo['acceptable_count'], request) >>> widget.setPrefix('field') >>> widget.getInputValue() Traceback (most recent call last): WidgetInputError: ('acceptable_count', u'Acceptable Count', MessageValidationError(u'${minimum} ... >>> print(widget()) <... ...input class="textType" id="field.acceptable_count.combination_00" name="field.acceptable_count.combination_00" size="10" type="text" value="20" />... ...<input class="textType" id="field.acceptable_count.combination_01" name="field.acceptable_count.combination_01" size="10" type="text" value="10" />... >>> print(widget.error()) ${minimum} must be less than or equal to ${maximum}.There’s also a display version of the widget:>>> request = TestRequest() >>> from zope.formlib.widget import DisplayWidget >>> from zope.formlib.interfaces import IDisplayWidget >>> component.provideAdapter( ... DisplayWidget, (IInt, IBrowserRequest), IDisplayWidget) >>> widget = CombinationDisplayWidget(IDemo['acceptable_count'], request) >>> widget.setPrefix('field') >>> widget.setRenderedValue(('10', '2')) >>> print(widget()) <input type='hidden' name='field.acceptable_count-marker' value='x' /> <table class="combinationFieldWidget"> <tr> <td class="label"> <label for="field.acceptable_count.combination_00"> <span>Minimum</span> </label> </td> <td class="field"> <div class="widget">10 </div> </td> </tr> <tr> <td class="label"> <label for="field.acceptable_count.combination_01"> <span>Maximum</span> </label> </td> <td class="field"> <div class="widget">2 </div> </td> </tr> </table>In case of a wrong amount of parameters, the missing_value is used:>>> field = IDemo['acceptable_count'] >>> field.missing_value=('23', '42') >>> widget = CombinationDisplayWidget(field, request) >>> widget.setPrefix('field') >>> widget.setRenderedValue(('10', '2', '3')) >>> print(widget()) <input type='hidden' name='field.acceptable_count-marker' value='x' /> <table class="combinationFieldWidget"> <tr> <td class="label"> <label for="field.acceptable_count.combination_00"> <span>Minimum</span> </label> </td> <td class="field"> <div class="widget">23 </div> </td> </tr> <tr> <td class="label"> <label for="field.acceptable_count.combination_01"> <span>Maximum</span> </label> </td> <td class="field"> <div class="widget">42 </div> </td> </tr> </table>In case the parameter is not a sequence, the missing_value is used:>>> widget = CombinationDisplayWidget(field, request) >>> widget.setPrefix('field') >>> widget.setRenderedValue(10) >>> print(widget()) <input type='hidden' name='field.acceptable_count-marker' value='x' /> <table class="combinationFieldWidget"> <tr> <td class="label"> <label for="field.acceptable_count.combination_00"> <span>Minimum</span> </label> </td> <td class="field"> <div class="widget">23 </div> </td> </tr> <tr> <td class="label"> <label for="field.acceptable_count.combination_01"> <span>Maximum</span> </label> </td> <td class="field"> <div class="widget">42 </div> </td> </tr> </table>The order of label and field are inverted in case of boolean:>>> request = TestRequest() >>> from zope.schema import Bool >>> from zope.schema.interfaces import IBool >>> from zope.formlib.boolwidgets import CheckBoxWidget >>> from zope.formlib.widget import DisplayWidget >>> from zope.formlib.interfaces import IDisplayWidget >>> component.provideAdapter( ... CheckBoxWidget, (IBool, IBrowserRequest), IInputWidget) >>> class IBoolDemo(interface.Interface): ... choices = Combination( ... (Bool(title=u'first'), ... Bool(title=u'second')), ... title=u'Choices', ... required=False,) >>> widget = CombinationWidget(IBoolDemo['choices'], request) >>> widget.setPrefix('field') >>> print(widget()) <input type='hidden' name='field.choices-marker' value='x' /> <table class="combinationFieldWidget"> <tr> <td></td> <td class="field"> <div class="widget"><input class="hiddenType" id="field.choices.combination_00.used" name="field.choices.combination_00.used" type="hidden" value="" /> <input class="checkboxType" id="field.choices.combination_00" name="field.choices.combination_00" type="checkbox" value="on" /> <span>first</span> </div> </td> </tr> <tr> <td></td> <td class="field"> <div class="widget"><input class="hiddenType" id="field.choices.combination_01.used" name="field.choices.combination_01.used" type="hidden" value="" /> <input class="checkboxType" id="field.choices.combination_01" name="field.choices.combination_01" type="checkbox" value="on" /> <span>second</span> </div> </td> </tr> </table>Most Recently Used (MRU) Source WidgetThe MRU widget keeps track of the last few values selected (on a per-principal basis) and allows quickly selecting from that list instead of using a query interface.We can see the widget in action by using a custom form. Let’s define a schema for the form that uses a source:>>> import zope.interface >>> import zope.schema >>> class IDemo(zope.interface.Interface): ... ... color = zope.schema.Choice( ... title=u"Color", ... description=u"My favorite color", ... source=AvailableColors, ... )And then a class that implements the interface:>>> @zope.interface.implementer(IDemo) ... class Demo(object): ... ... color = NoneWe’ll need a form that uses this schema:>>> import zope.formlib.form >>> class DemoInput(zope.formlib.form.EditForm): ... actions = () ... form_fields = zope.formlib.form.fields(IDemo)By rendering the form we can see that there are no MRU items to choose from (because this principal has never visited this form before) and the query interface is displayed:>>> import zope.publisher.browser >>> import zope.security.interfaces >>> import zope.security.management >>> import zope.component.hooks >>> @zope.interface.implementer(zope.security.interfaces.IPrincipal) ... class DummyPrincipal(object): ... ... id = "someuser" ... title = "Some User's Name" ... description = "A User"Note that we need to use the special resourcelibrary request. We’re hacking together the TestRequest and the resourcelibrary request here; when we switch to TestBrowser we can remove this oddity.>>> import zc.resourcelibrary.publication >>> class TestRequest(zope.publisher.browser.TestRequest, ... zc.resourcelibrary.publication.Request): ... def _createResponse(self): ... return zc.resourcelibrary.publication.Request._createResponse( ... self) ...>>> request = TestRequest() >>> principal = DummyPrincipal() >>> request.setPrincipal(principal) >>> zope.security.management.newInteraction(request)>>> oldsite = zope.component.hooks.getSite() >>> zope.component.hooks.setSite(getRootFolder())Now we can use an instance of our demo object to see that the form pulls the possible values from the vocabulary we’ve defined above:>>> form = DemoInput(Demo(), request) >>> print(form()) <... <div class="queries"...> <div class="query"...> <div class="queryinput"...> <query view for colors> </div> <!-- queryinput --> </div> <!-- query --> </div> <!-- queries --> ...Note that the select box of MRU values isn’t in the output, because the user has never selected a value before:>>> '<select name="form.color">' not in form() TrueNow, we can select one of the values:>>> zope.security.management.endInteraction() >>> request = TestRequest() >>> request.form = { ... 'form.color.query.selection': 'red_token', ... 'form.color.query.apply': 'Apply', ... 'form.color.displayed': '', ... } >>> request.setPrincipal(principal) >>> zope.security.management.newInteraction(request)Process the request and the list of MRU values is in the form:>>> form = DemoInput(Demo(), request) >>> print(form()) <... <select name="form.color" id="form.color"> <option value="red_token" selected="selected">Red</option> </select> ...And the query view is hidden because we have an MRU list:>>> print(form()) <... <input type="hidden" name="form.color.queries.visible" ... value="no"> ...If we select another value…:>>> request = TestRequest() >>> request.form = { ... 'form.color.query.selection': 'green_token', ... 'form.color.query.apply': 'Apply', ... 'form.color.displayed': '', ... } >>> request.setPrincipal(principal)…and process the request, the list of MRU values includes the new one, at the top, and it is selected:>>> form = DemoInput(Demo(), request) >>> print(form()) <... <select name="form.color" id="form.color"> <option value="green_token" selected="selected">Green</option> <option value="red_token">Red</option> </select> ...If we request a value not in the source everything stays the same, but nothing is selected:>>> request = TestRequest() >>> request.form = { ... 'form.color.query.selection': 'blue_token', ... 'form.color.query.apply': 'Apply', ... 'form.color.displayed': '', ... } >>> request.setPrincipal(principal) >>> form = DemoInput(Demo(), request) >>> print(form()) <... <select name="form.color" id="form.color"> <option value="green_token">Green</option> <option value="red_token">Red</option> </select> ...We can make the query visible:>>> request = TestRequest() >>> request.form = { ... 'form.color.query.selection': 'red_token', ... 'form.color.query.apply': 'Apply', ... 'form.color.queries.visible': 'yes', ... 'form.color.query.search': 'yes', ... 'form.color.query.searchstring': 'red', ... 'form.color.displayed': '', ... } >>> request.setPrincipal(principal) >>> form = DemoInput(Demo(), request) >>> print(form()) <... <select name="form.color" id="form.color"> <option value="red_token" selected="selected">Red</option> <option value="green_token">Green</option> </select> ... <select name="form.color.query.selection"> <option value="red_token">Red</option> </select> <input type="submit" name="form.color.query.apply" value="Apply" /> ...It is not shown if the query is not applied:>>> request = TestRequest() >>> request.form = { ... 'form.color.query.selection': 'red_token', ... 'form.color.queries.visible': 'yes', ... 'form.color.query.search': 'yes', ... 'form.color.query.searchstring': 'red', ... 'form.color.displayed': '', ... } >>> request.setPrincipal(principal) >>> form = DemoInput(Demo(), request) >>> print(form()) <... <select name="form.color" id="form.color"> <option value="red_token">Red</option> <option value="green_token">Green</option> </select> ... <select name="form.color.query.selection"> <option value="red_token">Red</option> </select> <input type="submit" name="form.color.query.apply" value="Apply" /> ...Tokens in the annotation of the principal are ignored if they are not in the source:>>> from zope.annotation.interfaces import IAnnotations >>> annotations = IAnnotations(principal) >>> annotation = annotations.get('zc.form.browser.mruwidget') >>> tokens = annotation.get('form.color') >>> tokens.append('black_token') >>> tokens ['red_token', 'green_token', 'black_token'] >>> print(form()) <... <select name="form.color" id="form.color"> <option value="red_token">Red</option> <option value="green_token">Green</option> </select> ... <select name="form.color.query.selection"> <option value="red_token">Red</option> </select> <input type="submit" name="form.color.query.apply" value="Apply" /> ...Clean up a bit:>>> zope.security.management.endInteraction() >>> zope.component.hooks.setSite(oldsite)
zc.freeze
Thezc.freezepackage provides a pattern for freezing objects. State is informational–enforcement unspecified. Some enforcement approaches and helpers are included.ContentsDetailed DocumentationFreezingConveniencesCHANGES1.2 (2011-04-08)1.11.1b1.01.0.1Detailed DocumentationFreezingThis package implements basic functionality for freezing objects: spellings to query whether an object can be frozen, to query whether it has been frozen, and to actually freeze an object. Further policies may be implemented above the basic code in this package; and much of the code in this package is offered as pluggable choices which can be omitted while still keeping the basic API.To discover whether an object is freezable, client code should ask if it provides zc.freeze.interfaces.IFreezable.Site configurations or code that declares that an object is IFreezable is assuring that the object provides or can be adaptable to zc.freeze.interfaces.IFreezing. This interface has only three elements: _z_frozen is a readonly boolean that returns whether the object has been versioned; _z_freeze_datetime is a readonly datetime in pytz.utc specifying when the object was frozen (or None, if it is not yet frozen); and _z_freeze is a method that actually freezes the object. If the object is already frozen, it raises zc.freeze.interfaces.FrozenError. If the object is not in a state to be frozen, it may raise zc.freeze.interfaces.FreezeError. If the freezing may succeed, the method should send a zc.freeze.interfaces.IObjectFrozenEvent (such as zc.freeze.interfaces.ObjectFrozenEvent).That’s the heart of the package: an API and an agreement, with nothing to test directly. One policy that this package does not directly support is that freezing an object might first create a copy and then version the copy rather than the original; or version the original but replace the copy in the location of the original; or make any other choices. These approaches are intended to be implemented on top of–above–the zc.freeze API. This package provides much simpler capabilities.ConveniencesThe package does provide two default implementations of IFreezing, and a few conveniences.One IFreezing implementation is for objects that are directly aware of this API (as opposed to having the functionality assembled from adapters and other components).>>> import zc.freeze >>> v = zc.freeze.Freezing() >>> from zc.freeze import interfaces >>> from zope.interface.verify import verifyObject >>> verifyObject(interfaces.IFreezing, v) True >>> verifyObject(interfaces.IFreezable, v) True >>> v._z_frozen False >>> v._z_frozen = True Traceback (most recent call last): ... AttributeError: can't set attribute >>> import pytz >>> import datetime >>> before = datetime.datetime.now(pytz.utc) >>> v._z_freeze() >>> before <= v._z_freeze_timestamp <= datetime.datetime.now(pytz.utc) True >>> v._z_frozen True >>> interfaces.IObjectFrozenEvent.providedBy(events[-1]) True >>> events[-1].object is v True >>> v._z_freeze() Traceback (most recent call last): ... FrozenErrorAnother available implementation is an adapter, and stores the information in an annotation. Here’s a quick demo.>>> import zope.annotation.interfaces >>> from zope import interface, component >>> class Demo(object): ... interface.implements(zope.annotation.interfaces.IAnnotatable) ... >>> import UserDict >>> class DemoAnnotations(UserDict.UserDict): ... interface.implements(zope.annotation.interfaces.IAnnotations) ... component.adapts(Demo) ... def __init__(self, context): ... self.context = context ... self.data = getattr(context, '_z_demo', None) ... if self.data is None: ... self.data = context._z_demo = {} ... >>> component.provideAdapter(DemoAnnotations) >>> component.provideAdapter(zc.freeze.FreezingAdapter) >>> d = Demo() >>> verifyObject(interfaces.IFreezing, interfaces.IFreezing(d)) True >>> verifyObject(interfaces.IFreezable, interfaces.IFreezing(d)) True >>> interfaces.IFreezing(d)._z_frozen False >>> interfaces.IFreezing(d)._z_frozen = True Traceback (most recent call last): ... AttributeError: can't set attribute >>> before = datetime.datetime.now(pytz.utc) >>> interfaces.IFreezing(d)._z_freeze() >>> (before <= interfaces.IFreezing(d)._z_freeze_timestamp <= ... datetime.datetime.now(pytz.utc)) True >>> interfaces.IFreezing(d)._z_frozen True >>> interfaces.IObjectFrozenEvent.providedBy(events[-1]) True >>> events[-1].object is d True >>> interfaces.IFreezing(d)._z_freeze() Traceback (most recent call last): ... FrozenErrorThe zc.freeze module also contains three helpers for writing properties and methods that are freeze-aware.A ‘method’ function can generate a freeze-aware method that raises a FrozenError if the object has been frozen.‘setproperty’ and ‘delproperty’ functions can generate a freeze-aware descriptor that raises a FrozenError if the set or del methods are called on a frozen object. These are rwproperties.‘makeProperty’ generates a freeze-aware descriptor that does a simple get/set but raises FrozenError if the set is attempted on a frozen object.>>> class BiggerDemo(Demo): ... counter = 0 ... @zc.freeze.method ... def increase(self): ... self.counter += 1 ... _complex = 1 ... @property ... def complex_property(self): ... return str(self._complex) ... @zc.freeze.setproperty ... def complex_property(self, value): ... self._complex = value * 2 ... zc.freeze.makeProperty('simple_property') ... >>> d = BiggerDemo() >>> d.counter 0 >>> d.complex_property '1' >>> d.simple_property # None >>> d.increase() >>> d.counter 1 >>> d.complex_property = 4 >>> d.complex_property '8' >>> d.simple_property = 'hi' >>> d.simple_property 'hi' >>> interfaces.IFreezing(d)._z_frozen False >>> interfaces.IFreezing(d)._z_freeze() >>> interfaces.IFreezing(d)._z_frozen True >>> d.counter 1 >>> d.increase() Traceback (most recent call last): ... FrozenError >>> d.counter 1 >>> d.complex_property '8' >>> d.complex_property = 10 Traceback (most recent call last): ... FrozenError >>> d.complex_property '8' >>> d.simple_property 'hi' >>> d.simple_property = 'bye' Traceback (most recent call last): ... FrozenError >>> d.simple_property 'hi'CHANGES1.2 (2011-04-08)Updated tests to run with ZTK 1.0.Using Python’sdoctestmodule instead of the deprecatedzope.testing.doctest.Depend on a newer bug-fix version ofzope.locking.1.1(supports Zope 3.4/eggs)1.1bSwitched to supporting eggs1.0(supports Zope 3.3/no eggs)1.0.1Removed the included rwproperty.py and added a dependency instead, as rwproperty is now available from pypi.
zc.generationalset
Generational SetsGenerational sets (GSets) are designed to facilitate data synchronization between a server and clients.Goals:Make synchronization simple by sending all updates for a tree of sets at once.Allow clients to be updated very quickly.Reduce data-transfer volume by sending only changes.Avoid conflict resolution.Assumptions:Disconnected data updates aren’t needed.Clients mirror server data.This implies that the server data, or more specifically, the user’s view of the server data, aren’t too large to store on the client.GSets track state by generation. A client presents a generation and is sent updates made since the presented generation. GSets can be grouped into trees with a shared generation. A client can present a single generation and be sent updates for all of the sets making up a database.This implementation of generational sets usesZODBto store data on the server.High-level usage patternDefine a tree of sets representing the data in an application. This may be user specific.Clients make updates via REST calls to a server. They don’t make local changes except in response to server updates.Client requests include their data generation.Most (JSON) responses to server calls have optional updates property that contains generational updates since the generation provided by the client. When the client gets updates, which include the new generation, it applies the updates to it’s internal data store.For native apps, the server sends push notifications when there are updates for a user and, in response, the client polls for the updates. This allows updates to be extremely timely without constant polling.Note that this package only provides the data structure implementation. Wrapping the data structure in a REST interface or sending notifications is up to applications.APIEvery object in a GSet must have an id. By default, this is provided by anidattribute, but you can configure a GSet to use another attribute or some other mechanism to get an id for an object.When an object is added to a GSet, call theaddmethod on the Gset with the object:>>> from zc.generationalset import GSet >>> things = GSet() >>> athing = Thing(42) >>> things.add(athing)When an object is changed, call thechangedmethod on the Gset with the object. If object is not present in the Gset, update will raise a KeyError:>>> things.changed(athing) >>> things.changed(Thing(43)) Traceback (most recent call last): ... KeyError: 43 >>> things.generational_updates(0) {'generation': 3, 'adds': [Thing(42)]}To remove an object, call theremovemethod with the object:>>> things.remove(athing)To get updates to a set since a given generation, callgenerational_updates, passing a generation:>>> things.generational_updates(0) {'generation': 4, 'removals': [42]} >>> things.add(Thing(1)) >>> things.generational_updates(0) {'generation': 5, 'removals': [42], 'adds': [Thing(1)]} >>> things.generational_updates(3) {'generation': 5, 'adds': [Thing(1)]}Note that generations start at 1.The result of callinggenerational_updatesis a dictionary with keys:generationThe current generation of the setaddsObjects added since the given generation.removalsIds of objects removed since the given generation.contentsAll of the object in the set.contentsare returned when there have been many removals since the given generation. A generational set only keeps track of a limited number (99 by default, but configurable) of removals. If a client is too out of date for the set to have relevant removals, it returns the entire contents, instead of returning adds and removals.GSets support iteration, and querying length and containment. They don’t currently support set operations, like intersection and union. You can also retrieve an item from a GSet using its id:>>> len(things) 1 >>> list(things) [Thing(1)] >>> Thing(1) in things True >>> things[1] Thing(1)Nested setsTo define nested sets:Define a parent set:>>> parent = GSet(superset=True)Note the use of thesupersetparameter.Define child sets, and add them to the parent:>>> messages = GSet("messages", parent) >>> parent.add(messages)When defining child sets, specify an id and the parent.We haven’t tested more than one level of nesting.When asking for generational updates on parent sets, the adds and contents contain the generational updates for subsets, with ids, but without subset generations:>>> messages.add(Thing(42)) >>> parent.generational_updates(0) {'generation': 3, 'adds': [{'id': 'messages', 'adds': [Thing(42)]}]}Changes0.4.0 (2017-06-20)Python 3 supportWhen asking for updates from generation 0, only adds are sent. Never removals, making this common case more efficient.0.3.0 (2014-08-28)Added achangedmethod to make intent clear when simply recording changes.Fixed: exceptions were raised when objects added to generational sets quacked a little like generational sets.0.2.0 (2014-08-10)Improved subset APIs:No longer need to specify superset flag.Can have set and non-set children.A subset can be created without a parent and the parent will be set when it’s added to a containing set.0.1.2 (2014-06-09)Fixed: Internal data structures were misshandled when there were morethan the maximum number of removals.(Release 0.1.1 was made in error.)0.1.0 (2014-06-08)Initial release